Skip to content

Commit

Permalink
Merge pull request #171 from Arquisoft/open-api
Browse files Browse the repository at this point in the history
Add REST API unit tests
  • Loading branch information
uo287545 authored Apr 6, 2024
2 parents 7e5370f + eedabb3 commit db166ee
Show file tree
Hide file tree
Showing 19 changed files with 848 additions and 58 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ public MultipleQuestionGenerator(QuestionGenerator... generators) {
this.generators = generators;
}

public List<Question> getQuestions() {
public List<Question> getQuestions() throws InterruptedException {
List<Question> questions = new ArrayList<>();
for (QuestionGenerator generator : generators) {
questions.addAll(generator.getQuestions());
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.nio.charset.StandardCharsets;
import java.security.SecureRandom;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
Expand All @@ -20,7 +21,7 @@ public abstract class AbstractQuestionGenerator implements QuestionGenerator{
private List<Question> questions = new ArrayList<>();
protected final CategoryService categoryService;

protected Random random = new Random();
protected Random random = new SecureRandom();

protected String statement;
protected String language;
Expand All @@ -45,7 +46,7 @@ public void questionGenerator(String statement, List<String> options, String cor
questions.add(question);
}

public List<Question> getQuestions() {
public List<Question> getQuestions() throws InterruptedException {
HttpClient client = HttpClient.newHttpClient();
try {

Expand Down Expand Up @@ -76,9 +77,9 @@ public List<Question> getQuestions() {

}
} catch (InterruptedException e) {
throw new QuestionGeneratorException("Generation of questions was interrupted");
throw e;
} catch (Exception e) {
throw new QuestionGeneratorException("An error occurred while generating questions");
throw new QuestionGeneratorException("An error occurred while generating questions." + e.getMessage());
}

return questions;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@
public interface QuestionGenerator {

String getQuery();
List<Question> getQuestions();
List<Question> getQuestions() throws InterruptedException;

Category getCategory();

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -6,17 +6,18 @@
import java.util.*;

public class BorderQuestionGenerator extends AbstractGeographyGenerator{
private static final Map<String, String> STATEMENTS = new HashMap<>() {
{
put("en", "Which countries share a border with ");
put("es", "¿Con qué países comparte frontera ");
put("fr", "Avec quels pays partage-t-il une frontière ");
}
};
private static Map<String, String> STATEMENTS = null;
private Set<String> usedCountries = new HashSet<>();

public BorderQuestionGenerator(CategoryService categoryService, String language) {
super(categoryService);
if (STATEMENTS == null) {
STATEMENTS = new HashMap<>();
STATEMENTS.put("en", "Which countries share a border with ");
STATEMENTS.put("es", "¿Con qué países comparte frontera ");
STATEMENTS.put("fr", "Avec quels pays partage-t-il une frontière ");
}

this.statement = STATEMENTS.get(language);
this.language = language;
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -8,16 +8,17 @@
import java.util.*;

public class CapitalQuestionGenerator extends AbstractGeographyGenerator{
private static final Map<String, String> STATEMENTS = new HashMap<>() {
{
put("en", "What is the capital of ");
put("es", "¿Cuál es la capital de ");
put("fr", "Quelle est la capitale de ");
}
};
private static Map<String, String> STATEMENTS = null;

public CapitalQuestionGenerator(CategoryService categoryService, String language) {
super(categoryService);
if (STATEMENTS == null) {
STATEMENTS = new HashMap<>();
STATEMENTS.put("en", "What is the capital of ");
STATEMENTS.put("es", "¿Cuál es la capital de ");
STATEMENTS.put("fr", "Quelle est la capitale de ");
}

this.statement = STATEMENTS.get(language);
this.language = language;
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -7,16 +7,18 @@
import java.util.*;

public class ContinentQuestionGeneration extends AbstractGeographyGenerator{
private static final Map<String, String> STATEMENTS = new HashMap<>() {
{
put("en", "In which continent is ");
put("es", "¿En qué continente se encuentra ");
put("fr", "Sur quel continent est-il situé ");
}
};
private static Map<String, String> STATEMENTS = null;

public ContinentQuestionGeneration(CategoryService categoryService, String language) {
super(categoryService);

if (STATEMENTS == null) {
STATEMENTS = new HashMap<>();
STATEMENTS.put("en", "In which continent is ");
STATEMENTS.put("es", "¿En qué continente se encuentra ");
STATEMENTS.put("fr", "Sur quel continent est-il situé ");
}

this.statement = STATEMENTS.get(language);
this.language = language;
}
Expand Down
4 changes: 3 additions & 1 deletion src/main/java/com/uniovi/controllers/GameController.java
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@
import java.security.Principal;
import java.time.Duration;
import java.time.LocalDateTime;
import java.util.Optional;

@Controller
public class GameController {
Expand Down Expand Up @@ -149,7 +150,8 @@ public String getPoints(HttpSession session) {
}

private Player getLoggedInPlayer(Principal principal) {
return playerService.getUserByUsername(principal.getName()).get();
Optional<Player> player = playerService.getUserByUsername(principal.getName());
return player.orElse(null);
}

/**
Expand Down
11 changes: 9 additions & 2 deletions src/main/java/com/uniovi/controllers/PlayersController.java
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@
import org.springframework.web.bind.annotation.RequestParam;

import java.security.Principal;
import java.util.Optional;

@Controller
public class PlayersController {
Expand Down Expand Up @@ -105,8 +106,14 @@ public String showGlobalRanking(Pageable pageable, Model model) {

@GetMapping("/ranking/playerRanking")
public String showPlayerRanking(Pageable pageable, Model model, Principal principal) {
Player player = playerService.getUserByUsername(principal.getName()).get();
Page<GameSession> ranking = gameSessionService.getPlayerRanking(pageable, player);
Optional<Player> player = playerService.getUserByUsername(principal.getName());
Player p = player.orElse(null);

if (p == null) {
return "redirect:/login";
}

Page<GameSession> ranking = gameSessionService.getPlayerRanking(pageable, p);

model.addAttribute("ranking", ranking.getContent());
model.addAttribute("page", ranking);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -221,6 +221,8 @@ public String updatePlayer(@RequestHeader(name = "API-KEY") String apiKeyStr,
return objectMapper.writeValueAsString(error);
}

playerDto.setPasswordConfirm(playerDto.getPassword());

Errors err = new SimpleErrors(playerDto);
signUpValidator.validate(playerDto, err);

Expand Down
2 changes: 1 addition & 1 deletion src/main/java/com/uniovi/entities/Answer.java
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@ public class Answer implements JsonEntity {
private boolean correct;

@JsonIgnore
@ManyToOne
@ManyToOne(fetch = FetchType.EAGER)
private Question question;

public Answer(String text, boolean correct) {
Expand Down
2 changes: 1 addition & 1 deletion src/main/java/com/uniovi/entities/ApiKey.java
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,6 @@ public class ApiKey {
@OneToOne
private Player player;

@OneToMany(mappedBy = "apiKey")
@OneToMany(mappedBy = "apiKey", cascade = CascadeType.ALL, orphanRemoval = true)
private Set<RestApiAccessLog> accessLogs = new HashSet<>();
}
3 changes: 2 additions & 1 deletion src/main/java/com/uniovi/entities/GameSession.java
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@
import lombok.NoArgsConstructor;
import lombok.Setter;

import java.io.Serializable;
import java.time.Duration;
import java.time.LocalDateTime;
import java.util.*;
Expand All @@ -17,7 +18,7 @@
@Setter
@Entity
@NoArgsConstructor
public class GameSession implements JsonEntity {
public class GameSession implements JsonEntity, Serializable {
@Id
@GeneratedValue
private Long id;
Expand Down
2 changes: 1 addition & 1 deletion src/main/java/com/uniovi/entities/Player.java
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,7 @@ public class Player implements JsonEntity {
@NotEmpty
private String password;

@ManyToMany(cascade = CascadeType.REMOVE, fetch = FetchType.EAGER)
@ManyToMany(cascade = CascadeType.MERGE, fetch = FetchType.EAGER)
private Set<Role> roles = new HashSet<>();

@OneToMany(mappedBy = "player", cascade = CascadeType.ALL, fetch = FetchType.EAGER)
Expand Down
2 changes: 1 addition & 1 deletion src/main/java/com/uniovi/entities/Question.java
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,7 @@ public class Question implements JsonEntity {
@OneToMany(mappedBy = "question", cascade = CascadeType.ALL, orphanRemoval = true, fetch = FetchType.EAGER)
private List<Answer> options = new ArrayList<>();

@OneToOne
@OneToOne(cascade = CascadeType.ALL)
private Answer correctAnswer;

@ManyToOne
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -49,7 +49,7 @@ public InsertSampleDataService(PlayerService playerService, QuestionService ques

@Transactional
@EventListener(ApplicationReadyEvent.class) // Uncomment this line to insert sample data on startup
public void insertSampleQuestions() {
public void insertSampleQuestions() throws InterruptedException {
if (!playerService.getUserByEmail("[email protected]").isPresent()) {
PlayerDto player = new PlayerDto();
player.setEmail("[email protected]");
Expand All @@ -68,7 +68,7 @@ public void insertSampleQuestions() {
}

@Transactional
public void generateSampleData() {
public void generateSampleData() throws InterruptedException {

questionRepository.deleteAll();

Expand Down
18 changes: 10 additions & 8 deletions src/main/java/com/uniovi/services/impl/QuestionServiceImpl.java
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@
import org.springframework.data.querydsl.QPageRequest;
import org.springframework.stereotype.Service;

import java.security.SecureRandom;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
Expand All @@ -29,7 +30,7 @@ public class QuestionServiceImpl implements QuestionService {
private final CategoryService categoryService;
private final AnswerService answerService;

private final Random random = new Random();
private final Random random = new SecureRandom();

public QuestionServiceImpl(QuestionRepository questionRepository, CategoryService categoryService, AnswerService answerService) {
this.questionRepository = questionRepository;
Expand Down Expand Up @@ -132,20 +133,21 @@ public void updateQuestion(Long id, QuestionDto questionDto) {
category = categoryService.getCategoryByName(questionDto.getCategory().getName());
}

Associations.QuestionAnswers.removeAnswer(question, question.getOptions());
Associations.QuestionsCategory.removeCategory(question, question.getCategory());

List<Answer> answers = new ArrayList<>();
for (int i = 0; i < question.getOptions().size(); i++) {
for (int i = 0; i < questionDto.getOptions().size(); i++) {
Answer a = new Answer();
a.setText(question.getOptions().get(i).getText());
a.setCorrect(question.getOptions().get(i).isCorrect());
answerService.addNewAnswer(a);
a.setText(questionDto.getOptions().get(i).getText());
a.setCorrect(questionDto.getOptions().get(i).isCorrect());
answers.add(a);
}

Associations.QuestionAnswers.removeAnswer(question, question.getOptions());
Associations.QuestionsCategory.removeCategory(question, question.getCategory());

Associations.QuestionAnswers.addAnswer(question, answers);
Associations.QuestionsCategory.addCategory(question, category);

question.setCorrectAnswer(question.getOptions().stream().filter(Answer::isCorrect).findFirst().orElse(null));
questionRepository.save(question);
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -125,10 +125,7 @@ public List<Question> getQuestions(Map<String, String> params, Pageable pageable
if (params.containsKey("id")) {
try {
Optional<Question> found = questionService.getQuestion(Long.parseLong(params.get("id")));
if (found.isPresent())
return List.of(found.get());
else
return List.of();
return found.map(List::of).orElseGet(List::of);
} catch (NumberFormatException e) {
return List.of();
}
Expand Down
15 changes: 15 additions & 0 deletions src/main/resources/application-testlocal.properties
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
# Port 3000 for testing, local deployment
server.port=3000
server.address=0.0.0.0

# HSQL db
spring.datasource.driver-class-name=org.hsqldb.jdbc.JDBCDriver
spring.datasource.url=jdbc:hsqldb:hsql://localhost:9001
spring.datasource.username=sa
spring.datasource.password=
spring.jpa.hibernate.ddl-auto=create

springdoc.api-docs.path=/api-docs
springdoc.swagger-ui.path=/api
springdoc.swagger-ui.operationsSorter=method
springdoc.packagesToScan=com.uniovi.controllers.api
Loading

0 comments on commit db166ee

Please sign in to comment.