diff --git a/web/src/main/java/org/cbioportal/web/ClinicalDataEnrichmentController.java b/web/src/main/java/org/cbioportal/web/ClinicalDataEnrichmentController.java index ffc5e754c82..94ab4cf0ab5 100644 --- a/web/src/main/java/org/cbioportal/web/ClinicalDataEnrichmentController.java +++ b/web/src/main/java/org/cbioportal/web/ClinicalDataEnrichmentController.java @@ -39,6 +39,7 @@ @InternalApi @RestController +@RequestMapping("/api") @Validated @Api(tags = "Clinical Data Enrichments", description = " ") public class ClinicalDataEnrichmentController { diff --git a/web/src/main/java/org/cbioportal/web/DiscreteCopyNumberController.java b/web/src/main/java/org/cbioportal/web/DiscreteCopyNumberController.java index 09ac3de8f34..879f8e07cd4 100644 --- a/web/src/main/java/org/cbioportal/web/DiscreteCopyNumberController.java +++ b/web/src/main/java/org/cbioportal/web/DiscreteCopyNumberController.java @@ -36,6 +36,7 @@ @PublicApi @RestController() +@RequestMapping("/api") @Validated @Api(tags = PublicApiTags.DISCRETE_COPY_NUMBER_ALTERATIONS, description = " ") public class DiscreteCopyNumberController { diff --git a/web/src/main/java/org/cbioportal/web/GenePanelDataController.java b/web/src/main/java/org/cbioportal/web/GenePanelDataController.java index 03ebec52c4f..c74f4930b88 100644 --- a/web/src/main/java/org/cbioportal/web/GenePanelDataController.java +++ b/web/src/main/java/org/cbioportal/web/GenePanelDataController.java @@ -35,6 +35,7 @@ @PublicApi @RestController +@RequestMapping("/api") @Validated @Api(tags = PublicApiTags.GENE_PANEL_DATA, description = " ") public class GenePanelDataController { diff --git a/web/src/main/java/org/cbioportal/web/GenericAssayDataController.java b/web/src/main/java/org/cbioportal/web/GenericAssayDataController.java index 5b546f63889..869eb204fbe 100644 --- a/web/src/main/java/org/cbioportal/web/GenericAssayDataController.java +++ b/web/src/main/java/org/cbioportal/web/GenericAssayDataController.java @@ -31,6 +31,7 @@ @PublicApi @RestController +@RequestMapping("/api") @Validated @Api(tags = PublicApiTags.GENERIC_ASSAY_DATA, description = " ") public class GenericAssayDataController { diff --git a/web/src/main/java/org/cbioportal/web/util/InvolvedCancerStudyExtractorInterceptor.java b/web/src/main/java/org/cbioportal/web/util/InvolvedCancerStudyExtractorInterceptor.java index d05b90b218d..2f4346f23bd 100644 --- a/web/src/main/java/org/cbioportal/web/util/InvolvedCancerStudyExtractorInterceptor.java +++ b/web/src/main/java/org/cbioportal/web/util/InvolvedCancerStudyExtractorInterceptor.java @@ -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)) { diff --git a/web/src/test/java/org/cbioportal/web/AlterationEnrichmentControllerTest.java b/web/src/test/java/org/cbioportal/web/AlterationEnrichmentControllerTest.java index 35e2dcce8de..54ab0b76405 100644 --- a/web/src/test/java/org/cbioportal/web/AlterationEnrichmentControllerTest.java +++ b/web/src/test/java/org/cbioportal/web/AlterationEnrichmentControllerTest.java @@ -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; @@ -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}) diff --git a/web/src/test/java/org/cbioportal/web/CacheControllerTest.java b/web/src/test/java/org/cbioportal/web/CacheControllerTest.java index a7e50ba01f8..cf40aee1d37 100644 --- a/web/src/test/java/org/cbioportal/web/CacheControllerTest.java +++ b/web/src/test/java/org/cbioportal/web/CacheControllerTest.java @@ -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)); - } - } diff --git a/web/src/test/java/org/cbioportal/web/DataAccessTokenControllerTest.java b/web/src/test/java/org/cbioportal/web/DataAccessTokenControllerTest.java index 80a3b4ff36e..23983b8fc20 100644 --- a/web/src/test/java/org/cbioportal/web/DataAccessTokenControllerTest.java +++ b/web/src/test/java/org/cbioportal/web/DataAccessTokenControllerTest.java @@ -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; @@ -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"; @@ -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() @@ -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)) @@ -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)) @@ -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)) @@ -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)) @@ -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 tokenServiceRevokeAllTokensAnswer = new Answer() { @@ -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)) @@ -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 tokenServiceGetAllTokensAnswer = new Answer() { @@ -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()) diff --git a/web/src/test/java/org/cbioportal/web/DiscreteCopyNumberControllerTest.java b/web/src/test/java/org/cbioportal/web/DiscreteCopyNumberControllerTest.java index 4b5f70c8c0b..126c183c204 100644 --- a/web/src/test/java/org/cbioportal/web/DiscreteCopyNumberControllerTest.java +++ b/web/src/test/java/org/cbioportal/web/DiscreteCopyNumberControllerTest.java @@ -100,6 +100,7 @@ public void getDiscreteCopyNumbersInMolecularProfileBySampleListIdDefaultProject } @Test + @WithMockUser public void getDiscreteCopyNumbersWithoutAnnotationJson() throws Exception { List discreteCopyNumberDataList = createExampleDiscreteCopyNumberData(); @@ -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)) diff --git a/web/src/test/java/org/cbioportal/web/DocRedirectControllerTest.java b/web/src/test/java/org/cbioportal/web/DocRedirectControllerTest.java index 6cda2d3c8e1..3765936985d 100644 --- a/web/src/test/java/org/cbioportal/web/DocRedirectControllerTest.java +++ b/web/src/test/java/org/cbioportal/web/DocRedirectControllerTest.java @@ -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; @@ -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; diff --git a/web/src/test/java/org/cbioportal/web/GeneControllerTest.java b/web/src/test/java/org/cbioportal/web/GeneControllerTest.java index ecca51c8137..c4b78fb7fde 100644 --- a/web/src/test/java/org/cbioportal/web/GeneControllerTest.java +++ b/web/src/test/java/org/cbioportal/web/GeneControllerTest.java @@ -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")); diff --git a/web/src/test/java/org/cbioportal/web/GenePanelControllerTest.java b/web/src/test/java/org/cbioportal/web/GenePanelControllerTest.java index d2e5174ec85..78ecb690ae0 100644 --- a/web/src/test/java/org/cbioportal/web/GenePanelControllerTest.java +++ b/web/src/test/java/org/cbioportal/web/GenePanelControllerTest.java @@ -201,100 +201,4 @@ public void getGenePanel() throws Exception { .andExpect(MockMvcResultMatchers.jsonPath("$.genes[1].entrezGeneId").value(TEST_ENTREZ_GENE_ID_2)) .andExpect(MockMvcResultMatchers.jsonPath("$.genes[1].hugoGeneSymbol").value(TEST_HUGO_GENE_SYMBOL_2)); } - - @Test - @WithMockUser - public void getGenePanelData() throws Exception { - - List genePanelDataList = createExampleGenePanelData(); - - Mockito.when(genePanelService.getGenePanelData(Mockito.anyString(), Mockito.anyString())).thenReturn(genePanelDataList); - - GenePanelDataFilter genePanelDataFilter = new GenePanelDataFilter(); - genePanelDataFilter.setSampleListId(TEST_SAMPLE_LIST_ID); - - mockMvc.perform(MockMvcRequestBuilders.post( - "/api/molecular-profiles/test_molecular_profile_id/gene-panel-data/fetch").with(csrf()) - .accept(MediaType.APPLICATION_JSON) - .contentType(MediaType.APPLICATION_JSON) - .content(objectMapper.writeValueAsString(genePanelDataFilter))) - .andExpect(MockMvcResultMatchers.status().isOk()) - .andExpect(MockMvcResultMatchers.content().contentTypeCompatibleWith(MediaType.APPLICATION_JSON)) - .andExpect(MockMvcResultMatchers.jsonPath("$", Matchers.hasSize(2))) - .andExpect(MockMvcResultMatchers.jsonPath("$[0].molecularProfileId").value(TEST_MOLECULAR_PROFILE_ID_1)) - .andExpect(MockMvcResultMatchers.jsonPath("$[0].sampleId").value(TEST_SAMPLE_ID_1)) - .andExpect(MockMvcResultMatchers.jsonPath("$[0].genePanelId").value(TEST_GENE_PANEL_ID_1)) - .andExpect(MockMvcResultMatchers.jsonPath("$[0].patientId").value(TEST_PATIENT_ID_1)) - .andExpect(MockMvcResultMatchers.jsonPath("$[0].studyId").value(TEST_STUDY_ID_1)) - .andExpect(MockMvcResultMatchers.jsonPath("$[0].profiled").value(true)) - .andExpect(MockMvcResultMatchers.jsonPath("$[1].molecularProfileId").value(TEST_MOLECULAR_PROFILE_ID_2)) - .andExpect(MockMvcResultMatchers.jsonPath("$[1].sampleId").value(TEST_SAMPLE_ID_2)) - .andExpect(MockMvcResultMatchers.jsonPath("$[1].genePanelId").doesNotExist()) - .andExpect(MockMvcResultMatchers.jsonPath("$[1].patientId").value(TEST_PATIENT_ID_2)) - .andExpect(MockMvcResultMatchers.jsonPath("$[1].studyId").value(TEST_STUDY_ID_2)) - .andExpect(MockMvcResultMatchers.jsonPath("$[1].profiled").value(true)); - } - - @Test - @WithMockUser - public void fetchGenePanelData() throws Exception { - - List genePanelDataList = createExampleGenePanelData(); - - Mockito.when(genePanelService.fetchGenePanelDataInMultipleMolecularProfiles(Mockito.anyList())).thenReturn(genePanelDataList); - - List sampleMolecularIdentifiers = new ArrayList<>(); - SampleMolecularIdentifier sampleMolecularIdentifier1 = new SampleMolecularIdentifier(); - sampleMolecularIdentifier1.setMolecularProfileId(TEST_MOLECULAR_PROFILE_ID_1); - sampleMolecularIdentifier1.setSampleId(TEST_SAMPLE_ID_1); - sampleMolecularIdentifiers.add(sampleMolecularIdentifier1); - SampleMolecularIdentifier sampleMolecularIdentifier2 = new SampleMolecularIdentifier(); - sampleMolecularIdentifier2.setMolecularProfileId(TEST_MOLECULAR_PROFILE_ID_2); - sampleMolecularIdentifier2.setSampleId(TEST_SAMPLE_ID_2); - sampleMolecularIdentifiers.add(sampleMolecularIdentifier2); - GenePanelDataMultipleStudyFilter genePanelDataMultipleStudyFilter = new GenePanelDataMultipleStudyFilter(); - genePanelDataMultipleStudyFilter.setSampleMolecularIdentifiers(sampleMolecularIdentifiers); - - mockMvc.perform(MockMvcRequestBuilders.post( - "/api/gene-panel-data/fetch").with(csrf()) - .accept(MediaType.APPLICATION_JSON) - .contentType(MediaType.APPLICATION_JSON) - .content(objectMapper.writeValueAsString(genePanelDataMultipleStudyFilter))) - .andExpect(MockMvcResultMatchers.status().isOk()) - .andExpect(MockMvcResultMatchers.content().contentTypeCompatibleWith(MediaType.APPLICATION_JSON)) - .andExpect(MockMvcResultMatchers.jsonPath("$", Matchers.hasSize(2))) - .andExpect(MockMvcResultMatchers.jsonPath("$[0].molecularProfileId").value(TEST_MOLECULAR_PROFILE_ID_1)) - .andExpect(MockMvcResultMatchers.jsonPath("$[0].sampleId").value(TEST_SAMPLE_ID_1)) - .andExpect(MockMvcResultMatchers.jsonPath("$[0].genePanelId").value(TEST_GENE_PANEL_ID_1)) - .andExpect(MockMvcResultMatchers.jsonPath("$[0].patientId").value(TEST_PATIENT_ID_1)) - .andExpect(MockMvcResultMatchers.jsonPath("$[0].studyId").value(TEST_STUDY_ID_1)) - .andExpect(MockMvcResultMatchers.jsonPath("$[0].profiled").value(true)) - .andExpect(MockMvcResultMatchers.jsonPath("$[1].molecularProfileId").value(TEST_MOLECULAR_PROFILE_ID_2)) - .andExpect(MockMvcResultMatchers.jsonPath("$[1].sampleId").value(TEST_SAMPLE_ID_2)) - .andExpect(MockMvcResultMatchers.jsonPath("$[1].genePanelId").doesNotExist()) - .andExpect(MockMvcResultMatchers.jsonPath("$[1].patientId").value(TEST_PATIENT_ID_2)) - .andExpect(MockMvcResultMatchers.jsonPath("$[1].studyId").value(TEST_STUDY_ID_2)) - .andExpect(MockMvcResultMatchers.jsonPath("$[1].profiled").value(true)); - } - - private List createExampleGenePanelData() { - - List genePanelDataList = new ArrayList<>(); - GenePanelData genePanelData1 = new GenePanelData(); - genePanelData1.setGenePanelId(TEST_GENE_PANEL_ID_1); - genePanelData1.setSampleId(TEST_SAMPLE_ID_1); - genePanelData1.setMolecularProfileId(TEST_MOLECULAR_PROFILE_ID_1); - genePanelData1.setPatientId(TEST_PATIENT_ID_1); - genePanelData1.setStudyId(TEST_STUDY_ID_1); - genePanelData1.setProfiled(true); - genePanelDataList.add(genePanelData1); - GenePanelData genePanelData2 = new GenePanelData(); - genePanelData2.setSampleId(TEST_SAMPLE_ID_2); - genePanelData2.setMolecularProfileId(TEST_MOLECULAR_PROFILE_ID_2); - genePanelData2.setPatientId(TEST_PATIENT_ID_2); - genePanelData2.setStudyId(TEST_STUDY_ID_2); - genePanelData2.setProfiled(true); - genePanelDataList.add(genePanelData2); - return genePanelDataList; - } } diff --git a/web/src/test/java/org/cbioportal/web/GenePanelDataControllerTest.java b/web/src/test/java/org/cbioportal/web/GenePanelDataControllerTest.java index a2ded39c3ae..824223ef8a9 100644 --- a/web/src/test/java/org/cbioportal/web/GenePanelDataControllerTest.java +++ b/web/src/test/java/org/cbioportal/web/GenePanelDataControllerTest.java @@ -7,6 +7,7 @@ import org.cbioportal.model.meta.BaseMeta; import org.cbioportal.service.GenePanelService; import org.cbioportal.service.exception.GenePanelNotFoundException; +import org.cbioportal.web.config.TestConfig; import org.cbioportal.web.parameter.GenePanelDataFilter; import org.cbioportal.web.parameter.GenePanelDataMultipleStudyFilter; import org.cbioportal.web.parameter.HeaderKeyConstants; @@ -17,9 +18,12 @@ 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.boot.test.mock.mockito.MockBean; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.http.MediaType; +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; @@ -34,9 +38,8 @@ import java.util.List; @RunWith(SpringJUnit4ClassRunner.class) -@WebAppConfiguration -@ContextConfiguration("/applicationContext-web-test.xml") -@Configuration +@WebMvcTest +@ContextConfiguration(classes = {GenePanelDataController.class, TestConfig.class}) public class GenePanelDataControllerTest { private static final String TEST_GENE_PANEL_ID_1 = "test_gene_panel_id_1"; @@ -66,7 +69,7 @@ public class GenePanelDataControllerTest { @Autowired private WebApplicationContext wac; - @Autowired + @MockBean private GenePanelService genePanelService; private ObjectMapper objectMapper = new ObjectMapper(); @@ -81,6 +84,7 @@ public void setUp() throws Exception { } @Test + @WithMockUser public void getGenePanelData() throws Exception { List genePanelDataList = createExampleGenePanelData(); @@ -91,7 +95,7 @@ public void getGenePanelData() throws Exception { genePanelDataFilter.setSampleListId(TEST_SAMPLE_LIST_ID); mockMvc.perform(MockMvcRequestBuilders.post( - "/molecular-profiles/test_molecular_profile_id/gene-panel-data/fetch") + "/api/molecular-profiles/test_molecular_profile_id/gene-panel-data/fetch") .accept(MediaType.APPLICATION_JSON) .contentType(MediaType.APPLICATION_JSON) .content(objectMapper.writeValueAsString(genePanelDataFilter))) @@ -113,6 +117,7 @@ public void getGenePanelData() throws Exception { } @Test + @WithMockUser public void fetchGenePanelData() throws Exception { List genePanelDataList = createExampleGenePanelData(); @@ -132,7 +137,7 @@ public void fetchGenePanelData() throws Exception { genePanelDataMultipleStudyFilter.setSampleMolecularIdentifiers(sampleMolecularIdentifiers); mockMvc.perform(MockMvcRequestBuilders.post( - "/gene-panel-data/fetch") + "/api/gene-panel-data/fetch") .accept(MediaType.APPLICATION_JSON) .contentType(MediaType.APPLICATION_JSON) .content(objectMapper.writeValueAsString(genePanelDataMultipleStudyFilter))) diff --git a/web/src/test/java/org/cbioportal/web/GenericAssayControllerTest.java b/web/src/test/java/org/cbioportal/web/GenericAssayControllerTest.java index 2f6ae944705..a3f81f70a38 100644 --- a/web/src/test/java/org/cbioportal/web/GenericAssayControllerTest.java +++ b/web/src/test/java/org/cbioportal/web/GenericAssayControllerTest.java @@ -1,19 +1,9 @@ package org.cbioportal.web; -import static org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestPostProcessors.csrf; - - import com.fasterxml.jackson.databind.ObjectMapper; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.HashMap; -import java.util.List; -import org.cbioportal.model.GenericAssayData; import org.cbioportal.model.meta.GenericAssayMeta; import org.cbioportal.service.GenericAssayService; import org.cbioportal.web.config.TestConfig; -import org.cbioportal.web.parameter.GenericAssayDataMultipleStudyFilter; -import org.cbioportal.web.parameter.GenericAssayFilter; import org.cbioportal.web.parameter.GenericAssayMetaFilter; import org.hamcrest.Matchers; import org.junit.Test; @@ -30,6 +20,13 @@ import org.springframework.test.web.servlet.request.MockMvcRequestBuilders; import org.springframework.test.web.servlet.result.MockMvcResultMatchers; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.HashMap; +import java.util.List; + +import static org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestPostProcessors.csrf; + @RunWith(SpringJUnit4ClassRunner.class) @WebMvcTest @ContextConfiguration(classes = {GenericAssayController.class, TestConfig.class}) @@ -63,14 +60,38 @@ public class GenericAssayControllerTest { private ObjectMapper objectMapper = new ObjectMapper(); + @Test @WithMockUser - public void testGenericAssayDataFetch() throws Exception { + public void testGenericAssayMetaGetMolecularProfileId() throws Exception { + List genericAssayMetaItems = createGenericAssayMetaItemsList(); + + Mockito.when(genericAssayService.getGenericAssayMetaByStableIdsAndMolecularIds(Mockito.any(), Mockito.any(), Mockito.any())).thenReturn(genericAssayMetaItems); + + mockMvc.perform(MockMvcRequestBuilders.get("/api/generic-assay-meta/" + PROF_ID) + .accept(MediaType.APPLICATION_JSON)) + .andExpect(MockMvcResultMatchers.status().isOk()) + .andExpect(MockMvcResultMatchers.content().contentTypeCompatibleWith(MediaType.APPLICATION_JSON)) + .andExpect(MockMvcResultMatchers.jsonPath("$", Matchers.hasSize(2))) + .andExpect(MockMvcResultMatchers.jsonPath("$[0].entityType").value(ENTITY_TYPE)) + .andExpect(MockMvcResultMatchers.jsonPath("$[0].stableId").value(GENERIC_ASSAY_STABLE_ID_1)) + .andExpect(MockMvcResultMatchers.jsonPath("$[1].entityType").value(ENTITY_TYPE)) + .andExpect(MockMvcResultMatchers.jsonPath("$[1].stableId").value(GENERIC_ASSAY_STABLE_ID_2)) + .andExpect(MockMvcResultMatchers.jsonPath("$[1].genericEntityMetaProperties", Matchers.hasKey(TEST_NAME))) + .andExpect(MockMvcResultMatchers.jsonPath("$[1].genericEntityMetaProperties", Matchers.hasValue(TEST_NAME_VALUE))) + .andExpect(MockMvcResultMatchers.jsonPath("$[1].genericEntityMetaProperties", Matchers.hasKey(TEST_DESCRIPTION))) + .andExpect(MockMvcResultMatchers.jsonPath("$[1].genericEntityMetaProperties", Matchers.hasValue(TEST_DESCRIPTION_VALUE))); + } + + + @Test + @WithMockUser + public void testGenericAssayMetaGetGenericAssayStableId() throws Exception { List genericAssayMetaSingleItem = createGenericAssayMetaSingleItem(); Mockito.when(genericAssayService.getGenericAssayMetaByStableIdsAndMolecularIds(Mockito.any(), Mockito.any(), Mockito.any())).thenReturn(genericAssayMetaSingleItem); - mockMvc.perform(MockMvcRequestBuilders.get("/generic-assay-meta/generic-assay/" + GENERIC_ASSAY_STABLE_ID_2) + mockMvc.perform(MockMvcRequestBuilders.get("/api/generic-assay-meta/generic-assay/" + GENERIC_ASSAY_STABLE_ID_2) .accept(MediaType.APPLICATION_JSON)) .andExpect(MockMvcResultMatchers.status().isOk()) .andExpect(MockMvcResultMatchers.status().isOk()) @@ -84,10 +105,9 @@ public void testGenericAssayDataFetch() throws Exception { .andExpect(MockMvcResultMatchers.jsonPath("$[0].genericEntityMetaProperties", Matchers.hasValue(TEST_DESCRIPTION_VALUE))); } - @Test @WithMockUser - public void testGenericAssayDataFetchInMultipleMolecularProfiles() throws Exception { + public void testGenericAssayMetaFetch() throws Exception { List genericAssayMetaItems = createGenericAssayMetaItemsList(); List genericAssayStableIds = Arrays.asList(GENERIC_ASSAY_STABLE_ID_1, GENERIC_ASSAY_STABLE_ID_2); GenericAssayMetaFilter genericAssayMetaFilter = new GenericAssayMetaFilter(); @@ -95,7 +115,7 @@ public void testGenericAssayDataFetchInMultipleMolecularProfiles() throws Except Mockito.when(genericAssayService.getGenericAssayMetaByStableIdsAndMolecularIds(Mockito.any(), Mockito.any(), Mockito.any())).thenReturn(genericAssayMetaItems); - mockMvc.perform(MockMvcRequestBuilders.post("/generic_assay_meta/fetch") + mockMvc.perform(MockMvcRequestBuilders.post("/api/generic_assay_meta/fetch").with(csrf()) .accept(MediaType.APPLICATION_JSON) .contentType(MediaType.APPLICATION_JSON) .content(objectMapper.writeValueAsString(genericAssayMetaFilter))) @@ -112,33 +132,6 @@ public void testGenericAssayDataFetchInMultipleMolecularProfiles() throws Except .andExpect(MockMvcResultMatchers.jsonPath("$[1].genericEntityMetaProperties", Matchers.hasValue(TEST_DESCRIPTION_VALUE))); } - @Test - @WithMockUser - public void testGenericAssayMetaDataFetch() throws Exception { - List genericAssayMetaItems = createGenericAssayMetaItemsList(); - List genericAssayStableIds = Arrays.asList(GENERIC_ASSAY_STABLE_ID_1, GENERIC_ASSAY_STABLE_ID_2); - GenericAssayMetaFilter genericAssayMetaFilter = new GenericAssayMetaFilter(); - genericAssayMetaFilter.setGenericAssayStableIds(genericAssayStableIds); - - Mockito.when(genericAssayService.getGenericAssayMetaByStableIdsAndMolecularIds(Mockito.any(), Mockito.any(), Mockito.any())).thenReturn(genericAssayMetaItems); - - mockMvc.perform(MockMvcRequestBuilders.post("/api/generic_assay_meta/fetch").with(csrf()) - .accept(MediaType.APPLICATION_JSON) - .contentType(MediaType.APPLICATION_JSON) - .content(objectMapper.writeValueAsString(genericAssayMetaFilter))) - .andExpect(MockMvcResultMatchers.status().isOk()) - .andExpect(MockMvcResultMatchers.content().contentTypeCompatibleWith(MediaType.APPLICATION_JSON)) - .andExpect(MockMvcResultMatchers.jsonPath("$", Matchers.hasSize(2))) - .andExpect(MockMvcResultMatchers.jsonPath("$[0].entityType").value(ENTITY_TYPE)) - .andExpect(MockMvcResultMatchers.jsonPath("$[0].stableId").value(GENERIC_ASSAY_STABLE_ID_1)) - .andExpect(MockMvcResultMatchers.jsonPath("$[1].entityType").value(ENTITY_TYPE)) - .andExpect(MockMvcResultMatchers.jsonPath("$[1].stableId").value(GENERIC_ASSAY_STABLE_ID_2)) - .andExpect(MockMvcResultMatchers.jsonPath("$[1].genericEntityMetaProperties", Matchers.hasKey(TEST_NAME))) - .andExpect(MockMvcResultMatchers.jsonPath("$[1].genericEntityMetaProperties", Matchers.hasValue(TEST_NAME_VALUE))) - .andExpect(MockMvcResultMatchers.jsonPath("$[1].genericEntityMetaProperties", Matchers.hasKey(TEST_DESCRIPTION))) - .andExpect(MockMvcResultMatchers.jsonPath("$[1].genericEntityMetaProperties", Matchers.hasValue(TEST_DESCRIPTION_VALUE))); - } - private List createGenericAssayMetaSingleItem() { List genericAssayMetaItems = new ArrayList<>(); diff --git a/web/src/test/java/org/cbioportal/web/GenericAssayDataControllerTest.java b/web/src/test/java/org/cbioportal/web/GenericAssayDataControllerTest.java index be24576b747..ee7fc0d285c 100644 --- a/web/src/test/java/org/cbioportal/web/GenericAssayDataControllerTest.java +++ b/web/src/test/java/org/cbioportal/web/GenericAssayDataControllerTest.java @@ -4,6 +4,7 @@ import org.cbioportal.model.GenericAssayData; import org.cbioportal.model.meta.GenericAssayMeta; import org.cbioportal.service.GenericAssayService; +import org.cbioportal.web.config.TestConfig; import org.cbioportal.web.parameter.GenericAssayDataMultipleStudyFilter; import org.cbioportal.web.parameter.GenericAssayFilter; import org.cbioportal.web.parameter.GenericAssayMetaFilter; @@ -14,6 +15,8 @@ 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.boot.test.mock.mockito.MockBean; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.http.MediaType; @@ -32,9 +35,8 @@ import java.util.List; @RunWith(SpringJUnit4ClassRunner.class) -@WebAppConfiguration -@ContextConfiguration("/applicationContext-web-test.xml") -@Configuration +@WebMvcTest +@ContextConfiguration(classes = {GenericAssayDataController.class, TestConfig.class}) public class GenericAssayDataControllerTest { private static final String PROF_ID = "test_prof_id"; @@ -60,8 +62,9 @@ public class GenericAssayDataControllerTest { @Autowired private WebApplicationContext wac; - @Autowired + @MockBean private GenericAssayService genericAssayService; + @Autowired private MockMvc mockMvc; private ObjectMapper objectMapper = new ObjectMapper(); @@ -83,7 +86,7 @@ public void testGenericAssayDataFetch() throws Exception { genericAssayDataFilter.setSampleIds(Arrays.asList(SAMPLE_ID)); genericAssayDataFilter.setGenericAssayStableIds(Arrays.asList(GENERIC_ASSAY_STABLE_ID_1, GENERIC_ASSAY_STABLE_ID_2, GENERIC_ASSAY_STABLE_ID_3, GENERIC_ASSAY_STABLE_ID_4)); - mockMvc.perform(MockMvcRequestBuilders.post("/generic_assay_data/" + PROF_ID + "/fetch") + mockMvc.perform(MockMvcRequestBuilders.post("/api/generic_assay_data/" + PROF_ID + "/fetch") .accept(MediaType.APPLICATION_JSON) .contentType(MediaType.APPLICATION_JSON) .content(objectMapper.writeValueAsString(genericAssayDataFilter))) @@ -109,7 +112,7 @@ public void testGenericAssayDataFetchInMultipleMolecularProfiles() throws Except Mockito.when(genericAssayService.fetchGenericAssayData(Mockito.anyList(), Mockito.any(), Mockito.any(), Mockito.any())).thenReturn(genericAssayDataItems); - mockMvc.perform(MockMvcRequestBuilders.post("/generic_assay_data/fetch") + mockMvc.perform(MockMvcRequestBuilders.post("/api/generic_assay_data/fetch") .accept(MediaType.APPLICATION_JSON) .contentType(MediaType.APPLICATION_JSON) .content(objectMapper.writeValueAsString(genericAssayDataMultipleStudyFilter))) @@ -131,7 +134,7 @@ public void testGenericAssayDataGet() throws Exception { Mockito.when(genericAssayService.fetchGenericAssayData(Mockito.anyString(), Mockito.anyList(), Mockito.anyList(), Mockito.anyString())).thenReturn(genericAssayDataItems); - mockMvc.perform(MockMvcRequestBuilders.get("/generic-assay-data/" + PROF_ID + "/generic-assay/" + GENERIC_ASSAY_STABLE_ID_1) + mockMvc.perform(MockMvcRequestBuilders.get("/api/generic-assay-data/" + PROF_ID + "/generic-assay/" + GENERIC_ASSAY_STABLE_ID_1) .accept(MediaType.APPLICATION_JSON)) .andExpect(MockMvcResultMatchers.status().isOk()) .andExpect(MockMvcResultMatchers.content().contentTypeCompatibleWith(MediaType.APPLICATION_JSON)) diff --git a/web/src/test/java/org/cbioportal/web/MutationControllerTest.java b/web/src/test/java/org/cbioportal/web/MutationControllerTest.java index ffe804dc842..9485d91ad70 100644 --- a/web/src/test/java/org/cbioportal/web/MutationControllerTest.java +++ b/web/src/test/java/org/cbioportal/web/MutationControllerTest.java @@ -36,7 +36,7 @@ @RunWith(SpringJUnit4ClassRunner.class) @WebMvcTest -@ContextConfiguration(classes = {MutationController.class, TestConfig.class}) +@ContextConfiguration(classes = {MutationController.class, MutationCountController.class, TestConfig.class}) public class MutationControllerTest { private static final String TEST_MOLECULAR_PROFILE_STABLE_ID_1 = "test_molecular_profile_stable_id_1"; @@ -631,6 +631,7 @@ public void fetchMutationsInMolecularProfileMetaProjection() throws Exception { } @Test + @WithMockUser public void fetchMutationCountsByPosition() throws Exception { List mutationCountByPositionList = new ArrayList<>(); @@ -663,7 +664,7 @@ public void fetchMutationCountsByPosition() throws Exception { mutationPositionIdentifier2.setProteinPosEnd(TEST_MUTATION_PROTEIN_POS_END_2); mutationPositionIdentifiers.add(mutationPositionIdentifier2); - mockMvc.perform(MockMvcRequestBuilders.post("/mutation-counts-by-position/fetch") + mockMvc.perform(MockMvcRequestBuilders.post("/api/mutation-counts-by-position/fetch").with(csrf()) .accept(MediaType.APPLICATION_JSON) .contentType(MediaType.APPLICATION_JSON) .content(objectMapper.writeValueAsString(mutationPositionIdentifiers))) diff --git a/web/src/test/java/org/cbioportal/web/SampleControllerTest.java b/web/src/test/java/org/cbioportal/web/SampleControllerTest.java index 72e4a73b3a2..7756f33acdf 100644 --- a/web/src/test/java/org/cbioportal/web/SampleControllerTest.java +++ b/web/src/test/java/org/cbioportal/web/SampleControllerTest.java @@ -8,6 +8,7 @@ import java.util.List; import org.cbioportal.model.Sample; import org.cbioportal.model.meta.BaseMeta; +import org.cbioportal.service.SampleListService; import org.cbioportal.service.SampleService; import org.cbioportal.service.StudyService; import org.cbioportal.service.exception.SampleNotFoundException; @@ -47,6 +48,9 @@ public class SampleControllerTest { @MockBean private SampleService sampleService; + + @MockBean + private SampleListService sampleListService; @MockBean private StudyService studyService; diff --git a/web/src/test/java/org/cbioportal/web/StructuralVariantControllerTest.java b/web/src/test/java/org/cbioportal/web/StructuralVariantControllerTest.java index b3e73fb280e..0be3faf380a 100644 --- a/web/src/test/java/org/cbioportal/web/StructuralVariantControllerTest.java +++ b/web/src/test/java/org/cbioportal/web/StructuralVariantControllerTest.java @@ -283,9 +283,10 @@ public void fetchStructuralVariantsBothMolecularProfileIdAndSampleMolecularIdent } @Test + @WithMockUser public void fetchStructuralVariantsWithBothEntrezIdsAndStructVariantIdsReturnsStatusOk() throws Exception { String structuralVariantFilter = createStructuralVariantFilterWithEntrezIdAndStructuralVariantJson(); - mockMvc.perform(MockMvcRequestBuilders.post("/structural-variant/fetch") + mockMvc.perform(MockMvcRequestBuilders.post("/api/structural-variant/fetch").with(csrf()) .accept(MediaType.APPLICATION_JSON) .contentType(MediaType.APPLICATION_JSON) .content(structuralVariantFilter)) @@ -293,6 +294,7 @@ public void fetchStructuralVariantsWithBothEntrezIdsAndStructVariantIdsReturnsSt } @Test + @WithMockUser public void fetchStructuralVariantsWithStructuralVariantSpecialQueryValues() throws Exception { List structuralVariant = createExampleStructuralVariant(); @@ -303,7 +305,7 @@ public void fetchStructuralVariantsWithStructuralVariantSpecialQueryValues() thr )).thenReturn(structuralVariant); String structuralVariantFilterJson = createStructuralVariantFilterWithStructuralVariantWildcard(); - mockMvc.perform(MockMvcRequestBuilders.post("/structural-variant/fetch") + mockMvc.perform(MockMvcRequestBuilders.post("/api/structural-variant/fetch").with(csrf()) .accept(MediaType.APPLICATION_JSON) .contentType(MediaType.APPLICATION_JSON) .content(structuralVariantFilterJson)) @@ -328,6 +330,7 @@ public void fetchStructuralVariantsWithStructuralVariantSpecialQueryValues() thr } @Test + @WithMockUser public void fetchStructuralVariantsWithStructuralVariantIdWithNoIdAndSpecialValueReturnsBadRequest() throws Exception { List structuralVariant = createExampleStructuralVariant(); @@ -337,7 +340,7 @@ public void fetchStructuralVariantsWithStructuralVariantIdWithNoIdAndSpecialValu )).thenReturn(structuralVariant); String structuralVariantFilterJson = createStructuralVariantFilterWithEmptyStructuralVariantId(); - mockMvc.perform(MockMvcRequestBuilders.post("/structural-variant/fetch") + mockMvc.perform(MockMvcRequestBuilders.post("/api/structural-variant/fetch").with(csrf()) .accept(MediaType.APPLICATION_JSON) .contentType(MediaType.APPLICATION_JSON) .content(structuralVariantFilterJson)) diff --git a/web/src/test/java/org/cbioportal/web/StudyControllerTest.java b/web/src/test/java/org/cbioportal/web/StudyControllerTest.java index 65bf4a38e3b..1540bf6244c 100644 --- a/web/src/test/java/org/cbioportal/web/StudyControllerTest.java +++ b/web/src/test/java/org/cbioportal/web/StudyControllerTest.java @@ -126,19 +126,21 @@ public void getAllStudiesDefaultProjection() throws Exception { } @Test + @WithMockUser public void getAllStudiesSetAccessLevelReadIsDefault() throws Exception { AccessLevel expectedAccessLevel = AccessLevel.READ; Mockito.when(studyService.getAllStudies(Mockito.any(), Mockito.any(), Mockito.any(), Mockito.any(), Mockito.any(), Mockito.any(), Mockito.any(), eq(expectedAccessLevel))).thenReturn(new ArrayList<>()); - mockMvc.perform(MockMvcRequestBuilders.get("/studies") + mockMvc.perform(MockMvcRequestBuilders.get("/api/studies") .accept(MediaType.APPLICATION_JSON)) .andExpect(MockMvcResultMatchers.status().isOk()); } @Test + @WithMockUser public void getAllStudiesSetAccessLevelListConditionally() throws Exception { ReflectionTestUtils.setField(studyController, "showUnauthorizedStudiesOnHomePage", true); @@ -147,7 +149,7 @@ public void getAllStudiesSetAccessLevelListConditionally() throws Exception { Mockito.when(studyService.getAllStudies(Mockito.any(), Mockito.any(), Mockito.any(), Mockito.any(), Mockito.any(), Mockito.any(), Mockito.any(), eq(expectedAccessLevel))).thenReturn(new ArrayList<>()); - mockMvc.perform(MockMvcRequestBuilders.get("/studies") + mockMvc.perform(MockMvcRequestBuilders.get("/api/studies") .accept(MediaType.APPLICATION_JSON)) .andExpect(MockMvcResultMatchers.status().isOk()); diff --git a/web/src/test/java/org/cbioportal/web/StudyViewControllerTest.java b/web/src/test/java/org/cbioportal/web/StudyViewControllerTest.java index d32ea65f6d1..2dd141225a8 100644 --- a/web/src/test/java/org/cbioportal/web/StudyViewControllerTest.java +++ b/web/src/test/java/org/cbioportal/web/StudyViewControllerTest.java @@ -35,14 +35,17 @@ import org.cbioportal.service.ClinicalAttributeService; import org.cbioportal.service.ClinicalDataService; import org.cbioportal.service.ClinicalEventService; +import org.cbioportal.service.CustomDataService; import org.cbioportal.service.DiscreteCopyNumberService; import org.cbioportal.service.GenePanelService; +import org.cbioportal.service.GeneService; import org.cbioportal.service.MolecularProfileService; import org.cbioportal.service.PatientService; import org.cbioportal.service.SampleListService; import org.cbioportal.service.SampleService; import org.cbioportal.service.StudyViewService; import org.cbioportal.service.TreatmentService; +import org.cbioportal.service.ViolinPlotService; import org.cbioportal.service.util.ClinicalAttributeUtil; import org.cbioportal.service.util.MolecularProfileUtil; import org.cbioportal.web.config.TestConfig; @@ -86,10 +89,10 @@ @RunWith(SpringJUnit4ClassRunner.class) @WebMvcTest // TODO clean up dependencies for this test (use Mocks better) +// TODO Rework to accurately test StudyViewController @ContextConfiguration(classes = {StudyViewController.class, StudyViewFilterUtil.class, MolecularProfileUtil.class, ClinicalDataBinUtil.class, DataBinner.class, DiscreteDataBinner.class, LinearDataBinner.class, ScientificSmallDataBinner.class, LogScaleDataBinner.class, ClinicalDataBinUtil.class, DataBinHelper.class, TestConfig.class}) -@Ignore public class StudyViewControllerTest { private static final String TEST_STUDY_ID = "test_study_id"; @@ -169,7 +172,16 @@ public class StudyViewControllerTest { @MockBean private ClinicalEventService clinicalEventService; - + + @MockBean + private GeneService geneService; + + @MockBean + private ViolinPlotService violinPlotService; + + @MockBean + private ClinicalDataBinUtil clinicalDataBinUtil; + @Autowired private MockMvc mockMvc; @@ -276,6 +288,8 @@ public void fetchClinicalDataCounts() throws Exception { @Test @WithMockUser + @Ignore + //TODO: Update Test currently out of scope of StudyViewController (need to make a new unit test to test ClinicalDataBinUtil) public void fetchClinicalDataBinCounts() throws Exception { List filteredSampleIdentifiers = new ArrayList<>(); @@ -328,6 +342,8 @@ public void fetchClinicalDataBinCounts() throws Exception StudyViewFilter studyViewFilter = new StudyViewFilter(); studyViewFilter.setStudyIds(Collections.singletonList(TEST_STUDY_ID)); clinicalDataBinCountFilter.setStudyViewFilter(studyViewFilter); + + when(clinicalDataBinUtil.removeSelfFromFilter(any())).thenReturn(studyViewFilter); mockMvc.perform(MockMvcRequestBuilders.post("/api/clinical-data-bin-counts/fetch").with(csrf()) .accept(MediaType.APPLICATION_JSON) @@ -602,6 +618,7 @@ public void fetchSampleCounts() throws Exception { @Test + @WithMockUser public void fetchGenomicDataCounts() throws Exception { when(studyViewFilterApplier.apply(any())).thenReturn(filteredSampleIdentifiers); @@ -662,7 +679,7 @@ public void fetchGenomicDataCounts() throws Exception { studyViewFilter.setStudyIds(Arrays.asList(TEST_STUDY_ID)); genomicDataCountFilter.setStudyViewFilter(studyViewFilter); - mockMvc.perform(MockMvcRequestBuilders.post("/genomic-data-counts/fetch") + mockMvc.perform(MockMvcRequestBuilders.post("/api/genomic-data-counts/fetch").with(csrf()) .accept(MediaType.APPLICATION_JSON) .contentType(MediaType.APPLICATION_JSON) .content(objectMapper.writeValueAsString(genomicDataCountFilter))) @@ -971,6 +988,7 @@ public void fetchGenericAssayDataCounts() throws Exception { } @Test + @WithMockUser public void fetchClinicalDataClinicalTable() throws Exception { // For this sake of this test the sample clinical data and patient clinical data are identical. when(clinicalDataService.fetchSampleClinicalTable(anyList(), anyList(), @@ -983,7 +1001,7 @@ public void fetchClinicalDataClinicalTable() throws Exception { when(studyViewFilterApplier.apply(any())).thenReturn(filteredSampleIdentifiers); - mockMvc.perform(MockMvcRequestBuilders.post("/clinical-data-table/fetch") + mockMvc.perform(MockMvcRequestBuilders.post("/api/clinical-data-table/fetch").with(csrf()) .accept(MediaType.APPLICATION_JSON) .contentType(MediaType.APPLICATION_JSON) .content(objectMapper.writeValueAsString(studyViewFilter))) @@ -1005,6 +1023,7 @@ public void fetchClinicalDataClinicalTable() throws Exception { } @Test + @WithMockUser public void fetchClinicalEventTypeCounts() throws Exception { List testEventTypeCounts = Arrays.asList(new ClinicalEventTypeCount(TEST_CLINICAL_EVENT_TYPE, TEST_CLINICAL_EVENT_TYPE_COUNT)); @@ -1016,7 +1035,7 @@ public void fetchClinicalEventTypeCounts() throws Exception StudyViewFilter studyViewFilter = new StudyViewFilter(); studyViewFilter.setStudyIds(Collections.singletonList(TEST_STUDY_ID)); - mockMvc.perform(MockMvcRequestBuilders.post("/clinical-event-type-counts/fetch") + mockMvc.perform(MockMvcRequestBuilders.post("/api/clinical-event-type-counts/fetch").with(csrf()) .accept(MediaType.APPLICATION_JSON) .contentType(MediaType.APPLICATION_JSON) .content(objectMapper.writeValueAsString(studyViewFilter))) @@ -1027,6 +1046,7 @@ public void fetchClinicalEventTypeCounts() throws Exception } @Test + @WithMockUser public void validateStructVarFilter() throws Exception { when(studyViewFilterApplier.apply(any())).thenReturn(filteredSampleIdentifiers); @@ -1061,13 +1081,14 @@ public void validateStructVarFilter() throws Exception { structVarFilterQuery.getGene1Query().setSpecialValue(StructuralVariantSpecialValue.ANY_GENE); structVarFilterQuery.getGene2Query().setSpecialValue(StructuralVariantSpecialValue.ANY_GENE); - mockMvc.perform(MockMvcRequestBuilders.post("/filtered-samples/fetch") + mockMvc.perform(MockMvcRequestBuilders.post("/api/filtered-samples/fetch").with(csrf()) .accept(MediaType.APPLICATION_JSON) .contentType(MediaType.APPLICATION_JSON) .content(objectMapper.writeValueAsString(studyViewFilter))) .andExpect(MockMvcResultMatchers.status().isBadRequest()); } @Test + @WithMockUser public void validateStructVarFilterBothAnyGene() throws Exception { when(studyViewFilterApplier.apply(any())).thenReturn(filteredSampleIdentifiers); @@ -1088,7 +1109,7 @@ public void validateStructVarFilterBothAnyGene() throws Exception { structVarFilterQuery.getGene1Query().setSpecialValue(StructuralVariantSpecialValue.ANY_GENE); structVarFilterQuery.getGene2Query().setSpecialValue(StructuralVariantSpecialValue.ANY_GENE); - mockMvc.perform(MockMvcRequestBuilders.post("/filtered-samples/fetch") + mockMvc.perform(MockMvcRequestBuilders.post("/api/filtered-samples/fetch").with(csrf()) .accept(MediaType.APPLICATION_JSON) .contentType(MediaType.APPLICATION_JSON) .content(objectMapper.writeValueAsString(studyViewFilter))) @@ -1096,6 +1117,7 @@ public void validateStructVarFilterBothAnyGene() throws Exception { } @Test + @WithMockUser public void validateStructVarFilterBothNoGene() throws Exception { when(studyViewFilterApplier.apply(any())).thenReturn(filteredSampleIdentifiers); @@ -1116,7 +1138,7 @@ public void validateStructVarFilterBothNoGene() throws Exception { structVarFilterQuery.getGene1Query().setSpecialValue(StructuralVariantSpecialValue.NO_GENE); structVarFilterQuery.getGene2Query().setSpecialValue(StructuralVariantSpecialValue.NO_GENE); - mockMvc.perform(MockMvcRequestBuilders.post("/filtered-samples/fetch") + mockMvc.perform(MockMvcRequestBuilders.post("/api/filtered-samples/fetch").with(csrf()) .accept(MediaType.APPLICATION_JSON) .contentType(MediaType.APPLICATION_JSON) .content(objectMapper.writeValueAsString(studyViewFilter))) @@ -1124,6 +1146,7 @@ public void validateStructVarFilterBothNoGene() throws Exception { } @Test + @WithMockUser public void validateStructVarFilterBothNoGeneId() throws Exception { when(studyViewFilterApplier.apply(any())).thenReturn(filteredSampleIdentifiers); @@ -1142,7 +1165,7 @@ public void validateStructVarFilterBothNoGeneId() throws Exception { structuralVariantFilter.setStructVarQueries(Arrays.asList(Arrays.asList(structVarFilterQuery))); studyViewFilter.setStructuralVariantFilters(Arrays.asList(structuralVariantFilter)); - mockMvc.perform(MockMvcRequestBuilders.post("/filtered-samples/fetch") + mockMvc.perform(MockMvcRequestBuilders.post("/api/filtered-samples/fetch").with(csrf()) .accept(MediaType.APPLICATION_JSON) .contentType(MediaType.APPLICATION_JSON) .content(objectMapper.writeValueAsString(studyViewFilter))) @@ -1150,6 +1173,7 @@ public void validateStructVarFilterBothNoGeneId() throws Exception { } @Test + @WithMockUser public void validateStructVarFilterBothGeneIdAndSpecialValueNull() throws Exception { when(studyViewFilterApplier.apply(any())).thenReturn(filteredSampleIdentifiers); @@ -1169,7 +1193,7 @@ public void validateStructVarFilterBothGeneIdAndSpecialValueNull() throws Except structuralVariantFilter.setStructVarQueries(Arrays.asList(Arrays.asList(structVarFilterQuery))); studyViewFilter.setStructuralVariantFilters(Arrays.asList(structuralVariantFilter)); - mockMvc.perform(MockMvcRequestBuilders.post("/filtered-samples/fetch") + mockMvc.perform(MockMvcRequestBuilders.post("/api/filtered-samples/fetch").with(csrf()) .accept(MediaType.APPLICATION_JSON) .contentType(MediaType.APPLICATION_JSON) .content(objectMapper.writeValueAsString(studyViewFilter))) diff --git a/web/src/test/java/org/cbioportal/web/config/DataAccessTokenControllerTestConfig.java b/web/src/test/java/org/cbioportal/web/config/DataAccessTokenControllerTestConfig.java index 029d6363c7a..63732509b4c 100644 --- a/web/src/test/java/org/cbioportal/web/config/DataAccessTokenControllerTestConfig.java +++ b/web/src/test/java/org/cbioportal/web/config/DataAccessTokenControllerTestConfig.java @@ -1,24 +1,34 @@ package org.cbioportal.web.config; +import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.TestConfiguration; import org.springframework.context.annotation.Bean; import org.springframework.security.authentication.AuthenticationManager; +import org.springframework.security.authentication.AuthenticationProvider; import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder; import org.springframework.security.config.annotation.web.builders.HttpSecurity; +import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; +import org.springframework.security.core.GrantedAuthority; +import org.springframework.security.core.authority.SimpleGrantedAuthority; +import org.springframework.security.core.userdetails.User; +import org.springframework.security.core.userdetails.UserDetails; +import org.springframework.security.core.userdetails.UserDetailsService; import org.springframework.security.crypto.factory.PasswordEncoderFactories; import org.springframework.security.crypto.password.PasswordEncoder; import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter; +import java.util.ArrayList; +import java.util.List; + @TestConfiguration +@EnableWebSecurity public class DataAccessTokenControllerTestConfig extends WebSecurityConfigurerAdapter { - @Override protected void configure(HttpSecurity http) throws Exception { http.antMatcher("/**") .authorizeRequests().anyRequest().authenticated() .and() - .addFilter(usernamePasswordAuthenticationFilter()) .httpBasic() .authenticationEntryPoint(restAuthenticationEntryPoint()); } @@ -27,11 +37,17 @@ protected void configure(HttpSecurity http) throws Exception { @Override protected void configure(AuthenticationManagerBuilder auth) throws Exception { PasswordEncoder encoder = PasswordEncoderFactories.createDelegatingPasswordEncoder(); - auth.inMemoryAuthentication() - .passwordEncoder(encoder) - .withUser("MOCK_USER") - .password(encoder.encode("{noop}MOCK_PASSWORD")) - .authorities("PLACEHOLDER_ROLE"); + // Define the authorities for the mock user + List authorities = new ArrayList<>(); + authorities.add(new SimpleGrantedAuthority("PLACEHOLDER_ROLE")); + UserDetails mockUser = User.withUsername("MOCK_USER") + .password("{noop}MOCK_PASSWORD") + .roles("PLACEHOLDER_ROLE") + .authorities(authorities) + .build(); + + auth.inMemoryAuthentication() + .passwordEncoder(encoder).withUser(mockUser); } @Bean @@ -45,10 +61,11 @@ public UsernamePasswordAuthenticationFilter usernamePasswordAuthenticationFilter UsernamePasswordAuthenticationFilter filter = new UsernamePasswordAuthenticationFilter(); filter.setPostOnly(false); - filter.setFilterProcessesUrl("j_spring_security_check"); + filter.setFilterProcessesUrl("/j_spring_security_check"); filter.setUsernameParameter("j_username"); filter.setPasswordParameter("j_password"); filter.setAuthenticationManager(authenticationManagerBean()); + filter.setAuthenticationSuccessHandler(tokenAuthenticationSuccessHandler()); return filter; } @@ -63,4 +80,9 @@ public AuthenticationManager authenticationManagerBean() throws Exception { return super.authenticationManagerBean(); } + @Bean + public UserDetailsService userDetailsService() { + return super.userDetailsService(); + } + } diff --git a/web/src/test/java/org/cbioportal/web/config/RestAuthenticationEntryPoint.java b/web/src/test/java/org/cbioportal/web/config/RestAuthenticationEntryPoint.java index bdd259ccce4..f0037c3639c 100644 --- a/web/src/test/java/org/cbioportal/web/config/RestAuthenticationEntryPoint.java +++ b/web/src/test/java/org/cbioportal/web/config/RestAuthenticationEntryPoint.java @@ -49,4 +49,6 @@ public void commence( HttpServletRequest request, HttpServletResponse response, AuthenticationException authException ) throws IOException{ response.sendError( HttpServletResponse.SC_UNAUTHORIZED, "Unauthorized" ); } + + } diff --git a/web/src/test/java/org/cbioportal/web/config/TestConfig.java b/web/src/test/java/org/cbioportal/web/config/TestConfig.java index 6d0a0c53e41..a3d4a7dde35 100644 --- a/web/src/test/java/org/cbioportal/web/config/TestConfig.java +++ b/web/src/test/java/org/cbioportal/web/config/TestConfig.java @@ -36,7 +36,8 @@ public class InterceptorAppConfig implements WebMvcConfigurer { @Override public void addInterceptors(InterceptorRegistry registry) { - registry.addInterceptor(involvedCancerStudyExtractorInterceptor); + registry.addInterceptor(involvedCancerStudyExtractorInterceptor) + .addPathPatterns("/api/**"); } } diff --git a/web/src/test/java/org/cbioportal/web/config/TokenAuthenticationSuccessHandler.java b/web/src/test/java/org/cbioportal/web/config/TokenAuthenticationSuccessHandler.java index 29ce1b7e7e7..a109025f365 100644 --- a/web/src/test/java/org/cbioportal/web/config/TokenAuthenticationSuccessHandler.java +++ b/web/src/test/java/org/cbioportal/web/config/TokenAuthenticationSuccessHandler.java @@ -38,10 +38,15 @@ import org.springframework.security.core.Authentication; import org.springframework.security.web.authentication.AuthenticationSuccessHandler; +import java.io.IOException; + public class TokenAuthenticationSuccessHandler implements AuthenticationSuccessHandler { @Override - public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) { + public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException { + response.setStatus(HttpServletResponse.SC_OK); + response.getWriter().write("Authentication successful"); + response.getWriter().flush(); // We do not need to do anything extra on REST authentication success, because there is no page to redirect to } diff --git a/web/src/test/java/org/cbioportal/web/util/DataBinnerTest.java b/web/src/test/java/org/cbioportal/web/util/DataBinnerTest.java index b2d0544b6b6..b6fe1f81688 100644 --- a/web/src/test/java/org/cbioportal/web/util/DataBinnerTest.java +++ b/web/src/test/java/org/cbioportal/web/util/DataBinnerTest.java @@ -1,6 +1,8 @@ package org.cbioportal.web.util; import java.math.BigDecimal; +import java.math.MathContext; +import java.math.RoundingMode; import java.util.ArrayList; import java.util.Arrays; import java.util.List; @@ -15,6 +17,7 @@ import org.cbioportal.model.Binnable; import org.cbioportal.model.ClinicalData; import org.cbioportal.model.DataBin; +import org.cbioportal.service.GeneService; import org.cbioportal.service.util.MolecularProfileUtil; import org.cbioportal.web.parameter.BinsGeneratorConfig; import org.cbioportal.web.parameter.ClinicalDataBinFilter; @@ -57,6 +60,9 @@ public class DataBinnerTest { @MockBean private MolecularProfileUtil molecularProfileUtil; + + @MockBean + private GeneService geneService; private List getCaseIds(List unfilteredClinicalData, boolean getPatientIds) { return unfilteredClinicalData @@ -1047,11 +1053,11 @@ public void testScientificDataBinner() { Assert.assertEquals(16, dataBins.get(1).getCount().intValue()); Assert.assertEquals(new BigDecimal("1.0e-6"), dataBins.get(2).getStart()); - Assert.assertEquals(new BigDecimal("1.0e-5"), dataBins.get(2).getEnd()); + Assert.assertEquals(new BigDecimal("1.0e-5").compareTo(dataBins.get(2).getEnd().round(new MathContext(5, RoundingMode.CEILING))), 0); Assert.assertEquals(32, dataBins.get(2).getCount().intValue()); Assert.assertEquals(">", dataBins.get(3).getSpecialValue()); - Assert.assertEquals(new BigDecimal("1.0e-5"), dataBins.get(3).getStart()); + Assert.assertEquals(new BigDecimal("1.0e-5").compareTo(dataBins.get(3).getStart().round(new MathContext(5, RoundingMode.CEILING))), 0); Assert.assertEquals(1, dataBins.get(3).getCount().intValue()); Assert.assertEquals("NA", dataBins.get(4).getSpecialValue());