Skip to content

Commit

Permalink
updated test for clusterfillroute
Browse files Browse the repository at this point in the history
  • Loading branch information
Aqua-sc committed May 12, 2024
1 parent 7ce666b commit a2b3de1
Show file tree
Hide file tree
Showing 5 changed files with 187 additions and 69 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -183,7 +183,7 @@ public ResponseEntity<?> doGroupClusterUpdate(GroupClusterEntity clusterEntity,
*
* @param clusterid identifier of a cluster
* @param auth authentication object of the requesting user
* @param clusterFillJson ClusterFillJson object containing a map of all groups and their
* @param clusterFillMap Map object containing a map of all groups and their
* members of that cluster
* @return ResponseEntity<?>
* @HttpMethod PUT
Expand Down Expand Up @@ -226,7 +226,7 @@ public ResponseEntity<?> fillCluster(@PathVariable("clusterid") Long clusterid,

groupCluster.setGroupAmount(clusterFillJson.getClusterGroupMembers().size());
groupClusterRepository.save(groupCluster);
return ResponseEntity.status(HttpStatus.OK).body("Filled group cluster successfully");
return ResponseEntity.status(HttpStatus.OK).body(entityToJsonConverter.clusterEntityToClusterJson(groupCluster));
} catch (Exception e) {
Logger.getGlobal().severe(e.getMessage());
return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("Something went wrong");
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -18,4 +18,8 @@ public Map<String, Long[]> getClusterGroupMembers() {
return clusterGroupMembers;
}

public void addClusterGroupMembers(String clusterId, Long[] groupIds) {
clusterGroupMembers.put(clusterId, groupIds);
}

}
Original file line number Diff line number Diff line change
Expand Up @@ -9,11 +9,15 @@
import com.ugent.pidgeon.postgre.models.GroupEntity;
import com.ugent.pidgeon.postgre.models.types.CourseRelation;
import com.ugent.pidgeon.postgre.repository.GroupClusterRepository;
import com.ugent.pidgeon.postgre.repository.GroupMemberRepository;
import com.ugent.pidgeon.postgre.repository.GroupRepository;
import com.ugent.pidgeon.util.*;
import java.time.OffsetDateTime;
import java.util.Collections;
import java.util.logging.Logger;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension;
Expand All @@ -30,7 +34,10 @@
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyLong;
import static org.mockito.ArgumentMatchers.argThat;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.reset;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath;
Expand All @@ -43,6 +50,8 @@ public class ClusterControllerTest extends ControllerTest{
GroupClusterRepository groupClusterRepository;
@Mock
GroupRepository groupRepository;
@Mock
GroupMemberRepository groupMemberRepository;


@Mock
Expand All @@ -54,8 +63,7 @@ public class ClusterControllerTest extends ControllerTest{
private CourseUtil courseUtil;
@Mock
private CommonDatabaseActions commonDatabaseActions;
@Mock
private GroupMemberController groupMemberController;

@InjectMocks
private ClusterController clusterController;

Expand All @@ -73,10 +81,20 @@ public void setup() {
setUpController(clusterController);

courseEntity = new CourseEntity("name", "description",2024);
groupClusterEntity = new GroupClusterEntity(1L, 20, "clustername", 5);
groupClusterJson = new GroupClusterJson(1L, "clustername", 20, 5, OffsetDateTime.now(), Collections.emptyList(), "");
courseEntity.setId(32L);
groupClusterEntity = new GroupClusterEntity(courseEntity.getId(), 20, "clustername", 5);
groupClusterEntity.setId(29L);
groupClusterJson = new GroupClusterJson(
groupClusterEntity.getId(),
groupClusterEntity.getName(),
groupClusterEntity.getMaxSize(),
groupClusterEntity.getGroupAmount(),
OffsetDateTime.now(),
Collections.emptyList(),
"");
groupEntity = new GroupEntity("groupName", 1L);
groupJson = new GroupJson(10, 1L, "Groupname", "");
groupEntity.setId(78L);
groupJson = new GroupJson(groupClusterEntity.getMaxSize(), groupEntity.getId(), groupEntity.getName(), "");
}

@Test
Expand Down Expand Up @@ -198,66 +216,92 @@ public void testUpdateCluster() throws Exception {
.andExpect(status().isBadRequest());
}

// TEST IS OUTDATED, SHOULD WORK WITH MINIMAL CHANGES
// @Test
// public void testFillCluster() throws Exception {
// String request = "{\"clusterGroupMembers\":{\"1\":[1,2,3],\"2\":[],\"3\":[4]}}";
//
// List<GroupJson> groupJsons = List.of(new GroupJson(3, 1L, "group 1", "groupclusterurl"));
// GroupClusterJson groupClusterJson = new GroupClusterJson(1L, "test cluster",
// 3, 5, OffsetDateTime.now(), groupJsons, "courseurl");
// when(clusterUtil.getGroupClusterEntityIfAdminAndNotIndividual(anyLong(), any()))
// .thenReturn(new CheckResult<>(HttpStatus.OK, "", groupClusterEntity));
// when(clusterUtil.getGroupClusterEntityIfNotIndividual(anyLong(), any()))
// .thenReturn(new CheckResult<>(HttpStatus.OK, "", groupClusterEntity));
// when(entityToJsonConverter.clusterEntityToClusterJson(groupClusterEntity))
// .thenReturn(groupClusterJson);
// mockMvc.perform(MockMvcRequestBuilders.put(ApiRoutes.CLUSTER_BASE_PATH+"/1/fill")
// .contentType(MediaType.APPLICATION_JSON)
// .content(request))
// .andExpect(status().isOk());
//
// when(commonDatabaseActions.removeGroup(anyLong()))
// .thenThrow(new RuntimeException("TEST ERROR"));
// mockMvc.perform(MockMvcRequestBuilders.put(ApiRoutes.CLUSTER_BASE_PATH+"/1/fill")
// .contentType(MediaType.APPLICATION_JSON)
// .content(request))
// .andExpect(status().isInternalServerError());
//
// // a group that is too big
// request = "{\"clusterGroupMembers\":{\"1\":[1,2,3,6],\"2\":[],\"3\":[4]}}";
// mockMvc.perform(MockMvcRequestBuilders.put(ApiRoutes.CLUSTER_BASE_PATH+"/1/fill")
// .contentType(MediaType.APPLICATION_JSON)
// .content(request))
// .andExpect(status().isBadRequest());
// // too many groups
// request = "{\"clusterGroupMembers\":{\"1\":[1,2,3],\"2\":[],\"3\":[4],\"4\":[],\"5\":[6],\"6\":[]}}";
// mockMvc.perform(MockMvcRequestBuilders.put(ApiRoutes.CLUSTER_BASE_PATH+"/1/fill")
// .contentType(MediaType.APPLICATION_JSON)
// .content(request))
// .andExpect(status().isBadRequest());
//
// when(entityToJsonConverter.clusterEntityToClusterJson(groupClusterEntity))
// .thenReturn(null);
// mockMvc.perform(MockMvcRequestBuilders.put(ApiRoutes.CLUSTER_BASE_PATH+"/1/fill")
// .contentType(MediaType.APPLICATION_JSON)
// .content(request))
// .andExpect(status().isNotFound());
//
// when(clusterUtil.getGroupClusterEntityIfNotIndividual(anyLong(), any()))
// .thenReturn(new CheckResult<>(HttpStatus.I_AM_A_TEAPOT, "", null));
// mockMvc.perform(MockMvcRequestBuilders.put(ApiRoutes.CLUSTER_BASE_PATH+"/1/fill")
// .contentType(MediaType.APPLICATION_JSON)
// .content(request))
// .andExpect(status().isIAmATeapot());
//
// when(clusterUtil.getGroupClusterEntityIfAdminAndNotIndividual(anyLong(), any()))
// .thenReturn(new CheckResult<>(HttpStatus.UNAUTHORIZED, "", null));
// mockMvc.perform(MockMvcRequestBuilders.put(ApiRoutes.CLUSTER_BASE_PATH+"/1/fill")
// .contentType(MediaType.APPLICATION_JSON)
// .content(request))
// .andExpect(status().isUnauthorized());
// }
@Test
public void testFillCluster() throws Exception {
String url = ApiRoutes.CLUSTER_BASE_PATH + "/" + groupClusterEntity.getId() + "/fill";
String request = """
{
"group1": [3, 2],
"group2": [4, 5]
}
""";

long newGroupEntityId = 89L;
GroupEntity newGroupEntity = new GroupEntity("group1", groupClusterEntity.getId());
newGroupEntity.setId(newGroupEntityId);
long newGroupEntityId2 = 221L;
GroupEntity newGroupEntity2 = new GroupEntity("group2", groupClusterEntity.getId());
newGroupEntity2.setId(newGroupEntityId2);
/* All checks succeed */
when(clusterUtil.getGroupClusterEntityIfAdminAndNotIndividual(groupClusterEntity.getId(), getMockUser()))
.thenReturn(new CheckResult<>(HttpStatus.OK, "", groupClusterEntity));

when(groupRepository.findAllByClusterId(groupClusterEntity.getId())).thenReturn(List.of(groupEntity));
when(clusterUtil.checkFillClusterJson(argThat(
json -> {
boolean check = json.getClusterGroupMembers().size() == 2;
check = check && json.getClusterGroupMembers().get("group1").length == 2;
check = check && json.getClusterGroupMembers().get("group1")[0] == 3;
check = check && json.getClusterGroupMembers().get("group1")[1] == 2;
check = check && json.getClusterGroupMembers().get("group2").length == 2;
check = check && json.getClusterGroupMembers().get("group2")[0] == 4;
check = check && json.getClusterGroupMembers().get("group2")[1] == 5;
return check;
}
), eq(groupClusterEntity)))
.thenReturn(new CheckResult<>(HttpStatus.OK, "", null));

when(groupRepository.save(argThat(
g1 -> g1 != null && g1.getName().equals("group1") && g1.getClusterId() == groupClusterEntity.getId()
))).thenReturn(newGroupEntity);

when(groupRepository.save(argThat(
g2 -> g2 != null && g2.getName().equals("group2") && g2.getClusterId() == groupClusterEntity.getId()
))).thenReturn(newGroupEntity2);

mockMvc.perform(MockMvcRequestBuilders.put(url)
.contentType(MediaType.APPLICATION_JSON)
.content(request))
.andExpect(status().isOk());

verify(commonDatabaseActions, times(1)).removeGroup(groupEntity.getId());
verify(groupMemberRepository, times(1)).addMemberToGroup(newGroupEntityId, 2);
verify(groupMemberRepository, times(1)).addMemberToGroup(newGroupEntityId, 3);
verify(groupMemberRepository, times(1)).addMemberToGroup(newGroupEntityId2, 4);
verify(groupMemberRepository, times(1)).addMemberToGroup(newGroupEntityId2, 5);
assertEquals(2, groupClusterEntity.getGroupAmount());
verify(groupClusterRepository, times(1)).save(groupClusterEntity);

/* Error when checking json */
reset(clusterUtil);
when(clusterUtil.getGroupClusterEntityIfAdminAndNotIndividual(groupClusterEntity.getId(), getMockUser()))
.thenReturn(new CheckResult<>(HttpStatus.OK, "", groupClusterEntity));
when(clusterUtil.checkFillClusterJson(any(), any())).thenReturn(new CheckResult<>(HttpStatus.I_AM_A_TEAPOT, "", null));
mockMvc.perform(MockMvcRequestBuilders.put(url)
.contentType(MediaType.APPLICATION_JSON)
.content(request))
.andExpect(status().isIAmATeapot());

/* Error when getting group cluster entity */
reset(clusterUtil);
when(clusterUtil.getGroupClusterEntityIfAdminAndNotIndividual(groupClusterEntity.getId(), getMockUser()))
.thenReturn(new CheckResult<>(HttpStatus.I_AM_A_TEAPOT, "", null));
mockMvc.perform(MockMvcRequestBuilders.put(url)
.contentType(MediaType.APPLICATION_JSON)
.content(request))
.andExpect(status().isIAmATeapot());

/* Unexepcted error */
reset(clusterUtil);
when(clusterUtil.getGroupClusterEntityIfAdminAndNotIndividual(groupClusterEntity.getId(), getMockUser()))
.thenReturn(new CheckResult<>(HttpStatus.OK, "", groupClusterEntity));
when(groupRepository.findAllByClusterId(groupClusterEntity.getId())).thenThrow(new RuntimeException());
mockMvc.perform(MockMvcRequestBuilders.put(url)
.contentType(MediaType.APPLICATION_JSON)
.content(request))
.andExpect(status().isInternalServerError());

}

@Test
public void testPatchCluster() throws Exception {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,14 +3,23 @@
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.argThat;
import static org.mockito.Mockito.doReturn;
import static org.mockito.Mockito.reset;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;

import com.ugent.pidgeon.model.json.ClusterFillJson;
import com.ugent.pidgeon.model.json.GroupClusterCreateJson;
import com.ugent.pidgeon.model.json.GroupClusterUpdateJson;
import com.ugent.pidgeon.postgre.models.CourseUserEntity;
import com.ugent.pidgeon.postgre.models.GroupClusterEntity;
import com.ugent.pidgeon.postgre.models.UserEntity;
import com.ugent.pidgeon.postgre.models.types.CourseRelation;
import com.ugent.pidgeon.postgre.models.types.UserRole;
import com.ugent.pidgeon.postgre.repository.CourseUserRepository;
import com.ugent.pidgeon.postgre.repository.GroupClusterRepository;
import java.util.Optional;
import org.hibernate.annotations.Check;
Expand All @@ -29,6 +38,8 @@ public class ClusterUtilTest {
@Mock
private GroupClusterRepository groupClusterRepository;
@Mock
private CourseUserRepository courseUserRepository;
@Mock
private CourseUtil courseUtil;

@Spy
Expand Down Expand Up @@ -251,4 +262,55 @@ void testCheckGroupClusterCreateJson() {
assertEquals(HttpStatus.BAD_REQUEST, result.getStatus());
}

@Test
public void testCheckFillClusterJson() {
ClusterFillJson fillJson = new ClusterFillJson();
CourseUserEntity enrolledCU = new CourseUserEntity(22L, 5L, CourseRelation.enrolled);
fillJson.addClusterGroupMembers("Group1", new Long[]{5L, 2L});
fillJson.addClusterGroupMembers("Group2", new Long[]{3L, 10L});

when(courseUserRepository.findById(any())).thenReturn(Optional.of(enrolledCU));

CheckResult<Void> result = clusterUtil.checkFillClusterJson(fillJson, clusterEntity);
assertEquals(HttpStatus.OK, result.getStatus());

verify(courseUserRepository, times(1)).findById(argThat(
arg -> arg.getCourseId() == clusterEntity.getCourseId() && arg.getUserId() == 5L));
verify(courseUserRepository, times(1)).findById(argThat(
arg -> arg.getCourseId() == clusterEntity.getCourseId() && arg.getUserId() == 2L));
verify(courseUserRepository, times(1)).findById(argThat(
arg -> arg.getCourseId() == clusterEntity.getCourseId() && arg.getUserId() == 3L));
verify(courseUserRepository, times(1)).findById(argThat(
arg -> arg.getCourseId() == clusterEntity.getCourseId() && arg.getUserId() == 10L));

/* User admin in course */
CourseUserEntity courseAdminCU = new CourseUserEntity(22L, 5L, CourseRelation.course_admin);
when(courseUserRepository.findById(argThat(
arg -> arg.getCourseId() == clusterEntity.getCourseId() && arg.getUserId() == 5L)))
.thenReturn(Optional.of(courseAdminCU));

result = clusterUtil.checkFillClusterJson(fillJson, clusterEntity);
assertEquals(HttpStatus.BAD_REQUEST, result.getStatus());

/* User not found in course */
reset(courseUserRepository);
when(courseUserRepository.findById(any())).thenReturn(Optional.of(enrolledCU));
when(courseUserRepository.findById(argThat(
arg -> arg.getCourseId() == clusterEntity.getCourseId() && arg.getUserId() == 3L)))
.thenReturn(Optional.empty());

result = clusterUtil.checkFillClusterJson(fillJson, clusterEntity);
assertEquals(HttpStatus.BAD_REQUEST, result.getStatus());

/* trying to add user twice */
reset(courseUserRepository);
when(courseUserRepository.findById(any())).thenReturn(Optional.of(enrolledCU));
fillJson.addClusterGroupMembers("Group3", new Long[]{5L, 4L});

result = clusterUtil.checkFillClusterJson(fillJson, clusterEntity);
assertEquals(HttpStatus.BAD_REQUEST, result.getStatus());

}


}
Original file line number Diff line number Diff line change
Expand Up @@ -166,6 +166,12 @@ public void TestCanAddUserToGroup() {
result = groupUtil.canAddUserToGroup(group.getId(), otherUserId, mockUser);
assertEquals(HttpStatus.OK, result.getStatus());

/* Group is already full but it's an admin adding someone else */
when(groupRepository.countUsersInGroup(group.getId())).thenReturn(groupCluster.getMaxSize());
result = groupUtil.canAddUserToGroup(group.getId(), otherUserId, mockUser);
assertEquals(HttpStatus.OK, result.getStatus());
when(groupRepository.countUsersInGroup(group.getId())).thenReturn(groupCluster.getMaxSize()-1);

/* User trying to add is admin */
doReturn(new CheckResult<>(HttpStatus.OK, "", null)).
when(groupUtil).isAdminOfGroup(group.getId(), otherUser);
Expand All @@ -179,7 +185,7 @@ public void TestCanAddUserToGroup() {

/* Group is already full */
when(groupRepository.countUsersInGroup(group.getId())).thenReturn(groupCluster.getMaxSize());
result = groupUtil.canAddUserToGroup(group.getId(), otherUserId, mockUser);
result = groupUtil.canAddUserToGroup(group.getId(), mockUser.getId(), mockUser);
assertEquals(HttpStatus.FORBIDDEN, result.getStatus());

/* ClusterEntity is not found */
Expand Down Expand Up @@ -312,4 +318,6 @@ public void testCanGetProjectGroupData() throws Exception {
result = groupUtil.canGetProjectGroupData(group.getId(), project.getId(), mockUser);
assertEquals(HttpStatus.I_AM_A_TEAPOT, result.getStatus());
}
}


}

0 comments on commit a2b3de1

Please sign in to comment.