Skip to content

Commit

Permalink
[backend/frontend] Fix removing a team from the context doesn't work
Browse files Browse the repository at this point in the history
  • Loading branch information
RomuDeuxfois committed Oct 2, 2024
1 parent c771b61 commit 4ae7d03
Show file tree
Hide file tree
Showing 12 changed files with 274 additions and 122 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -230,14 +230,7 @@ public Iterable<Team> addExerciseTeams(
@PreAuthorize("isExercisePlanner(#exerciseId)")
public Iterable<Team> removeExerciseTeams(@PathVariable String exerciseId,
@Valid @RequestBody ExerciseUpdateTeamsInput input) {
Exercise exercise = this.exerciseService.exercise(exerciseId);
// Remove teams from exercise
List<Team> teams = exercise.getTeams().stream().filter(team -> !input.getTeamIds().contains(team.getId())).toList();
exercise.setTeams(new ArrayList<>(teams));
this.exerciseService.updateExercise(exercise);
// Remove all association between users / exercises / teams
input.getTeamIds().forEach(exerciseTeamUserRepository::deleteTeamFromAllReferences);
return teamRepository.findAllById(input.getTeamIds());
return this.exerciseService.removeTeams(exerciseId, input.getTeamIds());

Check warning on line 233 in openbas-api/src/main/java/io/openbas/rest/exercise/ExerciseApi.java

View check run for this annotation

Codecov / codecov/patch

openbas-api/src/main/java/io/openbas/rest/exercise/ExerciseApi.java#L233

Added line #L233 was not covered by tests
}

@Transactional(rollbackOn = Exception.class)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,10 +4,8 @@
import com.fasterxml.jackson.databind.node.ArrayNode;
import io.openbas.config.OpenBASConfig;
import io.openbas.database.model.*;
import io.openbas.database.repository.ArticleRepository;
import io.openbas.database.repository.ExerciseRepository;
import io.openbas.database.repository.*;
import io.openbas.rest.exception.ElementNotFoundException;
import io.openbas.database.repository.TeamRepository;
import io.openbas.rest.exercise.form.ExerciseSimple;
import io.openbas.rest.inject.service.InjectDuplicateService;
import io.openbas.service.GrantService;
Expand All @@ -20,7 +18,6 @@
import jakarta.persistence.Tuple;
import jakarta.persistence.TypedQuery;
import jakarta.persistence.criteria.*;
import jakarta.transaction.Transactional;
import jakarta.validation.constraints.NotBlank;
import lombok.RequiredArgsConstructor;
import org.jetbrains.annotations.NotNull;
Expand All @@ -30,6 +27,7 @@
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.validation.annotation.Validated;

import java.time.Instant;
Expand Down Expand Up @@ -65,6 +63,8 @@ public class ExerciseService {
private final ArticleRepository articleRepository;
private final ExerciseRepository exerciseRepository;
private final TeamRepository teamRepository;
private final ExerciseTeamUserRepository exerciseTeamUserRepository;
private final InjectRepository injectRepository;

// region properties
@Value("${openbas.mail.imap.enabled}")
Expand Down Expand Up @@ -195,7 +195,7 @@ private List<ExerciseSimple> execution(TypedQuery<Tuple> query) {

// -- CREATION --

@Transactional(rollbackOn = Exception.class)
@Transactional(rollbackFor = Exception.class)
public Exercise createExercise(@NotNull final Exercise exercise){
if (imapEnabled) {
exercise.setFrom(imapUsername);
Expand Down Expand Up @@ -407,4 +407,17 @@ private void getObjectives(Exercise duplicatedExercise, Exercise originalExercis
duplicatedExercise.setObjectives(duplicatedObjectives);
}

// -- TEAMS --

@Transactional(rollbackFor = Exception.class)
public Iterable<Team> removeTeams(@NotBlank final String exerciseId, @NotNull final List<String> teamIds) {
// Remove teams from exercise
this.exerciseRepository.removeTeams(exerciseId, teamIds);
// Remove all association between users / exercises / teams
teamIds.forEach(exerciseTeamUserRepository::deleteTeamFromAllReferences);
// Remove all association between injects and teams
this.injectRepository.removeTeamsForExercise(exerciseId, teamIds);
return teamRepository.findAllById(teamIds);
}

}
Original file line number Diff line number Diff line change
Expand Up @@ -97,6 +97,7 @@ public class ScenarioService {
private final TeamService teamService;
private final FileService fileService;
private final InjectDuplicateService injectDuplicateService;
private final InjectRepository injectRepository;

@Transactional
public Scenario createScenario(@NotNull final Scenario scenario) {
Expand Down Expand Up @@ -440,13 +441,14 @@ public Iterable<Team> addTeams(@NotBlank final String scenarioId, @NotNull final
return teamsToAdd;
}

@Transactional(rollbackFor = Exception.class)
public Iterable<Team> removeTeams(@NotBlank final String scenarioId, @NotNull final List<String> teamIds) {
Scenario scenario = this.scenario(scenarioId);
List<Team> teams = scenario.getTeams().stream().filter(team -> !teamIds.contains(team.getId())).toList();
scenario.setTeams(new ArrayList<>(teams));
this.updateScenario(scenario);
// Remove teams from exercise
this.scenarioRepository.removeTeams(scenarioId, teamIds);
// Remove all association between users / exercises / teams
teamIds.forEach(this.scenarioTeamUserRepository::deleteTeamFromAllReferences);
// Remove all association between injects and teams
this.injectRepository.removeTeamsForScenario(scenarioId, teamIds);
return teamRepository.findAllById(teamIds);
}

Expand Down
181 changes: 119 additions & 62 deletions openbas-api/src/test/java/io/openbas/service/ExerciseServiceTest.java
Original file line number Diff line number Diff line change
@@ -1,81 +1,138 @@
package io.openbas.service;

import io.openbas.database.model.*;
import io.openbas.database.repository.ArticleRepository;
import io.openbas.database.repository.ExerciseRepository;
import io.openbas.database.repository.TeamRepository;
import io.openbas.database.repository.*;
import io.openbas.rest.exercise.ExerciseService;
import io.openbas.rest.inject.service.InjectDuplicateService;
import jakarta.transaction.Transactional;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
import io.openbas.utils.fixtures.ExerciseFixture;
import org.junit.jupiter.api.*;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

import static io.openbas.utils.fixtures.TeamFixture.getTeam;
import static io.openbas.database.specification.TeamSpecification.fromExercise;
import static io.openbas.injectors.email.EmailContract.EMAIL_DEFAULT;
import static io.openbas.utils.fixtures.ExerciseFixture.getExercise;
import static io.openbas.utils.fixtures.InjectFixture.getInjectForEmailContract;
import static io.openbas.utils.fixtures.TeamFixture.getTeam;
import static io.openbas.utils.fixtures.UserFixture.getUser;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotEquals;

@SpringBootTest
public class ExerciseServiceTest {
@Mock
GrantService grantService;
@Mock
InjectService injectService;
@Mock
InjectDuplicateService injectDuplicateService;
@Autowired
private TeamService teamService;
@Mock
VariableService variableService;

@Autowired
private ArticleRepository articleRepository;
@Autowired
private ExerciseRepository exerciseRepository;
@Autowired
private TeamRepository teamRepository;

@InjectMocks
private ExerciseService exerciseService;
@BeforeEach
void setUp() {
exerciseService = new ExerciseService(grantService, injectService, injectDuplicateService,
teamService,variableService, articleRepository,exerciseRepository,teamRepository);
}

@DisplayName("Should create new contextual teams while exercise duplication")
@Test
@Transactional(rollbackOn = Exception.class)
void createNewContextualTeamsWhileExerciseDuplication(){
// -- PREPARE --
List<Team> exerciseTeams = new ArrayList<>();;
Team contextualTeam = this.teamRepository.save(getTeam(null, "fakeTeamName1", true));
exerciseTeams.add(contextualTeam);
Team noContextualTeam = this.teamRepository.save(getTeam(null, "fakeTeamName2",false));
exerciseTeams.add(noContextualTeam);
Exercise exercise = this.exerciseRepository.save(getExercise(exerciseTeams));

// -- EXECUTE --
Exercise exerciseDuplicated = exerciseService.getDuplicateExercise(exercise.getId());

// -- ASSERT --
assertNotEquals(exercise.getId(), exerciseDuplicated.getId());
assertEquals(2, exerciseDuplicated.getTeams().size());
exerciseDuplicated.getTeams().forEach(team -> {
if (team.getContextual()){
assertNotEquals(contextualTeam.getId(), team.getId());
assertEquals(contextualTeam.getName(), team.getName());
} else {
assertEquals(noContextualTeam.getId(), team.getId());
}
});
}
@TestInstance(TestInstance.Lifecycle.PER_CLASS)
class ExerciseServiceTest {

@Mock
GrantService grantService;
@Mock
InjectService injectService;
@Mock
InjectDuplicateService injectDuplicateService;
@Autowired
private TeamService teamService;
@Mock
VariableService variableService;

@Autowired
private ArticleRepository articleRepository;
@Autowired
private ExerciseRepository exerciseRepository;
@Autowired
private TeamRepository teamRepository;

@Autowired
private UserRepository userRepository;
@Autowired
private InjectRepository injectRepository;
@Autowired
private ExerciseTeamUserRepository exerciseTeamUserRepository;
@Autowired
private InjectorContractRepository injectorContractRepository;

private static String USER_ID;
private static String TEAM_ID;
private static String INJECT_ID;

@InjectMocks
private ExerciseService exerciseService;

@BeforeEach
void setUp() {
exerciseService = new ExerciseService(grantService, injectService, injectDuplicateService,
teamService, variableService, articleRepository, exerciseRepository, teamRepository,
exerciseTeamUserRepository, injectRepository);
}

@AfterAll
public void teardown() {
this.userRepository.deleteById(USER_ID);
this.teamRepository.deleteById(TEAM_ID);
this.injectRepository.deleteById(INJECT_ID);
}

@DisplayName("Should create new contextual teams while exercise duplication")
@Test
@Transactional(rollbackFor = Exception.class)
void createNewContextualTeamsWhileExerciseDuplication() {
// -- PREPARE --
List<Team> exerciseTeams = new ArrayList<>();
Team contextualTeam = this.teamRepository.save(getTeam(null, "fakeTeamName1", true));
exerciseTeams.add(contextualTeam);
Team noContextualTeam = this.teamRepository.save(getTeam(null, "fakeTeamName2", false));
exerciseTeams.add(noContextualTeam);
Exercise exercise = this.exerciseRepository.save(getExercise(exerciseTeams));

// -- EXECUTE --
Exercise exerciseDuplicated = exerciseService.getDuplicateExercise(exercise.getId());

// -- ASSERT --
assertNotEquals(exercise.getId(), exerciseDuplicated.getId());
assertEquals(2, exerciseDuplicated.getTeams().size());
exerciseDuplicated.getTeams().forEach(team -> {
if (team.getContextual()) {
assertNotEquals(contextualTeam.getId(), team.getId());
assertEquals(contextualTeam.getName(), team.getName());
} else {
assertEquals(noContextualTeam.getId(), team.getId());
}
});
}

@DisplayName("Should remove team from exercise")
@Test
void testRemoveTeams() {
// -- PREPARE --
User user = getUser();
User userSaved = this.userRepository.saveAndFlush(user);
USER_ID = userSaved.getId();
Team team = getTeam(user);
Team teamSaved = this.teamRepository.saveAndFlush(team);
TEAM_ID = teamSaved.getId();
Exercise exercise = ExerciseFixture.getExercise();
exercise.setTeams(List.of(teamSaved));
exercise.setFrom(user.getEmail());
Exercise exerciseSaved = this.exerciseRepository.saveAndFlush(exercise);

InjectorContract injectorContract = this.injectorContractRepository.findById(EMAIL_DEFAULT).orElseThrow();
Inject injectDefaultEmail = getInjectForEmailContract(injectorContract);
injectDefaultEmail.setExercise(exerciseSaved);
injectDefaultEmail.setTeams(List.of(teamSaved));
Inject injectDefaultEmailSaved = this.injectRepository.saveAndFlush(injectDefaultEmail);
INJECT_ID = injectDefaultEmailSaved.getId();

// -- EXECUTE --
this.exerciseService.removeTeams(exerciseSaved.getId(), List.of(teamSaved.getId()));

// -- ASSERT --
List<Team> teams = this.teamRepository.findAll(fromExercise(exerciseSaved.getId()));
assertEquals(0, teams.size());
Inject injectAssert = this.injectRepository.findById(INJECT_ID).orElseThrow();
assertEquals(0, injectAssert.getTeams().size());
}
}
Loading

0 comments on commit 4ae7d03

Please sign in to comment.