Commit 0d2accb1 authored by Alexander Prendetskiy's avatar Alexander Prendetskiy Committed by Matija Obreza

Merge catalog tests

parent 65e83758
......@@ -268,6 +268,13 @@
<version>${spring-data-jpa.version}</version>
</dependency>
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-test</artifactId>
<version>${spring.security.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>com.querydsl</groupId>
<artifactId>querydsl-jpa</artifactId>
......
......@@ -61,7 +61,7 @@ import io.swagger.annotations.Api;
public class DatasetController {
// Rest controller base URL
protected static final String CONTROLLER_URL = ApiBaseController.APIv0_BASE + "/dataset";
public static final String CONTROLLER_URL = ApiBaseController.APIv0_BASE + "/dataset";
private static final Logger LOG = LoggerFactory.getLogger(DatasetController.class);
......
......@@ -49,7 +49,7 @@ import java.util.UUID;
public class DatasetCreatorController {
/** The Constant API_BASE. */
protected static final String CONTROLLER_URL = DatasetController.CONTROLLER_URL + "/{UUID}/datasetcreator";
public static final String CONTROLLER_URL = DatasetController.CONTROLLER_URL + "/{UUID}/datasetcreator";
/** The dataset service. */
@Autowired
......
......@@ -41,7 +41,7 @@ import java.util.Map;
public class DescriptorListExporter {
@Autowired
private FreemarkerTemplating freemarker;
private FreemarkerTemplating freemarkerTemplating;
/** The Constant OPTIONS. */
/*@formatter:off*/
......@@ -75,7 +75,7 @@ public class DescriptorListExporter {
public String markdownDescriptorList(final DescriptorList descriptorList) throws FreemarkerException {
final Map<String, Object> root = new HashMap<>();
root.put("descriptorList", descriptorList);
return freemarker.processTemplateResource("descriptorlist/booklet.ftl", root);
return freemarkerTemplating.processTemplateResource("descriptorlist/booklet.ftl", root);
}
/**
......@@ -88,7 +88,7 @@ public class DescriptorListExporter {
public String htmlDescriptorList(final DescriptorList descriptorList) throws FreemarkerException {
final Map<String, Object> root = new HashMap<>();
root.put("descriptorList", descriptorList);
final String markdown = freemarker.processTemplateResource("descriptorlist/booklet.ftl", root);
final String markdown = freemarkerTemplating.processTemplateResource("descriptorlist/booklet.ftl", root);
// System.err.println(markdown);
final Parser parser = Parser.builder(OPTIONS).build();
......@@ -103,7 +103,7 @@ public class DescriptorListExporter {
root.put("author", StringUtils.defaultIfEmpty(descriptorList.getPublisher(), descriptorList.getOwner().getName()));
root.put("html", html);
return freemarker.processTemplateResource("html.ftl", root);
return freemarkerTemplating.processTemplateResource("html.ftl", root);
}
}
......@@ -79,7 +79,7 @@ public class DatasetServiceImpl implements DatasetService {
/** The file repo service. */
@Autowired
private RepositoryService fileRepoService;
private RepositoryService repositoryService;
@Autowired
private CustomAclService aclService;
......@@ -304,7 +304,7 @@ public class DatasetServiceImpl implements DatasetService {
InvalidRepositoryFileDataException {
dataset = datasetRepository.findByUuidAndVersion(dataset.getUuid(), dataset.getVersion());
final RepositoryFile repositoryFile = fileRepoService.addFile(Paths.get(datasetRepositoryPath, dataset.getUuid().toString()).toAbsolutePath().toString(), file
final RepositoryFile repositoryFile = repositoryService.addFile(Paths.get(datasetRepositoryPath, dataset.getUuid().toString()).toAbsolutePath().toString(), file
.getOriginalFilename(), file.getContentType(), file.getBytes(), null);
dataset.getRepositoryFiles().add(repositoryFile);
return lazyLoad(datasetRepository.save(dataset));
......@@ -320,7 +320,7 @@ public class DatasetServiceImpl implements DatasetService {
if (datasetFile == null) {
throw new NotFoundElement("No such dataset file");
}
final RepositoryFile updated = fileRepoService.updateMetadata(metadata);
final RepositoryFile updated = repositoryService.updateMetadata(metadata);
// replace it
dataset.getRepositoryFiles().replaceAll(df -> df.getUuid().equals(datasetFile.getUuid()) ? updated : df);
return lazyLoad(dataset);
......@@ -335,9 +335,9 @@ public class DatasetServiceImpl implements DatasetService {
public Dataset removeDatasetFile(Dataset dataset, final UUID fileUuid) throws NotFoundElement, NoSuchRepositoryFileException, IOException {
dataset = datasetRepository.findByUuidAndVersion(dataset.getUuid(), dataset.getVersion());
final RepositoryFile repositoryFile = fileRepoService.getFile(fileUuid);
final RepositoryFile repositoryFile = repositoryService.getFile(fileUuid);
dataset.getRepositoryFiles().remove(repositoryFile);
fileRepoService.removeFile(repositoryFile);
repositoryService.removeFile(repositoryFile);
return lazyLoad(datasetRepository.save(dataset));
}
......
/*
* Copyright 2017 Global Crop Diversity Trust
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.genesys.catalog.config;
import java.io.File;
import org.genesys.filerepository.service.BytesStorageService;
import org.genesys.filerepository.service.RepositoryService;
import org.genesys.filerepository.service.impl.FilesystemStorageServiceImpl;
import org.genesys.filerepository.service.impl.RepositoryServiceImpl;
import org.genesys2.server.service.audit.SpringSecurityAuditorAware;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.test.annotation.DirtiesContext;
/**
* Loads and configures the test application context. Application configuration
* is loaded from
*
* <ul>
* <li>application.properties</li>
* <li>genesys-catalog.properties</li>
* <li>genesys-catalog-core.properties</li>
* </ul>
*
* @author Matija Obreza
*/
@Configuration
@ComponentScan(basePackages = { "org.genesys.catalog.service", "org.genesys.blocks.security.service",
"org.genesys2.server.security", "org.genesys.blocks.auditlog.service" })
public class TestApplicationConfig {
@Bean
public PasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}
@Bean(name = "bytesStorageService")
public BytesStorageService bytesStorageService() {
final File repoDir = new File("data");
final FilesystemStorageServiceImpl storageService = new FilesystemStorageServiceImpl();
storageService.setRepositoryBaseDirectory(repoDir);
return storageService;
}
@Bean
public RepositoryService repositoryService() {
return new RepositoryServiceImpl();
}
@Bean
public SpringSecurityAuditorAware auditorAware() {
return new SpringSecurityAuditorAware();
}
}
/*
* Copyright 2017 Global Crop Diversity Trust
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.genesys.catalog.server.controller.api.v0;
import org.genesys.catalog.model.Partner;
import org.genesys.catalog.model.dataset.Dataset;
import org.genesys.catalog.model.traits.Descriptor;
import org.genesys.catalog.persistence.PartnerRepository;
import org.genesys.catalog.persistence.dataset.DatasetRepository;
import org.genesys.catalog.persistence.traits.DescriptorRepository;
import org.genesys.catalog.server.controller.rest.AbstractRestTest;
import org.genesys.catalog.service.DatasetService;
import org.junit.After;
import org.junit.Before;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import org.springframework.web.context.WebApplicationContext;
import java.util.HashSet;
import java.util.UUID;
import static org.springframework.restdocs.mockmvc.MockMvcRestDocumentation.documentationConfiguration;
public abstract class AbstractDatasetControllerTest extends AbstractRestTest {
@Autowired
private WebApplicationContext webApplicationContext;
@Autowired
protected DatasetRepository datasetRepository;
@Autowired
private PartnerRepository partnerRepository;
@Autowired
protected DescriptorRepository descriptorRepository;
@Autowired
protected DatasetService datasetService;
protected MockMvc mockMvc;
public AbstractDatasetControllerTest() {
super();
}
@Before
public void setUp() {
mockMvc = MockMvcBuilders.webAppContextSetup(webApplicationContext).apply(documentationConfiguration(restDocumentation).uris().withScheme("https").withHost(
"api.catalog.genesys-pgr.org").withPort(443)).build();
}
@After
@Override
public void cleanup() {
datasetRepository.deleteAll();
partnerRepository.deleteAll();
super.cleanup();
}
protected Dataset setUpDataset(final boolean published) {
return setupDataset("Test Dataset Title", "Test Dataset Description", setUpPartner("Partner", true, "PartnerShortName", UUID.randomUUID()), published);
}
protected Dataset setupDataset(final String title, final String description, final Partner owner, final boolean published) {
final Dataset input = new Dataset();
input.setTitle(title);
input.setDescription(description);
input.setOwner(owner);
// input.setAccessionIdentifiers(accessions);
input.setPublished(published);
return input;
}
protected Partner setUpPartner(final String name, final boolean isActive, final String shortName, final UUID uuid) {
final Partner partner = new Partner();
partner.setName(name);
partner.setActive(isActive);
partner.setShortName(shortName);
partner.setUuid(uuid);
partner.setWiewsCodes(new HashSet<>());
partner.setUrls(new HashSet<>());
return partnerRepository.save(partner);
}
protected Descriptor setUpDescriptor() {
final Descriptor descriptor = new Descriptor();
descriptor.setUuid(UUID.randomUUID());
descriptor.setCategory(Descriptor.Category.PASSPORT);
descriptor.setDataType(Descriptor.DataType.BOOLEAN);
descriptor.setTitle("Title");
descriptor.setVocabulary(null);
descriptor.setMinValue(null);
descriptor.setMaxValue(null);
descriptor.setVersionTag("1.0");
descriptor.setOwner(setUpPartner("NewPartner", true, "ShortName", UUID.randomUUID()));
descriptor.setCrop("banana");
descriptor.setPublished(true);
return descriptor;
}
}
\ No newline at end of file
/*
* Copyright 2017 Global Crop Diversity Trust
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.genesys.catalog.server.controller.api.v0;
import org.genesys.catalog.api.v0.DatasetCreatorController;
import org.genesys.catalog.model.dataset.Dataset;
import org.genesys.catalog.model.dataset.DatasetCreator;
import org.genesys.catalog.server.controller.rest.WithMockOAuth2Authentication;
import org.genesys.catalog.service.DatasetCreatorService;
import org.junit.After;
import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.restdocs.mockmvc.RestDocumentationRequestBuilders;
import org.springframework.security.test.context.support.WithMockUser;
import static org.hamcrest.Matchers.*;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*;
/**
* @author Andrey Lugovskoy.
*/
@WithMockUser(username = "user", password = "user", roles = "USER")
public class DatasetCreatorControllerTest extends AbstractDatasetControllerTest {
@Autowired
private DatasetCreatorService datasetCreatorService;
@After
@Override
public void cleanup() {
super.cleanup();
}
@Test
@WithMockOAuth2Authentication(roles = { "ADMINISTRATOR" }, scopes = { "write" })
public void listDatasetCreators() throws Exception {
final Dataset dataset = datasetService.createDataset(setUpDataset(false));
final DatasetCreator datasetCreator = buildDatasetCreator("TestFullName", "TestEmailName", "0673579007", dataset);
final DatasetCreator creator = datasetCreatorService.createDatasetCreator(dataset, datasetCreator);
/*@formatter:off*/
this.mockMvc.perform(RestDocumentationRequestBuilders.get(DatasetCreatorController.CONTROLLER_URL.concat("/list"), dataset.getUuid()))
// .andDo(MockMvcResultHandlers.print())
.andExpect(status().isOk())
.andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8))
.andExpect(jsonPath("$.content[0]", not(nullValue())))
.andExpect(jsonPath("$.content[0].id", is(creator.getId().intValue())));
/*@formatter:on*/
}
@Test
@WithMockOAuth2Authentication(roles = { "ADMINISTRATOR" }, scopes = { "write" })
public void loadByUuid() throws Exception {
final Dataset dataset = datasetService.createDataset(setUpDataset(true));
final DatasetCreator datasetCreator = buildDatasetCreator("TestFullName", "TestEmailName", "0673579007", dataset);
final DatasetCreator creator = datasetCreatorService.createDatasetCreator(dataset, datasetCreator);
/*@formatter:off*/
this.mockMvc.perform(RestDocumentationRequestBuilders.get(DatasetCreatorController.CONTROLLER_URL.concat("/{creatorUuid}"), dataset.getUuid(),
creator.getUuid()))
// .andDo(MockMvcResultHandlers.print())
.andExpect(status().isOk())
.andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8))
.andExpect(jsonPath("$", not(nullValue())))
.andExpect(jsonPath("$.id", is(creator.getId().intValue())));
/*@formatter:on*/
}
@Test
@WithMockOAuth2Authentication(roles = { "ADMINISTRATOR" }, scopes = { "write" })
public void createDatasetCreator() throws Exception {
final Dataset dataset = datasetService.createDataset(setUpDataset(false));
final DatasetCreator datasetCreator = buildDatasetCreator("TestFullName", "TestEmailName", "0673579007", dataset);
final String s = verboseMapper.writeValueAsString(datasetCreator);
/*@formatter:off*/
mockMvc.perform(RestDocumentationRequestBuilders.post(DatasetCreatorController.CONTROLLER_URL + "/create", dataset.getUuid())
.content(s)
.contentType(MediaType.APPLICATION_JSON)
.accept(MediaType.APPLICATION_JSON))
// .andDo(MockMvcResultHandlers.print())
.andExpect(status().isOk())
.andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8))
.andExpect(jsonPath("$", not(nullValue())))
.andExpect(jsonPath("$.fullName", equalTo(datasetCreator.getFullName())));
/*@formatter:on*/
}
@Test
@WithMockOAuth2Authentication(roles = { "ADMINISTRATOR" }, scopes = { "write" })
public void deleteDatasetCreator() throws Exception {
final Dataset dataset = datasetService.createDataset(setUpDataset(false));
final DatasetCreator datasetCreator = buildDatasetCreator("TestFullName", "TestEmailName", "0673579007", dataset);
final DatasetCreator creator = datasetCreatorService.createDatasetCreator(dataset, datasetCreator);
final String s = verboseMapper.writeValueAsString(creator);
/*@formatter:off*/
mockMvc.perform(RestDocumentationRequestBuilders.post(DatasetCreatorController.CONTROLLER_URL + "/delete",
dataset.getUuid(), creator.getUuid())
.content(s)
.contentType(MediaType.APPLICATION_JSON)
.accept(MediaType.APPLICATION_JSON))
// .andDo(MockMvcResultHandlers.print())
.andExpect(status().isOk());
/*@formatter:on*/
}
protected DatasetCreator buildDatasetCreator(final String fullName, final String email, final String phoneNumber, final Dataset dataset) {
final DatasetCreator datasetCreator = new DatasetCreator();
datasetCreator.setDataset(dataset);
datasetCreator.setFullName(fullName);
datasetCreator.setRole(DatasetCreator.DatasetCreatorRole.MANAGER);
datasetCreator.setEmail(email);
datasetCreator.setPhoneNumber(phoneNumber);
return datasetCreator;
}
}
/*
* Copyright 2017 Global Crop Diversity Trust
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.genesys.catalog.server.controller.api.v0;
import com.google.common.collect.Sets;
import org.genesys.blocks.model.filters.StringFilter;
import org.genesys.catalog.api.v0.PartnerController;
import org.genesys.catalog.model.Partner;
import org.genesys.catalog.model.filters.PartnerFilter;
import org.genesys.catalog.persistence.PartnerRepository;
import org.genesys.catalog.server.controller.rest.AbstractRestTest;
import org.junit.After;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.restdocs.mockmvc.RestDocumentationRequestBuilders;
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.web.context.WebApplicationContext;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.UUID;
import java.util.stream.Collectors;
import static org.hamcrest.Matchers.*;
import static org.junit.Assert.assertThat;
import static org.springframework.restdocs.mockmvc.MockMvcRestDocumentation.document;
import static org.springframework.restdocs.mockmvc.MockMvcRestDocumentation.documentationConfiguration;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*;
/**
* @author Andrey Lugovskoy
* @author Matija Obreza
*/
public class PartnerControllerTest extends AbstractRestTest {
@Autowired
private WebApplicationContext webApplicationContext;
@Autowired
private PartnerRepository partnerRepository;
private MockMvc mockMvc;
@Before
public void setUp() {
mockMvc = MockMvcBuilders.webAppContextSetup(webApplicationContext).apply(documentationConfiguration(restDocumentation).uris().withScheme("https").withHost(
"api.catalog.genesys-pgr.org").withPort(443)).build();
}
@After
@Override
public void cleanup() {
partnerRepository.deleteAll();
super.cleanup();
}
@Test
public void listPartnersTest() throws Exception {
final PartnerFilter partnerFilter = new PartnerFilter();
partnerFilter.name = StringFilter.eq("Partner Two");
Partner partner = partnerRepository.save(setPartner("Partner one", true, "Partner one", UUID.randomUUID()));
partner = partnerRepository.save(setPartner("Partner Two", true, "Partner Two", UUID.randomUUID()));
/*@formatter:off*/
this.mockMvc
.perform(RestDocumentationRequestBuilders.post(PartnerController.CONTROLLER_URL.concat("/list"))
.contentType(MediaType.APPLICATION_JSON)
.content(verboseMapper.writeValueAsString(partnerFilter)))
// .andDo(MockMvcResultHandlers.print())
.andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8))
.andExpect(status().isOk())
.andExpect(jsonPath("$.filterCode", not(nullValue())))
.andExpect(jsonPath("$.filter", not(nullValue())))
.andExpect(jsonPath("$.content[0]", not(nullValue())))
.andExpect(jsonPath("$.content[0].uuid", is(partner.getUuid().toString())))
.andExpect(jsonPath("$.content[0].name", is(partner.getName())));
/*@formatter:on*/
}
@Test
public void listPartnersByFilterCodeTest() throws Exception {
final PartnerFilter partnerFilter = new PartnerFilter();
partnerFilter.name = StringFilter.eq("Partner one");
final Partner partner = partnerRepository.save(setPartner("Partner one", true, "Partner one", UUID.randomUUID()));
partnerRepository.save(setPartner("Partner Two", true, "Partner Two", UUID.randomUUID()));
assertThat(partnerRepository.count(), is(2L));
final String filterCode = shortFilterService.getCode(partnerFilter);
/*@formatter:off*/
mockMvc
.perform(RestDocumentationRequestBuilders.post(PartnerController.CONTROLLER_URL + "/list/{filterCode}", filterCode)
.contentType(MediaType.APPLICATION_JSON))
// .andDo(MockMvcResultHandlers.print())
.andExpect(status().isOk())
.andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8))
.andExpect(jsonPath("$.filterCode", is(filterCode)))
.andExpect(jsonPath("$.filter", not(nullValue())))
.andExpect(jsonPath("$.content[0].uuid", is(partner.getUuid().toString())));
/*@formatter:on*/
}
@Test
public void getPartnerTest() throws Exception {
final Partner partner = setPartner("Partner one", true, "Partner one", UUID.randomUUID());
final String s = verboseMapper.writeValueAsString(partnerRepository.save(partner));
/*@formatter:off*/
this.mockMvc
.perform(RestDocumentationRequestBuilders.get(PartnerController.CONTROLLER_URL.concat("/{UUID}"), partner.getUuid())
.content(s).contentType(MediaType.APPLICATION_JSON)
.accept(MediaType.APPLICATION_JSON))
// .andDo(MockMvcResultHandlers.print())
.andExpect(status().isOk())
.andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8))
.andExpect(jsonPath("$", not(nullValue())))
.andExpect(jsonPath("$.uuid", is(partner.getUuid().toString())))
.andExpect(jsonPath("$.wiewsCodes", containsInAnyOrder(partner.getWiewsCodes().toArray())))
.andExpect(jsonPath("$.urls", containsInAnyOrder(partner.getUrls().stream().map(url -> url.toString()).collect(Collectors.toSet()).toArray())))
.andDo(document("partner-get"));
/*@formatter:on*/
}
@Test
@WithMockUser(username = "user", password = "user", roles = "ADMINISTRATOR")
public void createPartnerTest() throws Exception {