This is the codeAbility Sharing Platform! Learn more about the codeAbility Sharing Platform.

Skip to content
Snippets Groups Projects
Commit 8283212e authored by Michael Breu's avatar Michael Breu :speech_balloon:
Browse files

Revert "Fixing most of the tests :-)"

This reverts commit 15b448d9.
parent 15b448d9
Branches
Tags
1 merge request!17Initial Merge to Prepare Release 1.0.0
Showing
with 287 additions and 230 deletions
......@@ -17,15 +17,15 @@ pipeline {
steps {
milestone 1
withSonarQubeEnv('SonarQube Production') {
sh "mvn -Dmaven.test.failure.ignore=true clean test"
sh "mvn -Dmaven.test.failure.ignore=true clean verify"
}
}
}
stage('Evaluate') {
steps {
milestone 2
junit(testResults: 'target/test-results/test/**/*.xml', healthScaleFactor: 100)
jacoco(execPattern: 'target/jacoco/test.exec', sourcePattern: 'src/main/java', sourceInclusionPattern: '**/*.java')
junit(testResults: 'target/test-results/test/**/*.xml,target/test-results/integrationTest/**/*.xml', healthScaleFactor: 100)
jacoco(execPattern: 'target/jacoco/test/test.exec,target/jacoco/integrationTest/integrationTest.exec', sourcePattern: 'src/main/java', sourceInclusionPattern: '**/*.java')
sh "npm test"
sh "mvn jacoco:report"
}
......
......@@ -10,7 +10,7 @@ sonar.java.codeCoveragePlugin=jacoco
sonar.java.sources=src/main/java
sonar.java.source=11
sonar.java.binaries=target/classes
sonar.junit.reportPaths=target/test-results/test,target/test-results/integrationTest
sonar.junit.reportPaths=target/test-results/test,target/test-results/integrationTest,target/test-results/test,target/test-results/test
sonar.testExecutionReportPaths=target/test-results/jest/TESTS-results-sonar.xml
sonar.typescript.lcov.reportPaths=target/test-results/lcov.info
......
......@@ -7,16 +7,38 @@ import static org.hamcrest.Matchers.is;
import java.io.IOException;
import java.util.List;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.node.NodeValidationException;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import at.ac.uibk.gitsearch.GitsearchApp;
import at.ac.uibk.gitsearch.repository.search.testESService.ElasticSearchTestServerConfiguration;
import at.ac.uibk.gitsearch.service.dto.AutoCompleteEntry;
@SpringBootTest(classes = GitsearchApp.class)
public class MetaDataRepositoryTests {
private static final Logger LOGGER = LogManager.getLogger(MetaDataRepositoryTests.class);
@Autowired
RestHighLevelClient elasticsearchTestClient;
@BeforeAll
public static void setUpESServer() throws IOException, NodeValidationException {
ElasticSearchTestServerConfiguration.getTestInstance().startTestNode();
}
@BeforeEach
public void setUpIndex() {
}
@Autowired
private MetaDataRepository metaDataRepository;
......
......@@ -2,8 +2,6 @@ package at.ac.uibk.gitsearch.service;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import org.codeability.sharing.plugins.api.SharingPluginConfig;
import org.codeability.sharing.plugins.api.SharingPluginConfig.Action;
......@@ -24,52 +22,60 @@ import at.ac.uibk.gitsearch.GitsearchApp;
import at.ac.uibk.gitsearch.service.PluginManagementService.PluginConfigWrapper;
import at.ac.uibk.gitsearch.service.PluginManagementService.PluginConfigWrapper.ActionWrapper;
import at.ac.uibk.gitsearch.service.dto.SearchResultDTO;
import at.ac.uibk.gitsearch.service.dto.UserProvidedMetadataDTO;
@SpringBootTest(classes = GitsearchApp.class)
public class PluginManagerActionIT {
private final Logger log = LoggerFactory.getLogger(PluginManagerActionIT.class);
private PluginConfigWrapper config;
@BeforeEach
public void initConfig() {
config = new PluginConfigWrapper(new SharingPluginConfig("TestPlugin",new Action[] {new Action("someId", "someImportURL", "someActionName", "metadata.type.externalName=='programming exercise'")}), "http://localhost:8080/xxx");
config = new PluginConfigWrapper(
new SharingPluginConfig("TestPlugin", new Action[] { new Action("someId", "someImportURL",
"someActionName", "metadata.type.externalName=='programming exercise'") }),
"http://localhost:8080/xxx");
}
@Test
@Test
public void testExpressionFiltersOnMetaData() throws JsonParseException, JsonMappingException, IOException {
ActionWrapper actionWrapper = config.getActions().get("someId");
Assert.assertTrue("metaData1 should be applicable", actionWrapper.isApplicable(readTestResults("metaData1.yaml")));
Assert.assertFalse("metaData2 should not be applicable", actionWrapper.isApplicable(readTestResults("metaData2.yaml")));
ActionWrapper actionWrapper = config.getActions().get("someId");
Assert.assertTrue("metaData1 should be applicable",
actionWrapper.isApplicable(readTestResults("metaData1.yaml")));
Assert.assertFalse("metaData2 should not be applicable",
actionWrapper.isApplicable(readTestResults("metaData2.yaml")));
}
/**
* temporary static test data.
*
* @param infoString just a string to add to testdata description.
* @return
* @throws IOException
* @throws JsonMappingException
* @throws JsonParseException
* @throws IOException
* @throws JsonMappingException
* @throws JsonParseException
*/
@SuppressWarnings("unused")
private SearchResultDTO readTestResults(String testFile) throws JsonParseException, JsonMappingException, IOException {
private SearchResultDTO readTestResults(String testFile)
throws JsonParseException, JsonMappingException, IOException {
ObjectMapper mapper = new ObjectMapper(new YAMLFactory());
mapper.findAndRegisterModules();
List<SearchResultDTO> loadedMetaData = new ArrayList<SearchResultDTO>();
log.debug("reading test data from {} ", testFile);
log.debug("reading test data from {} ", testFile);
final String resourceName = "./testData/" + testFile;
final InputStream resourceStream = this.getClass().getResourceAsStream(resourceName);
Assert.assertNotNull("cannot find resource at " + resourceName, resourceStream);
final InputStream resourceStream = this.getClass().getClassLoader().getResourceAsStream("at/ac/uibk/gitsearch/service/testData/" + testFile);
byte[] fileContent = FileCopyUtils.copyToByteArray(resourceStream);
SearchResultDTO searchResultDTO = mapper.readValue(fileContent, SearchResultDTO.class);
return searchResultDTO;
byte[] fileContent = FileCopyUtils.copyToByteArray(resourceStream);
UserProvidedMetadataDTO metaData = mapper.readValue(fileContent, UserProvidedMetadataDTO.class);
SearchResultDTO result = new SearchResultDTO();
result.setMetadata(metaData);
return result;
}
}
package at.ac.uibk.gitsearch.service;
import static at.ac.uibk.gitsearch.web.rest.AccountResourceIT.TEST_USER_LOGIN;
import static org.hamcrest.Matchers.anyOf;
import static org.hamcrest.Matchers.containsString;
import static org.hamcrest.Matchers.everyItem;
......@@ -11,134 +12,130 @@ import static org.junit.Assert.assertTrue;
import java.io.IOException;
import at.ac.uibk.gitsearch.service.dto.SearchInputMetadataDTO;
import org.junit.jupiter.api.BeforeEach;
import org.elasticsearch.node.NodeValidationException;
import org.junit.Ignore;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
import org.mockito.MockitoAnnotations;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.security.test.context.support.WithMockUser;
import at.ac.uibk.gitsearch.GitsearchApp;
import at.ac.uibk.gitsearch.repository.search.testESService.ElasticSearchTestServerConfiguration;
import at.ac.uibk.gitsearch.security.SecurityUtils;
import at.ac.uibk.gitsearch.service.dto.SearchInputDTO;
import at.ac.uibk.gitsearch.service.dto.SearchInputMetadataDTO;
import at.ac.uibk.gitsearch.service.dto.SearchResultsDTO;
/**
* Integration tests for {@link MailService}.
*/
@SpringBootTest(classes = GitsearchApp.class)
@WithMockUser(value = TEST_USER_LOGIN, authorities = "sharing")
public class SearchServiceIT {
@Autowired
private SearchService searchService;
@BeforeEach
public void setup() {
MockitoAnnotations.initMocks(this);
}
@Test
public void testFullTextSearch() throws Exception {
final String WIEN = "Wien";
final SearchInputMetadataDTO searchMetadata =
new SearchInputMetadataDTO(null, null, null, null, null);
SearchInputDTO searchQuery =
new SearchInputDTO(WIEN, searchMetadata, null, null, null, 0);
SearchResultsDTO searchResultPage =
searchService.searchResultPage(searchQuery, 0, SearchInputDTO.PAGE_SIZE);
org.junit.Assert.assertNotNull(searchResultPage.getSearchResult());
org.junit.Assert.assertTrue("At least one test hit", searchResultPage.getHitCount() >= 1);
org.junit.Assert.assertThat(searchResultPage.getSearchResult(), everyItem(
anyOf(hasProperty("description", containsString(WIEN)),
hasProperty("title", containsString(WIEN))
// hasProperty("keywords", containsString("Wien"))
)));
}
@Test
public void testSearchByAutor() throws Exception {
final String PODLIPNIG = "Stefan Podlipnig";
final SearchInputMetadataDTO searchMetadata =
new SearchInputMetadataDTO(null, null, null, null, PODLIPNIG);
SearchInputDTO searchQuery =
new SearchInputDTO(null, searchMetadata, null, null, null, 0);
SearchResultsDTO searchResultPage =
searchService.searchResultPage(searchQuery, 0, SearchInputDTO.PAGE_SIZE);
org.junit.Assert.assertNotNull(searchResultPage.getSearchResult());
org.junit.Assert.assertTrue("At least one test hit", searchResultPage.getHitCount() >= 1);
org.junit.Assert.assertThat(searchResultPage.getSearchResult(), everyItem(
hasProperty("creator", hasProperty("name", containsString(PODLIPNIG))))
);
}
@Test
public void testProgrammingLanguageSearch() throws Exception {
final SearchInputMetadataDTO searchMetadata =
new SearchInputMetadataDTO("JAVA", null, null, null, null);
SearchInputDTO searchQuery =
new SearchInputDTO(null, searchMetadata, null, null, null, 0);
SearchResultsDTO searchResultPage =
searchService.searchResultPage(searchQuery, 0, SearchInputDTO.PAGE_SIZE);
assertNotNull(searchResultPage.getSearchResult());
assertTrue("At least one test hit", searchResultPage.getHitCount() >= 1);
assertThat(searchResultPage.getSearchResult(), everyItem(
hasProperty("programmingLanguage",
hasItemInArray(containsString("JAVA")))
));
}
@Test
public void testCreatorSearch() throws IOException {
final SearchInputMetadataDTO searchMetadata =
new SearchInputMetadataDTO(null, null, null, null, "Podlipnig");
SearchInputDTO searchQuery =
new SearchInputDTO(null, searchMetadata, null, null, null, 0);
SearchResultsDTO searchResultPage =
searchService.searchResultPage(searchQuery, 0, SearchInputDTO.PAGE_SIZE);
org.junit.Assert.assertNotNull(searchResultPage.getSearchResult());
org.junit.Assert.assertTrue("At least one test hit", searchResultPage.getHitCount() >= 1);
assertThat(searchResultPage.getSearchResult(), everyItem(
hasProperty("creator", hasItemInArray(hasProperty("name", containsString("Podlipnig"))))
));
}
@Test
public void testKeywordSearch() throws IOException {
final SearchInputMetadataDTO searchMetadata =
new SearchInputMetadataDTO(null, "latex", null, null, null);
SearchInputDTO searchQuery =
new SearchInputDTO(null, searchMetadata, null, null, null, 0);
SearchResultsDTO searchResultPage =
searchService.searchResultPage(searchQuery, 0, SearchInputDTO.PAGE_SIZE);
org.junit.Assert.assertNotNull(searchResultPage.getSearchResult());
org.junit.Assert.assertTrue("At least one test hit", searchResultPage.getHitCount() >= 1);
assertThat(searchResultPage.getSearchResult(), everyItem(
hasProperty("keyword", hasItemInArray(containsString("latex")))
));
}
@Test
public void testLicenseSearch() throws IOException {
final SearchInputMetadataDTO searchMetadata =
new SearchInputMetadataDTO(null, null, null, "MIT", null);
SearchInputDTO searchQuery =
new SearchInputDTO(null, searchMetadata, null, null, null, 0);
SearchResultsDTO searchResultPage =
searchService.searchResultPage(searchQuery, 0, SearchInputDTO.PAGE_SIZE);
org.junit.Assert.assertNotNull(searchResultPage.getSearchResult());
org.junit.Assert.assertTrue("At least one test hit", searchResultPage.getHitCount() >= 1);
assertThat(searchResultPage.getSearchResult(), everyItem(
hasProperty("license", containsString("MIT"))
));
}
private static final Logger LOGGER = LoggerFactory.getLogger(SearchServiceIT.class);
@Autowired
private SearchService searchService;
@BeforeAll
public static void setUpESServer() throws IOException, NodeValidationException {
ElasticSearchTestServerConfiguration.getTestInstance().startTestNode();
}
@Test
public void testAllSearch() throws Exception {
final SearchInputMetadataDTO searchMetadata = new SearchInputMetadataDTO(null, null, null, null, null);
SearchInputDTO searchQuery = new SearchInputDTO(null, searchMetadata, null, null, null, 0);
SearchResultsDTO searchResultPage = searchService.searchResultPage(searchQuery, 0, SearchInputDTO.PAGE_SIZE);
LOGGER.info("found {} hits", searchResultPage.getHitCount());
}
@Test
public void testFullTextSearch() throws Exception {
LOGGER.info("starting testFullTextSearch");
final String WIEN = "Wien";
final SearchInputMetadataDTO searchMetadata = new SearchInputMetadataDTO(null, null, null, null, null);
SearchInputDTO searchQuery = new SearchInputDTO(WIEN, searchMetadata, null, null, null, 0);
SearchResultsDTO searchResultPage = searchService.searchResultPage(searchQuery, 0, SearchInputDTO.PAGE_SIZE);
org.junit.Assert.assertNotNull(searchResultPage.getSearchResult());
org.junit.Assert.assertTrue("At least one test hit", searchResultPage.getHitCount() >= 1);
org.junit.Assert.assertThat(searchResultPage.getSearchResult(),
everyItem(anyOf(hasProperty("metadata", hasProperty("description", containsString(WIEN))),
hasProperty("metadata", hasProperty("title", containsString(WIEN)))
// hasProperty("keywords", containsString("Wien"))
)));
LOGGER.info("exiting testFullTextSearch");
}
@Test
public void testSearchByAutor() throws Exception {
final String PODLIPNIG = "Stefan Podlipnig";
final SearchInputMetadataDTO searchMetadata = new SearchInputMetadataDTO(null, null, null, null, PODLIPNIG);
SearchInputDTO searchQuery = new SearchInputDTO(null, searchMetadata, null, null, null, 0);
SearchResultsDTO searchResultPage = searchService.searchResultPage(searchQuery, 0, SearchInputDTO.PAGE_SIZE);
org.junit.Assert.assertNotNull(searchResultPage.getSearchResult());
org.junit.Assert.assertTrue("At least one test hit", searchResultPage.getHitCount() >= 1);
org.junit.Assert.assertThat(searchResultPage.getSearchResult(), everyItem(
hasProperty("metadata", hasProperty("creator", hasItemInArray(hasProperty("name", containsString(PODLIPNIG)))))));
}
@Test
public void testProgrammingLanguageSearch() throws Exception {
final SearchInputMetadataDTO searchMetadata = new SearchInputMetadataDTO("JAVA", null, null, null, null);
SearchInputDTO searchQuery = new SearchInputDTO(null, searchMetadata, null, null, null, 0);
SearchResultsDTO searchResultPage = searchService.searchResultPage(searchQuery, 0, SearchInputDTO.PAGE_SIZE);
assertNotNull(searchResultPage.getSearchResult());
assertTrue("At least one test hit", searchResultPage.getHitCount() >= 1);
assertThat(searchResultPage.getSearchResult(), everyItem(
hasProperty("metadata", hasProperty("programmingLanguage", hasItemInArray(containsString("Java"))))));
}
@Test
public void testCreatorSearch() throws IOException {
final SearchInputMetadataDTO searchMetadata = new SearchInputMetadataDTO(null, null, null, null, "Podlipnig");
SearchInputDTO searchQuery = new SearchInputDTO(null, searchMetadata, null, null, null, 0);
SearchResultsDTO searchResultPage = searchService.searchResultPage(searchQuery, 0, SearchInputDTO.PAGE_SIZE);
org.junit.Assert.assertNotNull(searchResultPage.getSearchResult());
org.junit.Assert.assertTrue("At least one test hit", searchResultPage.getHitCount() >= 1);
assertThat(searchResultPage.getSearchResult(), everyItem(hasProperty("metadata",
hasProperty("creator", hasItemInArray(hasProperty("name", containsString("Podlipnig")))))));
}
@Test
public void testKeywordSearch() throws IOException {
final SearchInputMetadataDTO searchMetadata = new SearchInputMetadataDTO(null, "latex", null, null, null);
SearchInputDTO searchQuery = new SearchInputDTO(null, searchMetadata, null, null, null, 0);
SearchResultsDTO searchResultPage = searchService.searchResultPage(searchQuery, 0, SearchInputDTO.PAGE_SIZE);
org.junit.Assert.assertNotNull(searchResultPage.getSearchResult());
org.junit.Assert.assertTrue("At least one test hit", searchResultPage.getHitCount() >= 1);
assertThat(searchResultPage.getSearchResult(),
everyItem(hasProperty("metadata", hasProperty("keyword", hasItemInArray(containsString("latex"))))));
}
@Test()
@Ignore() // Test funktioniert momentan nicht?
public void testLicenseSearch() throws IOException {
final SearchInputMetadataDTO searchMetadata = new SearchInputMetadataDTO(null, null, null, "MIT", null);
SearchInputDTO searchQuery = new SearchInputDTO(null, searchMetadata, null, null, null, 0);
SearchResultsDTO searchResultPage = searchService.searchResultPage(searchQuery, 0, SearchInputDTO.PAGE_SIZE);
org.junit.Assert.assertNotNull(searchResultPage.getSearchResult());
org.junit.Assert.assertTrue("At least one test hit", searchResultPage.getHitCount() >= 1);
assertThat(searchResultPage.getSearchResult(),
everyItem(hasProperty("metadata", hasProperty("license", containsString("MIT")))));
}
}
......@@ -17,17 +17,18 @@ import at.ac.uibk.gitsearch.GitsearchApp;
@SpringBootTest(classes = GitsearchApp.class)
public class ShoppingBasketServiceIT {
private static final String TEST_ZIP_LOCATION = "at/ac/uibk/gitsearch/service/testData/junit-quality-tests-exercise-master.zip";
private static final String TEST_ZIP_LOCATION = "./testData/junit-quality-tests-exercise-master.zip";
@Autowired
protected ShoppingBasketService shoppingBasketService;
private final Logger log = LoggerFactory.getLogger(ShoppingBasketServiceIT.class);
private static final Logger log = LoggerFactory.getLogger(ShoppingBasketServiceIT.class);
@Test
public void testRepackage() throws IOException {
final InputStream resourceStream = this.getClass().getClassLoader().getResourceAsStream(TEST_ZIP_LOCATION);
final InputStream resourceStream = this.getClass().getResourceAsStream(TEST_ZIP_LOCATION);
Assert.assertNotNull("cannot find resource at " + TEST_ZIP_LOCATION, resourceStream);
final ZipInputStream testZip = new ZipInputStream(resourceStream);
final InputStream testRepackagedZipIS = shoppingBasketService.rePackageGitLabProjectZip(testZip, "from " + TEST_ZIP_LOCATION);
......
File suppressed by a .gitattributes entry or the file's encoding is unsupported.
# move to test directory later.
metadataVersion: 0.2
type: programming exercise
# format (not used here)
identifier: simpleIO
structure: atomic # one from atomic, networked, hierarchical, linear
version: "1.0" # just a version tag
status: final # one fo draft, final, revised, unavalable
title: Simple IO Test
description: This is a programming exercise to demonstrate a simple IO testing framework.
programmingLanguage: [JAVA]
language: [de]
educationLevel: "high school" # just for demonstration
"audience": {
"@type": "EducationalAudience",
"educationalRole": "student"
}
timeRequired: 0:05:00 # [hh:mm:ss]
keyword: [Java, IOTest, artemis]
license: CC-SA-BY 4.0 # mandatory
creator:
- {name: "Breu Michael", affiliation: "University of Innsbruck", email: "c703257@uibk.ac.at"}
publisher:
- {name: "Breu Michael", affiliation: "University of Innsbruck", email: "c703257@uibk.ac.at"}
deprecated: false
difficulty: simple
source:
- "cf. cunit"
contributor:
- {name: "Manuel Seywald", affiliation: "University of Klagenfurt", email: "maseywald@edu.aau.at"}
requires: [] # empty, t.b.d. later
image: 'https://sharing-codeability.uibk.ac.at/static/CodeAbility%20Austria-Dateien/Partner_UIBK.png'
# move to test directory later.
metadataVersion: "0.2"
type: collection
identifier: javaCourseTUWienTest
structure: hierarchical # one from atomic, networked, hierarchical, linear
version: "1.0" # just a version tag
status: final # one fo draft, final, revised, unavalable
title: Java Einführungskurs der TU Wien (Test)
description: Dies sind Teile des Einfhrungskurses an der TU Wien. Momentan hier genutzt zum Testen der Metadateninfrastruktur.
programmingLanguage:
- JAVA
language: [de]
educationLevel: "Anfänger, (to be detailed)"
audience: "Anfänger"
keyword: [Java, IOTest, latex]
license: MIT # mandatory
creator:
- {name: "Stefan Podlipnig", affiliation: "TU Wien", email: "stefan.podlipnig@tuwien.ac.at"}
contributor:
- {name: "Daniel Bastta", affiliation: "TU Wien", email: "daniel.bastta@tuwien.ac.at"}
- {name: "Andreas Merckel", affiliation: "TU Wien", email: "andreas.merkel@tuwien.ac.at"}
- {name: "Kerstin Limbeck", affiliation: "TU Wien", email: "kerstin.limbeck@tuwien.ac.at"}
publisher:
- {name: "Andreas Merckel", affiliation: "TU Wien", email: "andreas.merkel@tuwien.ac.at"}
format: [latex]
deprecated: false
difficulty: EASY
requires: [Java14]
image: 'https://sharing-codeability.uibk.ac.at/static/CodeAbility%20Austria-Dateien/Partner_UIBK.png'
......@@ -2,6 +2,8 @@ package at.ac.uibk.gitsearch.web.rest;
import static at.ac.uibk.gitsearch.web.rest.AccountResourceIT.TEST_USER_LOGIN;
import static org.assertj.core.api.Assertions.assertThat;
import static org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestPostProcessors.csrf;
import static org.springframework.security.test.web.servlet.setup.SecurityMockMvcConfigurers.springSecurity;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content;
......@@ -15,6 +17,7 @@ import java.util.Optional;
import java.util.Set;
import org.apache.commons.lang3.RandomStringUtils;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
......@@ -23,7 +26,9 @@ import org.springframework.http.MediaType;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.test.context.support.WithMockUser;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.context.WebApplicationContext;
import at.ac.uibk.gitsearch.GitsearchApp;
import at.ac.uibk.gitsearch.config.Constants;
......@@ -36,7 +41,6 @@ import at.ac.uibk.gitsearch.service.dto.PasswordChangeDTO;
import at.ac.uibk.gitsearch.service.dto.UserDTO;
import at.ac.uibk.gitsearch.web.rest.vm.KeyAndPasswordVM;
import at.ac.uibk.gitsearch.web.rest.vm.ManagedUserVM;
/**
* Integration tests for the {@link AccountResource} REST controller.
*/
......@@ -44,7 +48,11 @@ import at.ac.uibk.gitsearch.web.rest.vm.ManagedUserVM;
@WithMockUser(value = TEST_USER_LOGIN)
@SpringBootTest(classes = GitsearchApp.class)
public class AccountResourceIT {
static final String TEST_USER_LOGIN = "test";
public static final String TEST_USER_LOGIN = "test";
@Autowired
private WebApplicationContext context;
@Autowired
private UserRepository userRepository;
......@@ -58,13 +66,23 @@ public class AccountResourceIT {
@Autowired
private PasswordEncoder passwordEncoder;
@Autowired
// @Autowired
private MockMvc restAccountMockMvc;
@BeforeEach
public void setup() {
restAccountMockMvc = MockMvcBuilders
.webAppContextSetup(context)
.apply(springSecurity())
// .apply(ConfigurableReactiveWebServerFactory()f)
.build();
}
@Test
@WithUnauthenticatedMockUser
public void testNonAuthenticatedUser() throws Exception {
restAccountMockMvc.perform(get("/api/authenticate")
.with(csrf().asHeader())
.accept(MediaType.APPLICATION_JSON))
.andExpect(status().isOk())
.andExpect(content().string(""));
......@@ -73,6 +91,7 @@ public class AccountResourceIT {
@Test
public void testAuthenticatedUser() throws Exception {
restAccountMockMvc.perform(get("/api/authenticate")
.with(csrf().asHeader())
.with(request -> {
request.setRemoteUser(TEST_USER_LOGIN);
return request;
......@@ -98,6 +117,7 @@ public class AccountResourceIT {
userService.createUser(user);
restAccountMockMvc.perform(get("/api/account")
.with(csrf().asHeader())
.accept(MediaType.APPLICATION_JSON))
.andExpect(status().isOk())
.andExpect(content().contentType(MediaType.APPLICATION_JSON_VALUE))
......@@ -113,11 +133,12 @@ public class AccountResourceIT {
@Test
public void testGetUnknownAccount() throws Exception {
restAccountMockMvc.perform(get("/api/account")
.with(csrf().asHeader())
.accept(MediaType.APPLICATION_PROBLEM_JSON))
.andExpect(status().isInternalServerError());
}
@Test
// @Test Self-Registration is not supported any more
@Transactional
public void testRegisterValid() throws Exception {
ManagedUserVM validUser = new ManagedUserVM();
......@@ -133,6 +154,7 @@ public class AccountResourceIT {
restAccountMockMvc.perform(
post("/api/register")
.with(csrf().asHeader())
.contentType(MediaType.APPLICATION_JSON)
.content(TestUtil.convertObjectToJsonBytes(validUser)))
.andExpect(status().isCreated());
......@@ -140,7 +162,31 @@ public class AccountResourceIT {
assertThat(userRepository.findOneByLogin("test-register-valid").isPresent()).isTrue();
}
@Test
@Test
@Transactional
public void testRegisterDisabled() throws Exception {
ManagedUserVM validUser = new ManagedUserVM();
validUser.setLogin("test-register-valid");
validUser.setPassword("password");
validUser.setFirstName("Alice");
validUser.setLastName("Test");
validUser.setEmail("test-register-valid@example.com");
validUser.setImageUrl("http://placehold.it/50x50");
validUser.setLangKey(Constants.DEFAULT_LANGUAGE);
validUser.setAuthorities(Collections.singleton(AuthoritiesConstants.USER));
assertThat(userRepository.findOneByLogin("test-register-valid").isPresent()).isFalse();
restAccountMockMvc.perform(
post("/api/register")
.with(csrf().asHeader())
.contentType(MediaType.APPLICATION_JSON)
.content(TestUtil.convertObjectToJsonBytes(validUser)))
.andExpect(status().isForbidden());
// assertThat(userRepository.findOneByLogin("test-register-valid").isPresent()).isTrue();
}
// @Test Self-Registration is not supported any more
@Transactional
public void testRegisterInvalidLogin() throws Exception {
ManagedUserVM invalidUser = new ManagedUserVM();
......@@ -156,6 +202,7 @@ public class AccountResourceIT {
restAccountMockMvc.perform(
post("/api/register")
.with(csrf().asHeader())
.contentType(MediaType.APPLICATION_JSON)
.content(TestUtil.convertObjectToJsonBytes(invalidUser)))
.andExpect(status().isBadRequest());
......@@ -164,7 +211,7 @@ public class AccountResourceIT {
assertThat(user.isPresent()).isFalse();
}
@Test
// @Test Self-Registration is not supported any more
@Transactional
public void testRegisterInvalidEmail() throws Exception {
ManagedUserVM invalidUser = new ManagedUserVM();
......@@ -180,6 +227,7 @@ public class AccountResourceIT {
restAccountMockMvc.perform(
post("/api/register")
.with(csrf().asHeader())
.contentType(MediaType.APPLICATION_JSON)
.content(TestUtil.convertObjectToJsonBytes(invalidUser)))
.andExpect(status().isBadRequest());
......@@ -188,7 +236,7 @@ public class AccountResourceIT {
assertThat(user.isPresent()).isFalse();
}
@Test
// @Test Self-Registration is not supported any more
@Transactional
public void testRegisterInvalidPassword() throws Exception {
ManagedUserVM invalidUser = new ManagedUserVM();
......@@ -204,6 +252,7 @@ public class AccountResourceIT {
restAccountMockMvc.perform(
post("/api/register")
.with(csrf().asHeader())
.contentType(MediaType.APPLICATION_JSON)
.content(TestUtil.convertObjectToJsonBytes(invalidUser)))
.andExpect(status().isBadRequest());
......@@ -212,7 +261,7 @@ public class AccountResourceIT {
assertThat(user.isPresent()).isFalse();
}
@Test
// @Test Self-Registration is not supported any more
@Transactional
public void testRegisterNullPassword() throws Exception {
ManagedUserVM invalidUser = new ManagedUserVM();
......@@ -228,6 +277,7 @@ public class AccountResourceIT {
restAccountMockMvc.perform(
post("/api/register")
.with(csrf().asHeader())
.contentType(MediaType.APPLICATION_JSON)
.content(TestUtil.convertObjectToJsonBytes(invalidUser)))
.andExpect(status().isBadRequest());
......@@ -236,7 +286,7 @@ public class AccountResourceIT {
assertThat(user.isPresent()).isFalse();
}
@Test
// @Test Self-Registration is not supported any more
@Transactional
public void testRegisterDuplicateLogin() throws Exception {
// First registration
......@@ -268,6 +318,7 @@ public class AccountResourceIT {
// First user
restAccountMockMvc.perform(
post("/api/register")
.with(csrf().asHeader())
.contentType(MediaType.APPLICATION_JSON)
.content(TestUtil.convertObjectToJsonBytes(firstUser)))
.andExpect(status().isCreated());
......@@ -292,7 +343,7 @@ public class AccountResourceIT {
.andExpect(status().is4xxClientError());
}
@Test
// @Test Self-Registration is not supported any more
@Transactional
public void testRegisterDuplicateEmail() throws Exception {
// First user
......@@ -309,6 +360,7 @@ public class AccountResourceIT {
// Register first user
restAccountMockMvc.perform(
post("/api/register")
.with(csrf().asHeader())
.contentType(MediaType.APPLICATION_JSON)
.content(TestUtil.convertObjectToJsonBytes(firstUser)))
.andExpect(status().isCreated());
......@@ -330,6 +382,7 @@ public class AccountResourceIT {
// Register second (non activated) user
restAccountMockMvc.perform(
post("/api/register")
.with(csrf().asHeader())
.contentType(MediaType.APPLICATION_JSON)
.content(TestUtil.convertObjectToJsonBytes(secondUser)))
.andExpect(status().isCreated());
......@@ -355,6 +408,7 @@ public class AccountResourceIT {
// Register third (not activated) user
restAccountMockMvc.perform(
post("/api/register")
.with(csrf().asHeader())
.contentType(MediaType.APPLICATION_JSON)
.content(TestUtil.convertObjectToJsonBytes(userWithUpperCaseEmail)))
.andExpect(status().isCreated());
......@@ -369,12 +423,13 @@ public class AccountResourceIT {
// Register 4th (already activated) user
restAccountMockMvc.perform(
post("/api/register")
.with(csrf().asHeader())
.contentType(MediaType.APPLICATION_JSON)
.content(TestUtil.convertObjectToJsonBytes(secondUser)))
.andExpect(status().is4xxClientError());
}
@Test
// @Test Self-Registration is not supported any more
@Transactional
public void testRegisterAdminIsIgnored() throws Exception {
ManagedUserVM validUser = new ManagedUserVM();
......@@ -390,6 +445,7 @@ public class AccountResourceIT {
restAccountMockMvc.perform(
post("/api/register")
.with(csrf().asHeader())
.contentType(MediaType.APPLICATION_JSON)
.content(TestUtil.convertObjectToJsonBytes(validUser)))
.andExpect(status().isCreated());
......@@ -413,7 +469,8 @@ public class AccountResourceIT {
userRepository.saveAndFlush(user);
restAccountMockMvc.perform(get("/api/activate?key={activationKey}", activationKey))
restAccountMockMvc.perform(get("/api/activate?key={activationKey}", activationKey)
.with(csrf().asHeader()))
.andExpect(status().isOk());
user = userRepository.findOneByLogin(user.getLogin()).orElse(null);
......@@ -450,6 +507,7 @@ public class AccountResourceIT {
restAccountMockMvc.perform(
post("/api/account")
.with(csrf().asHeader())
.contentType(MediaType.APPLICATION_JSON)
.content(TestUtil.convertObjectToJsonBytes(userDTO)))
.andExpect(status().isOk());
......@@ -489,6 +547,7 @@ public class AccountResourceIT {
restAccountMockMvc.perform(
post("/api/account")
.with(csrf().asHeader())
.contentType(MediaType.APPLICATION_JSON)
.content(TestUtil.convertObjectToJsonBytes(userDTO)))
.andExpect(status().isBadRequest());
......@@ -527,6 +586,7 @@ public class AccountResourceIT {
restAccountMockMvc.perform(
post("/api/account")
.with(csrf().asHeader())
.contentType(MediaType.APPLICATION_JSON)
.content(TestUtil.convertObjectToJsonBytes(userDTO)))
.andExpect(status().isBadRequest());
......@@ -558,6 +618,7 @@ public class AccountResourceIT {
restAccountMockMvc.perform(
post("/api/account")
.with(csrf().asHeader())
.contentType(MediaType.APPLICATION_JSON)
.content(TestUtil.convertObjectToJsonBytes(userDTO)))
.andExpect(status().isOk());
......@@ -578,6 +639,7 @@ public class AccountResourceIT {
userRepository.saveAndFlush(user);
restAccountMockMvc.perform(post("/api/account/change-password")
.with(csrf().asHeader())
.contentType(MediaType.APPLICATION_JSON)
.content(TestUtil.convertObjectToJsonBytes(new PasswordChangeDTO("1"+currentPassword, "new password")))
)
......@@ -600,6 +662,7 @@ public class AccountResourceIT {
userRepository.saveAndFlush(user);
restAccountMockMvc.perform(post("/api/account/change-password")
.with(csrf().asHeader())
.contentType(MediaType.APPLICATION_JSON)
.content(TestUtil.convertObjectToJsonBytes(new PasswordChangeDTO(currentPassword, "new password")))
)
......@@ -623,6 +686,7 @@ public class AccountResourceIT {
String newPassword = RandomStringUtils.random(ManagedUserVM.PASSWORD_MIN_LENGTH - 1);
restAccountMockMvc.perform(post("/api/account/change-password")
.with(csrf().asHeader())
.contentType(MediaType.APPLICATION_JSON)
.content(TestUtil.convertObjectToJsonBytes(new PasswordChangeDTO(currentPassword, newPassword)))
)
......@@ -646,6 +710,7 @@ public class AccountResourceIT {
String newPassword = RandomStringUtils.random(ManagedUserVM.PASSWORD_MAX_LENGTH + 1);
restAccountMockMvc.perform(post("/api/account/change-password")
.with(csrf().asHeader())
.contentType(MediaType.APPLICATION_JSON)
.content(TestUtil.convertObjectToJsonBytes(new PasswordChangeDTO(currentPassword, newPassword)))
)
......@@ -667,6 +732,7 @@ public class AccountResourceIT {
userRepository.saveAndFlush(user);
restAccountMockMvc.perform(post("/api/account/change-password")
.with(csrf().asHeader())
.contentType(MediaType.APPLICATION_JSON)
.content(TestUtil.convertObjectToJsonBytes(new PasswordChangeDTO(currentPassword, "")))
)
......@@ -687,9 +753,9 @@ public class AccountResourceIT {
userRepository.saveAndFlush(user);
restAccountMockMvc.perform(post("/api/account/reset-password/init")
.content("password-reset@example.com")
)
.andExpect(status().isOk());
.with(csrf().asHeader())
.content("password-reset@example.com"))
.andExpect(status().isOk());
}
@Test
......@@ -703,6 +769,7 @@ public class AccountResourceIT {
userRepository.saveAndFlush(user);
restAccountMockMvc.perform(post("/api/account/reset-password/init")
.with(csrf().asHeader())
.content("password-reset-upper-case@EXAMPLE.COM")
)
.andExpect(status().isOk());
......@@ -712,6 +779,7 @@ public class AccountResourceIT {
public void testRequestPasswordResetWrongEmail() throws Exception {
restAccountMockMvc.perform(
post("/api/account/reset-password/init")
.with(csrf().asHeader())
.content("password-reset-wrong-email@example.com"))
.andExpect(status().isOk());
}
......@@ -733,6 +801,7 @@ public class AccountResourceIT {
restAccountMockMvc.perform(
post("/api/account/reset-password/finish")
.with(csrf().asHeader())
.contentType(MediaType.APPLICATION_JSON)
.content(TestUtil.convertObjectToJsonBytes(keyAndPassword)))
.andExpect(status().isOk());
......@@ -758,6 +827,7 @@ public class AccountResourceIT {
restAccountMockMvc.perform(
post("/api/account/reset-password/finish")
.with(csrf().asHeader())
.contentType(MediaType.APPLICATION_JSON)
.content(TestUtil.convertObjectToJsonBytes(keyAndPassword)))
.andExpect(status().isBadRequest());
......@@ -775,6 +845,7 @@ public class AccountResourceIT {
restAccountMockMvc.perform(
post("/api/account/reset-password/finish")
.with(csrf().asHeader())
.contentType(MediaType.APPLICATION_JSON)
.content(TestUtil.convertObjectToJsonBytes(keyAndPassword)))
.andExpect(status().isInternalServerError());
......
......@@ -4,6 +4,7 @@ import static org.hamcrest.Matchers.emptyString;
import static org.hamcrest.Matchers.is;
import static org.hamcrest.Matchers.not;
import static org.hamcrest.Matchers.nullValue;
import static org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestPostProcessors.csrf;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.header;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath;
......@@ -54,6 +55,7 @@ public class UserJWTControllerIT {
login.setUsername("user-jwt-controller");
login.setPassword("test");
mockMvc.perform(post("/api/authenticate")
.with(csrf().asHeader())
.contentType(MediaType.APPLICATION_JSON)
.content(TestUtil.convertObjectToJsonBytes(login)))
.andExpect(status().isOk())
......@@ -79,6 +81,7 @@ public class UserJWTControllerIT {
login.setPassword("test");
login.setRememberMe(true);
mockMvc.perform(post("/api/authenticate")
.with(csrf().asHeader())
.contentType(MediaType.APPLICATION_JSON)
.content(TestUtil.convertObjectToJsonBytes(login)))
.andExpect(status().isOk())
......@@ -94,6 +97,7 @@ public class UserJWTControllerIT {
login.setUsername("wrong-user");
login.setPassword("wrong password");
mockMvc.perform(post("/api/authenticate")
.with(csrf().asHeader())
.contentType(MediaType.APPLICATION_JSON)
.content(TestUtil.convertObjectToJsonBytes(login)))
.andExpect(status().isUnauthorized())
......
......@@ -29,6 +29,7 @@ import java.util.function.Consumer;
import static org.assertj.core.api.Assertions.assertThat;
import static org.hamcrest.Matchers.hasItems;
import static org.hamcrest.Matchers.hasItem;
import static org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestPostProcessors.csrf;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*;
......@@ -138,6 +139,7 @@ public class UserResourceIT {
managedUserVM.setAuthorities(Collections.singleton(AuthoritiesConstants.USER));
restUserMockMvc.perform(post("/api/users")
.with(csrf().asHeader())
.contentType(MediaType.APPLICATION_JSON)
.content(TestUtil.convertObjectToJsonBytes(managedUserVM)))
.andExpect(status().isCreated());
......@@ -174,6 +176,7 @@ public class UserResourceIT {
// An entity with an existing ID cannot be created, so this API call must fail
restUserMockMvc.perform(post("/api/users")
.with(csrf().asHeader())
.contentType(MediaType.APPLICATION_JSON)
.content(TestUtil.convertObjectToJsonBytes(managedUserVM)))
.andExpect(status().isBadRequest());
......@@ -203,6 +206,7 @@ public class UserResourceIT {
// Create the User
restUserMockMvc.perform(post("/api/users")
.with(csrf().asHeader())
.contentType(MediaType.APPLICATION_JSON)
.content(TestUtil.convertObjectToJsonBytes(managedUserVM)))
.andExpect(status().isBadRequest());
......@@ -232,6 +236,7 @@ public class UserResourceIT {
// Create the User
restUserMockMvc.perform(post("/api/users")
.with(csrf().asHeader())
.contentType(MediaType.APPLICATION_JSON)
.content(TestUtil.convertObjectToJsonBytes(managedUserVM)))
.andExpect(status().isBadRequest());
......@@ -316,6 +321,7 @@ public class UserResourceIT {
managedUserVM.setAuthorities(Collections.singleton(AuthoritiesConstants.USER));
restUserMockMvc.perform(put("/api/users")
.with(csrf().asHeader())
.contentType(MediaType.APPLICATION_JSON)
.content(TestUtil.convertObjectToJsonBytes(managedUserVM)))
.andExpect(status().isOk());
......@@ -359,6 +365,7 @@ public class UserResourceIT {
managedUserVM.setAuthorities(Collections.singleton(AuthoritiesConstants.USER));
restUserMockMvc.perform(put("/api/users")
.with(csrf().asHeader())
.contentType(MediaType.APPLICATION_JSON)
.content(TestUtil.convertObjectToJsonBytes(managedUserVM)))
.andExpect(status().isOk());
......@@ -415,6 +422,7 @@ public class UserResourceIT {
managedUserVM.setAuthorities(Collections.singleton(AuthoritiesConstants.USER));
restUserMockMvc.perform(put("/api/users")
.with(csrf().asHeader())
.contentType(MediaType.APPLICATION_JSON)
.content(TestUtil.convertObjectToJsonBytes(managedUserVM)))
.andExpect(status().isBadRequest());
......@@ -459,6 +467,7 @@ public class UserResourceIT {
managedUserVM.setAuthorities(Collections.singleton(AuthoritiesConstants.USER));
restUserMockMvc.perform(put("/api/users")
.with(csrf().asHeader())
.contentType(MediaType.APPLICATION_JSON)
.content(TestUtil.convertObjectToJsonBytes(managedUserVM)))
.andExpect(status().isBadRequest());
......@@ -473,6 +482,7 @@ public class UserResourceIT {
// Delete the user
restUserMockMvc.perform(delete("/api/users/{login}", user.getLogin())
.with(csrf().asHeader())
.accept(MediaType.APPLICATION_JSON))
.andExpect(status().isNoContent());
......@@ -486,6 +496,7 @@ public class UserResourceIT {
@Transactional
public void getAllAuthorities() throws Exception {
restUserMockMvc.perform(get("/api/users/authorities")
.with(csrf().asHeader())
.accept(MediaType.APPLICATION_JSON)
.contentType(MediaType.APPLICATION_JSON))
.andExpect(status().isOk())
......
......@@ -9,6 +9,7 @@ import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMock
import org.springframework.http.MediaType;
import org.springframework.test.web.servlet.MockMvc;
import static org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestPostProcessors.csrf;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content;
......@@ -36,7 +37,9 @@ public class ExceptionTranslatorIT {
@Test
public void testMethodArgumentNotValid() throws Exception {
mockMvc.perform(post("/api/exception-translator-test/method-argument").content("{}").contentType(MediaType.APPLICATION_JSON))
mockMvc.perform(post("/api/exception-translator-test/method-argument")
.with(csrf().asHeader())
.content("{}").contentType(MediaType.APPLICATION_JSON))
.andExpect(status().isBadRequest())
.andExpect(content().contentType(MediaType.APPLICATION_PROBLEM_JSON))
.andExpect(jsonPath("$.message").value(ErrorConstants.ERR_VALIDATION))
......@@ -82,7 +85,8 @@ public class ExceptionTranslatorIT {
@Test
public void testMethodNotSupported() throws Exception {
mockMvc.perform(post("/api/exception-translator-test/access-denied"))
mockMvc.perform(post("/api/exception-translator-test/access-denied")
.with(csrf().asHeader()))
.andExpect(status().isMethodNotAllowed())
.andExpect(content().contentType(MediaType.APPLICATION_PROBLEM_JSON))
.andExpect(jsonPath("$.message").value("error.http.405"))
......
......@@ -52,6 +52,9 @@ spring:
properties:
path:
home: target/elasticsearch
elasticsearch:
rest:
uris: http://localhost:29200
liquibase:
contexts: test
mail:
......
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment