Skip to content

Commit

Permalink
Fix Unit Tests in Web Module (#10371)
Browse files Browse the repository at this point in the history
  • Loading branch information
haynescd authored Sep 7, 2023
1 parent f6b9b9a commit eedd9c6
Show file tree
Hide file tree
Showing 25 changed files with 196 additions and 283 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,7 @@

@InternalApi
@RestController
@RequestMapping("/api")
@Validated
@Api(tags = "Clinical Data Enrichments", description = " ")
public class ClinicalDataEnrichmentController {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,7 @@

@PublicApi
@RestController()
@RequestMapping("/api")
@Validated
@Api(tags = PublicApiTags.DISCRETE_COPY_NUMBER_ALTERATIONS, description = " ")
public class DiscreteCopyNumberController {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,7 @@

@PublicApi
@RestController
@RequestMapping("/api")
@Validated
@Api(tags = PublicApiTags.GENE_PANEL_DATA, description = " ")
public class GenePanelDataController {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,7 @@

@PublicApi
@RestController
@RequestMapping("/api")
@Validated
@Api(tags = PublicApiTags.GENERIC_ASSAY_DATA, description = " ")
public class GenericAssayDataController {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -139,9 +139,7 @@ public class InvolvedCancerStudyExtractorInterceptor implements HandlerIntercept
// TODO when reimplemeting different dispatcherservlets with different context roots
// reset this to 'String requestPathInfo = request.getPathInfo();'
String requestPathInfo = request.getPathInfo() == null? request.getServletPath() : request.getPathInfo();
if (requestPathInfo.startsWith("/api")) {
requestPathInfo = requestPathInfo.substring("/api".length());
}
requestPathInfo = requestPathInfo.replaceFirst("^/api", "");
if (requestPathInfo.equals(PATIENT_FETCH_PATH)) {
return extractAttributesFromPatientFilter(request);
} else if (requestPathInfo.equals(SAMPLE_FETCH_PATH)) {
Expand Down
Original file line number Diff line number Diff line change
@@ -1,18 +1,6 @@
package org.cbioportal.web;

import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.argThat;
import static org.mockito.Mockito.when;
import static org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestPostProcessors.csrf;


import com.fasterxml.jackson.databind.ObjectMapper;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.cbioportal.model.AlterationEnrichment;
import org.cbioportal.model.AlterationFilter;
import org.cbioportal.model.CNA;
Expand All @@ -36,12 +24,23 @@
import org.springframework.http.MediaType;
import org.springframework.security.test.context.support.WithMockUser;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.TestPropertySource;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.request.MockMvcRequestBuilders;
import org.springframework.test.web.servlet.result.MockMvcResultMatchers;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.argThat;
import static org.mockito.Mockito.when;
import static org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestPostProcessors.csrf;

@RunWith(SpringJUnit4ClassRunner.class)
@WebMvcTest(AlterationEnrichmentControllerTest.class)
@ContextConfiguration(classes={AlterationEnrichmentController.class, TestConfig.class})
Expand Down
68 changes: 0 additions & 68 deletions web/src/test/java/org/cbioportal/web/CacheControllerTest.java
Original file line number Diff line number Diff line change
Expand Up @@ -98,72 +98,4 @@ public void clearAllCachesSkipSpringManaged() throws Exception {
.andExpect(MockMvcResultMatchers.content().contentTypeCompatibleWith(MediaType.TEXT_PLAIN_VALUE));
verify(cacheService, times(1)).clearCaches(false);
}

@Ignore // Unable to configure context with the GlobalExceptionHandler ControllerAdvise.
@Test
public void clearAllCachesServiceException() throws Exception {
//doThrow(CacheOperationException.class).when(cacheService).clearCaches(anyBoolean());
mockMvc.perform(MockMvcRequestBuilders.delete("/cache")
.header("X-API-KEY", "correct-key"))
.andExpect(MockMvcResultMatchers.status().isInternalServerError())
.andExpect(MockMvcResultMatchers.content().contentTypeCompatibleWith(MediaType.TEXT_PLAIN_VALUE));
verify(cacheService, times(1)).clearCaches(true);
}

@Test
public void clearCacheForStudyNoKeyProvided() throws Exception {
mockMvc.perform(MockMvcRequestBuilders.delete("/cache/study_es_0"))
.andExpect(MockMvcResultMatchers.status().isBadRequest());
verify(cacheService, never()).clearCachesForStudy(anyString(), anyBoolean());
}

@Test
public void clearCacheForStudyUnauthorized() throws Exception {
mockMvc.perform(MockMvcRequestBuilders.delete("/cache/study_es_0")
.header("X-API-KEY", "incorrect-key"))
.andExpect(MockMvcResultMatchers.status().isUnauthorized())
.andExpect(MockMvcResultMatchers.content().contentTypeCompatibleWith(MediaType.TEXT_PLAIN_VALUE));
verify(cacheService, never()).clearCachesForStudy(anyString(), anyBoolean());
}

@Test
public void clearCacheForStudySuccess() throws Exception {
mockMvc.perform(MockMvcRequestBuilders.delete("/cache/study_es_0")
.header("X-API-KEY", "correct-key"))
.andExpect(MockMvcResultMatchers.status().isOk())
.andExpect(MockMvcResultMatchers.content().contentTypeCompatibleWith(MediaType.TEXT_PLAIN_VALUE));
verify(cacheService, times(1)).clearCachesForStudy(eq("study_es_0"), anyBoolean());
}

@Test
public void clearCacheForStudyDisabled() throws Exception {
ReflectionTestUtils.setField(cacheController, "cacheEndpointEnabled", false);
mockMvc.perform(MockMvcRequestBuilders.delete("/cache/study_es_0")
.header("X-API-KEY", "correct-key"))
.andExpect(MockMvcResultMatchers.status().isNotFound())
.andExpect(MockMvcResultMatchers.content().contentTypeCompatibleWith(MediaType.TEXT_PLAIN_VALUE));
verify(cacheService, never()).clearCachesForStudy(anyString(), anyBoolean());
ReflectionTestUtils.setField(cacheController, "cacheEndpointEnabled", true);
}

@Test
public void clearCacheForStudySkipSpringManaged() throws Exception {
mockMvc.perform(MockMvcRequestBuilders.delete("/cache/study_es_0").param("springManagedCache", "false")
.header("X-API-KEY", "correct-key"))
.andExpect(MockMvcResultMatchers.status().isOk())
.andExpect(MockMvcResultMatchers.content().contentTypeCompatibleWith(MediaType.TEXT_PLAIN_VALUE));
verify(cacheService, times(1)).clearCachesForStudy(anyString(), eq(false));
}

@Ignore // Unable to to configure context with the GlobalExceptionHandler ControllerAdvise.
@Test
public void clearCacheForStudyServiceException() throws Exception {
doThrow(CacheOperationException.class).when(cacheService).clearCachesForStudy(eq("study_es_0"), anyBoolean());
mockMvc.perform(MockMvcRequestBuilders.delete("/cache/study_es_0")
.header("X-API-KEY", "correct-key"))
.andExpect(MockMvcResultMatchers.status().isInternalServerError())
.andExpect(MockMvcResultMatchers.content().contentTypeCompatibleWith(MediaType.TEXT_PLAIN_VALUE));
verify(cacheService, times(1)).clearCachesForStudy(anyString(), eq(true));
}

}
Original file line number Diff line number Diff line change
Expand Up @@ -44,7 +44,6 @@
import org.springframework.security.test.context.support.WithMockUser;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.web.WebAppConfiguration;
import org.springframework.test.util.ReflectionTestUtils;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.MvcResult;
Expand All @@ -53,10 +52,9 @@

// TODO fix these tests. The basic adaptation is correct, but I cannot het the security config in
// DataAccessTokenControllerTestConfig.java correct
@Ignore
@RunWith(SpringJUnit4ClassRunner.class)
@WebMvcTest
@ContextConfiguration(classes = {DataAccessTokenController.class, TestConfig.class, DataAccessTokenControllerTestConfig.class})
@ContextConfiguration(classes = {DataAccessTokenController.class, TestConfig.class, DataAccessTokenControllerTestConfig.class })
public class DataAccessTokenControllerTest extends WebSecurityConfigurerAdapter {

public static final String MOCK_USER = "MOCK_USER";
Expand All @@ -80,8 +78,8 @@ public void resetReceivedArgument() {
}

private HttpSession getSession(String user, String password) throws Exception {
return mockMvc.perform(MockMvcRequestBuilders.post("/api/j_spring_security_check").with(csrf())
.param("j_user", user)
return mockMvc.perform(MockMvcRequestBuilders.post("/j_spring_security_check").with(csrf())
.param("j_username", user)
.param("j_password", password))
.andExpect(MockMvcResultMatchers.status().isOk())
.andReturn()
Expand Down Expand Up @@ -140,7 +138,7 @@ public Void answer(InvocationOnMock revokeTokenInvocation) {
};
Mockito.doAnswer(tokenServiceRevokeTokenAnswer).when(tokenService).revokeDataAccessToken(ArgumentMatchers.anyString());
HttpSession session = getSession(MOCK_USER, MOCK_PASSWORD);
MvcResult result = mockMvc.perform(MockMvcRequestBuilders.delete("/data-access-tokens/" + VALID_TOKEN_STRING).with(csrf())
MvcResult result = mockMvc.perform(MockMvcRequestBuilders.delete("/api/data-access-tokens/" + VALID_TOKEN_STRING).with(csrf())
.session((MockHttpSession) session)
.accept(MediaType.APPLICATION_JSON)
.contentType(MediaType.APPLICATION_JSON))
Expand All @@ -161,7 +159,7 @@ public void revokeNonexistentTokenTest() throws Exception {
resetReceivedArgument();
Mockito.doThrow(new TokenNotFoundException()).when(tokenService).revokeDataAccessToken(NONEXISTENT_TOKEN_STRING);;
HttpSession session = getSession(MOCK_USER, MOCK_PASSWORD);
MvcResult result = mockMvc.perform(MockMvcRequestBuilders.delete("/data-access-tokens/" + NONEXISTENT_TOKEN_STRING).with(csrf())
MvcResult result = mockMvc.perform(MockMvcRequestBuilders.delete("/api/data-access-tokens/" + NONEXISTENT_TOKEN_STRING).with(csrf())
.session((MockHttpSession) session)
.accept(MediaType.APPLICATION_JSON)
.contentType(MediaType.APPLICATION_JSON))
Expand Down Expand Up @@ -189,11 +187,12 @@ public void createTokenValidUserTest() throws Exception {
}

@Test
@WithMockUser(username = MOCK_USER, password = MOCK_PASSWORD, authorities = "PLACEHOLDER_ROLE")
public void createTokenValidUserTestWithUserRole() throws Exception {
ReflectionTestUtils.setField(DataAccessTokenController.class, "userRoleToAccessToken", "PLACEHOLDER_ROLE");
Mockito.when(tokenService.createDataAccessToken(ArgumentMatchers.anyString())).thenReturn(MOCK_TOKEN_INFO);
HttpSession session = getSession(MOCK_USER, MOCK_PASSWORD);
MvcResult result = mockMvc.perform(MockMvcRequestBuilders.post("/data-access-tokens")
MvcResult result = mockMvc.perform(MockMvcRequestBuilders.post("/api/data-access-tokens").with(csrf())
.session((MockHttpSession) session)
.accept(MediaType.APPLICATION_JSON)
.contentType(MediaType.APPLICATION_JSON))
Expand All @@ -202,11 +201,13 @@ public void createTokenValidUserTestWithUserRole() throws Exception {
}

@Test
@WithMockUser
public void createTokenUnauthorizedUserTestWithUserRole() throws Exception {
ReflectionTestUtils.setField(DataAccessTokenController.class, "userRoleToAccessToken", "TEST");
Mockito.when(tokenService.createDataAccessToken(ArgumentMatchers.anyString())).thenReturn(MOCK_TOKEN_INFO);
HttpSession session = getSession(MOCK_USER, MOCK_PASSWORD);
MvcResult result = mockMvc.perform(MockMvcRequestBuilders.post("/data-access-tokens")
MvcResult result = mockMvc.perform(MockMvcRequestBuilders.post("/api/data-access-tokens")
.with(csrf())
.session((MockHttpSession) session)
.accept(MediaType.APPLICATION_JSON)
.contentType(MediaType.APPLICATION_JSON))
Expand All @@ -219,7 +220,7 @@ public void createTokenUnauthorizedUserTestWithUserRole() throws Exception {
* Checks that correct username argument is passed to service class
*/
@Test
@WithMockUser
@WithMockUser(username = MOCK_USER, password = MOCK_PASSWORD)
public void revokeAllTokensForUserTest() throws Exception {
resetReceivedArgument();
Answer<Void> tokenServiceRevokeAllTokensAnswer = new Answer<Void>() {
Expand All @@ -230,7 +231,7 @@ public Void answer(InvocationOnMock revokeAllTokensInvocation) {
};
Mockito.doAnswer(tokenServiceRevokeAllTokensAnswer).when(tokenService).revokeAllDataAccessTokens(ArgumentMatchers.anyString());
HttpSession session = getSession(MOCK_USER, MOCK_PASSWORD);
MvcResult result = mockMvc.perform(MockMvcRequestBuilders.delete("/data-access-tokens").with(csrf())
MvcResult result = mockMvc.perform(MockMvcRequestBuilders.delete("/api/data-access-tokens").with(csrf())
.session((MockHttpSession) session)
.accept(MediaType.APPLICATION_JSON)
.contentType(MediaType.APPLICATION_JSON))
Expand All @@ -246,7 +247,7 @@ public Void answer(InvocationOnMock revokeAllTokensInvocation) {
* Checks that correct username argument is passed to service class
*/
@Test
@WithMockUser
@WithMockUser(username = MOCK_USER, password = MOCK_PASSWORD)
public void getAllTokensForUserTest() throws Exception {
resetReceivedArgument();
Answer<Void> tokenServiceGetAllTokensAnswer = new Answer<Void>() {
Expand All @@ -271,7 +272,8 @@ public Void answer(InvocationOnMock getAllTokensInvocation) {
@Test
public void createTokenNotLoggedIn() throws Exception {
Mockito.when(tokenService.createDataAccessToken(ArgumentMatchers.anyString())).thenReturn(MOCK_TOKEN_INFO);
MvcResult result = mockMvc.perform(MockMvcRequestBuilders.post("/data-access-tokens")
MvcResult result = mockMvc.perform(MockMvcRequestBuilders.post("/api/data-access-tokens")
.with(csrf())
.accept(MediaType.APPLICATION_JSON)
.contentType(MediaType.APPLICATION_JSON))
.andExpect(MockMvcResultMatchers.status().isUnauthorized())
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -100,6 +100,7 @@ public void getDiscreteCopyNumbersInMolecularProfileBySampleListIdDefaultProject
}

@Test
@WithMockUser
public void getDiscreteCopyNumbersWithoutAnnotationJson() throws Exception {

List<DiscreteCopyNumberData> discreteCopyNumberDataList = createExampleDiscreteCopyNumberData();
Expand All @@ -108,7 +109,7 @@ public void getDiscreteCopyNumbersWithoutAnnotationJson() throws Exception {
Mockito.any(), Mockito.any(), Mockito.any(),
Mockito.any(), Mockito.any())).thenReturn(discreteCopyNumberDataList);

mockMvc.perform(MockMvcRequestBuilders.get("/molecular-profiles/test_molecular_profile_id/discrete-copy-number")
mockMvc.perform(MockMvcRequestBuilders.get("/api/molecular-profiles/test_molecular_profile_id/discrete-copy-number")
.param("sampleListId", TEST_SAMPLE_LIST_ID)
.param("discreteCopyNumberEventType", DiscreteCopyNumberEventType.HOMDEL_AND_AMP.name())
.accept(MediaType.APPLICATION_JSON))
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,11 +3,14 @@
import com.fasterxml.jackson.databind.ObjectMapper;
import junit.framework.TestCase;
import org.cbioportal.service.DiscreteCopyNumberService;
import org.cbioportal.web.config.TestConfig;
import org.junit.Before;
import org.junit.Ignore;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mockito;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.test.context.ContextConfiguration;
Expand All @@ -20,9 +23,10 @@
import org.springframework.web.context.WebApplicationContext;

@RunWith(SpringJUnit4ClassRunner.class)
@WebAppConfiguration
@ContextConfiguration("/applicationContext-web-test.xml")
@Configuration
@WebMvcTest
@ContextConfiguration(classes = {DocRedirectController.class, TestConfig.class})
@Ignore
// TODO: Had to disable docredirect Controller
public class DocRedirectControllerTest {
@Autowired
private WebApplicationContext wac;
Expand Down
2 changes: 0 additions & 2 deletions web/src/test/java/org/cbioportal/web/GeneControllerTest.java
Original file line number Diff line number Diff line change
Expand Up @@ -95,8 +95,6 @@ public void getAllGenesMetaProjection() throws Exception {

@Test
@WithMockUser
// TODO investigate
@Ignore
public void getGeneNotFound() throws Exception {

Mockito.when(geneService.getGene(eq("test_gene_id"))).thenThrow(new GeneNotFoundException("test_gene_id"));
Expand Down
Loading

0 comments on commit eedd9c6

Please sign in to comment.