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

AccessionControllerTest completed

parent 67634536
......@@ -335,6 +335,9 @@ public abstract class AbstractRestTest {
}
}
@Autowired
AccessionHistoricRepository accessionHistoricRepository;
@Autowired
CropRuleRepository cropRuleRepository;
......
package org.genesys2.tests.resttests;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonNode;
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.AccessionController;
import org.genesys2.server.servlet.controller.rest.model.AccessionHeaderJson;
import org.genesys2.server.servlet.controller.rest.model.AccessionNamesJson;
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;
public class AccessionControllerTest extends AbstractRestTest{
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.result.MockMvcResultMatchers.*;
public class AccessionControllerTest extends AbstractRestTest {
private static final Log LOG = LogFactory.getLog(AccessionControllerTest.class);
......@@ -19,22 +52,372 @@ public class AccessionControllerTest extends AbstractRestTest{
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 = new Country();
@Before
public void setUp(){
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");
country.setCode3("UKR");
country.setName("Ukraine");
countryRepository.save(country);
accession = new Accession();
accession.setVersion(1);
accession.setInstitute(faoInstitute);
accession.setAccessionName("NameAccession");
accession.setHistoric(false);
accession.setTaxonomy(taxonomy2);
accession.setCountryOfOrigin(country);
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(){
public void tearDown() {
methodRepository.deleteAll();
parameterRepository.deleteAll();
parameterCategoryRepository.deleteAll();
cropRepository.deleteAll();
userPersistence.deleteAll();
accessionHistoricRepository.deleteAll();
accessionRepository.deleteAll();
countryRepository.deleteAll();
taxonomy2Repository.deleteAll();
instituteRepository.deleteAll();
metadataMethodRepository.deleteAll();
metadataRepository.deleteAll();
}
@Test
public void existsTest(){
public void existsTest() throws Exception {
LOG.info("Start test-method existsTest");
mockMvc.perform(get("/api/v0/acn/exists/{instCode}/{genus}", accession.getInstituteCode(), accession.getTaxGenus())
.contentType(MediaType.APPLICATION_JSON)
.param("acceNumb", accession.getAccessionName()))
.andExpect(status().isOk())
.andExpect(content().contentType(MediaType.APPLICATION_JSON))
.andExpect(content().string("true"));
LOG.info("Test existsTest passed.");
}
@Test
public void checkTest() throws Exception {
LOG.info("Start test-method checkTest");
ObjectMapper objectMapper = new ObjectMapper();
mockMvc.perform(post("/api/v0/acn/{instCode}/check", accession.getInstituteCode())
.contentType(MediaType.APPLICATION_JSON)
.content(objectMapper.writeValueAsString(accession.getAccessionName())))
.andExpect(status().isOk())
.andExpect(content().contentType(MediaType.APPLICATION_JSON))
.andExpect(jsonPath("$", hasSize(1)))
.andExpect(jsonPath("$[0]", is(Integer.parseInt(accession.getAccessionId().getId().toString()))));
LOG.info("Test checkTest passed.");
}
@Test
public void upsertInstituteAccessionTest() throws Exception {
LOG.info("Start test-method upsertInstituteAccessionTest");
ObjectMapper objectMapper = new ObjectMapper();
String JSON_OK = "{\"result\":true}";
JsonNode node = objectMapper.readTree(JSON_OK);
AccessionNamesJson accessionHeaderJson = new AccessionNamesJson();
accessionHeaderJson.acceNumb = accession.getAccessionName();
accessionHeaderJson.genus = String.valueOf(accession.getTaxGenus());
accessionHeaderJson.instCode = accession.getInstituteCode();
mockMvc.perform(post("/api/v0/acn/{instCode}/upsert", accession.getInstituteCode())
.contentType(MediaType.APPLICATION_JSON)
.content(objectMapper.writeValueAsString(accessionHeaderJson)))
.andExpect(status().isOk())
.andExpect(content().contentType(MediaType.APPLICATION_JSON))
.andExpect(content().string(objectMapper.writeValueAsString(node)));
LOG.info("Test upsertInstituteAccessionTest passed.");
}
@Test
public void upsertAccessionNamesTest() throws Exception {
LOG.info("Start test-method upsertAccessionNamesTest");
ObjectMapper objectMapper = new ObjectMapper();
String JSON_OK = "{\"result\":true}";
JsonNode node = objectMapper.readTree(JSON_OK);
List<AccessionNamesJson> batch = new ArrayList<>();
AccessionNamesJson accessionHeaderJson = new AccessionNamesJson();
accessionHeaderJson.acceNumb = accession.getAccessionName();
accessionHeaderJson.genus = String.valueOf(accession.getTaxGenus());
accessionHeaderJson.instCode = accession.getInstituteCode();
batch.add(accessionHeaderJson);
mockMvc.perform(post("/api/v0/acn/{instCode}/names", accession.getInstituteCode())
.contentType(MediaType.APPLICATION_JSON)
.content(objectMapper.writeValueAsString(batch)))
.andExpect(status().isOk())
.andExpect(content().contentType(MediaType.APPLICATION_JSON))
.andExpect(content().string(objectMapper.writeValueAsString(node)));
LOG.info("Test upsertAccessionNamesTest passed.");
}
@Test
public void deleteAccessionsTest() throws Exception {
LOG.info("Start test-method deleteAccessionsTest");
ObjectMapper objectMapper = new ObjectMapper();
List<AccessionHeaderJson> batch = new ArrayList<>();
AccessionHeaderJson accessionHeaderJson = new AccessionHeaderJson();
accessionHeaderJson.acceNumb = accession.getAccessionName();
accessionHeaderJson.genus = String.valueOf(accession.getTaxGenus());
accessionHeaderJson.instCode = accession.getInstituteCode();
batch.add(accessionHeaderJson);
mockMvc.perform(post("/api/v0/acn/{instCode}/delete-named", accession.getInstituteCode())
.contentType(MediaType.APPLICATION_JSON)
.content(objectMapper.writeValueAsString(batch)))
.andExpect(status().isOk())
.andExpect(content().contentType(MediaType.APPLICATION_JSON))
.andExpect(jsonPath("$.deleted", is(notNullValue())));
LOG.info("Test deleteAccessionsTest passed.");
}
@Test
public void deleteAccessionsByIdTest() throws Exception {
LOG.info("Start test-method deleteAccessionsByIdTest");
ObjectMapper objectMapper = new ObjectMapper();
List<Long> batch = new ArrayList<>();
batch.add(accession.getId());
mockMvc.perform(post("/api/v0/acn/{instCode}/delete", accession.getInstituteCode())
.contentType(MediaType.APPLICATION_JSON)
.content(objectMapper.writeValueAsString(batch)))
.andExpect(status().isOk())
.andExpect(content().contentType(MediaType.APPLICATION_JSON))
.andExpect(jsonPath("$.deleted", is(1)))
.andExpect(jsonPath("$.result", is(true)));
LOG.info("Test deleteAccessionsByIdTest passed.");
}
@Test
public void searchTest() throws Exception {
LOG.info("Start test-method searchTest");
mockMvc.perform(get("/api/v0/acn/search")
.contentType(MediaType.APPLICATION_JSON)
.param("page", "1")
.param("query", "*"))
.andExpect(status().isOk())
.andExpect(content().contentType(MediaType.APPLICATION_JSON))
.andExpect(jsonPath("$.content", hasSize(greaterThan(0))));
LOG.info("Test searchTest passed.");
}
@Test
public void listTest() throws Exception {
LOG.info("Start test-method listTest");
mockMvc.perform(get("/api/v0/acn/{instCode}/list", accession.getInstituteCode())
.contentType(MediaType.APPLICATION_JSON)
.param("page", "1")
.param("query", "*"))
.andExpect(status().isOk())
.andExpect(content().contentType(MediaType.APPLICATION_JSON))
.andExpect(jsonPath("$.content", hasSize(greaterThan(0))));
LOG.info("Test listTest passed.");
}
@Test
public void getDetailsTest() throws Exception {
LOG.info("Start test-method getDetailsTest");
mockMvc.perform(get("/api/v0/acn/{id}", accession.getId())
.contentType(MediaType.APPLICATION_JSON))
.andExpect(status().isOk())
.andExpect(content().contentType(MediaType.APPLICATION_JSON))
.andExpect(jsonPath("$.version", is(1)))
.andExpect(jsonPath("$.id", notNullValue()))
.andExpect(jsonPath("$.acceNumb", is("NameAccession")))
.andExpect(jsonPath("$.institute.fullName", is("This is name of institute")))
.andExpect(jsonPath("$.orgCty.name", is("Ukraine")))
.andExpect(jsonPath("$.taxonomy.sciName", is("0 Species taxonomy SpAuthor SubTaxa SubtAuthor")))
.andExpect(jsonPath("$.historic", is(false)));
LOG.info("Test getDetailsTest passed.");
}
@Test
public void getTest() throws Exception {
LOG.info("Start test-method getTest");
List<Long> listId = new ArrayList<>();
listId.add(accession.getId());
ObjectMapper objectMapper = new ObjectMapper();
mockMvc.perform(post("/api/v0/acn/list", accession.getId())
.contentType(MediaType.APPLICATION_JSON)
.content(objectMapper.writeValueAsString(listId)))
.andExpect(status().isOk())
.andExpect(content().contentType(MediaType.APPLICATION_JSON))
.andExpect(jsonPath("$", hasSize(greaterThan(0))))
.andExpect(jsonPath("$[0].version", is(1)))
.andExpect(jsonPath("$[0].instCode", is("Code")))
.andExpect(jsonPath("$[0].acceNumb", is("NameAccession")))
.andExpect(jsonPath("$[0].species", is("Species taxonomy")));
LOG.info("Test getTest passed.");
}
@Test
public void getAccTest() throws Exception {
LOG.info("Start test-method getAccTest");
AccessionController.JsonData jsonData = new AccessionController.JsonData();
jsonData.crop = crop.getShortName();
jsonData.maxRecords = 50;
jsonData.startAt = 1;
ObjectMapper objectMapper = new ObjectMapper();
mockMvc.perform(post("/api/v0/acn/filter", accession.getId())
.contentType(MediaType.APPLICATION_JSON)
.content(objectMapper.writeValueAsString(jsonData)))
.andExpect(status().isOk())
.andExpect(content().contentType("application/json;charset=UTF-8"))
.andExpect(jsonPath("$.content", hasSize(greaterThan(0))));
LOG.info("Test getAccTest passed.");
}
}
Markdown is supported
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