Commit ec575b8b authored by Alexander Basov's avatar Alexander Basov Committed by Matija Obreza
Browse files

DataSetControllerTest completed

parent 5a822e50
package org.genesys2.tests.resttests;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.SerializationFeature;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.velocity.app.VelocityEngine;
import org.genesys2.server.aspect.AsAdminAspect;
......@@ -17,6 +19,7 @@ import org.genesys2.server.service.impl.*;
import org.genesys2.server.servlet.controller.rest.*;
import org.genesys2.server.test.JpaDataConfig;
import org.genesys2.server.test.PropertyPlacholderInitializer;
import org.genesys2.spring.config.ElasticsearchConfig;
import org.genesys2.spring.config.HazelcastConfig;
import org.junit.runner.RunWith;
import org.mockito.Mockito;
......@@ -28,6 +31,7 @@ import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;
import org.springframework.context.annotation.PropertySource;
import org.springframework.http.converter.json.Jackson2ObjectMapperFactoryBean;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.JavaMailSenderImpl;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
......@@ -50,7 +54,7 @@ public abstract class AbstractRestTest {
@Configuration
@EnableWebMvc
@Import({JpaDataConfig.class, HazelcastConfig.class})
@Import({JpaDataConfig.class, HazelcastConfig.class, ElasticsearchConfig.class})
@PropertySource({"classpath:application.properties", "classpath:spring/spring.properties"})
public static class Config {
......@@ -272,8 +276,79 @@ public abstract class AbstractRestTest {
public KPIService kpiService() {
return new KPIServiceImpl();
}
@Bean
public DatasetController datasetController() {
return new DatasetController();
}
@Bean
public DatasetService datasetService() {
return new GenesysServiceImpl();
}
@Bean
public CropsController cropsController() {
return new CropsController();
}
@Bean
public CacheController cacheController() {
return new CacheController();
}
@Bean
public MappingService mappingService() {
return new MappingServiceImpl();
}
@Bean
public GenesysFilterService genesysFilterService() {
return new GenesysFilterServiceImpl();
}
@Bean
public AccessionController accessionController() {
return new AccessionController();
}
@Bean
public GenesysRESTService genesysRESTService() {
return new GenesysRESTServiceImpl();
}
@Bean
public ElasticService elasticService() {
return new ElasticsearchSearchServiceImpl();
}
@Bean
public FilterHandler filterHandler() {
return new FilterHandler();
}
@Bean
public Jackson2ObjectMapperFactoryBean objectMapper() {
final Jackson2ObjectMapperFactoryBean mapperFactoryBean = new Jackson2ObjectMapperFactoryBean();
mapperFactoryBean.setFeaturesToDisable(SerializationFeature.FAIL_ON_EMPTY_BEANS, DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES);
return mapperFactoryBean;
}
}
@Autowired
TaxonomyService taxonomyService;
@Autowired Taxonomy2Repository taxonomy2Repository;
@Autowired
MetadataMethodRepository metadataMethodRepository;
@Autowired
MetadataRepository metadataRepository;
@Autowired
DatasetService datasetService;
@Autowired
ObservationRepository observationRepository;
......@@ -316,6 +391,9 @@ public abstract class AbstractRestTest {
@Autowired
JavaMailSender mailSender;
@Autowired
AccessionRepository accessionRepository;
@Autowired
AccessionCustomRepository accessionCustomRepository;
......
package org.genesys2.tests.resttests;
/**
* Created by alexander on 25.05.15.
*/
public class AccessionControllerTest {
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
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;
public class AccessionControllerTest extends AbstractRestTest{
private static final Log LOG = LogFactory.getLog(AccessionControllerTest.class);
@Autowired
private WebApplicationContext webApplicationContext;
MockMvc mockMvc;
@Before
public void setUp(){
mockMvc = MockMvcBuilders.webAppContextSetup(webApplicationContext).build();
}
@After
public void tearDown(){
}
@Test
public void existsTest(){
LOG.info("Start test-method existsTest");
LOG.info("Test existsTest passed.");
}
}
package org.genesys2.tests.resttests;
/**
* Created by alexander on 25.05.15.
*/
public class CacheControllerTest {
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
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;
public class CacheControllerTest extends AbstractRestTest{
private static final Log LOG = LogFactory.getLog(CacheControllerTest.class);
@Autowired
private WebApplicationContext webApplicationContext;
MockMvc mockMvc;
@Before
public void setUp(){
mockMvc = MockMvcBuilders.webAppContextSetup(webApplicationContext).build();
}
@After
public void tearDown(){
}
@Test
public void cacheStatsTest(){
LOG.info("Start test-method cacheStatsTest");
LOG.info("Test cacheStatsTest passed.");
}
}
package org.genesys2.tests.resttests;
/**
* Created by alexander on 25.05.15.
*/
public class CropsControllerTest {
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
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;
public class CropsControllerTest extends AbstractRestTest{
private static final Log LOG = LogFactory.getLog(CropsControllerTest.class);
@Autowired
WebApplicationContext webApplicationContext;
MockMvc mockMvc;
@Before
public void setUp(){
mockMvc = MockMvcBuilders.webAppContextSetup(webApplicationContext).build();
}
@After
public void tearDown(){
}
@Test
public void listCropsTest(){
LOG.info("Start test-method listCropsTest");
LOG.info("Test listCropsTest passed");
}
}
package org.genesys2.tests.resttests;
/**
* Created by alexander on 25.05.15.
*/
public class DatasetControllerTest {
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.genesys2.server.exception.UserException;
import org.genesys2.server.model.UserRole;
import org.genesys2.server.model.genesys.*;
import org.genesys2.server.model.impl.Country;
import org.genesys2.server.model.impl.Crop;
import org.genesys2.server.model.impl.FaoInstitute;
import org.genesys2.server.model.impl.User;
import org.genesys2.server.model.oauth.OAuthClientDetails;
import org.genesys2.server.model.oauth.OAuthClientType;
import org.genesys2.server.model.oauth.OAuthRefreshToken;
import org.genesys2.server.security.AuthUserDetails;
import org.genesys2.server.servlet.controller.rest.DatasetController;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.oauth2.common.OAuth2AccessToken;
import org.springframework.security.oauth2.provider.DefaultAuthorizationRequest;
import org.springframework.security.oauth2.provider.OAuth2Authentication;
import org.springframework.security.oauth2.provider.token.DefaultTokenServices;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import org.springframework.web.context.WebApplicationContext;
import java.util.*;
import static org.hamcrest.Matchers.*;
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.request.MockMvcRequestBuilders.put;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*;
public class DatasetControllerTest extends AbstractRestTest {
private static final Log LOG = LogFactory.getLog(DatasetControllerTest.class);
@Autowired
public WebApplicationContext webApplicationContext;
MockMvc mockMvc;
private Metadata metadata;
private FaoInstitute faoInstitute;
private List<FaoInstitute> institutes = new ArrayList<>();
private User user = new User();
private OAuth2AccessToken accessToken;
private OAuthRefreshToken refreshToken;
private OAuthClientDetails oAuthClientDetails;
private Method method;
private Crop crop;
private ParameterCategory category;
private Parameter parameter;
private MetadataMethod metadataMethod;
private Accession accession;
private Country country;
@Before
public void setup() throws UserException, JsonProcessingException, InterruptedException {
mockMvc = MockMvcBuilders.webAppContextSetup(webApplicationContext).build();
oAuthClientDetails = clientDetailsService.addClientDetails("title", "description", "redirectUri", 1, 2, OAuthClientType.SERVICE);
user = new User();
user.setEmail("salexandrbasov@gmail.com");
user.setPassword("Alexandr19011990");
user.setName("SYS_ADMIN");
userService.addUser(user);
faoInstitute = new FaoInstitute();
faoInstitute.setFullName("This is name of institute");
faoInstitute.setCurrent(true);
faoInstitute.setPgrActivity(true);
faoInstitute.setMaintainsCollection(true);
faoInstitute.setPgrActivity(true);
faoInstitute.setAccessionCount(1);
faoInstitute.setUniqueAcceNumbs(true);
faoInstitute.setCode("Code");
institutes.add(faoInstitute);
instituteService.update(institutes);
ObjectMapper objectMapper = new ObjectMapper();
crop = cropService.addCrop("shortName", "Name", "description", "en");
traitService.addCategory("nameOfParameterCategory", objectMapper.writeValueAsString("en"));
parameter = traitService.addParameter("rdfUri", crop, "nameOfParameterCategory", "titleOfParameter", objectMapper.writeValueAsString("en"));
method = traitService.addMethod("rdfUriMethod", "descriptionMethod", objectMapper.writeValueAsString("en"), "unitForMethod", "fieldName", 1, 2, "options", "range", parameter);
metadata = datasetService.addDataset(faoInstitute, "TitleMetaData", "Description metaData");
Map<Integer, Boolean> permission = new HashMap<>();
metadataMethod = new MetadataMethod();
metadataMethod.setMetadata(metadata);
metadataMethod.setMethodId(method.getId());
metadataMethodRepository.save(metadataMethod);
permission.put(4, true);
permission.put(1, false);
permission.put(2, false);
permission.put(8, false);
permission.put(16, true);
aclService.addPermissions(metadata.getId(), Metadata.class.getName(), "SYS_ADMIN", true, permission);
HashMap<String, String> authorizationParameters = new HashMap<String, String>();
authorizationParameters.put("scope", "read");
authorizationParameters.put("username", user.getName());
authorizationParameters.put("client_id", user.getName());
authorizationParameters.put("grant", user.getPassword());
DefaultAuthorizationRequest authorizationRequest = new DefaultAuthorizationRequest(authorizationParameters);
authorizationRequest.setApproved(true);
List<GrantedAuthority> authorities = new ArrayList<>();
GrantedAuthority simpleGrantedAuthority = new SimpleGrantedAuthority(UserRole.ADMINISTRATOR.getName());
authorities.add(simpleGrantedAuthority);
authorizationRequest.setAuthorities(authorities);
HashSet<String> resourceIds = new HashSet<String>();
resourceIds.add(user.getName());
authorizationRequest.setResourceIds(resourceIds);
oAuthClientDetails.setResourceIds(user.getName());
AuthUserDetails authUserDetails = new AuthUserDetails(user.getName(), user.getPassword(), authorities);
// set actual DB user
authUserDetails.setUser(user);
UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(authUserDetails, authUserDetails, authorities);
OAuth2Authentication authenticationRequest = new OAuth2Authentication(authorizationRequest, authenticationToken);
authenticationRequest.setAuthenticated(true);
accessToken = ((DefaultTokenServices) tokenServices).createAccessToken(authenticationRequest);
refreshToken = new OAuthRefreshToken();
refreshToken.setValue("Value");
refreshToken.setClientId(user.getName());
refreshTokenPersistence.save(refreshToken);
Taxonomy2 taxonomy2 = taxonomyService.internalEnsure(String.valueOf(0), "Species taxonomy", "SpAuthor", "SubTaxa", "SubtAuthor");
accession = new Accession();
accession.setVersion(1);
accession.setInstitute(faoInstitute);
accession.setAccessionName("NameAccession");
accession.setHistoric(false);
accession.setTaxonomy(taxonomy2);
AccessionId accessionId = new AccessionId();
accessionId.setVersion(1);
accession.setAccessionId(accessionId);
List<Accession> accessionList = new ArrayList<>();
accessionList.add(accession);
genesysService.addAccessions(accessionList);
SecurityContextHolder.getContext().setAuthentication(authenticationRequest);
}
@After
public void tearDown() {
methodRepository.deleteAll();
parameterRepository.deleteAll();
parameterCategoryRepository.deleteAll();
cropRepository.deleteAll();
userPersistence.deleteAll();
accessionRepository.deleteAll();
taxonomy2Repository.deleteAll();
instituteRepository.deleteAll();
metadataMethodRepository.deleteAll();
metadataRepository.deleteAll();
}
@Test
public void listDatasetsTest() throws Exception {
LOG.info("Start test-method listDatasetsTest");
mockMvc.perform(get("/api/v0/datasets")
.contentType(MediaType.APPLICATION_JSON))
.andExpect(status().isOk())
.andExpect(content().contentType(MediaType.APPLICATION_JSON))
.andExpect(jsonPath("$", hasSize(1)))
.andExpect(jsonPath("$[0].id", is(notNullValue())))
.andExpect(jsonPath("$[0].instituteCode", is("Code")))
.andExpect(jsonPath("$[0].title", is("TitleMetaData")))
.andExpect(jsonPath("$[0].description", is("Description metaData")))
.andExpect(jsonPath("$[0].uuid", is(notNullValue())));
LOG.info("Test listDatasetsTest passed");
}
@Test
public void createDatasetTest() throws Exception {
LOG.info("Start test-method createDatasetTest");
metadataMethodRepository.deleteAll();
metadataRepository.deleteAll();
DatasetController.MetadataJson metadataJson = new DatasetController.MetadataJson();
metadataJson.title = metadata.getTitle();
metadataJson.institute = metadata.getInstituteCode();
metadataJson.description = metadata.getDescription();
ObjectMapper objectMapper = new ObjectMapper();
mockMvc.perform(post("/api/v0/datasets")
.contentType(MediaType.APPLICATION_JSON)
.content(objectMapper.writeValueAsString(metadataJson)))
.andExpect(status().isOk())
.andExpect(content().contentType(MediaType.APPLICATION_JSON))
.andExpect(jsonPath("$.id", is(notNullValue())))
.andExpect(jsonPath("$.instituteCode", is("Code")))
.andExpect(jsonPath("$.title", is("TitleMetaData")))
.andExpect(jsonPath("$.description", is("Description metaData")))
.andExpect(jsonPath("$.uuid", is(notNullValue())));
LOG.info("Test createDatasetTest passed");
}
@Test
public void getCropTest() throws Exception {
LOG.info("Start test-method getCropTest");
mockMvc.perform(get("/api/v0/datasets/{metadataId}", metadata.getId())
.contentType(MediaType.APPLICATION_JSON))
.andExpect(status().isOk())
.andExpect(content().contentType(MediaType.APPLICATION_JSON))
.andExpect(jsonPath("$.id", is(notNullValue())))
.andExpect(jsonPath("$.instituteCode", is("Code")))
.andExpect(jsonPath("$.title", is("TitleMetaData")))
.andExpect(jsonPath("$.description", is("Description metaData")))
.andExpect(jsonPath("$.uuid", is(notNullValue())));
LOG.info("Test getCropTest passed");
}
@Test
public void getMetadataMethodsTest() throws Exception {
LOG.info("Start test-method getMetadataMethodsTest");
mockMvc.perform(get("/api/v0/datasets/{metadataId}/methods", metadata.getId())
.contentType(MediaType.APPLICATION_JSON))
.andExpect(status().isOk())
.andExpect(content().contentType(MediaType.APPLICATION_JSON))
.andExpect(jsonPath("$", hasSize(1)))
.andExpect(jsonPath("$[0].id", is(notNullValue())))
.andExpect(jsonPath("$[0].version", is(0)))
.andExpect(jsonPath("$[0].rdfUri", is("rdfUriMethod")))
.andExpect(jsonPath("$[0].method", is("descriptionMethod")))
.andExpect(jsonPath("$[0].uuid", is(notNullValue())))
.andExpect(jsonPath("$[0].unit", is("unitForMethod")))
.andExpect(jsonPath("$[0].options", is("options")))
.andExpect(jsonPath("$[0].fieldName", is("fieldName")))
.andExpect(jsonPath("$[0].fieldType", is(1)))
.andExpect(jsonPath("$[0].range", is("range")))
.andExpect(jsonPath("$[0].localMethodMap", is(Map.class)))
.andExpect(jsonPath("$[0].dataType", is("java.lang.Double")))
.andExpect(jsonPath("$[0].coded", is(true)));
LOG.info("Test getMetadataMethodsTest passed");
}
@Test
public void upsertMetadataDataTest() throws Exception {
LOG.info("Start test-method upsertMetadataDataTest");
ObjectMapper objectMapper = new ObjectMapper();
DatasetController.DataJson dataJson = new DatasetController.DataJson();
dataJson.genus = String.valueOf(accession.getTaxGenus());
dataJson.acceNumb = accession.getAccessionName();
dataJson.instCode = accession.getInstituteCode();
mockMvc.perform(put("/api/v0/datasets/{metadataId}/data", metadata.getId())
.contentType(MediaType.APPLICATION_JSON)
.content(objectMapper.writeValueAsString(dataJson)))
.andExpect(status().isOk());
LOG.info("Test upsertMetadataDataTest passed");
}
}
......@@ -86,12 +86,10 @@ public class TokenControllerTest extends AbstractRestTest {
UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(authUserDetails, authUserDetails, authorities);
OAuth2Authentication authenticationRequest = new OAuth2Authentication(authorizationRequest, authenticationToken);
// OAuth2Authentication authenticationRequestTwo = new OAuth2Authentication(authorizationRequest, null);
authenticationRequest.setAuthenticated(true);
accessToken = ((DefaultTokenServices) tokenServices).createAccessToken(authenticationRequest);
// accessTokenTwo = ((DefaultTokenServices) tokenServices).createAccessToken(authenticationRequestTwo);
SecurityContextHolder.getContext().setAuthentication(authenticationRequest);
}
......
Supports Markdown
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