Skip to content

Instantly share code, notes, and snippets.

@hasandiwan
Last active December 26, 2018 05:53
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save hasandiwan/7efbd34561f10086c41366af5ec9e6e2 to your computer and use it in GitHub Desktop.
Save hasandiwan/7efbd34561f10086c41366af5ec9e6e2 to your computer and use it in GitHub Desktop.
Geonotes Unit Tests
package hello;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import java.util.List;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.TestPropertySource;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.MvcResult;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;
@RunWith(SpringRunner.class)
@SpringBootTest
@TestPropertySource(locations = "classpath:test.properties")
@AutoConfigureMockMvc
public class GeoErrorControllerTest {
@Autowired
private MockMvc mockMvc;
final String METHOD_RESPONSE = "[{\"methodName\":\"boundsCheck\",\"parameters\":\"point longitude, point latitude\"},{\"methodName\":\"decodeGeohash\",\"parameters\":\"incoming geohash\"},{\"methodName\":\"distanceAndBearing\",\"parameters\":\"our longitude, our latitude, marker latitude, marker longitude\"},{\"methodName\":\"geohash\",\"parameters\":\"latitude, longitude\"},{\"methodName\":\"intersects\",\"parameters\":\"first point1, first point2, point, tolerance, velocity\"},{\"methodName\":\"kmlFromPoint\",\"parameters\":\"latitude, longitude\"},{\"methodName\":\"locationCode\",\"parameters\":\"latitude, longitude\"},{\"methodName\":\"median\",\"parameters\":\"pts\"},{\"methodName\":\"pointInsideCircle\",\"parameters\":\"point longitude, point latitude\"}]";
@Test
public void testHelpMethodListContainsAllSupportedMethods() throws Exception {
MvcResult result = this.mockMvc.perform(get("/help").header("Content-Type", "application/json")).andReturn();
String content = result.getResponse().getContentAsString();
try {
new ObjectMapper().readValue(content, List.class);
Assert.assertTrue("error returns list", true);
} catch (JsonMappingException e) {
Assert.fail("/error doesn't return list");
}
Assert.assertEquals(METHOD_RESPONSE, content);
}
@Test
public void testErrorMethodListIsAList() throws Exception {
MvcResult result = this.mockMvc.perform(get("/error").header("Content-Type", "application/json")).andReturn();
String content = result.getResponse().getContentAsString();
try {
new ObjectMapper().readValue(content, List.class);
Assert.assertTrue("error returns list", true);
} catch (JsonMappingException e) {
Assert.fail("/error doesn't return list");
}
}
}
package hello;
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.MockMvcResultHandlers.print;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;
import org.hamcrest.Matchers;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.TestPropertySource;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.MvcResult;
import org.springframework.web.util.HtmlUtils;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
@RunWith(SpringRunner.class)
@SpringBootTest
@TestPropertySource(locations = "classpath:test.properties")
@AutoConfigureMockMvc
// https://hd1-atlas.herokuapp.com/
public class GreetingControllerTest {
private static final int UPSTREAM_ERROR_STATUS = 408;
@Autowired
private MockMvc mockMvc;
@Test
public void median() throws Exception {
MvcResult response = this.mockMvc.perform(get("/median?points="+HtmlUtils.htmlEscape("(0 0), (1 1), (2 2), (200 200)"))).andReturn();
Map<String, String> map = new ObjectMapper().readValue(response.getResponse().getContentAsString(),
new TypeReference<Map<String, String>>() {
});
Assert.assertTrue(map.get("xCoordinateOfMedian").startsWith("1.97"));
Assert.assertTrue(map.get("yCoordinateOfMedian").startsWith("1.97")); }
@Test
public void intersectsWithSpeed() throws Exception {
MvcResult response = this.mockMvc.perform(get("/intersects?fp1=0,0&fp2=2,2&p=1,1&speed=2")).andReturn();
Map<String, String> map = new ObjectMapper().readValue(response.getResponse().getContentAsString(),
new TypeReference<Map<String, String>>() {
});
Assert.assertEquals("0.7071067811865476",map.get("intersectsAt"));
}
@Test
public void intersectionWithTolerance() throws Exception {
MvcResult response = this.mockMvc.perform(get("/intersects?fp1=0,0&fp2=2,0&p=1,1&tol=2")).andReturn();
Map<String, String> map = new ObjectMapper().readValue(response.getResponse().getContentAsString(),
new TypeReference<Map<String, String>>() {
});
Assert.assertEquals("true", map.get("intersects?"));
response = this.mockMvc.perform(get("/intersects?fp1=0,0&fp2=2,0&p=1,14&tol=1")).andReturn();
map = new ObjectMapper().readValue(response.getResponse().getContentAsString(),
new TypeReference<Map<String, String>>() {
});
Assert.assertEquals("false", map.get("intersects?"));
}
@Test
public void intersection() throws Exception {
MvcResult response = this.mockMvc.perform(get("/intersects?fp1=0,0&fp2=2,0&p=1,0")).andReturn();
Map<String, String> map = new ObjectMapper().readValue(response.getResponse().getContentAsString(),
new TypeReference<Map<String, String>>() {
});
Assert.assertEquals("true", map.get("intersects?"));
}
@Test
public void geocodingIpReturnsCityAndCountry() throws Exception {
MvcResult response = this.mockMvc.perform(get("/geocode?ip=" + URLEncoder.encode("128.113.1.5", "UTF-8"))
.header("Content-Type", "application/json")).andReturn();
Map<String, String> ret = new ObjectMapper().readValue(response.getResponse().getContentAsString(),
new TypeReference<Map<String, String>>() {
});
Assert.assertTrue(ret.containsKey("city"));
Assert.assertTrue(ret.containsKey("country"));
}
@Test
public void geocodingStreetAddressReturnsLatitudeAndLongitude() throws Exception {
MvcResult response = this.mockMvc.perform(get("/geocode?q=10+downing+street,+london")).andReturn();
Map<String, String> ret = new ObjectMapper().readValue(response.getResponse().getContentAsString(),
new TypeReference<Map<String, String>>() {
});
LoggerFactory.getLogger("hello.GreetingControllerTest").info(response.getResponse().getContentAsString());
if (response.getResponse().getStatus() == UPSTREAM_ERROR_STATUS) {
Assert.assertTrue(ret.containsKey("error"));
Assert.assertEquals(ret.get("error"), "upstream timeout");
} else {
Assert.assertTrue(ret.containsKey("displayName"));
Assert.assertTrue(ret.containsKey("latitude"));
Assert.assertEquals("\"https://www.openstreetmap.org/#map=19/51.50344025/-0.127708209585621",
ret.get("openstreetmapUrl"));
Assert.assertTrue(ret.get("latitude").startsWith("51"));
Assert.assertTrue(ret.containsKey("longitude"));
Assert.assertTrue(ret.get("longitude").startsWith("-0.12"));
}
}
@Test
public void isPointInCircle() throws Exception {
java.util.Map<String, Float> params = new HashMap<>();
params.put("center.x", (float) 1);
params.put("center.y", (float) -1);
params.put("radius", (float) 3);
this.mockMvc.perform(post("/0/0/isRound").content(new ObjectMapper().writeValueAsString(params))
.header("Content-Type", "application/json")).andExpect(jsonPath("$.inCircle").value("true"));
this.mockMvc.perform(post("/8/8/isRound").content(new ObjectMapper().writeValueAsString(params))
.header("Content-Type", "application/json")).andExpect(jsonPath("$.inCircle").value("false"));
}
@Test
public void outOfRangeLatitudeOrLongitudeReturns422WithAppropriateErrorMessage() throws Exception {
this.mockMvc.perform(get("/info?olat=0&olng=0&lat=181&lng=0")).andDo(print()).andExpect(status().is(412))
.andExpect(jsonPath("$.error").value(
"One of your values is out of range -- latitudes must be from -90 to 90; longitudes must be from -180 to 180"));
}
@Test
public void zeroBearingDoesNotReturnNull() throws Exception {
this.mockMvc.perform(get("/info?olat=0&olng=0&lat=0&lng=0")).andDo(print()).andExpect(status().is(200))
.andExpect(jsonPath("$.bearing").isNotEmpty());
}
@Test
public void bearingCalculationWorks() throws Exception {
this.mockMvc.perform(get("/info?olng=0&olat=0&lat=90&lng=0")).andDo(print()).andExpect(status().is(200))
.andExpect(jsonPath("$.bearing").value(0.0))
.andExpect(jsonPath("$.bearinginradians", Matchers.equalTo("0")));
}
@Test
public void geohash() throws Exception {
this.mockMvc.perform(get("/geohash?lat=48&lng=-126")).andDo(print())
.andExpect(jsonPath("$.geohash").value("c0w3hf1s70w3hf1s70w3"));
}
@Test
public void kmlFromPointIsEscaped() throws Exception {
String expected = "&lt;Point&gt;&lt;coordinates&gt;0,0&lt;/coordinates&gt;&lt;/Point&gt;";
String actual = this.mockMvc.perform(get("/kmlFromPoint?lat=0&lng=0")).andReturn().getResponse()
.getContentAsString();
Assert.assertEquals(expected, actual);
}
@Test
public void reverseGeohash() throws Exception {
String response = this.mockMvc.perform(get("/resolveGeohash?q=c0w3hf1s70w3hf1s70w3")).andReturn().getResponse()
.getContentAsString();
Map<String, String> geohashResponse = new ObjectMapper().readValue(response,
new TypeReference<Map<String, String>>() {
});
Assert.assertTrue(geohashResponse.get("latitude").startsWith("48"));
Assert.assertTrue(geohashResponse.get("longitude").startsWith("-126"));
Assert.assertEquals(geohashResponse.get("openstreetMap"),
String.format("https://www.openstreetmap.org/?mlon=%s&mlat=%s", geohashResponse.get("longitude"),
geohashResponse.get("latitude")));
}
@Test
public void pointsInEnvelope() throws Exception {
Map<String, Float> params = new HashMap<>();
params.put("minX", (float) 9.0);
params.put("maxX", (float) 12.0);
params.put("minY", (float) 9.0);
params.put("maxY", (float) 12.0);
this.mockMvc
.perform(post("/10.5/11/bounds").content(new ObjectMapper().writeValueAsString(params))
.header("Content-Type", "application/json"))
.andExpect(jsonPath("$.inBoundingBox").value(Boolean.TRUE));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment