Skip to content

Instantly share code, notes, and snippets.

@hasandiwan
Created November 23, 2020 20:06
Show Gist options
  • Save hasandiwan/683a24ac051107616b520f63eceeefbf to your computer and use it in GitHub Desktop.
Save hasandiwan/683a24ac051107616b520f63eceeefbf to your computer and use it in GitHub Desktop.
hd1-units tests 2020-11-23
package us.d8u.balance;
import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.Serializable;
import java.io.StringReader;
import java.math.BigDecimal;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.text.DecimalFormat;
import java.text.NumberFormat;
import java.text.ParseException;
import java.time.LocalDate;
import java.util.ArrayList;
import java.util.Base64;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
import java.util.TreeMap;
import java.util.regex.Pattern;
import org.apache.commons.lang3.math.NumberUtils;
import org.assertj.core.api.Assertions;
import org.assertj.core.util.Lists;
import org.codehaus.plexus.util.StringUtils;
import org.joda.time.DateTime;
import org.joda.time.Days;
import org.joda.time.MutableDateTime;
import org.joda.time.format.DateTimeFormat;
import org.joda.time.format.DateTimeFormatter;
import org.joda.time.format.ISODateTimeFormat;
import org.junit.Assert;
import org.junit.Assume;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.TestName;
import org.junit.runner.RunWith;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.context.SpringBootTest.WebEnvironment;
import org.springframework.boot.web.server.LocalServerPort;
import org.springframework.http.HttpStatus;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.util.Base64Utils;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.Maps;
import com.google.common.collect.Sets;
import com.opencsv.CSVParser;
import com.opencsv.CSVParserBuilder;
import com.opencsv.CSVReader;
import com.opencsv.CSVReaderBuilder;
import okhttp3.HttpUrl;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT)
public class Tests {
@Value(value = "${fit.helper.jdbc}")
private String FIT_HELPER_URL;
private static Logger LOG = LoggerFactory.getLogger("us.d8u.balance.Tests");
@Autowired
private AuthRepository authRepo;
@Autowired
UserRepositoryImpl userRepo;
String SAMPLE_CSV = "9,8,7,6";
@Rule
public final TestName testName = new TestName();
@LocalServerPort
private int port;
@Autowired
private UserRepository userRepository;
@Autowired
private EndpointRepository endpointRepository;
private Map<String, String> fetchFromKeyserverReturnsValidKey(String param)
throws Exception {
Map<String, String> response = PGPUtils.fetchFromKeyserver(param);
return response;
}
@Before
public void populateAuth() throws Exception {
if (this.testName.getMethodName().equals("getAuth")) {
Optional<User> possibleUser = this.userRepository
.findById((Integer.toUnsignedLong(1)));
EndpointBean e = this.endpointRepository.findByEndpoint("/auth")
.get();
AuthBean auth = new AuthBean();
auth.setCreatedAt(DateTime.now());
auth.setEndpointBean(e);
auth.setUser(possibleUser.get());
this.authRepo.save(auth);
}
}
@Test
public void stockInfoWithoutSymReturnsPredictionForW5000()
throws Exception {
Set<String> expectedKeys = Sets.newHashSet("date", "prediction");
HttpUrl requestUrl = new HttpUrl.Builder().scheme("http")
.host("localhost").port(this.port)
.addEncodedPathSegments("/stock/info").build();
Request request = new Request.Builder().url(requestUrl).build();
Response response = new OkHttpClient().newCall(request).execute();
Map<String, String> json = new ObjectMapper().readValue(
response.body().bytes(),
new TypeReference<Map<String, String>>() {
});
Assert.assertEquals(expectedKeys, json.keySet());
Assert.assertTrue(Sets.newHashSet("up", "no change", "down")
.contains(json.get("prediction")));
}
@Test
public void validUnitsDefaultAmount() throws Exception {
Set<String> expectedKeys = Sets.newHashSet("request", "result", "time");
HttpUrl requestUrl = new HttpUrl.Builder().scheme("http")
.host("localhost").port(this.port)
.addEncodedPathSegments("/units/inch/cm").build();
Request request = new Request.Builder().url(requestUrl).build();
Response response = new OkHttpClient().newCall(request).execute();
Map<String, String> json = new ObjectMapper().readValue(
response.body().bytes(),
new TypeReference<Map<String, String>>() {
});
Assert.assertEquals(expectedKeys, json.keySet());
Assert.assertEquals("2.5 cms", json.get("result"));
Assert.assertEquals("1 inch", json.get("request"));
json.keySet().removeAll(expectedKeys);
Assert.assertTrue(json.isEmpty());
}
@Test
public void covidReturnsJsonWithChromium() throws Exception {
HttpUrl requestUrl = new HttpUrl.Builder().host("localhost")
.scheme("http").port(this.port).addPathSegments("covid")
.build();
Request request = new Request.Builder().url(requestUrl)
.header("user-agent", "Chromium/83.0.4098.0").build();
Response response = new OkHttpClient().newCall(request).execute();
Assert.assertTrue(
response.header("content-type").contains("application/json"));
}
@Test
public void covidReturnsCsvWithCurl() throws Exception {
HttpUrl requestUrl = new HttpUrl.Builder().host("localhost")
.scheme("http").port(this.port).addPathSegments("covid")
.build();
Request request = new Request.Builder().url(requestUrl)
.header("user-agent", "libcurl").build();
Response response = new OkHttpClient().newCall(request).execute();
Assert.assertEquals(response.header("content-type"), "text/csv");
}
@Test
public void newsReturnsSourcesWithNoParameters() throws Exception {
Set<String> expected = Sets.newHashSet("name", "url", "country",
"language", "attribution");
OkHttpClient client = new OkHttpClient();
HttpUrl requestUrl = new HttpUrl.Builder().host("localhost")
.scheme("http").port(this.port).addPathSegments("news").build();
Request request = new Request.Builder().url(requestUrl).build();
Response response = client.newCall(request).execute();
List<Map<String, String>> responseObj = new ObjectMapper().readValue(
response.body().string(),
new TypeReference<List<Map<String, String>>>() {
});
for (Map<String, String> r : responseObj) {
Set<String> actual = r.keySet();
Assert.assertEquals(expected, actual);
Assert.assertEquals("powered by NewsAPI.org", r.get("attribution"));
}
}
@Test
public void redditUserNoGold() throws Exception {
OkHttpClient client = new OkHttpClient();
HttpUrl requestUrl = new HttpUrl.Builder().host("localhost")
.scheme("http").port(this.port).addPathSegment("reddit")
.build();
Map<String, String> bodyMap = Collections.singletonMap("user", "meh613");
byte[] body = new ObjectMapper().writeValueAsBytes(bodyMap);
Request request = new Request.Builder().url(requestUrl).put(RequestBody.create(body)).build();
Response response = client.newCall(request).execute();
int responseCode = response.code();
Assert.assertEquals(277, responseCode);
}
@Test
public void redditUserHasGold() throws Exception {
OkHttpClient client = new OkHttpClient();
HttpUrl requestUrl = new HttpUrl.Builder().host("localhost")
.scheme("http").port(this.port).addPathSegment("reddit")
.build();
Map<String, String> bodyMap = Collections.singletonMap("user", "spez");
byte[] body = new ObjectMapper().writeValueAsBytes(bodyMap);
Request request = new Request.Builder().url(requestUrl).put(RequestBody.create(body)).build();
Response response = client.newCall(request).execute();
int responseCode = response.code();
Assert.assertEquals(204, responseCode);
}
@Test
public void redditTopLevelApiKeysStartWithNumbersLackUnderscores()
throws Exception {
OkHttpClient client = new OkHttpClient();
HttpUrl requestUrl = new HttpUrl.Builder().host("localhost")
.scheme("http").port(this.port).addPathSegment("reddit")
.build();
Request request = new Request.Builder().url(requestUrl).build();
Response response = client.newCall(request).execute();
JsonNode responseObj = new ObjectMapper()
.readValue(response.body().string(), JsonNode.class);
final Pattern pattern = Pattern.compile("^(\\d+.*)");
for (String k : Lists.newArrayList(responseObj.fieldNames())) {
Assert.assertFalse("snake case found at " + k, k.contains("_"));
if (k == "request") {
continue;
}
Tests.LOG.debug("key being examined is " + k);
Assert.assertTrue(k + " does not begin with a digit",
pattern.matcher(k).matches());
}
}
@Test
public void udReturnsDefinitionsForWordsThatAreFound() throws Exception {
Set<String> expected = Sets.newHashSet("request", "definitions",
"source");
OkHttpClient client = new OkHttpClient();
HttpUrl requestUrl = new HttpUrl.Builder().host("localhost")
.scheme("http").port(this.port).addPathSegment("ud")
.addQueryParameter("word", "Limbaugh").build();
Request request = new Request.Builder().url(requestUrl).build();
Response rawResponse = client.newCall(request).execute();
JsonNode response = new ObjectMapper()
.readValue(rawResponse.body().string(), JsonNode.class);
Assert.assertEquals(expected,
ImmutableList.copyOf(response.fieldNames()));
Assert.assertEquals("Limbaugh", response.get("request").asText());
try {
Lists.newArrayList(response.get("definitions").elements());
} catch (Exception e) {
Assert.fail(
response.get("definitions").asText() + " is not a list");
}
}
@Test
public void tweetTakesFullUrlsAndReturnsTextAndAuthor() throws Exception {
String url = "https://twitter.com/HasanDiwan2/status/1268417818317316097";
HttpUrl requestUrl = new HttpUrl.Builder().host("localhost")
.scheme("http").port(this.port).addPathSegment("twitter")
.addQueryParameter("url", url).build();
Request request = new Request.Builder().url(requestUrl).build();
Response rawResponse = new OkHttpClient().newCall(request).execute();
Map<String, String> response = new ObjectMapper().readValue(
rawResponse.body().string(),
new TypeReference<Map<String, String>>() {
});
Assert.assertEquals("hasandiwan2", response.get("author"));
Assert.assertEquals(
"if you’re wondering why death rates are so low in Germany and so high in America, it’s because their leader used to be a quantum chemist and yours used to be a reality television host.",
response.get("text"));
}
@Test
public void tweetReturnsTextAndAuthor() throws Exception {
OkHttpClient client = new OkHttpClient();
HttpUrl requestUrl = new HttpUrl.Builder().host("localhost")
.scheme("http").port(this.port).addPathSegment("twitter")
.addQueryParameter("tweet", "1250650485205241857").build();
Request request = new Request.Builder().url(requestUrl).build();
Response rawResponse = client.newCall(request).execute();
Map<String, String> response = new ObjectMapper().readValue(
rawResponse.body().string(),
new TypeReference<Map<String, String>>() {
});
Assert.assertEquals("hasandiwan2", response.get("author"));
Assert.assertEquals("2020-04-16T05:01:26.000Z", response.get("when"));
Assert.assertEquals(
"if you’re wondering why death rates are so low in Germany and so high in America, it’s because their leader used to be a quantum chemist and yours used to be a reality television host.",
response.get("text"));
}
@Test
public void udReturnValueForWordsNotFound() throws Exception {
Set<String> expected = Sets.newHashSet("request", "definitions",
"source");
OkHttpClient client = new OkHttpClient();
HttpUrl requestUrl = new HttpUrl.Builder().host("localhost")
.scheme("http").port(this.port).addPathSegment("ud")
.addQueryParameter("word", "foobar").build();
Request request = new Request.Builder().url(requestUrl).build();
Response rawResponse = client.newCall(request).execute();
JsonNode response = new ObjectMapper()
.readValue(rawResponse.body().string(), JsonNode.class);
Assert.assertEquals(expected,
ImmutableSet.copyOf(response.fieldNames()));
Assert.assertEquals(response.get("request").asText(), "foobar");
Assert.assertEquals(response.get("definitions").asText(), "not found");
Assert.assertEquals(response.get("source"), "Urban Dictionary");
}
@Test
public void newsReturnsPieceWithParameters() throws Exception {
Set<String> expected = Sets.newHashSet("author", "title", "publishedAt",
"attribution", "link", "total");
OkHttpClient client = new OkHttpClient();
HttpUrl requestUrl = new HttpUrl.Builder().host("localhost")
.scheme("http").port(this.port).addPathSegment("news")
.addQueryParameter("q", "Boris Johnson").build();
Request request = new Request.Builder().url(requestUrl).build();
Response response = client.newCall(request).execute();
List<Map<String, String>> responseObj = new ObjectMapper().readValue(
response.body().string(),
new TypeReference<List<Map<String, String>>>() {
});
for (Map<String, String> r : responseObj) {
Set<String> actual = r.keySet();
Assert.assertEquals(expected, actual);
Assert.assertTrue(r.get("link").startsWith("http"));
Assert.assertEquals(r.get("attribution"), "powered by NewsAPI.org");
try {
DateTimeFormatter df = ISODateTimeFormat.dateTimeNoMillis();
Assert.assertTrue(df.parseDateTime(r.get("publishedAt"))
.isBefore(DateTime.now()));
} catch (Exception e) {
Assert.fail("Not a date -- " + r.get("publishedAt"));
}
}
}
@Test
public void sdrReturnsCorrectFormat() throws Exception {
OkHttpClient client = new OkHttpClient();
HttpUrl requestUrl = new HttpUrl.Builder().host("localhost")
.scheme("http").port(this.port).addPathSegments("sdr").build();
Request request = new Request.Builder().url(requestUrl).get().build();
Response rawResponse = client.newCall(request).execute();
Map<String, String> response = new ObjectMapper().readValue(
rawResponse.body().string(),
new TypeReference<Map<String, String>>() {
});
for (Map.Entry<String, String> item : response.entrySet()) {
String k = item.getKey();
Assert.assertEquals(k, StringUtils.capitalise(k));
String v = item.getValue();
Assert.assertTrue(v.matches("^[0-9.,]+$"));
}
}
@Test
public void lookingUpGooglxReturnsErrorNotFound() throws Exception {
OkHttpClient client = new OkHttpClient();
HttpUrl requestUrl = new HttpUrl.Builder().host("localhost")
.scheme("http").port(this.port).addPathSegments("stock/info")
.addQueryParameter("sym", "GOOGLx").build();
Request request = new Request.Builder().url(requestUrl).get().build();
Response rawResponse = client.newCall(request).execute();
Map<String, String> response = new ObjectMapper().readValue(
rawResponse.body().string(),
new TypeReference<Map<String, String>>() {
});
Assert.assertEquals("symbol not found", response.get("error"));
}
@Test
public void lookingUpWillyOnWheelsIIReturnsRNTError() throws Exception {
OkHttpClient client = new OkHttpClient();
HttpUrl requestUrl = new HttpUrl.Builder().host("localhost")
.scheme("http").port(this.port).addPathSegment("stock")
.addPathSegment("info")
.addQueryParameter("sym", "WillyOnWheelsII").build();
Request request = new Request.Builder().url(requestUrl).get().build();
Response rawResponse = client.newCall(request).execute();
Map<String, String> response = new ObjectMapper().readValue(
rawResponse.body().string(),
new TypeReference<Map<String, String>>() {
});
Assert.assertEquals(
"RNT is fighting for the future of South Australia!",
response.get("error"));
}
@Test
public void lookingUpChaosHyenaReturnsArbeitMachtFrei() throws Exception {
OkHttpClient client = new OkHttpClient();
HttpUrl requestUrl = new HttpUrl.Builder().host("localhost")
.scheme("http").port(this.port).addPathSegment("stock")
.addPathSegment("info").addQueryParameter("sym", "ChaosHyena")
.build();
Request request = new Request.Builder().url(requestUrl).get().build();
Response rawResponse = client.newCall(request).execute();
Map<String, String> response = new ObjectMapper().readValue(
rawResponse.body().string(),
new TypeReference<Map<String, String>>() {
});
Assert.assertEquals("Arbeit macht frei", response.get("error"));
}
public void getQrReturnsHtmlPage() throws Exception {
OkHttpClient client = new OkHttpClient();
HttpUrl requestUrl = new HttpUrl.Builder().host("localhost")
.scheme("http").port(this.port).addPathSegment("qr").build();
Request request = new Request.Builder().url(requestUrl).get().build();
Response rawResponse = client.newCall(request).execute();
Assert.assertTrue(rawResponse.body().string().contains("<html>"));
}
@Test
public void xmlTakesAtomAndReturnsJsonProperly() throws Exception {
OkHttpClient client = new OkHttpClient();
HttpUrl requestUrl = new HttpUrl.Builder().host("localhost")
.scheme("http").port(this.port).addPathSegment("xml")
.addQueryParameter("xml", "https://news.google.com/news/atom")
.build();
Request request = new Request.Builder().url(requestUrl).get().build();
Response rawResponse = client.newCall(request).execute();
String string = rawResponse.body().string();
Tests.LOG.info(string);
Map<String, String> response = new ObjectMapper().readValue(string,
new TypeReference<Map<String, String>>() {
});
Set<String> expectedKeys = Sets.newHashSet("request",
"tag.content[type]", "tag.email", "tag.feed[xmlns]",
"tag.generator", "tag.id", "tag.link[href]", "tag.link[rel]",
"tag.link[type]", "tag.name", "tag.rights", "tag.subtitle",
"tag.title[type]", "tag.updated", "tag.uri");
for (String required : expectedKeys) {
Assert.assertTrue("Missing key: " + required,
response.containsKey(required));
}
}
@Test
public void endpointCostCanBeUpdated() throws Exception {
OkHttpClient client = new OkHttpClient();
HttpUrl requestUrl = new HttpUrl.Builder().host("localhost")
.scheme("http").port(this.port).addPathSegment("cost")
.addQueryParameter("endpoint", "/")
.addQueryParameter("newCost", "0").build();
Request request = new Request.Builder().url(requestUrl)
.patch(RequestBody.create("".getBytes(), null)).build();
Response rawResponse = client.newCall(request).execute();
String string = rawResponse.body().string();
Map<String, String> response = new ObjectMapper().readValue(string,
new TypeReference<Map<String, String>>() {
});
Set<String> expectedKeys = Sets.newHashSet("endpoint", "newCost");
for (String required : expectedKeys) {
Assert.assertTrue("Missing key: " + required,
response.containsKey(required));
}
Assert.assertEquals("endpoint / is missing", "/",
response.get("endpoint"));
Assert.assertEquals("newCost incorrect", response.get("newCost"), "0");
Assert.assertTrue(rawResponse.isSuccessful());
}
@Test
public void visibleSatellitesList() throws Exception {
OkHttpClient client = new OkHttpClient();
HttpUrl requestUrl = new HttpUrl.Builder().host("localhost")
.scheme("http").port(this.port).addPathSegment("space")
.addPathSegment("0").addPathSegment("0").build();
Request request = new Request.Builder().url(requestUrl).build();
Response rawResponse = client.newCall(request).execute();
String string = rawResponse.body().string();
List<Map<String, String>> response = new ObjectMapper().readValue(
string, new TypeReference<List<Map<String, String>>>() {
});
Set<String> expected = Sets.newHashSet("satelliteName", "id");
for (Map<String, String> satellite : response) {
Assert.assertEquals(expected, satellite.keySet());
Assert.assertTrue(satellite.get("id") + " is not numeric",
satellite.get("id").matches("[0-9]+"));
Assert.assertFalse(satellite.get("satellite") + " has a newline",
satellite.get("satellite").contains("\n"));
}
}
@Test
public void subredditStatusForOperationGetSmash() throws Exception {
OkHttpClient client = new OkHttpClient();
HttpUrl requestUrl = new HttpUrl.Builder().host("localhost")
.scheme("http").port(this.port).addPathSegment("reddit")
.addPathSegment("the_donald").build();
Request request = new Request.Builder().url(requestUrl).build();
Response rawResponse = client.newCall(request).execute();
String string = rawResponse.body().string();
Map<String, String> response = new ObjectMapper().readValue(string,
new TypeReference<Map<String, String>>() {
});
Assert.assertEquals(Sets.newHashSet("subreddit", "status"),
response.keySet());
Assert.assertEquals("private", response.get("status"));
}
@Test
public void subredditStatusForTheDonald() throws Exception {
OkHttpClient client = new OkHttpClient();
HttpUrl requestUrl = new HttpUrl.Builder().host("localhost")
.scheme("http").port(this.port).addPathSegment("reddit")
.addPathSegment("the_donald").build();
Request request = new Request.Builder().url(requestUrl).build();
Response rawResponse = client.newCall(request).execute();
String string = rawResponse.body().string();
Map<String, String> response = new ObjectMapper().readValue(string,
new TypeReference<Map<String, String>>() {
});
Assert.assertEquals(Sets.newHashSet("subreddit", "status"),
response.keySet());
Assert.assertEquals("quarantined", response.get("status"));
}
@Test
public void subredditStatusForFroenlegzos() throws Exception {
OkHttpClient client = new OkHttpClient();
HttpUrl requestUrl = new HttpUrl.Builder().host("localhost")
.scheme("http").port(this.port).addPathSegment("reddit")
.addPathSegment("froenlegzos").build();
Request request = new Request.Builder().url(requestUrl).build();
Response rawResponse = client.newCall(request).execute();
String string = rawResponse.body().string();
Map<String, String> response = new ObjectMapper().readValue(string,
new TypeReference<Map<String, String>>() {
});
Assert.assertEquals(Sets.newHashSet("subreddit", "status"),
response.keySet());
Assert.assertEquals("available", response.get("status"));
}
@Test
public void subredditStatusForGreatAwakening() throws Exception {
OkHttpClient client = new OkHttpClient();
HttpUrl requestUrl = new HttpUrl.Builder().host("localhost")
.scheme("http").port(this.port).addPathSegment("reddit")
.addPathSegment("GreatAwakening").build();
Request request = new Request.Builder().url(requestUrl).build();
Response rawResponse = client.newCall(request).execute();
String string = rawResponse.body().string();
Map<String, String> response = new ObjectMapper().readValue(string,
new TypeReference<Map<String, String>>() {
});
Assert.assertEquals(Sets.newHashSet("subreddit", "status"),
response.keySet());
Assert.assertEquals("private", response.get("status"));
}
@Test
public void subredditStatusForDepthhub() throws Exception {
OkHttpClient client = new OkHttpClient();
HttpUrl requestUrl = new HttpUrl.Builder().host("localhost")
.scheme("http").port(this.port).addPathSegment("reddit")
.addPathSegment("depthhub").build();
Request request = new Request.Builder().url(requestUrl).build();
Response rawResponse = client.newCall(request).execute();
String string = rawResponse.body().string();
Map<String, String> response = new ObjectMapper().readValue(string,
new TypeReference<Map<String, String>>() {
});
Assert.assertEquals(Sets.newHashSet("subreddit", "status"),
response.keySet());
Assert.assertEquals("public", response.get("status"));
}
@Test
public void subredditDoesNotExist() throws Exception {
OkHttpClient client = new OkHttpClient();
HttpUrl requestUrl = new HttpUrl.Builder().host("localhost")
.scheme("http").port(this.port).addPathSegment("reddit")
.addPathSegment("q").build();
Request request = new Request.Builder().url(requestUrl).build();
Response rawResponse = client.newCall(request).execute();
String string = rawResponse.body().string();
Map<String, String> response = new ObjectMapper().readValue(string,
new TypeReference<Map<String, String>>() {
});
Assert.assertEquals(Sets.newHashSet("subreddit", "status"),
response.keySet());
Assert.assertEquals("available", response.get("status"));
}
@Test
public void redditSummary() throws Exception {
OkHttpClient client = new OkHttpClient();
HttpUrl requestUrl = new HttpUrl.Builder().host("localhost")
.scheme("http").port(this.port).addPathSegment("summary")
.addQueryParameter("url",
"https://www.reddit.com/r/neoliberal/comments/fej8al/on_dementia_and_older_candidates/")
.build();
Request request = new Request.Builder().url(requestUrl).get().build();
Response rawResponse = client.newCall(request).execute();
String string = rawResponse.body().string();
Tests.LOG.info(string);
Map<String, String> response = new ObjectMapper().readValue(string,
new TypeReference<Map<String, String>>() {
});
Assert.assertEquals(
"'1)**'' Dementia is a symptom of a disease process in the brain, and is not a normal process of aging.**.**in an unethical manner**no**to such an extent that it interferes with a person's daily life and activities.10 years ago Obama was making jokes about Biden's gaffe-prone nature.",
response.get("summary"));
}
@Test
public void covidCsvIsSemicolonDelimited() throws Exception {
OkHttpClient client = new OkHttpClient();
HttpUrl requestUrl = new HttpUrl.Builder().host("localhost")
.scheme("http").port(this.port).addPathSegment("covid")
.addQueryParameter("suffix", "csv").build();
Request request = new Request.Builder().url(requestUrl).get().build();
Response rawResponse = client.newCall(request).execute();
String string = rawResponse.body().string();
Tests.LOG.info(string);
CSVParser parser = new CSVParserBuilder().withSeparator(';').build();
BufferedReader br = new BufferedReader(new StringReader(string));
CSVReader reader = new CSVReaderBuilder(br).withCSVParser(parser)
.build();
List<String[]> rows = reader.readAll();
for (String[] row : rows.subList(1, rows.size())) {
if (row[0].equals("date")) {
try {
DateTimeFormat.forPattern("yyyy-MM-dd")
.parseDateTime(row[1]);
} catch (Exception e) {
Assert.fail("not a date " + row[1]);
}
}
Assert.assertEquals(2, row.length);
try {
NumberFormat.getNumberInstance().parse(row[1]);
} catch (NumberFormatException e) {
Assert.fail("\"" + String.join("; ", row)
+ "\" missing numeric value");
}
}
}
@Test
public void covidDoesNotContainIntegerAsVictimCounts() throws Exception {
OkHttpClient client = new OkHttpClient();
HttpUrl requestUrl = new HttpUrl.Builder().host("localhost")
.scheme("http").port(this.port).addPathSegment("covid")
.addQueryParameter("suffix", "csv").build();
Request request = new Request.Builder().url(requestUrl).get().build();
Response rawResponse = client.newCall(request).execute();
String string = rawResponse.body().string();
Tests.LOG.info(string);
CSVParser parser = new CSVParserBuilder().withSeparator(';').build();
BufferedReader br = new BufferedReader(new StringReader(string));
CSVReader reader = new CSVReaderBuilder(br).withCSVParser(parser)
.build();
List<String[]> rows = reader.readAll();
for (String[] row : rows.subList(1, rows.size())) {
if (row[0].equals("date")) {
DateTimeFormatter df = DateTimeFormat.forPattern("yyyy-MM-dd");
try {
df.parseDateTime(row[1]);
continue;
} catch (Exception e) {
Assert.fail(row[1] + " is not a valid date");
}
}
if (!row[1].strip().matches("[,0-9]+")) {
Assert.fail(String.join("; ", row) + " is invalid");
}
}
}
@Test
public void nearMeReturnsPlaceNamesDistancesBearingsForPlace()
throws Exception {
OkHttpClient client = new OkHttpClient();
HttpUrl requestUrl = new HttpUrl.Builder().host("localhost")
.scheme("http").port(this.port).addPathSegment("nearme")
.addQueryParameter("lat", "41.3813934")
.addQueryParameter("lng", "2.1730637").build();
Request request = new Request.Builder().url(requestUrl).get().build();
Response rawResponse = null;
try {
rawResponse = client.newCall(request).execute();
} catch (Exception e) {
Assert.fail(e.getMessage());
}
Assert.assertEquals(200, rawResponse.code());
String string = rawResponse.body().string();
List<Map<String, String>> response = new ObjectMapper().readValue(
string, new TypeReference<List<Map<String, String>>>() {
});
Set<String> expectedKeys = Sets.newHashSet("venue", "distance",
"bearing", "crowd", "latitude", "longitude", "request");
for (Map<String, String> result : response) {
try {
NumberFormat.getIntegerInstance().parse(result.get("crowd"));
} catch (NumberFormatException e) {
Assert.fail("Expected integer. found " + result.get("crowd"));
}
try {
Number distance = NumberFormat.getInstance()
.parse(result.get("distance"));
org.springframework.util.Assert.isTrue(
distance.doubleValue() > (BigDecimal.ZERO
.doubleValue()),
"distance " + distance.doubleValue()
+ " is not positive!");
} catch (NumberFormatException e) {
Assert.fail("Expected number. found " + result.get("distance"));
}
try {
Number bearing = NumberFormat.getInstance()
.parse(result.get("bearing"));
org.springframework.util.Assert.isTrue(
(Math.abs(bearing.doubleValue()) > 0)
&& (Math.abs(bearing.doubleValue()) < 360),
"bearing must be between 0 and 360, it is "
+ result.get("bearing"));
} catch (NumberFormatException e) {
Assert.fail("Expected number. found " + result.get("bearing"));
}
try {
Number latitude = NumberFormat.getInstance()
.parse(result.get("latitude"));
org.springframework.util.Assert.isTrue(
Math.abs(latitude.doubleValue()) < 180,
"latitude" + latitude + " outside range of -180, 180");
} catch (NumberFormatException e) {
Assert.fail("Expected number. found " + result.get("latitude"));
}
try {
Number longitude = NumberFormat.getInstance()
.parse(result.get("longitude"));
org.springframework.util.Assert.isTrue(
Math.abs(longitude.doubleValue()) < 90, "Longitude "
+ longitude + " outside range of -90 to 90");
} catch (NumberFormatException e) {
Assert.fail(
"Expected number. found " + result.get("longitude"));
}
Assert.assertNotNull(result.get("venue"));
Assert.assertEquals("Strange key found in " + result.keySet(),
result.keySet(), expectedKeys);
}
}
@Test
public void nearMeReturnsOutOfBoundsForNonexistentLatitudeLongitudePair()
throws Exception {
OkHttpClient client = new OkHttpClient();
HttpUrl requestUrl = new HttpUrl.Builder().host("localhost")
.scheme("http").port(this.port).addPathSegment("nearme")
.addQueryParameter("lat", "341.3813934")
.addQueryParameter("lng", "2.1730637").build();
Request request = new Request.Builder().url(requestUrl).get().build();
Response rawResponse = client.newCall(request).execute();
String string = rawResponse.body().string();
List<Map<String, String>> response = new ObjectMapper().readValue(
string, new TypeReference<List<Map<String, String>>>() {
});
Set<String> expectedKeys = Sets.newHashSet("error");
for (String key : response.get(0).keySet()) {
Assert.assertTrue("Strange key found " + key,
expectedKeys.contains(key));
}
Assert.assertEquals("Location out of bounds",
response.get(0).get("error"));
}
@Test
public void covidDoesNotContainGambiaThe() throws Exception {
OkHttpClient client = new OkHttpClient();
HttpUrl requestUrl = new HttpUrl.Builder().host("localhost")
.scheme("http").port(this.port).addPathSegment("covid")
.addQueryParameter("suffix", "csv").build();
Request request = new Request.Builder().url(requestUrl).get().build();
Response rawResponse = client.newCall(request).execute();
String string = rawResponse.body().string();
Tests.LOG.info(string);
CSVParser parser = new CSVParserBuilder().withSeparator(';').build();
BufferedReader br = new BufferedReader(new StringReader(string));
CSVReader reader = new CSVReaderBuilder(br).withCSVParser(parser)
.build();
List<String[]> rows = reader.readAll();
boolean gambiaThe = false;
for (String[] r : rows) {
if (r[0].equals("Gambia, The")) {
gambiaThe = true;
}
}
Assert.assertFalse(gambiaThe);
}
@Test
public void timeSupportsMultipleTimezones() throws Exception {
OkHttpClient client = new OkHttpClient();
HttpUrl requestUrl = new HttpUrl.Builder().host("localhost")
.scheme("http").port(this.port).addPathSegment("time")
.addQueryParameter("z", "3").build();
Request request = new Request.Builder().url(requestUrl).get().build();
Response rawResponse = client.newCall(request).execute();
String string = rawResponse.body().string();
JsonNode response = new ObjectMapper().readValue(string,
JsonNode.class);
String time = response.get("now").asText();
Assert.assertTrue(time.endsWith("+03:00"));
java.util.Iterator<String> fields = response.fieldNames();
List<String> fieldList = Lists.newArrayList(fields);
Assert.assertEquals("now", fieldList.get(0));
try {
fieldList.get(1);
Assert.fail("fieldList has a second element.");
} catch (IndexOutOfBoundsException e) {
}
}
@Test
public void timeSupportsArbitraryTimes() throws Exception {
OkHttpClient client = new OkHttpClient();
HttpUrl requestUrl = new HttpUrl.Builder().host("localhost")
.scheme("http").port(this.port).addPathSegment("time")
.addQueryParameter("fz", "-8")
.addQueryParameter("time", "202003312317")
.addQueryParameter("tz", "0").build();
Request request = new Request.Builder().url(requestUrl).get().build();
Response rawResponse = client.newCall(request).execute();
String string = rawResponse.body().string();
JsonNode response = new ObjectMapper().readValue(string,
JsonNode.class);
DateTime time = ISODateTimeFormat.dateTimeNoMillis()
.parseDateTime(response.get("destTime").asText());
Assert.assertEquals(2020, time.getYear());
Assert.assertEquals(17, time.getMinuteOfHour());
Assert.assertTrue(response.get("destTime").asText().endsWith("Z"));
}
@Test
public void covidHasWorldSum() throws Exception {
HttpUrl requestUrl = new HttpUrl.Builder().host("localhost")
.scheme("http").port(this.port).addPathSegment("covid")
.addQueryParameter("suffix", "json").build();
Request request = new Request.Builder().url(requestUrl).get().build();
Response rawResponse = new OkHttpClient().newCall(request).execute();
String string = rawResponse.body().string();
Map<String, String> json = new ObjectMapper().readValue(string,
new TypeReference<Map<String, String>>() {
});
Assert.assertTrue(json.containsKey(" World"));
NumberFormat formatter = NumberFormat.getIntegerInstance();
Integer totalInWorld = formatter
.parse(json.get(" World").replaceAll(",", "")).intValue();
json.remove(" World");
for (String k : json.keySet()) {
Integer value = formatter.parse(json.get(k).replaceAll(",", ""))
.intValue();
Assert.assertTrue(value + " is greater than " + totalInWorld + "!",
value <= totalInWorld);
}
}
@Test
public void timeDoesntErrorIfOffsetsHaveLeadingSpaces() throws Exception {
OkHttpClient client = new OkHttpClient();
HttpUrl requestUrl = new HttpUrl.Builder().host("localhost")
.scheme("http").port(this.port).addPathSegment("time")
.addQueryParameter("fz", "-8")
.addQueryParameter("time", "202003312317")
.addQueryParameter("tz", "+2").build();
Request request = new Request.Builder().url(requestUrl).get().build();
Response rawResponse = client.newCall(request).execute();
Assert.assertTrue("arbitrary times fail with positive timezones",
rawResponse.isSuccessful());
}
@Test
public void lookingUpGoogleReturnsCompanyInfo() throws Exception {
OkHttpClient client = new OkHttpClient();
HttpUrl requestUrl = new HttpUrl.Builder().host("localhost")
.scheme("http").port(this.port).addPathSegments("stock/info")
.addQueryParameter("sym", "GOOG").build();
Request request = new Request.Builder().url(requestUrl).get().build();
Response rawResponse = client.newCall(request).execute();
Set<String> expectedKeys = Sets.newHashSet("companyName", "now",
"tradeDate", "requestDate", "requestSym");
Map<String, String> response = new ObjectMapper().readValue(
rawResponse.body().string(),
new TypeReference<Map<String, String>>() {
});
for (String e : expectedKeys) {
if (!response.containsKey(e)) {
Assert.fail(e + " not found in " + response.keySet());
}
}
Assert.assertEquals("Alphabet Inc. - Class C Capital Stock",
response.get("companyName"));
Assert.assertTrue(response.get("now").matches("^[0-9.]+$"));
Assert.assertTrue(response.get("volume").matches("^[0-9]+$"));
DateTime dt = ISODateTimeFormat.dateTimeNoMillis()
.parseDateTime(response.get("tradeDate"));
Assert.assertNotNull(dt);
Assertions.assertThat(ISODateTimeFormat.date()
.parseDateTime(response.get("requestDate")));
Assert.assertEquals("GOOG", response.get("requestSym"));
}
@Test
public void bearingReturnsZeroForIdenticalPoints() throws Exception {
OkHttpClient client = new OkHttpClient();
HttpUrl requestUrl = new HttpUrl.Builder().host("localhost")
.scheme("http").port(this.port).addPathSegment("bearing")
.addQueryParameter("point1", "0,0")
.addQueryParameter("point2", "0,0").build();
Request request = new Request.Builder().url(requestUrl).get().build();
String rawResponse = client.newCall(request).execute().body().string();
Map<String, String> response = new ObjectMapper().readValue(rawResponse,
new TypeReference<Map<String, String>>() {
});
Assert.assertEquals("0", response.get("bearingInDegreesFromEast"));
}
@Test
public void xmlValid() throws Exception {
Map<String, String> expected = Maps.newHashMap();
expected.put("valid", "true");
expected.put("xmlUrl", "https://hd1-devel.blogspot.com/atom.xml");
HttpUrl requestUrl = new HttpUrl.Builder().scheme("http")
.host("localhost").port(this.port).addPathSegment("validate")
.addQueryParameter("xmlUrl", expected.get("xmlUrl")).build();
Request request = new Request.Builder().url(requestUrl).build();
Response response = new OkHttpClient().newCall(request).execute();
Assert.assertTrue(response.isSuccessful());
Map<String, String> actual = new ObjectMapper().readValue(
response.body().string(),
new TypeReference<Map<String, String>>() {
});
Assert.assertEquals(expected, actual);
}
@Test
public void quakeReturnsPlusCode() throws Exception {
OkHttpClient client = new OkHttpClient();
HttpUrl requestUrl = new HttpUrl.Builder().host("localhost")
.scheme("http").port(this.port).addPathSegment("quake").build();
Request request = new Request.Builder().url(requestUrl).get().build();
Response rawResponse = client.newCall(request).execute();
Map<String, List<Map<String, String>>> response = new ObjectMapper()
.readValue(rawResponse.body().string(),
new TypeReference<Map<String, List<Map<String, String>>>>() {
});
for (Map<String, String> quake : response.get("results")) {
Assert.assertTrue(quake.containsKey("plusCode"));
}
}
@Test
public void timeTakesZone() throws Exception {
OkHttpClient client = new OkHttpClient();
HttpUrl requestUrl = new HttpUrl.Builder().host("localhost")
.scheme("http").port(this.port).addPathSegment("time")
.addQueryParameter("z", "UTC").build();
Request request = new Request.Builder().url(requestUrl).get().build();
Response rawResponse = client.newCall(request).execute();
Map<String, String> response = new ObjectMapper().readValue(
rawResponse.body().charStream(),
new TypeReference<Map<String, String>>() {
});
Assert.assertTrue(response.get("now").endsWith("Z"));
}
@Test
public void timezoneDefault() throws Exception {
OkHttpClient client = new OkHttpClient();
HttpUrl requestUrl = new HttpUrl.Builder().host("localhost")
.scheme("http").port(this.port).addPathSegment("time").build();
Request request = new Request.Builder().url(requestUrl).get().build();
Response rawResponse = client.newCall(request).execute();
JsonNode response = new ObjectMapper()
.readValue(rawResponse.body().charStream(), JsonNode.class);
Assert.assertTrue(response.get("zones").isArray());
}
@Test
public void timeInvalidZoneReturnsError() throws Exception {
OkHttpClient client = new OkHttpClient();
HttpUrl requestUrl = new HttpUrl.Builder().host("localhost")
.scheme("http").port(this.port).addQueryParameter("z", "local")
.addPathSegment("time").build();
Request request = new Request.Builder().url(requestUrl).get().build();
Response rawResponse = client.newCall(request).execute();
Assert.assertTrue(rawResponse.isSuccessful());
JsonNode response = new ObjectMapper()
.readValue(rawResponse.body().charStream(), JsonNode.class);
Assert.assertEquals("invalid timezone or offset -- local",
response.get("error").asText());
}
@Test
public void filesCanBeRemovedUsingDeleteWithTheirHash() throws Exception {
String hash = "8514df7f9a2220151632fa1dc10564bafa10e24a86a99d48fa088ac6bf5f8762cbbd74a9c384f559a79ad3aa059338475426bc2881209c850fad0972b1abf3e2";
OkHttpClient client = new OkHttpClient();
HttpUrl requestUrl = new HttpUrl.Builder().scheme("http")
.host("localhost").port(this.port).addPathSegment("upload")
.addQueryParameter("hash", hash).build();
Request request = new Request.Builder().url(requestUrl).delete()
.build();
Response response = client.newCall(request).execute();
Assert.assertEquals(HttpStatus.NO_CONTENT.value(), response.code());
}
@Test
public void canUploadFilesAndHaveTheEncryptedBytesReturned()
throws Exception {
String home = System.getProperty("user.home");
String contents = new String(
Files.readAllBytes(Paths.get(home + "/.zshrc")));
Map<String, String> bodyContent = new HashMap<>();
bodyContent.put("contents", contents);
String json = new ObjectMapper().writeValueAsString(bodyContent);
RequestBody body = RequestBody.create(json,
MediaType.parse("application/json"));
OkHttpClient client = new OkHttpClient();
HttpUrl requestUrl = new HttpUrl.Builder().scheme("http")
.host("localhost").port(this.port).addPathSegment("upload")
.build();
Request request = new Request.Builder().url(requestUrl).post(body)
.build();
Response rawResponseObj = client.newCall(request).execute();
String rawResponse = rawResponseObj.body().string();
Set<String> expectedKeys = Sets.newHashSet("size", "hash", "url");
Map<String, String> response = new ObjectMapper().readValue(rawResponse,
new TypeReference<Map<String, String>>() {
});
Assert.assertEquals(expectedKeys, response.keySet());
Assert.assertEquals("923", response.get("size"));
Assert.assertEquals(
"8514df7f9a2220151632fa1dc10564bafa10e24a86a99d48fa088ac6bf5f8762cbbd74a9c384f559a79ad3aa059338475426bc2881209c850fad0972b1abf3e2",
response.get("hash"));
Assert.assertEquals("flle:///Users/hdiwan/.zshrc", response.get("url"));
}
@Test
public void verifiesUploadedFiles() throws Exception {
HttpUrl requestUrl = new HttpUrl.Builder().host("localhost")
.scheme("http").port(this.port).addPathSegment("upload")
.addQueryParameter("hash",
"8514df7f9a2220151632fa1dc10564bafa10e24a86a99d48fa088ac6bf5f8762cbbd74a9c384f559a79ad3aa059338475426bc2881209c850fad0972b1abf3e2")
.build();
Request request = new Request.Builder().url(requestUrl).get().build();
Response rawResponseObj = new OkHttpClient().newCall(request).execute();
String rawResponse = rawResponseObj.body().string();
Set<String> expectedKeys = Sets.newHashSet("hash", "verified", "url");
Map<String, String> response = new ObjectMapper().readValue(rawResponse,
new TypeReference<Map<String, String>>() {
});
Assert.assertEquals(expectedKeys, response.keySet());
Assert.assertEquals(
"8514df7f9a2220151632fa1dc10564bafa10e24a86a99d48fa088ac6bf5f8762cbbd74a9c384f559a79ad3aa059338475426bc2881209c850fad0972b1abf3e2",
response.get("hash"));
Assert.assertEquals("true", response.get("verified"));
Assert.assertEquals("flle:///Users/hdiwan/.zshrc", response.get("url"));
}
@Test
public void weatherTakesCityStateCountry() throws Exception {
OkHttpClient client = new OkHttpClient();
HttpUrl requestUrl = new HttpUrl.Builder().host("localhost")
.scheme("http").port(this.port).addPathSegment("weather")
.addQueryParameter("zip", "Oakland, California, USA").build();
Request request = new Request.Builder().url(requestUrl).get().build();
Response responseObj = client.newCall(request).execute();
Assert.assertEquals(200, responseObj.code());
Set<String> expectedKeys = new HashSet<>();
expectedKeys.add("dewpointF");
expectedKeys.add("dewpointC");
expectedKeys.add("barometricPressure");
expectedKeys.add("temperatureFahrenheit");
expectedKeys.add("temperatureCelcius");
expectedKeys.add("humidity");
expectedKeys.add("time");
expectedKeys.add("precipitation");
expectedKeys.add("current");
expectedKeys.add("request");
expectedKeys.add("location");
Map<String, String> response = new ObjectMapper().readValue(
responseObj.body().string(),
new TypeReference<Map<String, String>>() {
});
Assert.assertEquals(expectedKeys, response.keySet());
Assert.assertEquals(HttpStatus.OK.value(), responseObj.code());
}
@Test
public void weatherWorksOutsideUs() throws Exception {
OkHttpClient client = new OkHttpClient();
HttpUrl requestUrl = new HttpUrl.Builder().host("localhost")
.scheme("http").port(this.port).addPathSegment("weather")
.addQueryParameter("zip", "Singapore, Singapore").build();
Request request = new Request.Builder().url(requestUrl).get().build();
Response responseObj = client.newCall(request).execute();
Assert.assertEquals(200, responseObj.code());
}
@Test
public void weatherTakesZipcode() throws Exception {
OkHttpClient client = new OkHttpClient();
HttpUrl requestUrl = new HttpUrl.Builder().host("localhost")
.scheme("http").port(this.port).addPathSegment("weather")
.addQueryParameter("zip", "94920").build();
Request request = new Request.Builder().url(requestUrl).get().build();
Response responseObj = client.newCall(request).execute();
Assert.assertEquals(200, responseObj.code());
Set<String> expectedKeys = new HashSet<>();
expectedKeys.add("dewpointF");
expectedKeys.add("dewpointC");
expectedKeys.add("barometricPressure");
expectedKeys.add("temperatureFahrenheit");
expectedKeys.add("temperatureCelcius");
expectedKeys.add("humidity");
expectedKeys.add("time");
expectedKeys.add("precipitation");
expectedKeys.add("current");
expectedKeys.add("request");
expectedKeys.add("location");
Map<String, String> response = new ObjectMapper().readValue(
responseObj.body().string(),
new TypeReference<Map<String, String>>() {
});
Assert.assertEquals(expectedKeys, response.keySet());
Assert.assertEquals("94920", response.get("request"));
Assert.assertEquals(
"Belvedere, Marin County, California, 94920, United States of America",
response.get("location"));
expectedKeys.removeAll(
Sets.newHashSet("time", "request", "location", "current"));
NumberFormat nf = NumberFormat.getNumberInstance();
for (String key : expectedKeys) {
try {
nf.parse(response.get(key));
} catch (ParseException e) {
if (key.equals("barometricPressure") && !response
.get("barometricPressure").equals("-Infinity")) {
Assert.fail("<" + key + ", " + response.get(key) + " -- "
+ e.getMessage());
}
}
}
}
@Test
public void gisNamedColumn() throws Exception {
Map<String, String> body = Collections.singletonMap("statement",
"select 1 as column1");
HttpUrl requestUrl = new HttpUrl.Builder().scheme("http")
.host("localhost").port(this.port).addPathSegment("gis")
.build();
Request request = new Request.Builder().url(requestUrl)
.post(RequestBody.create(
new ObjectMapper().writeValueAsString(body),
MediaType.parse("application/json")))
.build();
String rawResponse = new OkHttpClient().newCall(request).execute()
.body().string();
List<Map<String, String>> response = new ObjectMapper().readValue(
rawResponse, new TypeReference<List<Map<String, String>>>() {
});
String value = response.get(0).get("column 1");
Assert.assertEquals("1", value);
}
@Test
public void gisDefaultColumns() throws Exception {
Map<String, String> body = Collections.singletonMap("statement",
"select 1");
HttpUrl requestUrl = new HttpUrl.Builder().scheme("http")
.host("localhost").port(this.port).addPathSegment("gis")
.build();
Request request = new Request.Builder().url(requestUrl)
.post(RequestBody.create(
new ObjectMapper().writeValueAsString(body),
MediaType.parse("application/json")))
.build();
String rawResponse = new OkHttpClient().newCall(request).execute()
.body().string();
List<Map<String, String>> response = new ObjectMapper().readValue(
rawResponse, new TypeReference<List<Map<String, String>>>() {
});
Map<String, String> expected = Collections.singletonMap("column 1",
"1");
Assert.assertTrue(expected.keySet().toString() + " not found",
response.contains(expected));
}
@Test
public void gisAllowsOnlySelect() throws Exception {
Map<String, String> body = Collections.singletonMap("statement",
"insert into foo (id) values (1)");
HttpUrl requestUrl = new HttpUrl.Builder().scheme("http")
.host("localhost").port(this.port).addPathSegment("gis")
.build();
Request request = new Request.Builder().url(requestUrl)
.post(RequestBody.create(
new ObjectMapper().writeValueAsString(body),
MediaType.parse("application/json")))
.build();
Response responseObj = new OkHttpClient().newCall(request).execute();
String rawResponse = responseObj.body().string();
List<Map<String, String>> response = new ObjectMapper().readValue(
rawResponse, new TypeReference<List<Map<String, String>>>() {
});
Assert.assertEquals("select statements allowed only",
response.get(0).get("error"));
Assert.assertEquals(400, responseObj.code());
}
@Test
public void pomXmlUrlReturnsJson() throws Exception {
String expectedJson = "{\"groupId\":\"us.d8u\",\"artifactId\":\"here\",\"packaging\":\"jar\",\"version\":\"1.0-SNAPSHOT\",\"url\":\"http://maven.apache.org\",\"dependencies\":\"[{\\\"groupId\\\":\\\"com.squareup.okhttp\\\",\\\"scope\\\":\\\"test\\\",\\\"artifactId\\\":\\\"okhttp\\\",\\\"type\\\":\\\"jar\\\",\\\"version\\\":\\\"2.5.0\\\"},{\\\"groupId\\\":\\\"org.junit.jupiter\\\",\\\"scope\\\":\\\"test\\\",\\\"artifactId\\\":\\\"junit-jupiter-engine\\\",\\\"type\\\":\\\"jar\\\",\\\"version\\\":\\\"5.5.2\\\"}]\"}";
HttpUrl url = new HttpUrl.Builder().scheme("http").host("localhost")
.port(this.port).addPathSegment("maven")
.addQueryParameter("url",
"https://raw.githubusercontent.com/hasandiwan/here/master/pom.xml")
.build();
Request requestToUpstream = new Request.Builder().url(url).build();
Response responseFromUpstream = new OkHttpClient()
.newCall(requestToUpstream).execute();
Map<String, String> actual = new ObjectMapper().readValue(
responseFromUpstream.body().charStream(),
new TypeReference<Map<String, String>>() {
});
Map<String, String> expected = new ObjectMapper().readValue(
expectedJson, new TypeReference<Map<String, String>>() {
});
try {
Assert.assertEquals(actual.entrySet(), expected.entrySet());
} catch (Throwable t) {
// this.mailIfFails(this.getClass().getEnclosingMethod().getName());
}
}
@Test
public void statDefaultsToCommaAsDelimiter() throws Exception {
MediaType mediaType = MediaType.parse("application/csv");
RequestBody body = RequestBody.create("9;8;7", mediaType);
OkHttpClient client = new OkHttpClient();
Request request = new Request.Builder()
.url("http://localhost:" + this.port + "/stat")
.method("POST", body)
.addHeader("Content-Type", "application/csv").build();
Response response = client.newCall(request).execute();
Map<String, String> responseMap = new ObjectMapper().readValue(
response.body().string(),
new TypeReference<Map<String, String>>() {
});
Assert.assertEquals("body must be ','-delimited numbers",
responseMap.get("error"));
}
@Test
public void houseBillGetsCorrectKeys() throws Exception {
HttpUrl url = HttpUrl
.parse("http://localhost:" + this.port + "/congress")
.newBuilder().addPathSegment("116")
.addQueryParameter("bill", "HR502").build();
Request request = new Request.Builder().url(url).build();
Response response = new OkHttpClient().newCall(request).execute();
Map<String, String> responseMap = new ObjectMapper().readValue(
response.body().string(),
new TypeReference<Map<String, String>>() {
});
Assert.assertEquals("Vargas, Juan", responseMap.get("sponsor"));
Assert.assertEquals("Democratic", responseMap.get("party"));
Assert.assertEquals("CA/51", responseMap.get("district"));
Assert.assertEquals("2019-01-11", responseMap.get("introductionDate"));
Assert.assertEquals("pending", responseMap.get("becameLawOn"));
Assert.assertEquals(
"https://www.congress.gov/bill/116th-congress/house-bill/502",
responseMap.get("link"));
}
@Test
public void congressionalBillIsCaseInsensitive() throws Exception {
HttpUrl url = HttpUrl
.parse("http://localhost:" + this.port + "/congress")
.newBuilder().addPathSegment("116")
.addQueryParameter("bill", "hr502").build();
Request request = new Request.Builder().url(url).build();
Response response = new OkHttpClient().newCall(request).execute();
Assert.assertTrue(response.isSuccessful());
}
@Test
public void randomGivesIntegerGaussianStringWithDefaultLengthOf10()
throws Exception {
OkHttpClient client = new OkHttpClient();
Request request = new Request.Builder()
.url("http://localhost:" + this.port + "/random").build();
Response response = client.newCall(request).execute();
Map<String, String> responseMap = new ObjectMapper().readValue(
response.body().string(),
new TypeReference<Map<String, String>>() {
});
Assert.assertTrue(responseMap.containsKey("integer"));
Assert.assertTrue(responseMap.containsKey("gaussian"));
Assert.assertTrue(responseMap.containsKey("string"));
Assert.assertEquals(10, responseMap.get("string").length());
}
@Test
public void statReturnsKurtosisAndSkewIfSourceIsMoreThanThreeOnly()
throws Exception {
MediaType mediaType = MediaType.parse("text/csv");
RequestBody body = RequestBody.create(
"19.09, 19.55, 17.89, 17.73, 25.15, 27.27, 25.24, 21.05, 21.65, 20.92, 22.61, 15.71, 22.04, 22.6",
mediaType);
OkHttpClient client = new OkHttpClient();
Request request = new Request.Builder()
.url("http://localhost:" + this.port + "/stat")
.method("POST", body).addHeader("Content-Type", "text/csv")
.build();
Response response = client.newCall(request).execute();
JsonNode responseMap = new ObjectMapper()
.readValue(response.body().string(), JsonNode.class);
Assert.assertFalse(responseMap.has("kurtosis"));
Assert.assertTrue(responseMap.has("skew"));
Assert.assertEquals("-0.33097877474997217",
responseMap.get("kurtosis"));
Assert.assertEquals("0.1392264466270439", responseMap.get("skew"));
}
@Test
public void statTakesNumbersOnly() throws Exception {
MediaType mediaType = MediaType.parse("text/csv");
RequestBody body = RequestBody.create("a,b,c", mediaType);
OkHttpClient client = new OkHttpClient();
Request request = new Request.Builder()
.url("http://localhost:" + this.port + "/stat")
.method("POST", body).addHeader("Content-Type", " text/csv")
.build();
Response response = client.newCall(request).execute();
Map<String, String> responseMap = new ObjectMapper().readValue(
response.body().string(),
new TypeReference<Map<String, String>>() {
});
Assert.assertEquals(responseMap.get("error"),
"body must be ','-delimited numbers");
Assert.assertEquals(HttpStatus.OK.value(), response.code());
}
@Test
public void statReturnsExpectedKeysAndNoMore() throws Exception {
MediaType mediaType = MediaType.parse("text/csv");
RequestBody body = RequestBody.create(
"19.09, 19.55, 17.89, 17.73, 25.15, 27.27, 25.24, 21.05, 21.65, 20.92, 22.61, 15.71, 22.04, 22.6",
mediaType);
OkHttpClient client = new OkHttpClient();
Request request = new Request.Builder()
.url("http://localhost:" + this.port + "/stat")
.method("POST", body).addHeader("Content-Type", " text/csv")
.build();
Response response = client.newCall(request).execute();
Map<String, String> responseMap = new ObjectMapper().readValue(
response.body().string(),
new TypeReference<Map<String, String>>() {
});
Set<String> expected = Sets.newHashSet("arithmeticMean",
"arithmeticMeanWeight", "geometricMean", "harmonicMean",
"intercept", "kurtosis", "lowerQuartile", "maximum", "median",
"minimum", "normalized", "pearsonCorrelation", "product",
"rSquared", "skew", "slope", "source", "stderr", "sum", "time",
"unitVector", "upperQuartile", "variance", "sd");
for (String expectedKey : expected) {
if (!responseMap.containsKey(expectedKey)) {
throw new RuntimeException(
expectedKey + " missing from return value");
}
}
Assert.assertEquals(Collections.EMPTY_SET,
Sets.difference(responseMap.keySet(), expected));
}
@Test
public void statReturnsCorrectStandardDeviation() throws Exception {
MediaType mediaType = MediaType.parse("text/csv");
RequestBody body = RequestBody.create(
"19.09,19.55, 17.89, 17.73, 25.15, 27.27, 25.24, 21.05, 21.65, 20.92, 22.61, 15.71, 22.04, 22.6",
mediaType);
Request request = new Request.Builder()
.url("http://localhost:" + this.port + "/stat")
.method("POST", body).addHeader("Content-Type", " text/csv")
.build();
Response response = new OkHttpClient().newCall(request).execute();
Map<String, String> responseMap = new ObjectMapper().readValue(
response.body().string(),
new TypeReference<Map<String, String>>() {
});
Assert.assertEquals("3.0918252980188554", responseMap.get("sd"));
}
@Test
public void statReturnsCorrectPopulationVariance() throws Exception {
MediaType mediaType = MediaType.parse("text/csv");
RequestBody body = RequestBody.create("1,2,1,1,1.5,2.1,3.0", mediaType);
Request request = new Request.Builder()
.url("http://localhost:" + this.port + "/stat")
.method("POST", body).addHeader("Content-Type", "text/csv")
.build();
Response response = new OkHttpClient().newCall(request).execute();
Map<String, String> responseMap = new ObjectMapper().readValue(
response.body().string(),
new TypeReference<Map<String, String>>() {
});
Assert.assertEquals("0.4910204081632653", responseMap.get("variance"));
}
@Test
public void statReturnsCorrectZedScores() throws Exception {
MediaType mediaType = MediaType.parse("text/csv");
RequestBody body = RequestBody.create("1,2,1,1,1.5,2.1,3.0", mediaType);
Request request = new Request.Builder()
.url("http://localhost:" + this.port + "/stat")
.method("POST", body)
.addHeader("Content-Type", "application/csv").build();
Response response = new OkHttpClient().newCall(request).execute();
Map<String, String> responseMap = new ObjectMapper().readValue(
response.body().string(),
new TypeReference<Map<String, String>>() {
});
Assert.assertEquals(
"-0.9377995503704291, 0.489286721932398, -0.9377995503704291, -0.9377995503704291, -0.22425641421901552, 0.6319953491626809, 1.916372994235225",
responseMap.get("zScores"));
}
@Test
public void canChangeAuthKeyOnDemand() throws Exception {
Map<String, String> body = Maps.newHashMap();
body.put("userId", "1");
body.put("endpoint", "/");
RequestBody patchBody = RequestBody.create(
new ObjectMapper().writeValueAsBytes(body),
MediaType.parse("application/json"));
HttpUrl patchUrl = new HttpUrl.Builder().scheme("http")
.host("localhost").port(this.port)
.addEncodedPathSegment("/auth").build();
AuthBean original = null, newest = null;
for (AuthBean a : this.userRepository
.findById(Long.valueOf(body.get("userId"))).get().getKeys()) {
if (a.getEndpointBean().getEndpoint().equals("/")) {
original = a;
break;
}
}
Request patchRequest = new Request.Builder().url(patchUrl)
.post(patchBody).build();
Response patchResponse = new OkHttpClient().newCall(patchRequest)
.execute();
for (AuthBean a : this.userRepository
.findById(Long.valueOf(body.get("userId"))).get().getKeys()) {
if (a.getEndpointBean().getEndpoint().equals("/")) {
newest = a;
break;
}
}
Assert.assertNotEquals(newest, original);
Assert.assertEquals(HttpStatus.NO_CONTENT.value(),
patchResponse.code());
}
@Test
public void berkeleyAuthFailedYields415() throws Exception {
MediaType mediaType = MediaType.parse("application/json");
Map<String, String> body = Maps.newHashMap();
body.put("user", "[email protected]");
body.put("password", "foo");
Request request = new Request.Builder()
.url("http://localhost:" + this.port + "/stat")
.post(RequestBody.create(
new ObjectMapper().writeValueAsString(body), mediaType))
.addHeader("Content-Type", "text/csv").build();
Response response = new OkHttpClient().newCall(request).execute();
Assert.assertEquals(415, response.code());
}
@Test
public void statReturnsCorrectMedian() throws Exception {
MediaType mediaType = MediaType.parse("text/csv");
RequestBody body = RequestBody.create(this.SAMPLE_CSV, mediaType);
OkHttpClient client = new OkHttpClient();
Request request = new Request.Builder()
.url("http://localhost:" + this.port + "/stat")
.method("POST", body).addHeader("Content-Type", " text/csv")
.build();
Response response = client.newCall(request).execute();
Map<String, String> responseMap = new ObjectMapper().readValue(
response.body().string(),
new TypeReference<Map<String, String>>() {
});
Assert.assertEquals("7.5", responseMap.get("median"));
}
@Test
public void statReturnsCorrectLowerQuartile() throws Exception {
MediaType mediaType = MediaType.parse("text/csv");
RequestBody body = RequestBody.create(this.SAMPLE_CSV, mediaType);
OkHttpClient client = new OkHttpClient();
Request request = new Request.Builder()
.url("http://localhost:" + this.port + "/stat")
.method("POST", body).addHeader("Content-Type", " text/csv")
.build();
Response response = client.newCall(request).execute();
Map<String, String> responseMap = new ObjectMapper().readValue(
response.body().string(),
new TypeReference<Map<String, String>>() {
});
Assert.assertEquals("6.25", responseMap.get("lowerQuartile"));
}
@Test
public void statReturnsCorrectUpperQuartile() throws Exception {
MediaType mediaType = MediaType.parse("text/csv");
RequestBody body = RequestBody.create(this.SAMPLE_CSV, mediaType);
OkHttpClient client = new OkHttpClient();
Request request = new Request.Builder()
.url("http://localhost:" + this.port + "/stat")
.method("POST", body).addHeader("Content-Type", " text/csv")
.build();
Response response = client.newCall(request).execute();
Map<String, String> responseMap = new ObjectMapper().readValue(
response.body().string(),
new TypeReference<Map<String, String>>() {
});
Assert.assertEquals("8.75", responseMap.get("upperQuartile"));
}
@Test
public void statReturnsCorrectArithmeticMean() throws Exception {
MediaType mediaType = MediaType.parse("text/csv");
RequestBody body = RequestBody.create(this.SAMPLE_CSV, mediaType);
OkHttpClient client = new OkHttpClient();
Request request = new Request.Builder()
.url("http://localhost:" + this.port + "/stat")
.method("POST", body).addHeader("Content-Type", " text/csv")
.build();
Response response = client.newCall(request).execute();
Map<String, String> responseMap = new ObjectMapper().readValue(
response.body().string(),
new TypeReference<Map<String, String>>() {
});
Assert.assertEquals("7.5", responseMap.get("arithmeticMean"));
}
@Test
public void statReturnsCorrectGeometricMean() throws Exception {
MediaType mediaType = MediaType.parse("text/csv");
RequestBody body = RequestBody.create(this.SAMPLE_CSV, mediaType);
OkHttpClient client = new OkHttpClient();
Request request = new Request.Builder()
.url("http://localhost:" + this.port + "/stat")
.method("POST", body).addHeader("Content-Type", " text/csv")
.build();
Response response = client.newCall(request).execute();
Map<String, String> responseMap = new ObjectMapper().readValue(
response.body().string(),
new TypeReference<Map<String, String>>() {
});
Assert.assertEquals("7.415585502134682",
responseMap.get("geometricMean"));
}
@Test
public void statReturnsCorrectHarmonicMean() throws Exception {
MediaType mediaType = MediaType.parse("text/csv");
RequestBody body = RequestBody.create(this.SAMPLE_CSV, mediaType);
OkHttpClient client = new OkHttpClient();
Request request = new Request.Builder()
.url("http://localhost:" + this.port + "/stat")
.method("POST", body).addHeader("Content-Type", " text/csv")
.build();
Response response = client.newCall(request).execute();
Map<String, String> responseMap = new ObjectMapper().readValue(
response.body().string(),
new TypeReference<Map<String, String>>() {
});
Assert.assertEquals("7.415585502134682",
responseMap.get("harmonicMean"));
}
@Test
public void statReturnsCorrectIntercept() throws Exception {
MediaType mediaType = MediaType.parse("text/csv");
RequestBody body = RequestBody.create("1,2,1,1,1.5,2.1,3.0", mediaType);
OkHttpClient client = new OkHttpClient();
Request request = new Request.Builder()
.url("http://localhost:" + this.port + "/stat")
.method("POST", body).addHeader("Content-Type", " text/csv")
.build();
Response response = client.newCall(request).execute();
Map<String, String> responseMap = new ObjectMapper().readValue(
response.body().string(),
new TypeReference<Map<String, String>>() {
});
Assert.assertEquals("0.9392857142857143", responseMap.get("intercept"));
}
@Test
public void statReturnsCorrectKurtosis() throws Exception {
MediaType mediaType = MediaType.parse("text/csv");
RequestBody body = RequestBody.create(this.SAMPLE_CSV, mediaType);
OkHttpClient client = new OkHttpClient();
Request request = new Request.Builder()
.url("http://localhost:" + this.port + "/stat")
.method("POST", body).addHeader("Content-Type", " text/csv")
.build();
Response response = client.newCall(request).execute();
Map<String, String> responseMap = new ObjectMapper().readValue(
response.body().string(),
new TypeReference<Map<String, String>>() {
});
Assert.assertEquals("-1.1999999999999993", responseMap.get("kurtosis"));
}
@Test
public void statReturnsCorrectMaximum() throws Exception {
MediaType mediaType = MediaType.parse("text/csv");
RequestBody body = RequestBody.create(this.SAMPLE_CSV, mediaType);
OkHttpClient client = new OkHttpClient();
Request request = new Request.Builder()
.url("http://localhost:" + this.port + "/stat")
.method("POST", body).addHeader("Content-Type", " text/csv")
.build();
Response response = client.newCall(request).execute();
Map<String, String> responseMap = new ObjectMapper().readValue(
response.body().string(),
new TypeReference<Map<String, String>>() {
});
Assert.assertEquals("9.0", responseMap.get("maximum"));
}
@Test
public void statReturnsCorrectMinimum() throws Exception {
MediaType mediaType = MediaType.parse("text/csv");
RequestBody body = RequestBody.create(this.SAMPLE_CSV, mediaType);
OkHttpClient client = new OkHttpClient();
Request request = new Request.Builder()
.url("http://localhost:" + this.port + "/stat")
.method("POST", body).addHeader("Content-Type", " text/csv")
.build();
Response response = client.newCall(request).execute();
Map<String, String> responseMap = new ObjectMapper().readValue(
response.body().string(),
new TypeReference<Map<String, String>>() {
});
Assert.assertEquals("6.0", responseMap.get("minimum"));
}
@Test
public void statReturnsCorrectMode() throws Exception {
MediaType mediaType = MediaType.parse("text/csv");
RequestBody body = RequestBody.create("1,1,1,1", mediaType);
OkHttpClient client = new OkHttpClient();
String host = "http://localhost:" + this.port + "/stat";
Tests.LOG.debug(host + " is where the server is running.");
Request request = new Request.Builder().url(host).method("POST", body)
.addHeader("Content-Type", " text/csv").build();
Response response = client.newCall(request).execute();
Map<String, String> responseMap = new ObjectMapper().readValue(
response.body().string(),
new TypeReference<Map<String, String>>() {
});
Assert.assertEquals("1.0", responseMap.get("mode"));
}
@Test
public void covidHasDateIfBeforeToday() throws Exception {
HttpUrl requestUrl = new HttpUrl.Builder().scheme("http")
.host("localhost").port(this.port).addPathSegment("covid")
.addQueryParameter("suffix", "json")
.addQueryParameter("days", Integer.toString(1)).build();
Tests.LOG.debug("About to request " + requestUrl.toString());
Request request = new Request.Builder().url(requestUrl).build();
Response response = new OkHttpClient().newCall(request).execute();
Map<String, String> data = new ObjectMapper().readValue(
response.body().string(),
new TypeReference<Map<String, String>>() {
});
Assert.assertTrue(data.containsKey("date"));
DateTimeFormatter dtf = ISODateTimeFormat.date();
try {
int delta = Days.daysBetween(dtf.parseDateTime(data.get("date")),
DateTime.now().minusDays(1)).getDays();
Assert.assertEquals(1, delta);
} catch (IllegalArgumentException e) {
Assert.fail("failed to parse " + data.get("date"));
}
}
@Test
public void statReturnsCorrectNormalized() throws Exception {
MediaType mediaType = MediaType.parse("application/csv");
RequestBody body = RequestBody.create(this.SAMPLE_CSV, mediaType);
OkHttpClient client = new OkHttpClient();
Request request = new Request.Builder()
.url(new HttpUrl.Builder().scheme("http").host("localhost")
.port(this.port).addEncodedPathSegment("stat").build())
.method("POST", body)
.addHeader("Content-Type", "application/csv").build();
Response response = client.newCall(request).execute();
JsonNode responseMap = new ObjectMapper()
.readValue(response.body().string(), JsonNode.class)
.get("stats");
Assert.assertEquals(
"0.5934424260562083, 0.5275043787166296, 0.4615663313770509, 0.3956282840374722",
responseMap.get("normalized"));
}
@Test
public void statReturnsCorrectPearsonCorrelation() throws Exception {
MediaType mediaType = MediaType.parse("text/csv");
RequestBody body = RequestBody.create(this.SAMPLE_CSV, mediaType);
OkHttpClient client = new OkHttpClient();
Request request = new Request.Builder()
.url("http://localhost:" + this.port + "/stat")
.method("POST", body).addHeader("Content-Type", " text/csv")
.build();
Response response = client.newCall(request).execute();
Map<String, String> responseMap = new ObjectMapper().readValue(
response.body().string(),
new TypeReference<Map<String, String>>() {
});
Assert.assertEquals("-1.0", responseMap.get("pearsonCorrelation"));
}
@Test
public void statReturnsCorrectProduct() throws Exception {
MediaType mediaType = MediaType.parse("text/csv");
RequestBody body = RequestBody.create(this.SAMPLE_CSV, mediaType);
OkHttpClient client = new OkHttpClient();
Request request = new Request.Builder()
.url("http://localhost:" + this.port + "/stat")
.method("POST", body).addHeader("Content-Type", " text/csv")
.build();
Response response = client.newCall(request).execute();
Map<String, String> responseMap = new ObjectMapper().readValue(
response.body().string(),
new TypeReference<Map<String, String>>() {
});
Assert.assertEquals("3024.0", responseMap.get("product"));
}
@Test
public void statReturnsCorrectRSquared() throws Exception {
MediaType mediaType = MediaType.parse("text/csv");
RequestBody body = RequestBody.create(this.SAMPLE_CSV, mediaType);
OkHttpClient client = new OkHttpClient();
Request request = new Request.Builder()
.url("http://localhost:" + this.port + "/stat")
.method("POST", body).addHeader("Content-Type", " text/csv")
.build();
Response response = client.newCall(request).execute();
Map<String, String> responseMap = new ObjectMapper().readValue(
response.body().string(),
new TypeReference<Map<String, String>>() {
});
Assert.assertEquals("1.0", responseMap.get("rSquared"));
}
@Test
public void statReturnsCorrectSlope() throws Exception {
MediaType mediaType = MediaType.parse("text/csv");
RequestBody body = RequestBody.create(this.SAMPLE_CSV, mediaType);
OkHttpClient client = new OkHttpClient();
Request request = new Request.Builder()
.url("http://localhost:" + this.port + "/stat")
.method("POST", body).addHeader("Content-Type", " text/csv")
.build();
Response response = client.newCall(request).execute();
Map<String, String> responseMap = new ObjectMapper().readValue(
response.body().string(),
new TypeReference<Map<String, String>>() {
});
Assert.assertEquals("-1.0", responseMap.get("slope"));
}
@Test
public void statReturnsCorrectVariance() throws Exception {
MediaType mediaType = MediaType.parse("text/csv");
RequestBody body = RequestBody.create(this.SAMPLE_CSV, mediaType);
OkHttpClient client = new OkHttpClient();
Request request = new Request.Builder()
.url("http://localhost:" + this.port + "/stat")
.method("POST", body).addHeader("Content-Type", " text/csv")
.build();
Response response = client.newCall(request).execute();
Map<String, String> responseMap = new ObjectMapper().readValue(
response.body().string(),
new TypeReference<Map<String, String>>() {
});
Assert.assertEquals("1.667", responseMap.get("variance"));
}
@Test
public void statAllowsNegativeAndFractionalValues() throws Exception {
MediaType mediaType = MediaType.parse("text/csv");
RequestBody body = RequestBody.create("-6,7,8,9,0.1", mediaType);
OkHttpClient client = new OkHttpClient();
Request request = new Request.Builder()
.url("http://localhost:" + this.port + "/stat")
.method("POST", body).addHeader("Content-Type", " text/csv")
.build();
Response response = client.newCall(request).execute();
Assert.assertEquals(true, response.isSuccessful());
}
@Test
public void distanceBetweenPointAndItselfIsZeroMeters() throws Exception {
Request request = new Request.Builder()
.url(new HttpUrl.Builder().addQueryParameter("point1", "0,0")
.addQueryParameter("point2", "0,0").host("localhost")
.port(this.port).scheme("http")
.addPathSegment("distance").build())
.build();
OkHttpClient client = new OkHttpClient();
Response response = client.newCall(request).execute();
Map<String, String> responseMap = new ObjectMapper().readValue(
response.body().string(),
new TypeReference<Map<String, String>>() {
});
Assert.assertEquals("0,0", responseMap.get("point1"));
Assert.assertEquals("0,0", responseMap.get("point2"));
Assert.assertEquals("0", responseMap.get("distanceInMeters"));
}
@Test
public void countryForItu34IsSpain() throws Exception {
HttpUrl requestUrl = new HttpUrl.Builder().host("localhost")
.scheme("http").port(this.port).addPathSegment("itu")
.addQueryParameter("cc", "34").build();
Request request = new Request.Builder().url(requestUrl).get().build();
String rawResponse = new OkHttpClient().newCall(request).execute()
.body().string();
List<Map<String, String>> response = new ObjectMapper().readValue(
rawResponse, new TypeReference<List<Map<String, String>>>() {
});
Assert.assertEquals("Spain", response.get(0).get("English"));
Assert.assertEquals("+34", response.get(0).get("itu"));
}
@Test
public void moneyIsCaseInsensitive() throws Exception {
Request request = new Request.Builder()
.url("http://localhost:" + this.port + "/money/2/eur/eur")
.build();
Response response = new OkHttpClient.Builder().build().newCall(request)
.execute();
Assert.assertEquals(200, response.code());
}
@Test
public void moneyHandlesAdjustmentFactor() throws Exception {
Request request = new Request.Builder().url(
"http://localhost:" + this.port + "/money/2/usd/usd?adj=0.8")
.build();
Response rawResponse = new OkHttpClient.Builder().build()
.newCall(request).execute();
Map<String, String> response = new ObjectMapper().readValue(
rawResponse.body().bytes(),
new TypeReference<Map<String, String>>() {
});
Assert.assertEquals("1.6",
NumberFormat.getCurrencyInstance(Locale.GERMANY)
.parse(response.get("destinationAmount")).toString());
}
@Test
public void moneySupportsEUR() throws Exception {
Request request = new Request.Builder()
.url("http://localhost:" + this.port + "/money/2/EUR/EUR")
.build();
Response response = new OkHttpClient.Builder().build().newCall(request)
.execute();
Assert.assertEquals(200, response.code());
}
@Test
public void twoDollarsEqualsTwoDollars() throws Exception {
Request request = new Request.Builder()
.url("http://localhost:" + this.port + "/money/2/USD/USD")
.build();
Response responseObj = new OkHttpClient.Builder().build()
.newCall(request).execute();
String rawResponse = responseObj.body().string();
Map<String, String> response = new ObjectMapper().readValue(rawResponse,
new TypeReference<Map<String, String>>() {
});
DateTime today = DateTime.now();
DateTimeFormatter fmt = ISODateTimeFormat.date();
String timestamp = fmt.print(today);
Assert.assertEquals("US$2.00", response.get("destinationAmount"));
Assert.assertEquals("USD", response.get("sourceCurrency"));
Assert.assertEquals("USD", response.get("destinationCurrency"));
Assert.assertEquals(timestamp, response.get("requestedDate"));
}
@Test
public void noAmountReturnsCountry() throws Exception {
HttpUrl url = new HttpUrl.Builder().host("localhost").scheme("http")
.port(this.port).addPathSegment("money").addPathSegment("AFN")
.build();
Request requstObj = new Request.Builder().url(url).build();
String rawResponse = new OkHttpClient().newCall(requstObj).execute()
.body().string();
Map<String, String> response = new ObjectMapper().readValue(rawResponse,
new TypeReference<Map<String, String>>() {
});
Assert.assertEquals("Afghani", response.get("currency"));
Assert.assertEquals("Afghanistan", response.get("country"));
Assert.assertEquals("AFN", response.get("iso4217"));
}
@Test
public void moneyReturnsErrorForInvalidSynbols() throws Exception {
HttpUrl url = new HttpUrl.Builder().scheme("http").host("localhost")
.port(this.port).addEncodedPathSegments("money/2/UnitY/USD")
.build();
Response rawResponse = new OkHttpClient()
.newCall(new Request.Builder().url(url).build()).execute();
Map<String, String> returnMessage = new ObjectMapper().readValue(
rawResponse.body().string(),
new TypeReference<Map<String, String>>() {
});
Assert.assertEquals(
"Money amount UNITY cannot be parsed, valid currencies are: {CHF,HRK,MXN,ZAR,INR,CNY,THB,AUD,ILS,KRW,JPY,PLN,GBP,IDR,HUF,PHP,TRY,RUB,ISK,HKD,EUR,DKK,USD,CAD,MYR,BGN,NOK,RON,SGD,CZK,SEK,NZD,BRL}",
returnMessage.get("error"));
}
@Test
public void plusEncodingOsmUrlsWorks() throws Exception {
String content = "https://www.openstreetmap.org/#map=18/34.10568/-118.44618";
Map<String, String> params = Collections.singletonMap("url", content);
RequestBody body = RequestBody.create(
new ObjectMapper().writeValueAsString(params),
MediaType.parse("application/json"));
Request request = new Request.Builder()
.url(new HttpUrl.Builder().host("localhost").port(this.port)
.scheme("http").addPathSegment("plus").build())
.post(body).build();
Response resp = new OkHttpClient().newCall(request).execute();
Map<String, String> response = new ObjectMapper().readValue(
resp.body().string(), new TypeReference<Map<String, String>>() {
});
Assert.assertEquals("85634H43+7G", response.get("plusCode"));
}
@Test
public void nonexistentUserReturnsNotFoundAndSentinelAmountForBalance() {
Request request = new Request.Builder()
.url(new HttpUrl.Builder().host("localhost").port(this.port)
.scheme("http").addPathSegment("bal")
.addQueryParameter("user", "[email protected]").build())
.get().build();
Response res = null;
try {
res = new OkHttpClient().newCall(request).execute();
} catch (IOException e) {
Tests.LOG.error(e.getMessage(), e);
}
Map<String, BigDecimal> response = null;
try {
response = new ObjectMapper().readValue(res.body().string(),
new TypeReference<Map<String, BigDecimal>>() {
});
} catch (IOException e) {
Tests.LOG.error(e.getMessage(), e);
}
List<String> keys = new ArrayList<>(response.keySet());
Assert.assertTrue(keys.get(0).endsWith("not found"));
Assert.assertEquals("-999",
response.get("[email protected] not found").toPlainString());
Assert.assertEquals(HttpStatus.INTERNAL_SERVER_ERROR.value(),
res.code());
}
@Test
public void statHandlesEmbeddedSpaces() throws Exception {
String requestBody = "1, 2, 3";
RequestBody body = RequestBody.create(requestBody,
MediaType.parse("application/csv"));
Request request = new Request.Builder()
.url(new HttpUrl.Builder().host("localhost").scheme("http")
.port(this.port).addPathSegment("stat").build())
.post(body).build();
Response response = new OkHttpClient().newCall(request).execute();
Assert.assertTrue(response.isSuccessful());
}
@Test
public void statHandlesTrailingCommas() throws Exception {
String requestBody = "1,2,3,";
RequestBody body = RequestBody.create(requestBody,
MediaType.parse("application/csv"));
Request request = new Request.Builder()
.url(new HttpUrl.Builder().host("localhost").scheme("http")
.port(this.port).addPathSegment("stat").build())
.post(body).build();
Response response = new OkHttpClient().newCall(request).execute();
Assert.assertTrue(response.isSuccessful());
}
@Test
public void geocodeRequiresAddressOrLatLon() throws Exception {
Map<String, String> responseComponent = new HashMap<>();
responseComponent.put("error", "specify both lat and lng **or** addr");
List<Map<String, String>> expectedResponse = Collections
.singletonList(responseComponent);
String expected = new ObjectMapper()
.writeValueAsString(expectedResponse);
RequestBody body = RequestBody.create(
new ObjectMapper().writeValueAsString(expected),
MediaType.parse("application/json"));
Request request = new Request.Builder()
.url(new HttpUrl.Builder().host("localhost").scheme("http")
.port(this.port).addPathSegment("geocode").build())
.post(body).build();
Response response = new OkHttpClient().newCall(request).execute();
Assert.assertTrue(!response.isSuccessful());
}
@Test
public void plusEncodingRequiresCodeOrLocationOrUrl() throws Exception {
String message = "addr, code, latitude/longitude, or url required as body";
Map<String, String> expected = Collections.singletonMap("error",
message);
RequestBody body = RequestBody.create(
new ObjectMapper().writeValueAsString(expected),
MediaType.parse("application/json"));
Request request = new Request.Builder()
.url(new HttpUrl.Builder().scheme("http").host("localhost")
.port(this.port).addPathSegment("plus").build())
.post(body).build();
Response response = new OkHttpClient().newCall(request).execute();
Assert.assertEquals(response.code(),
HttpStatus.PRECONDITION_REQUIRED.value());
Assert.assertEquals(expected,
new ObjectMapper().readValue(response.body().string(),
new TypeReference<Map<String, String>>() {
}));
}
@Test
public void reversePlusEncodingWorks() throws Exception {
Map<String, String> expected = new ObjectMapper().readValue(
"{\"request\":\"849VRH2X+68\",\"latitude\":\"37.8005625\",\"radius\":\"1.7677669530250526E-4\",\"longitude\":\"-122.40168750000001\"} ",
new TypeReference<Map<String, String>>() {
});
Map<String, String> body = Collections.singletonMap("code",
"849VRH2X+68");
RequestBody requestBody = RequestBody.create(
new ObjectMapper().writeValueAsString(body),
MediaType.parse("application/json"));
Request request = new Request.Builder()
.url("http://localhost:" + this.port + "/plus")
.post(requestBody).build();
String actualSrc = new OkHttpClient().newCall(request).execute().body()
.string();
Map<String, String> actual = new ObjectMapper().readValue(actualSrc,
new TypeReference<Map<String, String>>() {
});
Assert.assertEquals(expected, actual);
}
@Test
public void plusEncodingLatLonWorks() throws Exception {
Map<String, String> expected = new HashMap<>();
expected.put("plusCode", "85634H42+HH");
Map<String, String> params = new HashMap<>();
params.put("latitude", "34.10638");
params.put("longitude", "-118.44858");
expected.putAll(params);
// this.restTemplate.postForObject("/plus", params, String.class)
HttpUrl url = new HttpUrl.Builder().scheme("http").host("localhost")
.port(this.port).addPathSegment("plus").build();
Request request = new Request.Builder().url(url)
.post(RequestBody.create(
new ObjectMapper().writeValueAsString(params),
MediaType.parse("application/json")))
.build();
Response response = new OkHttpClient().newCall(request).execute();
Map<String, String> actual = new ObjectMapper().readValue(
response.body().string(),
new TypeReference<Map<String, String>>() {
});
Assert.assertEquals(expected.keySet(), actual.keySet());
}
@Test
public void uuWorks() throws Exception {
Map<String, String> bodyMap = Maps.newHashMap();
bodyMap.put("string", "java");
okhttp3.RequestBody body = okhttp3.RequestBody.create(
new ObjectMapper().writeValueAsString(bodyMap),
MediaType.parse("application/json"));
HttpUrl endpoint = HttpUrl
.parse("http://localhost:" + this.port + "/uu");
Request request = new Request.Builder().url(endpoint).post(body)
.build();
Response response = new OkHttpClient().newCall(request).execute();
Map<String, String> result = new ObjectMapper().readValue(
response.body().bytes(),
new TypeReference<Map<String, String>>() {
});
Map<String, String> expected = Maps.newHashMap();
expected.put("in", "java");
expected.put("output", "$:F%V80 ");
Assert.assertEquals(expected, result);
}
// FIXME verify GET /auth/<userId> functionality
@Test
public void getAuth() throws Exception {
// setup code
User ninthUser = new User();
ninthUser.setUsing2FA(Boolean.FALSE);
ninthUser.setName("[email protected]");
ninthUser.setUserId(-9l);
ninthUser.setNumber("44079122467");
this.userRepository.save(ninthUser);
try {
Request request = new Request.Builder()
.url("http://localhost:" + this.port + "/auth/9").build();
Response response = null;
try {
response = new OkHttpClient().newCall(request).execute();
} catch (IOException e1) {
Tests.LOG.error(e1.getMessage(), e1);
}
Assert.assertEquals(HttpStatus.OK.value(), response.code());
Map<String, String> responseBody = null;
try {
responseBody = new ObjectMapper().readValue(
response.body().string(),
new TypeReference<Map<String, String>>() {
});
} catch (IOException e) {
Tests.LOG.error(e.getMessage(), e);
}
Set<String> expected = Sets.newHashSet("accessKey", "request",
"accessSecret");
Assert.assertEquals(expected, responseBody.keySet());
Assert.assertEquals(Collections.EMPTY_SET,
Sets.difference(expected, responseBody.keySet()));
Assert.assertEquals("1", responseBody.get("request"));
} catch (Exception e) {
} finally {
this.userRepository.delete(ninthUser);
}
}
// FIXME verify PATCH /auth functionality
public void patchAuth() throws Exception {
Map<String, String> bodyObj = Maps.newHashMap();
bodyObj.put("userId", "1");
bodyObj.put("endpoint", "/");
String bodyJson = new ObjectMapper().writeValueAsString(bodyObj);
RequestBody body = RequestBody.create(bodyJson,
MediaType.parse("application/json"));
Request request = new Request.Builder()
.url("http://localhost:" + this.port + "/auth").patch(body)
.build();
OkHttpClient client = new OkHttpClient();
Response response = client.newCall(request).execute();
Map<String, String> responseBody = null;
responseBody = new ObjectMapper().readValue(response.body().string(),
new TypeReference<Map<String, String>>() {
});
Assert.assertNotNull("accessKey is null",
responseBody.get("accessKey"));
Assert.assertNotNull("accessSecret is null",
responseBody.get("accessSecret"));
Assert.assertEquals(HttpStatus.OK.value(), response.code());
Set<String> expected = Sets.newHashSet("accessKey", "endpoint",
"accessSecret");
Assert.assertEquals(expected, responseBody.keySet());
Assert.assertEquals(Collections.EMPTY_SET,
Sets.difference(expected, responseBody.keySet()));
}
@Test
public void zipReturnsCitiesStateCountyTimezoneAreacodesCountryLatitudeLongitude()
throws Exception {
Set<String> expected = Sets.newHashSet("cities", "state", "county",
"timezone", "itu", "country", "latitude", "longitude", "valid?",
"request");
Request request = new Request.Builder()
.url("http://localhost:" + this.port + "/zip?code=00602")
.build();
Response rawResponse = new OkHttpClient().newCall(request).execute();
ObjectMapper mapper = new ObjectMapper();
Map<String, String> response = mapper.readValue(
rawResponse.body().bytes(),
new TypeReference<Map<String, String>>() {
});
Assert.assertEquals(expected, response.keySet());
Assert.assertEquals("00602", response.get("request"));
Assert.assertEquals("true", response.get("valid?"));
Assert.assertEquals("PR", response.get("state"));
Assert.assertEquals("Aguada Municipio", response.get("county"));
Assert.assertEquals("18.38", response.get("latitude"));
Assert.assertEquals("-67.18", response.get("longitude"));
Assert.assertEquals("United States", response.get("country"));
Assert.assertEquals(HttpStatus.OK.value(), rawResponse.code());
}
public void getCreditLetsAccountBeUpdated() {
String auth = "aaf5ba98-78a3-44a2-8370-7347052aa6cb:6017a423-6728-4e60-83b7-34b807d304fe";
String authHeaderValue = new String(
Base64.getEncoder().encode(("Bearer " + auth).getBytes()));
DateTime dt = new DateTime().withDayOfMonth(1).withYear(2000)
.withMonthOfYear(1);
Map<String, String> params = new HashMap<>();
params.put("date", ISODateTimeFormat.date().print(dt));
params.put("card", "5105105105105100");
params.put("balance", "100000");
params.put("usage", "16.7");
HttpUrl.Builder urlBuilder = new HttpUrl.Builder().scheme("http")
.host("localhost").port(this.port).addPathSegment("credit");
for (String key : params.keySet()) {
urlBuilder.addQueryParameter(key, params.get(key));
}
Request request = new Request.Builder().url(urlBuilder.build())
.addHeader("Authorization", authHeaderValue).build();
Response response = null;
try {
response = new OkHttpClient().newCall(request).execute();
} catch (IOException e1) {
Tests.LOG.error(e1.getMessage(), e1);
}
Assert.assertEquals(201, response.code());
Map<String, String> responseBody = null;
try {
responseBody = new ObjectMapper().readValue(
response.body().string(),
new TypeReference<Map<String, String>>() {
});
} catch (IOException e) {
Tests.LOG.error(e.getMessage(), e);
}
Assert.assertEquals("5105105105105100", responseBody.get("cardNumber"));
Assert.assertEquals("2000-01-01", responseBody.get("date"));
Assert.assertEquals("1000000", responseBody.get("balance"));
Assert.assertEquals("16.7%", responseBody.get("usage"));
}
@Test
public void plusEncodingLocationWorks() throws Exception {
Map<String, String> expected = new HashMap<>();
expected.put("request",
"2017 North Beverly Glen Blvd, Los Angeles, CA 90077, USA");
expected.put("plusCode", "85634H43+7G");
HttpUrl url = new HttpUrl.Builder().scheme("http").host("localhost")
.port(this.port).addPathSegment("plus").build();
Map<String, String> body = Maps.newHashMap();
body.put("addr", expected.get("request"));
MediaType contentType = MediaType.parse("application/json");
String content = new ObjectMapper().writeValueAsString(body);
RequestBody params = RequestBody.create(content, contentType);
Request request = new Request.Builder().url(url).post(params).build();
Response response = new OkHttpClient().newCall(request).execute();
String actualSrc = response.body().string();
Map<String, String> actual = new ObjectMapper().readValue(actualSrc,
new TypeReference<Map<String, String>>() {
});
Assert.assertEquals(expected, actual);
}
@Test
public void forwardGeocodeWorks() throws Exception {
TreeMap<String, String> expected = new TreeMap<>();
expected.put("address",
"Emerging Market Services, 2017, North Beverly Glen Boulevard, Bel-Air, Los Angeles, Los Angeles County, California, 90077, United States of America");
String paramsJson = "{\"latitude\": \"34.1056855\", \"longitude\": \"-118.446178\"}";
RequestBody body = RequestBody.create(paramsJson,
MediaType.parse("application/json"));
HttpUrl requestingUrl = new HttpUrl.Builder().scheme("http")
.host("localhost").port(this.port).addPathSegment("geocode")
.build();
Request request = new Request.Builder().url(requestingUrl).post(body)
.build();
Response rawResponse = new OkHttpClient().newCall(request).execute();
TreeMap<String, String> actual = new ObjectMapper().readValue(
rawResponse.body().string(),
new TypeReference<TreeMap<String, String>>() {
});
actual.remove("request");
expected.remove("request");
for (String k : expected.keySet()) {
Assert.assertTrue(k + "missing", actual.containsKey(k));
Assert.assertTrue(
"value for " + k + " differs. -- " + expected.get(k)
+ " vs " + actual.get(k),
expected.get(k).equals(actual.get(k)));
}
}
@Test
public void reverseGeocodeWorks() throws Exception {
Map<String, Serializable> parts = new HashMap<>();
Map<String, String> params = new HashMap<>();
params.put("latitude", "41.3813934");
params.put("longitude", "2.1730637");
parts.put("address",
"82, La Rambla, Barri Gòtic, el Gòtic, Ciutat Vella, Barcelona, Barcelonès, Barcelona, Catalunya, 80002, España");
parts.put("request", "(" + params.get("latitude") + ", "
+ params.get("longitude") + ")");
RequestBody body = RequestBody.create(
new ObjectMapper().writeValueAsString(params),
MediaType.parse("application/json"));
Request request = new Request.Builder()
.url(new HttpUrl.Builder().scheme("http").host("localhost")
.port(this.port).addPathSegment("geocode").build())
.post(body).build();
Response resp = new OkHttpClient().newCall(request).execute();
String rawResponse = resp.body().string();
Map<String, String> actual = new ObjectMapper().readValue(rawResponse,
new TypeReference<Map<String, String>>() {
});
Assert.assertEquals(parts, actual);
}
@Test
public void fetchValidKeyFromKeyserver() throws Exception {
Map<String, String> actual = this
.fetchFromKeyserverReturnsValidKey("[email protected]");
Assert.assertTrue(actual.containsKey("fingerprint"));
Assert.assertTrue(actual.containsKey("keyId"));
Assert.assertTrue(actual.containsKey("key"));
Assert.assertTrue(actual.containsKey("request"));
}
@Test
public void fetchInvalidKeyFromKeyserver() throws Exception {
Map<String, String> actual = this
.fetchFromKeyserverReturnsValidKey("[email protected]");
Assert.assertTrue(actual.containsKey("error"));
Assert.assertEquals(actual.get("error"), "Key not found");
Assert.assertTrue(actual.containsKey("request"));
Assert.assertEquals(actual.get("request"), "[email protected]");
}
@Test
public void fetchKeyFromKeyserverUsingFingerprint() throws Exception {
this.fetchFromKeyserverReturnsValidKey(
"44D0 5643 E391 4542 7702 E1E7 FEBA D7FF D041 BBA1");
}
@Test
public void invalidPageRaisesExpectationFailed() throws Exception {
String url = "http://localhost:" + this.port + "/json?page=foo";
Request request = new Request.Builder().url(url).build();
Response resp = new OkHttpClient().newCall(request).execute();
Assert.assertEquals(HttpStatus.SERVICE_UNAVAILABLE.value(),
resp.code());
}
@Test
public void missingPageReturns226() throws Exception {
HttpUrl url = new HttpUrl.Builder().scheme("http").host("localhost")
.port(this.port).addPathSegment("json").build();
Request request = new Request.Builder().url(url).build();
Response response = new OkHttpClient().newCall(request).execute();
Assert.assertEquals(HttpStatus.IM_USED.value(), response.code());
}
public void htmlTableParsesProperly() throws Exception {
List<List<Map<String, String>>> expectedSrc = new ArrayList<>();
List<Map<String, String>> tbls = new ArrayList<>();
Map<String, String> tbl = new HashMap<>();
tbl.put("city", "Barcelona");
tbl.put("visited", "true");
tbls.add(tbl);
tbl = new HashMap<>();
tbl.put("city", "Copenhagen");
tbl.put("visited", "false");
tbls.add(tbl);
tbl = new HashMap<>();
tbl.put("city", "Los Angeles");
tbl.put("visited", "true");
tbls.add(tbl);
expectedSrc.add(tbls);
HttpUrl url = new HttpUrl.Builder().scheme("http").host("localhost")
.port(this.port).addPathSegment("json")
.addQueryParameter("page",
"http://localhost:" + this.port + "/test.html")
.build();
Request request = new Request.Builder().url(url).build();
Response response = new OkHttpClient().newCall(request).execute();
Assert.assertEquals(HttpStatus.OK.value(), response.code());
String jsonBody = response.body().string();
List<List<Map<String, String>>> actual = new ObjectMapper().readValue(
jsonBody, new TypeReference<List<List<Map<String, String>>>>() {
});
Assert.assertEquals(expectedSrc, actual);
}
@Test
public void icmpWithPort() throws Exception {
HttpUrl url = new HttpUrl.Builder().scheme("http").host("localhost")
.port(this.port).addPathSegment("icmp")
.addPathSegment("localhost")
.addQueryParameter("port", Integer.toString(this.port)).build();
Request request = new Request.Builder().url(url).build();
Response response = new OkHttpClient().newCall(request).execute();
Map<String, String> actual = new ObjectMapper().readValue(
response.body().string(),
new TypeReference<Map<String, String>>() {
});
Map<String, String> expected = new HashMap<>();
expected.put("host", "localhost");
expected.put("port", Integer.toString(this.port));
expected.put("path", "/");
expected.put("reachableSsl", "false");
Assert.assertTrue(response.isSuccessful());
Assert.assertEquals(expected, actual);
}
@Test
public void icmpWithPortNoSSL() throws Exception {
HttpUrl endpoint = new HttpUrl.Builder().addPathSegment("icmp")
.addPathSegment("localhost").port(this.port)
.addQueryParameter("port",
Integer.valueOf(this.port).toString())
.scheme("http").host("localhost").build();
Request request = new Request.Builder().get().url(endpoint).build();
Response response = new OkHttpClient().newCall(request).execute();
Map<String, String> expected = new HashMap<>();
expected.put("host", "localhost");
expected.put("port", Integer.toString(this.port));
expected.put("path", "/");
expected.put("reachableSsl", "false");
Map<String, String> actual = new ObjectMapper().readValue(
response.body().string(),
new TypeReference<Map<String, String>>() {
});
Assert.assertTrue(response.isSuccessful());
Assert.assertEquals(expected, actual);
}
@Test
public void stockReturnsNumericVolumeDecimalCloseAndKeyedByDate()
throws Exception {
HttpUrl url = new HttpUrl.Builder().scheme("http").host("localhost")
.port(this.port).addPathSegment("stock")
.addQueryParameter("sym", "aapl").build();
Request request = new Request.Builder().url(url).build();
Response rawResponse = new OkHttpClient().newCall(request).execute();
Assert.assertEquals(HttpStatus.OK.value(), rawResponse.code());
Map<String, String> response = new ObjectMapper().readValue(
rawResponse.body().charStream(),
new TypeReference<Map<String, String>>() {
});
Assert.assertEquals("aapl", response.get("request"));
response.remove("request");
DateTimeFormatter fmt = DateTimeFormat.forPattern("yyyy-MM-dd");
NumberFormat volFormat = NumberFormat.getIntegerInstance();
DecimalFormat priceFormat = new DecimalFormat();
priceFormat.setMinimumFractionDigits(4);
priceFormat.setMaximumFractionDigits(4);
for (String key : response.keySet()) {
String date = key.split(" ")[0];
if (key.toLowerCase().equals("volume")
|| key.equals("companyName")) {
continue;
}
try {
fmt.parseDateTime(date);
} catch (Exception e) {
Assert.fail(date + " -- not a date ");
}
try {
volFormat.parse(response.get(date + " Volume"));
} catch (NumberFormatException e) {
Assert.fail(
response.get(date + " Volume") + " is not an integer.");
}
try {
priceFormat.parse(response.get(date + " Close"));
} catch (Exception e) {
Assert.fail(response.get(date + " Close")
+ " is not properly formatted");
}
}
}
@Test
public void fredReturnsNonemptyForCanada() throws Exception {
Map<String, String> results = new HashMap<>();
results.put("DDDM01CAA156NWDB",
"Stock Market Capitalization to GDP for Canada -- Total value of all listed shares in a stock market as a percentage of GDP.\\n\\nValue of listed shares to GDP, calculated using the following deflation method: {(0.5)*[Ft/P_et + Ft-1/P_et-1]}/[GDPt/P_at] where F is stock market capitalization, P_e is end-of period CPI, and P_a is average annual CPI. End-of period CPI (IFS line 64M..ZF or, if not available, 64Q..ZF) and annual CPI (IFS line 64..ZF) are from the IMF's International Financial Statistics. Standard & Poor's, Global Stock Markets Factbook and supplemental S&P data)\\n\\nSource Code: GFDD.DM.01");
HttpUrl testUrl = new HttpUrl.Builder().scheme("http").host("localhost")
.port(this.port).addPathSegment("fred")
.addQueryParameter("lookup", "true")
.addQueryParameter("series", "canada").build();
Tests.LOG.debug(testUrl + " is the URL we need to access.");
Request request = new Request.Builder().url(testUrl).build();
Response response = new OkHttpClient().newCall(request).execute();
Assert.assertTrue(response.isSuccessful());
Map<String, Map<String, String>> actual = new ObjectMapper().readValue(
response.body().string(),
new TypeReference<Map<String, Map<String, String>>>() {
});
for (String result : results.keySet()) {
if (!actual.get("lookup").containsKey(result)) {
Assert.fail(result + " missing from " + results.keySet());
}
}
}
@Test
public void fredGetsSeries() throws Exception {
HttpUrl testUrl = new HttpUrl.Builder().scheme("http").host("localhost")
.port(this.port).addPathSegment("fred")
.addQueryParameter("lookup", "false")
.addQueryParameter("series", "DEXUSUK").build();
Request request = new Request.Builder().url(testUrl).build();
Response response = new OkHttpClient().newCall(request).execute();
Assert.assertTrue(response.isSuccessful());
Map<String, Map<String, String>> actual = new ObjectMapper().readValue(
response.body().string(),
new TypeReference<Map<String, Map<String, String>>>() {
});
Map<String, String> series = actual.get("series");
DateTimeFormatter keyFormat = ISODateTimeFormat.dateParser();
for (String date : series.keySet()) {
try {
keyFormat.parseDateTime(date);
} catch (Exception e) {
Assert.fail(date + " failed to parse as a date");
}
try {
NumberFormat.getInstance().parse(series.get(date));
} catch (ParseException e) {
Assert.fail("<" + date + ", " + series.get(date)
+ "> failed to parse as a number");
}
}
}
@Test
public void getSummary() throws Exception {
Set<String> expected = Sets.newHashSet("summary", "summaryLength",
"time", "request");
HttpUrl url = new HttpUrl.Builder().scheme("http").host("localhost")
.port(this.port).addPathSegment("summary")
.addQueryParameter("length", "1")
.addQueryParameter("url",
"https://www.bbc.com/news/world-australia-51513886")
.build();
Tests.LOG.info(url.toString());
Request request = new Request.Builder().url(url).build();
Response response = new OkHttpClient().newCall(request).execute();
Assert.assertTrue(response.isSuccessful());
Map<String, String> responseObj = new ObjectMapper().readValue(
response.body().string(),
new TypeReference<Map<String, String>>() {
});
Assert.assertEquals(expected, responseObj.keySet());
Assert.assertEquals("https://www.bbc.com/news/world-australia-51513886",
responseObj.get("request"));
Assert.assertEquals(
"\"How would you feel if the Russians laid down infrastructure in your own networks?",
responseObj.get("summary"));
Assert.assertEquals("1", responseObj.get("summaryLength"));
}
@Test
public void covid() throws Exception {
Set<String> keys = Sets.newHashSet("Afghanistan", "Albania", "Algeria",
"Andorra", "Angola", "Antigua and Barbuda", "Argentina",
"Armenia", "Australia", "Austria", "Azerbaijan", "Bahamas",
"Bahrain", "Bangladesh", "Barbados", "Belarus", "Belgium",
"Belize", "Benin", "Bhutan", "Bolivia",
"Bosnia and Herzegovina", "Botswana", "Brazil", "Brunei",
"Bulgaria", "Burkina Faso", "Burma", "Burundi", "Cabo Verde",
"Cambodia", "Cameroon", "Canada", "Central African Republic",
"Chad", "Chile", "China", "Colombia", "Congo (Brazzaville)",
"Congo (Kinshasa)", "Costa Rica", "Cote d'Ivoire", "Croatia",
"Cuba", "Cyprus", "Czech Republic", "Denmark",
"Diamond Princess", "Djibouti", "Dominica",
"Dominican Republic", "Ecuador", "Egypt", "El Salvador",
"Equatorial Guinea", "Eritrea", "Estonia", "Eswatini",
"Ethiopia", "Fiji", "Finland", "France", "Gabon", "Gambia",
"Georgia", "Germany", "Ghana", "Greece", "Grenada", "Guatemala",
"Guinea", "Guinea-Bissau", "Guyana", "Haiti", "Holy See",
"Honduras", "Hungary", "Iceland", "India", "Indonesia", "Iran",
"Iraq", "Ireland", "Israel", "Italy", "Jamaica", "Japan",
"Jordan", "Kazakhstan", "Kenya", "Kosovo", "Kuwait",
"Kyrgyzstan", "Laos", "Latvia", "Lebanon", "Liberia", "Libya",
"Liechtenstein", "Lithuania", "Luxembourg", "MS Zaandam",
"Madagascar", "Malaysia", "Maldives", "Mali", "Malta",
"Mauritania", "Mauritius", "Mexico", "Moldova", "Monaco",
"Mongolia", "Montenegro", "Morocco", "Mozambique", "Namibia",
"Nepal", "Netherlands", "New Zealand", "Nicaragua", "Niger",
"Nigeria", "North Macedonia", "Norway", "Oman", "Pakistan",
"Panama", "Papua New Guinea", "Paraguay", "Peru", "Philippines",
"Poland", "Portugal", "Qatar", "Romania", "Russia", "Rwanda",
"Saint Kitts and Nevis", "Saint Lucia",
"Saint Vincent and the Grenadines", "San Marino",
"Saudi Arabia", "Senegal", "Serbia", "Seychelles",
"Sierra Leone", "Singapore", "Slovakia", "Slovenia", "Somalia",
"South Africa", "South Korea", "Spain", "Sri Lanka", "Sudan",
"Suriname", "Sweden", "Switzerland", "Syria", "Taiwan",
"Tanzania", "Thailand", "Timor-Leste", "Togo",
"Trinidad and Tobago", "Tunisia", "Turkey", "Uganda", "Ukraine",
"United Arab Emirates", "United Kingdom",
"United States of America", "Uruguay", "Uzbekistan",
"Venezuela", "Vietnam", "West Bank and Gaza", "Zambia",
"Zimbabwe");
MutableDateTime aprilThird2020 = new MutableDateTime();
aprilThird2020.setYear(2020);
aprilThird2020.setMonthOfYear(4);
aprilThird2020.setDayOfMonth(2);
Integer distanceFromToday = Days
.daysBetween(aprilThird2020.toDateTime(), new DateTime())
.getDays();
HttpUrl url = new HttpUrl.Builder().scheme("http").host("localhost")
.port(this.port).addPathSegment("covid")
.addQueryParameter("suffix", "json")
.addQueryParameter("days", Integer.toString(distanceFromToday))
.build();
Request request = new Request.Builder().url(url).build();
Response response = new OkHttpClient().newCall(request).execute();
Assert.assertTrue(response.isSuccessful());
String rawJson = response.body().string();
Map<String, String> json = new ObjectMapper().readValue(rawJson,
new TypeReference<Map<String, String>>() {
});
json.remove("date");
for (String s : keys) {
Assert.assertTrue(s + " missing from " + json.keySet(),
json.containsKey(s));
try {
Number i = NumberFormat.getIntegerInstance().parse(json.get(s));
Assert.assertTrue("Negative victim amount found for " + s,
i.intValue() > 0);
} catch (NumberFormatException e) {
Assert.fail(e.getMessage() + " " + s);
} catch (IllegalArgumentException e) {
Assert.fail(e.getMessage() + " " + s);
}
}
}
@Before
public void pretest() throws Exception {
Runtime.getRuntime()
.exec("/usr/local/bin/heroku pg:killall -a hd1-units");
}
@Test
public void covidContainsUnitedStates() throws Exception {
HttpUrl url = new HttpUrl.Builder().scheme("http").host("localhost")
.port(this.port).addPathSegment("covid")
.addQueryParameter("suffix", "json").build();
Request request = new Request.Builder().url(url).build();
Response response = new OkHttpClient().newCall(request).execute();
Assert.assertTrue(response.isSuccessful());
String rawJson = response.body().string();
Map<String, String> json = new ObjectMapper().readValue(rawJson,
new TypeReference<Map<String, String>>() {
});
for (String k : json.keySet()) {
Assert.assertFalse(k.contains("US"));
}
Assert.assertTrue(json.containsKey("United States of America"));
}
@Test
public void covidKeysHaveNoEmbeddedQuotes() throws Exception {
HttpUrl url = new HttpUrl.Builder().scheme("http").host("localhost")
.port(this.port).addPathSegment("covid")
.addQueryParameter("suffix", "json").build();
Request request = new Request.Builder().url(url).build();
Response response = new OkHttpClient().newCall(request).execute();
Assert.assertTrue(response.isSuccessful());
String rawJson = response.body().string();
Map<String, String> json = new ObjectMapper().readValue(rawJson,
new TypeReference<Map<String, String>>() {
});
for (String k : json.keySet()) {
String kVal = k.substring(1, k.length() - 1);
Assert.assertFalse(kVal.contains("\""));
}
}
@Test
public void covidSouthKoreaInversionWorks() throws Exception {
HttpUrl url = new HttpUrl.Builder().scheme("http").host("localhost")
.port(this.port).addPathSegment("covid").build();
Request request = new Request.Builder().url(url).build();
Response response = new OkHttpClient().newCall(request).execute();
Assert.assertTrue(response.isSuccessful());
String rawJson = response.body().string();
Assert.assertFalse(rawJson.contains("Korea, South"));
}
@Test
public void postNer() throws Exception {
HttpUrl testUrl = new HttpUrl.Builder().scheme("http").host("localhost")
.port(this.port).addPathSegment("ner").build();
OkHttpClient client = new OkHttpClient().newBuilder().build();
MediaType mediaType = MediaType.parse("text/plain");
RequestBody body = RequestBody.create(
"In the first six weeks of 2020, more than 1.6bn of the 2.4bn presidential campaign ads shown to US Facebook users were from the Bloomberg campaign, a new analysis shows. Since launching his campaign in mid-November, the former New York mayor has spent nearly $45m on Facebook ads – more than all his opponents combined. Bloomberg’s spending doesn’t just dwarf that of other Democrats; Donald Trump’s giant re-election effort on Facebook looks paltry in comparison. The Bloomberg campaign has run three times as many ads as Trump.",
mediaType);
Request request = new Request.Builder().url(testUrl)
.method("POST", body).addHeader("Content-Type", "text/plain")
.build();
Response response = client.newCall(request).execute();
String rawResponse = response.body().string();
JsonNode actual = new ObjectMapper().readValue(rawResponse,
JsonNode.class);
Assert.assertEquals("the first six weeks of 2020, mid-November",
actual.get("temporal").asText());
Assert.assertEquals("US, Bloomberg, New York, Trump",
actual.get("places").asText());
Assert.assertEquals("Facebook", actual.get("companies").asText());
Assert.assertEquals("Bloomberg, Donald Trump",
actual.get("people").asText());
Assert.assertTrue(response.isSuccessful());
}
@Test
public void github() throws Exception {
HttpUrl testUrl = new HttpUrl.Builder().scheme("http").host("localhost")
.port(this.port).addPathSegment("github")
.addPathSegment("rails|rails").build();
OkHttpClient client = new OkHttpClient().newBuilder().build();
Request request = new Request.Builder().url(testUrl).build();
Response response = client.newCall(request).execute();
Map<String, String> actual = new ObjectMapper().readValue(
response.body().string(),
new TypeReference<Map<String, String>>() {
});
for (String k : actual.keySet()) {
String value = actual.get(k);
String[] parts = value.split(":- ");
String permalink = parts[1];
HttpUrl commitLink = HttpUrl.parse(permalink);
Assert.assertEquals("api.github.com", commitLink.host());
Assert.assertEquals("https", commitLink.scheme());
try {
DateTime date = ISODateTimeFormat.dateTimeNoMillis()
.parseDateTime(k);
Assert.assertTrue(date.isBeforeNow());
Assert.assertTrue(date.isAfter(new DateTime().minusHours(24)));
} catch (Exception e) {
Assert.fail(k + " is not a date");
}
}
}
@Test
public void githubNoCommits() throws Exception {
HttpUrl testUrl = new HttpUrl.Builder().scheme("http").host("localhost")
.port(this.port).addPathSegment("github")
.addPathSegment("hasandiwan|zsh").build();
OkHttpClient client = new OkHttpClient().newBuilder().build();
Request request = new Request.Builder().url(testUrl).build();
Response response = client.newCall(request).execute();
Map<String, String> actual = new ObjectMapper().readValue(
response.body().string(),
new TypeReference<Map<String, String>>() {
});
Assert.assertEquals("No commits", actual.get("error"));
}
@Test
public void githubTakesAbsoluteTimestamps() throws Exception {
HttpUrl testUrl = new HttpUrl.Builder().scheme("http").host("localhost")
.port(this.port).addPathSegment("github")
.addPathSegment("hasandiwan|units")
.addQueryParameter("date", "0").build();
Request request = new Request.Builder().url(testUrl).build();
Response response = new OkHttpClient().newCall(request).execute();
Map<String, String> actual = new ObjectMapper().readValue(
response.body().string(),
new TypeReference<Map<String, String>>() {
});
for (String messageAndLink : actual.values()) {
if (messageAndLink.toLowerCase().startsWith("initial commit")) {
Assert.assertTrue("initial message not found", true);
}
}
}
@Test
public void unitsWorksWithAmounts() throws Exception {
HttpUrl testUrl = new HttpUrl.Builder().scheme("http").host("localhost")
.port(this.port).addPathSegments("units/inches/centimeter/")
.addQueryParameter("amount", "64").build();
OkHttpClient client = new OkHttpClient().newBuilder().build();
Request request = new Request.Builder().url(testUrl).build();
Response response = client.newCall(request).execute();
Map<String, String> actual = new ObjectMapper().readValue(
response.body().string(),
new TypeReference<Map<String, String>>() {
});
Assert.assertEquals("64 inches", actual.get("request"));
Assert.assertEquals("160.0 centimeters", actual.get("result"));
}
@Test
public void canGetFitData() throws Exception {
HttpUrl testUrl = new HttpUrl.Builder().scheme("http").host("localhost")
.port(this.port).addPathSegments("fit/-1").build();
OkHttpClient client = new OkHttpClient().newBuilder().build();
Request request = new Request.Builder().url(testUrl).build();
Response rawResponse = client.newCall(request).execute();
Map<String, String> response = new ObjectMapper().readValue(
rawResponse.body().bytes(),
new TypeReference<Map<String, String>>() {
});
Set<String> expectedKeys = Sets.newHashSet("data", "fit", "time");
Assert.assertEquals(expectedKeys, response.keySet());
Assert.assertEquals(HttpStatus.FOUND.value(), rawResponse.code());
}
@Test
public void canCheckForFit() throws Exception {
HttpUrl testUrl = new HttpUrl.Builder().scheme("http").host("localhost")
.port(this.port).addPathSegments("fit/-1").build();
OkHttpClient client = new OkHttpClient().newBuilder().build();
Request request = new Request.Builder().url(testUrl).head().build();
Response rawResponse = client.newCall(request).execute();
int status = rawResponse.code();
Assert.assertTrue(
Sets.newHashSet(HttpStatus.NOT_FOUND.value(), HttpStatus.OK)
.contains(status));
}
@Test
public void unitsUsesOneIfAmountUnspecified() throws Exception {
HttpUrl testUrl = new HttpUrl.Builder().scheme("http").host("localhost")
.port(this.port).addPathSegments("units/centimeters/inch")
.build();
OkHttpClient client = new OkHttpClient().newBuilder().build();
Request request = new Request.Builder().url(testUrl).build();
Response response = client.newCall(request).execute();
Map<String, String> actual = new ObjectMapper().readValue(
response.body().string(),
new TypeReference<Map<String, String>>() {
});
Assert.assertTrue(actual.get("request").startsWith("1"));
}
@Test
public void postSummary() throws Exception {
HttpUrl testUrl = new HttpUrl.Builder().scheme("http").host("localhost")
.port(this.port).addPathSegment("summary")
.addQueryParameter("length", "1").build();
OkHttpClient client = new OkHttpClient().newBuilder().build();
MediaType mediaType = MediaType.parse("text/plain");
RequestBody body = RequestBody.create(
"In the first six weeks of 2020, more than 1.6bn of the 2.4bn presidential campaign ads shown to US Facebook users were from the Bloomberg campaign, a new analysis shows. Since launching his campaign in mid-November, the former New York mayor has spent nearly $45m on Facebook ads – more than all his opponents combined. Bloomberg’s spending doesn’t just dwarf that of other Democrats; Donald Trump’s giant re-election effort on Facebook looks paltry in comparison. The Bloomberg campaign has run three times as many ads as Trump.",
mediaType);
Request request = new Request.Builder().url(testUrl)
.method("POST", body).addHeader("Content-Type", "text/plain")
.build();
Response response = client.newCall(request).execute();
Assert.assertTrue(response.isSuccessful());
Map<String, String> actual = new ObjectMapper().readValue(
response.body().string(),
new TypeReference<Map<String, String>>() {
});
String summary = actual.get("summary");
Assert.assertEquals(
"Bloomberg’s spending doesn’t just dwarf that of other Democrats; Donald Trump’s giant re-election effort on Facebook looks paltry in comparison.",
summary);
Assert.assertTrue(actual.get("time").matches("^[0-9.]+$"));
}
@Test
public void newGmail() throws Exception {
Assume.assumeTrue("no newGmailUser property set",
System.getProperty("newGmailUser") != null);
Map<String, String> body = Maps.newHashMap();
body.put("user", System.getProperty("newGmailUser"));
body.put("expiry", "1");
MediaType mediaType = MediaType.parse("application/json");
RequestBody requestBody = RequestBody
.create(new ObjectMapper().writeValueAsString(body), mediaType);
HttpUrl testUrl = new HttpUrl.Builder().scheme("http").host("localhost")
.port(this.port).addPathSegment("newgmail").build();
Request request = new Request.Builder().post(requestBody).url(testUrl)
.build();
Response response = new OkHttpClient().newCall(request).execute();
Assert.assertTrue(response.isSuccessful());
Map<String, String> actual = new ObjectMapper().readValue(
response.body().string(),
new TypeReference<Map<String, String>>() {
});
Set<String> keys = Sets.newHashSet("endpoint", "until", "secret",
"label", "key");
for (String k : keys) {
Assert.assertTrue("Missing k, " + k + " from " + keys,
actual.containsKey(k));
}
Assert.assertEquals(actual.get("endpoint"), "/gmail");
try {
NumberFormat.getIntegerInstance().parse(actual.get("until"));
} catch (NumberFormatException e) {
Assert.fail("Not a number -- " + actual.get("until"));
}
Assert.assertTrue(actual.get("secret").matches("^[-a-z0-9]+$"));
Assert.assertTrue(actual.get("key").matches("^[-a-z0-9]+$"));
Assert.assertEquals("all", actual.get("label"));
}
@Test
public void postgresIsLiving() throws Exception {
HttpUrl endpoint = new HttpUrl.Builder().scheme("http")
.host("localhost").port(this.port).addPathSegment("sql")
.addQueryParameter("stmt", "select 1+1 as a")
.addQueryParameter("jdbcUrl", this.FIT_HELPER_URL)
.addQueryParameter("driverClass", "org.postgresql.Driver")
.build();
Request request = new Request.Builder().url(endpoint).build();
Response response = new OkHttpClient().newCall(request).execute();
Assert.assertTrue(response.isSuccessful());
Map<String, List<Map<String, String>>> results = new ObjectMapper()
.readValue(response.body().string(),
new TypeReference<Map<String, List<Map<String, String>>>>() {
});
List<Map<String, String>> metadata = results.get("incoming");
Map<String, String> metaQuery = Collections.singletonMap("query",
"select 1+1 as a");
Assert.assertTrue("Missing query", metadata.contains(metaQuery));
Map<String, String> metaDriver = Collections.singletonMap("driverClass",
"org.postgresql.Driver");
Assert.assertTrue(metadata.contains(metaDriver));
Map<String, String> metaUrl = Collections.singletonMap("jdbcUrl",
this.FIT_HELPER_URL);
Assert.assertTrue(metadata.contains(metaUrl));
Map<String, String> ourResults = results.get("results").get(0);
Assert.assertEquals("2", ourResults.get("a"));
}
@Test
public void noColonMemory() throws Exception {
File f = new File(":memory");
Assert.assertFalse(f.exists());
}
@Test
public void oandaHasDatesAndRequests() throws Exception {
HttpUrl endpoint = new HttpUrl.Builder().scheme("http")
.host("localhost").port(this.port).addPathSegment("fx")
.addPathSegment("gbp").addPathSegment("usd").build();
Request request = new Request.Builder().url(endpoint).build();
Response response = new OkHttpClient().newCall(request).execute();
Assert.assertTrue(response.isSuccessful());
Map<String, String> actual = new ObjectMapper().readValue(
response.body().string(),
new TypeReference<Map<String, String>>() {
});
Assert.assertEquals("GBP => USD", actual.get("request"));
actual.remove("request");
for (String k : actual.keySet()) {
try {
LocalDate.parse(k);
} catch (IllegalArgumentException e) {
Assert.fail(k + " is not a date");
}
try {
NumberFormat.getNumberInstance().parse(actual.get(k));
} catch (ParseException e) {
Assert.fail(
"<" + k + ", " + actual.get(k) + "> is not a number");
}
}
}
@Test
public void summaryProcessesUrls() throws Exception {
HttpUrl endpoint = HttpUrl.parse("http://localhost:" + this.port
+ "/summary?url=https://www.bbc.com/news/world-us-canada-52265989");
Request request = new Request.Builder().url(endpoint).build();
Response response = new OkHttpClient().newCall(request).execute();
Map<String, String> actual = new ObjectMapper().readValue(
response.body().string(),
new TypeReference<Map<String, String>>() {
});
Assert.assertEquals(
Sets.newHashSet("summary", "request", "summaryLength", "time"),
actual.keySet());
Assert.assertEquals(
": How do I protect myself?\\nA SIMPLE GUIDEAVOIDING CONTACT:America's gun culture in charts\\nAn investigation is under way, Kern County Sheriff's Department says.\\nAs of 11 April, the state reported 21,794 cases and 651 fatalities.\\nCalifornian police say six people have been shot and injured at a \\\"large\\\" party despite the \\\"stay at home\\\" order in place in the US state.\\nFour dates that explain the US gun debate\\n",
actual.get("summary"));
Assert.assertTrue(actual.get("time").matches("^[0-9.]$+"));
}
@Test
public void faviconIsNot404() throws Exception {
HttpUrl endpoint = HttpUrl
.parse("http://localhost:" + this.port + "/favicon.ico");
Request request = new Request.Builder().url(endpoint).build();
Response response = new OkHttpClient().newCall(request).execute();
Assert.assertEquals(200, response.code());
}
@Test
public void tvIsValid() throws Exception {
Set<String> expectedKeys = Sets.newHashSet("show", "channel",
"startTime", "duration");
HttpUrl endpoint = HttpUrl
.parse("http://localhost:" + this.port + "/tv");
Request request = new Request.Builder().url(endpoint).build();
Response response = new OkHttpClient().newCall(request).execute();
Assert.assertTrue(response.isSuccessful());
List<Map<String, String>> showsForToday = new ObjectMapper().readValue(
response.body().string(),
new TypeReference<List<Map<String, String>>>() {
});
for (Map<String, String> show : showsForToday) {
Assert.assertEquals(expectedKeys, show.keySet());
Assert.assertTrue(show.get("duration") + " is not a number",
show.get("duration").matches("[0-9.]"));
try {
DateTime parsed = DateTimeFormat.shortTime()
.parseDateTime(show.get("startTime"));
if (parsed.isBefore(DateTime.now())) {
Assert.fail("start time should be in the future");
}
} catch (Exception e) {
Assert.fail(show.get("startTime") + " is not a date");
}
}
}
@Test
public void covidDoesNotContainCzechia() throws Exception {
HttpUrl endpoint = new HttpUrl.Builder().scheme("http")
.host("localhost").port(this.port)
.addEncodedPathSegment("covid")
.addQueryParameter("suffix", "json").build();
Request request = new Request.Builder().url(endpoint).build();
Response response = new OkHttpClient().newCall(request).execute();
Assert.assertTrue(response.isSuccessful());
Map<String, String> places = new ObjectMapper().readValue(
response.body().string(),
new TypeReference<Map<String, String>>() {
});
Assert.assertTrue("Czechia crept in!", !places.containsKey("Czechia"));
}
@Test
public void covidHasCanadaSum() throws Exception {
HttpUrl endpoint = new HttpUrl.Builder().scheme("http")
.host("localhost").port(this.port)
.addEncodedPathSegment("covid")
.addQueryParameter("suffix", "json").build();
Request request = new Request.Builder().url(endpoint).build();
Response response = new OkHttpClient().newCall(request).execute();
Map<String, String> countries = new ObjectMapper().readValue(
response.body().bytes(),
new TypeReference<Map<String, String>>() {
});
Assert.assertTrue("Canada sum missing",
countries.containsKey("Canada"));
}
@Test
public void covidHasUnitedKingdomSum() throws Exception {
HttpUrl endpoint = new HttpUrl.Builder().scheme("http")
.host("localhost").port(this.port)
.addEncodedPathSegment("covid")
.addQueryParameter("suffix", "json").build();
Request request = new Request.Builder().url(endpoint).build();
Response response = new OkHttpClient().newCall(request).execute();
Map<String, String> countries = new ObjectMapper().readValue(
response.body().bytes(),
new TypeReference<Map<String, String>>() {
});
Assert.assertTrue("United Kingdom sum missing",
countries.containsKey("United Kingdom"));
}
@Test
public void covidHasAustraliaSum() throws Exception {
HttpUrl endpoint = new HttpUrl.Builder().scheme("http")
.host("localhost").port(this.port)
.addEncodedPathSegment("covid")
.addQueryParameter("suffix", "json").build();
Request request = new Request.Builder().url(endpoint).build();
Response response = new OkHttpClient().newCall(request).execute();
Map<String, String> json = new ObjectMapper().readValue(
response.body().string(),
new TypeReference<Map<String, String>>() {
});
Set<String> countries = json.keySet();
Assert.assertTrue("Australia sum missing",
countries.contains("Australia"));
}
@Test
public void faviconReturnsCustomStatus() throws Exception {
HttpUrl endpoint = new HttpUrl.Builder().scheme("http")
.host("localhost").port(this.port).addPathSegment("favicon.ico")
.addQueryParameter("code", "404").build();
Request request = new Request.Builder().url(endpoint).build();
Response response = new OkHttpClient().newCall(request).execute();
Assert.assertEquals(404, response.code());
}
@Test
public void canViewTestCode() throws Exception {
HttpUrl endpoint = new HttpUrl.Builder().scheme("http")
.host("localhost").port(this.port).addPathSegment("tests")
.build();
Request request = new Request.Builder().url(endpoint).build();
Response response = new OkHttpClient().newCall(request).execute();
Assert.assertTrue(response.isSuccessful());
}
@Test
public void canAddNewDataToBeFittedWithDefaultSeparator() throws Exception {
Map<String, String> postBody = Maps.newHashMap();
postBody.put("email", "[email protected]");
postBody.put("data", this.SAMPLE_CSV.replace(" ", ""));
okhttp3.RequestBody body = okhttp3.RequestBody.create(
new ObjectMapper().writeValueAsBytes(postBody),
MediaType.parse("application/json"));
HttpUrl fitEndpoint = HttpUrl
.parse("http://localhost:" + this.port + "/fit");
Request request = new Request.Builder().url(fitEndpoint).post(body)
.build();
Response response = new OkHttpClient().newCall(request).execute();
Map<String, String> result = new ObjectMapper().readValue(
response.body().bytes(),
new TypeReference<Map<String, String>>() {
});
Assert.assertTrue(result.containsKey("id")
&& result.get("id").matches("^[0-9]+$"));
Assert.assertTrue(result.containsKey("time")
&& result.get("time").matches("^[0-9]+$"));
Assert.assertTrue(response.isSuccessful());
}
@Test
public void canAddNewDataToBeFittedWithCustomSeparator() throws Exception {
Map<String, String> postBody = Maps.newHashMap();
postBody.put("email", "[email protected]");
postBody.put("data",
this.SAMPLE_CSV.replace(" ", "").replace(",", ";"));
postBody.put("separator", ";");
okhttp3.RequestBody body = okhttp3.RequestBody.create(
new ObjectMapper().writeValueAsBytes(postBody),
MediaType.parse("application/json"));
HttpUrl fitEndpoint = HttpUrl
.parse("http://localhost:" + this.port + "/fit");
Request request = new Request.Builder().url(fitEndpoint).post(body)
.build();
Response response = new OkHttpClient().newCall(request).execute();
Map<String, String> result = new ObjectMapper().readValue(
response.body().bytes(),
new TypeReference<Map<String, String>>() {
});
Assert.assertTrue(result.containsKey("id")
&& result.get("id").matches("^[0-9]+$"));
Assert.assertTrue(result.containsKey("time")
&& result.get("time").matches("^[0-9]+$"));
Assert.assertTrue(response.isSuccessful());
}
@Test
public void base64GivesIndeterminateStringWithSecure() throws Exception {
Map<String, String> bodyMap = Maps.newHashMap();
bodyMap.put("string", "java");
bodyMap.put("secure", "1");
okhttp3.RequestBody body = okhttp3.RequestBody.create(
new ObjectMapper().writeValueAsString(bodyMap),
MediaType.parse("application/json"));
HttpUrl endpoint = HttpUrl
.parse("http://localhost:" + this.port + "/base64");
Request request = new Request.Builder().url(endpoint).post(body)
.build();
Response response = new OkHttpClient().newCall(request).execute();
Map<String, String> result = new ObjectMapper().readValue(
response.body().bytes(),
new TypeReference<Map<String, String>>() {
});
Map<String, String> expected = Maps.newHashMap();
expected.put("in", "java");
expected.put("timestamp", Long.valueOf(System.nanoTime()).toString());
expected.put("output", Base64Utils.encodeToUrlSafeString(
("java" + expected.get("timestamp")).getBytes()));
for (String key : expected.keySet()) {
Assert.assertTrue(result.keySet().contains(key));
}
Assert.assertEquals("java", result.get("in"));
Assert.assertFalse(expected.get("in").equals(Base64Utils
.encodeToUrlSafeString(expected.get("in").getBytes())));
Assert.assertTrue(Long.valueOf(expected.get("timestamp")).toString()
.equals(expected.get("timestamp")));
}
@Test
public void base64GivesPredictableStringWithoutSecure() throws Exception {
Map<String, String> bodyMap = Maps.newHashMap();
bodyMap.put("string", "java");
okhttp3.RequestBody body = okhttp3.RequestBody.create(
new ObjectMapper().writeValueAsString(bodyMap),
MediaType.parse("application/json"));
HttpUrl endpoint = HttpUrl
.parse("http://localhost:" + this.port + "/base64");
Request request = new Request.Builder().url(endpoint).post(body)
.build();
Response response = new OkHttpClient().newCall(request).execute();
Map<String, String> result = new ObjectMapper().readValue(
response.body().bytes(),
new TypeReference<Map<String, String>>() {
});
Map<String, String> expected = Maps.newHashMap();
expected.put("in", "java");
expected.put("output", Base64Utils.encodeToUrlSafeString(
"java".getBytes()));
for (String key : expected.keySet()) {
Assert.assertTrue(result.keySet().contains(key));
}
Assert.assertEquals("java", result.get("in"));
Assert.assertEquals("amF2YQ==", expected.get("output"));
Assert.assertFalse(result.containsKey("timestamp"));
}
@Test
public void base64GivesErrorWithoutString() throws Exception {
okhttp3.RequestBody body = okhttp3.RequestBody.create(
new ObjectMapper().writeValueAsString(Maps.newHashMap()), MediaType.parse("application/json"));
HttpUrl endpoint = HttpUrl
.parse("http://localhost:" + this.port + "/base64");
Request request = new Request.Builder().url(endpoint).post(body)
.build();
Response response = new OkHttpClient().newCall(request).execute();
Map<String, String> result = new ObjectMapper().readValue(
response.body().bytes(),
new TypeReference<Map<String, String>>() {
});
Assert.assertTrue(result.containsKey("error"));
Assert.assertEquals("string key required in body", result.get("error"));
}
@Test
public void timeReturnsProperly() throws Exception {
HttpUrl endpoint = HttpUrl
.parse("http://localhost:" + this.port + "/time");
Request request = new Request.Builder().url(endpoint)
.build();
Response response = new OkHttpClient().newCall(request).execute();
Map<String, String> result = new ObjectMapper().readValue(
response.body().bytes(),
new TypeReference<Map<String, String>>() {
});
Assert.assertEquals(Sets.newHashSet("zones", "now","buddhist","coptic","ethiopic","islamic", "epoch"), result.keySet());
Assert.assertNotNull(ISODateTimeFormat.dateTime().parseDateTime(result.get("now")));
Assert.assertNotNull(ISODateTimeFormat.dateTime().parseDateTime(result.get("buddhist")));
Assert.assertNotNull(ISODateTimeFormat.dateTime().parseDateTime(result.get("coptic")));
Assert.assertNotNull(ISODateTimeFormat.dateTime().parseDateTime(result.get("ethiopic")));
Assert.assertNotNull(ISODateTimeFormat.dateTime().parseDateTime(result.get("islamic")));
Assert.assertTrue(NumberUtils.isDigits(result.get("epoch")));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment