Commit 431b2c38 authored by Matija Obreza's avatar Matija Obreza

Tests: JUnit and Mockito

parent 9871018b
......@@ -100,6 +100,29 @@
<artifactId>jackson-databind</artifactId>
<version>2.2.3</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.mockito</groupId>
<artifactId>mockito-core</artifactId>
<version>2.0.5-beta</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.hamcrest</groupId>
<artifactId>hamcrest-integration</artifactId>
<version>1.3</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.3.6</version>
</dependency>
</dependencies>
......
......@@ -73,7 +73,7 @@ public class AccessionJson {
@JsonProperty(value = Accession.REMARKS)
private Remark[] remarks;
@JsonProperty(value = Accession.HISTORIC)
private boolean historic;
private Boolean historic;
public long getVersion() {
return version;
......@@ -283,11 +283,21 @@ public class AccessionJson {
this.remarks = remarks;
}
public void setHistoric(boolean historic) {
/**
* Sets the historic.
*
* @param historic the new historic
*/
public void setHistoric(Boolean historic) {
this.historic = historic;
}
public boolean getHistoric() {
/**
* Gets the historic.
*
* @return the historic
*/
public Boolean getHistoric() {
return this.historic;
}
}
/**
* Copyright 2015 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.geneys2.client.oauth;
import static org.hamcrest.CoreMatchers.*;
import static org.hamcrest.MatcherAssert.*;
import static org.mockito.Matchers.*;
import static org.mockito.Mockito.*;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import org.genesys2.client.oauth.GenesysApiException;
import org.genesys2.client.oauth.GenesysClient;
import org.genesys2.client.oauth.OAuthAuthenticationException;
import org.genesys2.client.oauth.PleaseRetryException;
import org.genesys2.client.oauth.api.AccessionJson;
import org.hamcrest.CoreMatchers;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Matchers;
import org.mockito.Mock;
import org.mockito.runners.MockitoJUnitRunner;
import com.fasterxml.jackson.annotation.JsonInclude.Include;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import com.fasterxml.jackson.databind.node.ObjectNode;
@RunWith(MockitoJUnitRunner.class)
public class AccessionApiTest {
private static ObjectMapper objectMapper;
@Mock
protected GenesysClient genesysClient;
private String instCode = "INS000";
private MockGenesysServer mockServer = new MockGenesysServer();
static {
objectMapper = new ObjectMapper();
objectMapper.configure(SerializationFeature.WRITE_ENUMS_USING_TO_STRING, true);
objectMapper.configure(SerializationFeature.WRITE_EMPTY_JSON_ARRAYS, false);
objectMapper.setSerializationInclusion(Include.NON_NULL);
}
@Before
public void initMocks() throws OAuthAuthenticationException, PleaseRetryException, GenesysApiException,
InterruptedException {
System.err.println("Initializing mocks");
when(genesysClient.listAccessions(anyString(), anyInt(), Matchers.isNull(String.class))).then(
mockServer.listAccessions());
when(genesysClient.updateAccessions(anyString(), anyCollectionOf(ObjectNode.class))).then(
mockServer.updateAccessions());
}
@Test
public void testAccessions0() throws OAuthAuthenticationException, PleaseRetryException, GenesysApiException,
JsonProcessingException, IOException {
List<AccessionJson> results = objectMapper.readValue(genesysClient.listAccessions(instCode, 1, null),
new TypeReference<List<AccessionJson>>() {
});
assertThat("Expected empty list", results.size(), is(0));
}
@Test
public void testAccessions1() throws OAuthAuthenticationException, PleaseRetryException, GenesysApiException,
JsonProcessingException, IOException {
when(genesysClient.listAccessions(instCode, 1, null)).thenReturn(
"[{\"instCode\":\"INS000\",\"acceNumb\":\"ACC-1\"}]");
List<AccessionJson> results = objectMapper.readValue(genesysClient.listAccessions(instCode, 1, null),
new TypeReference<List<AccessionJson>>() {
});
assertThat("Expected empty list", results.size(), is(1));
AccessionJson acc1 = results.get(0);
assertThat("INSTCODE doesn't match", acc1.getInstCode(), is(instCode));
acc1.setHistoric(true);
}
@Test
public void testUpsertAccessions1() throws OAuthAuthenticationException, PleaseRetryException, GenesysApiException,
JsonProcessingException, IOException, InterruptedException {
String result = genesysClient.listAccessions(instCode, 1, null);
assertThat("Non-null result expected from genesysClient", result, notNullValue());
List<AccessionJson> results = objectMapper.readValue(result, new TypeReference<List<AccessionJson>>() {
});
assertThat("Expected empty list", results.size(), is(0));
List<ObjectNode> nodeList = new ArrayList<ObjectNode>();
for (int i = 0; i < 4; i++) {
AccessionJson aj = new AccessionJson();
aj.setInstCode(instCode);
aj.setAcceNumb("ACC-" + (i + 1));
aj.setGenus("Genus");
ObjectNode node = (ObjectNode) objectMapper.readTree(objectMapper.writeValueAsString(aj));
nodeList.add(node);
}
result = genesysClient.updateAccessions(instCode, nodeList);
System.err.println(result);
results = objectMapper.readValue(genesysClient.listAccessions(instCode, 1, null),
new TypeReference<List<AccessionJson>>() {
});
assertThat("Expected list with 4 entries", results.size(), is(4));
for (AccessionJson aj1 : results) {
assertThat("Expected matching INSTCODE", aj1.getInstCode(), is(instCode));
assertThat("Expected ACCENUMB starting with", aj1.getAcceNumb(), CoreMatchers.startsWith("ACC-"));
assertThat("Expected GENUS=Genus", aj1.getGenus(), is("Genus"));
assertThat("Expected SPECIES=null", aj1.getSpecies(), nullValue());
}
}
}
/**
* Copyright 2015 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.geneys2.client.oauth;
import static org.hamcrest.CoreMatchers.*;
import static org.hamcrest.MatcherAssert.*;
import static org.mockito.Matchers.*;
import static org.mockito.Mockito.*;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collection;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.genesys2.client.oauth.GenesysApiException;
import org.genesys2.client.oauth.GenesysClient;
import org.genesys2.client.oauth.OAuthAuthenticationException;
import org.genesys2.client.oauth.PleaseRetryException;
import org.genesys2.client.oauth.api.Api1Constants.Accession;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.Mockito;
import org.mockito.MockitoAnnotations;
import org.mockito.invocation.InvocationOnMock;
import org.mockito.runners.MockitoJUnitRunner;
import org.mockito.stubbing.Answer;
import org.scribe.model.Verb;
import com.fasterxml.jackson.annotation.JsonInclude.Include;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import com.fasterxml.jackson.databind.node.ObjectNode;
@RunWith(MockitoJUnitRunner.class)
public class ApiTest {
private static ObjectMapper objectMapper;
private static final String bananaJson;
@Mock
protected HttpGet httpGetMock;
@Mock
protected HttpPost httpPostMock;
@Mock
protected GenesysClient genesysClient;
static {
objectMapper = new ObjectMapper();
objectMapper.configure(SerializationFeature.WRITE_ENUMS_USING_TO_STRING, true);
objectMapper.configure(SerializationFeature.WRITE_EMPTY_JSON_ARRAYS, false);
objectMapper.setSerializationInclusion(Include.NON_NULL);
bananaJson = objectMapper.createObjectNode().put("shortName", "banana").toString();
}
@BeforeClass
public static void initOAuthParams() {
}
@Before
public void initRequestMocks() throws OAuthAuthenticationException, PleaseRetryException, GenesysApiException {
MockitoAnnotations.initMocks(this);
when(httpGetMock.getMethod()).thenReturn("GET");
when(httpPostMock.getMethod()).thenReturn("POST");
when(genesysClient.getCrop("banana")).thenReturn(bananaJson);
}
@Test
public void testMockGetCrop() throws OAuthAuthenticationException, PleaseRetryException, GenesysApiException,
JsonProcessingException, IOException {
String json = genesysClient.getCrop("banana");
assertThat("Returned banana JSON doesn't match", json, equalTo(bananaJson));
// Must be able to read the json
objectMapper.readTree(json);
}
@Test
public void testMockUpdateCrop() throws OAuthAuthenticationException, PleaseRetryException, GenesysApiException,
JsonProcessingException, IOException {
String json = genesysClient.getCrop("banana");
assertThat("Returned banana JSON doesn't match", json, equalTo(bananaJson));
// Must be able to read the json
objectMapper.readTree(json);
}
@Test
public void testOrganizationMembers() throws OAuthAuthenticationException, PleaseRetryException,
GenesysApiException, JsonProcessingException, IOException {
String orgSlug = "org";
when(genesysClient.getOrganizationMembers(orgSlug)).then(returnOrganizationMembers(orgSlug));
String members = genesysClient.getOrganizationMembers(orgSlug);
objectMapper.readTree(members);
System.err.println(members);
}
private Answer<String> returnOrganizationMembers(String orgSlug) {
return new Answer<String>() {
@Override
public String answer(InvocationOnMock invocation) throws Throwable {
return "[\"ORG1\",\"ORG2\"]";
}
};
}
@Test(expected = PleaseRetryException.class)
public void testPleaseRetryException() throws OAuthAuthenticationException, PleaseRetryException,
GenesysApiException {
when(genesysClient.updateMLS("INS000", null)).thenThrow(PleaseRetryException.class);
genesysClient.updateMLS("INS000", null);
}
@Test(expected = NullPointerException.class)
public void testNullUpdate() throws OAuthAuthenticationException, PleaseRetryException, GenesysApiException {
when(genesysClient.updateMLS("INS000", null)).thenCallRealMethod();
genesysClient.updateMLS("INS000", null);
}
@Test
public void test2() throws OAuthAuthenticationException, PleaseRetryException, GenesysApiException {
when(genesysClient.query(Mockito.isA(Verb.class), anyString(), anyMap(), anyString())).thenCallRealMethod();
when(genesysClient.updateMLS(anyString(), anyCollection())).thenCallRealMethod();
Collection<ObjectNode> list = new ArrayList<ObjectNode>();
list.add(objectMapper.createObjectNode().put(Accession.INSTCODE, "INS000").put(Accession.ACCENUMB, "ACC-1")
.put(Accession.GENUS, "Genus"));
String x = genesysClient.updateMLS("INS000", list);
System.out.println(x);
}
}
/**
* Copyright 2015 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.geneys2.client.oauth;
import static org.hamcrest.CoreMatchers.*;
import org.hamcrest.Factory;
import org.hamcrest.Matcher;
import org.hamcrest.collection.IsIterableWithSize;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.node.ArrayNode;
import com.fasterxml.jackson.databind.node.NumericNode;
import com.fasterxml.jackson.databind.node.TextNode;
public class JsonNodeMatchers {
@Factory
public static Matcher<Iterable<JsonNode>> withSize(int size) {
return IsIterableWithSize.<JsonNode> iterableWithSize(size);
}
@Factory
public static Matcher<? super JsonNode> isTextNode() {
return is(instanceOf(TextNode.class));
}
@Factory
public static Matcher<? super JsonNode> isNumericNode() {
return is(instanceOf(NumericNode.class));
}
public static Matcher<? super JsonNode> isArrayNode() {
return is(instanceOf(ArrayNode.class));
}
}
/**
* Copyright 2015 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.geneys2.client.oauth;
import org.genesys2.client.oauth.GenesysApiException;
public class MockGenesysException extends GenesysApiException {
private static final long serialVersionUID = 1L;
public MockGenesysException(String message) {
super(message);
}
}
/**
* Copyright 2015 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.geneys2.client.oauth;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.genesys2.client.oauth.GenesysApiException;
import org.genesys2.client.oauth.api.AccessionJson;
import org.mockito.invocation.InvocationOnMock;
import org.mockito.stubbing.Answer;
import com.fasterxml.jackson.annotation.JsonInclude.Include;
import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
/**
* Mock Genesys server
*
* @author mobreza
*/
public class MockGenesysServer {
private static final ArrayList<AccessionJson> BLANK_LIST = new ArrayList<AccessionJson>();
private final Map<String, List<AccessionJson>> instAcc = new HashMap<String, List<AccessionJson>>();
private static ObjectMapper objectMapper;
static {
objectMapper = new ObjectMapper();
objectMapper.configure(SerializationFeature.WRITE_ENUMS_USING_TO_STRING, true);
objectMapper.configure(SerializationFeature.WRITE_EMPTY_JSON_ARRAYS, false);
objectMapper.setSerializationInclusion(Include.NON_NULL);
}
public Answer<String> listAccessions() {
return new Answer<String>() {
@Override
public String answer(InvocationOnMock invocation) throws Throwable {
Object[] args = invocation.getArguments();
if (args[2] != null)
throw new MockGenesysException("Querying is not supported.");
String instCode = (String) args[0];
int page = (Integer) args[1];
System.err.println("Listing accessions instCode=" + instCode + " page=" + page);
return objectMapper.writeValueAsString(getAccessionsPage(instCode, page));
}
};
}
public Answer<String> updateAccessions() {
return new Answer<String>() {
@Override
public String answer(InvocationOnMock invocation) throws Throwable {
Object[] args = invocation.getArguments();
String instCode = (String) args[0];
List arrayNode = (List) args[1];
String res = objectMapper.writeValueAsString(upsertAccessions(instCode, arrayNode));
System.err.println("Result: " + res);
return res;
}
};
}
protected String upsertAccessions(final String instCode, List nodeList) throws JsonParseException,
JsonMappingException, IOException, GenesysApiException {
List<AccessionJson> accList = instAcc.get(instCode);
if (accList == null) {
instAcc.put(instCode, accList = new ArrayList<AccessionJson>());
}
for (int i = 0; i < nodeList.size(); i++) {
JsonNode node = (JsonNode) nodeList.get(i);
AccessionJson aj = objectMapper.readValue(node.toString(), AccessionJson.class);
AccessionJson existing = findMatch(accList, aj);
merge(accList, existing, aj);
}
return "OK";
}
private void merge(List<AccessionJson> accList, AccessionJson existing, AccessionJson aj)
throws MockGenesysException {
if (existing == null) {
accList.add(aj);
} else {
if (aj.getAvailable() != null)
existing.setAvailable(aj.getAvailable());
if (aj.getHistoric() != null)
existing.setHistoric(aj.getHistoric());
if (aj.getInTrust() != null)
existing.setInTrust(aj.getInTrust());
if (aj.getMlsStat() != null)
existing.setMlsStat(aj.getMlsStat());
if (aj.getAcceNumb() != null)
existing.setAcceNumb(aj.getAcceNumb());
if (aj.getAcqDate() != null)
existing.setAcqDate(aj.getAcqDate());
if (aj.getAncest() != null)
existing.setAncest(aj.getAncest());
if (aj.getBredCode() != null)
existing.setBredCode(aj.getBredCode());
if (aj.getColl() != null) {
}
if (aj.getDonorCode() != null)
existing.setDonorCode(aj.getDonorCode());
if (aj.getDonorName() != null)
existing.setDonorName(aj.getDonorName());
if (aj.getDonorNumb() != null)
existing.setDonorNumb(aj.getDonorNumb());
if (aj.getDuplSite() != null)
existing.setDuplSite(aj.getDuplSite());
if (aj.getGeo() != null) {
}
if (aj.getOrgCty() != null)
existing.setOrgCty(aj.getOrgCty());
if (aj.getRemarks() != null)
existing.setRemarks(aj.getRemarks());
if (aj.getSampStat() != null)
existing.setSampStat(aj.getSampStat());
if (aj.getSpecies() != null)
existing.setSpecies(aj.getSpecies());
if (aj.getSpauthor() != null)
existing.setSpauthor(aj.getSpauthor());
if (aj.getSubtaxa() != null)
existing.setSubtaxa(aj.getSubtaxa());
if (aj.getSubtauthor() != null)
existing.setSubtauthor(aj.getSubtauthor());
if (aj.getUuid() != null) {
if (existing.getUuid() == null) {
existing.setUuid(aj.getUuid());
} else if (!existing.getUuid().equals(aj.getUuid())) {
// Can this happen?
throw new MockGenesysException("UUID mismatch");
}
}
if (aj.getAvailable() != null)
existing.setAvailable(aj.getAvailable());
}