Skip to content

Instantly share code, notes, and snippets.

@hasandiwan
Last active May 2, 2024 18:50
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save hasandiwan/aab72fe07eee666189c8d43c3914b749 to your computer and use it in GitHub Desktop.
Save hasandiwan/aab72fe07eee666189c8d43c3914b749 to your computer and use it in GitHub Desktop.
Test tree, as of 2024-05-02T18:50:39Z
package us.d8u.balance;
import java.util.Map;
import java.util.Set;
import org.apache.http.HttpStatus;
import org.joda.time.DateTime;
import org.joda.time.format.ISODateTimeFormat;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
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.test.context.junit4.SpringRunner;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.common.collect.Maps;
import com.google.common.collect.Sets;
import okhttp3.HttpUrl;
import okhttp3.OkHttpClient;
import okhttp3.Request;
@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT)
public class AgeTests {
private static final OkHttpClient client = new OkHttpClient();
@LocalServerPort
private int port;
@Test
public void correctKeysAndRelationsBetweenValues() throws Exception {
final DateTime birthDate = DateTime.now().minusYears(1);
final Map<String, String> params = Maps.newHashMap();
params.put("birthdate", ISODateTimeFormat.date().print(birthDate));
final HttpUrl remoteUrl = HttpUrl.parse("http://localhost/age").newBuilder().port(this.port)
.addQueryParameter("birthdate", params.get("birthDate")).build();
final JsonNode response = new ObjectMapper().readTree(
AgeTests.client.newCall(new Request.Builder().url(remoteUrl).build()).execute().body().bytes());
final Set<String> expected = Sets.newHashSet("birthdate", "ageInDays", "ageInWeeks", "ageInMonths");
for (final String k : expected) {
Assert.assertTrue(!response.get(k).isNull());
}
Assert.assertTrue(response.get("ageInDays").asInt() > 0);
Assert.assertTrue(response.get("ageInWeeks").asInt() <= response.get("ageInDays").asInt());
Assert.assertTrue(response.get("ageInMonths").asInt() <= response.get("ageInWeeks").asInt());
}
@Test
public void missingBirthdateGivesError() throws Exception {
final HttpUrl remoteUrl = HttpUrl.parse("http://localhost/age").newBuilder().port(this.port).build();
final JsonNode response = new ObjectMapper().readTree(
AgeTests.client.newCall(new Request.Builder().url(remoteUrl).build()).execute().body().bytes());
Assert.assertTrue("error key missing", response.has("error"));
Assert.assertTrue("parameter \"birthdate\" required".equals(response.get("error").asText()));
Assert.assertTrue(response.get("status").asInt() == HttpStatus.SC_BAD_REQUEST);
}
}
package us.d8u.balance;
import org.joda.time.DateTime;
import org.joda.time.format.ISODateTimeFormat;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
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.test.context.junit4.SpringRunner;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.common.collect.Sets;
import okhttp3.HttpUrl;
import okhttp3.OkHttpClient;
import okhttp3.Request;
@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT)
public class AgoTests {
private static final OkHttpClient client = new OkHttpClient();
private static final ObjectMapper mapper = new ObjectMapper();
@LocalServerPort
private int port;
@Test
public void worksWithNoParameters() throws Exception {
JsonNode response = mapper.readTree(client
.newCall(new Request.Builder()
.url(HttpUrl.parse("http://localhost/ago").newBuilder().port(port).build()).build())
.execute().body().string());
Sets.newHashSet("from", "to", "difference").stream()
.forEach(s -> Assert.assertTrue("Expected key " + s + " missing!", response.has(s)));
try {
ISODateTimeFormat.dateTimeNoMillis().parseDateTime((response.get("from")).asText());
} catch (Exception e) {
Assert.fail(response.get("from").asText() + "is not in ISO format");
}
try {
ISODateTimeFormat.dateTimeNoMillis().parseDateTime((response.get("to")).asText());
} catch (Exception e) {
Assert.fail(response.get("to").asText() + "is not in ISO format");
}
Assert.assertTrue("Difference incorrect",
response.get("difference").asText().equals("about " + DateTime.now().getYear() + " years"));
}
@Test
public void worksWithOneParameter() throws Exception {
DateTime dt = DateTime.now().minusHours(1);
HttpUrl url = HttpUrl.parse("http://localhost/ago").newBuilder().port(port)
.addQueryParameter("from", ISODateTimeFormat.dateTimeNoMillis().print(dt)).build();
JsonNode response = mapper
.readTree(client.newCall(new Request.Builder().url(url).build()).execute().body().string());
Sets.newHashSet("from", "to", "difference").stream()
.forEach(s -> Assert.assertTrue("Expected key " + s + " missing!", response.has(s)));
try {
ISODateTimeFormat.dateTimeNoMillis().parseDateTime((response.get("from")).asText());
} catch (Exception e) {
Assert.fail(response.get("from").asText() + "is not in ISO format");
}
try {
ISODateTimeFormat.dateTimeNoMillis().parseDateTime((response.get("to")).asText());
} catch (Exception e) {
Assert.fail(response.get("to").asText() + "is not in ISO format");
}
Assert.assertTrue("Difference incorrect", response.get("difference").asText().equals("about 20 hours"));
}
@Test
public void worksWithTwoParameters() throws Exception {
DateTime fromTime = DateTime.now().plusHours(1);
DateTime toTime = fromTime.minusHours(1);
HttpUrl url = HttpUrl.parse("http://localhost/ago").newBuilder().port(port)
.addQueryParameter("from", ISODateTimeFormat.dateTimeNoMillis().print(fromTime))
.addQueryParameter("to", ISODateTimeFormat.dateTimeNoMillis().print(toTime)).build();
JsonNode response = mapper
.readTree(client.newCall(new Request.Builder().url(url).build()).execute().body().string());
Sets.newHashSet("from", "to", "difference").stream()
.forEach(s -> Assert.assertTrue("Expected key " + s + " missing!", response.has(s)));
Assert.assertTrue("Difference incorrect", response.get("difference").asText().equals("about 2 hours"));
}
}
package us.d8u.balance;
import java.io.FileReader;
import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;
import org.joda.time.DateTime;
import org.joda.time.Instant;
import org.joda.time.format.ISODateTimeFormat;
import org.junit.After;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
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.test.context.junit4.SpringRunner;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ObjectNode;
import com.google.common.collect.Sets;
import okhttp3.HttpUrl;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT)
public class AuthTests {
private static final OkHttpClient client = new OkHttpClient();
static final ObjectMapper mapper = new ObjectMapper();
@Autowired
private AuthRepository authRepository;
@LocalServerPort
private int port;
@Autowired
private UserRepository userRepository;
Connection conn = null;
@After
public void _done() {
System.clearProperty("testing");
}
@Before
public void _setup() {
FileReader propertiesReader;
try {
propertiesReader = new FileReader("src/main/resources/application.properties");
System.getProperties().load(propertiesReader);
propertiesReader.close();
} catch (final IOException e) {
}
System.setProperty("testing", "true");
if (null == this.conn) {
try {
this.conn = DriverManager.getConnection(System.getProperty("auth.url"));
} catch (final SQLException e) {
}
}
try {
final Statement ddlStat = this.conn.createStatement();
ddlStat.execute(System.getProperty("auth.ddl"));
} catch (final SQLException e) {
}
}
@Test
public void expiringItemsWorks() throws Exception {
final int oldCount = this.authRepository.countExpired();
this.authRepository.removeExpired();
Assert.assertTrue(oldCount >= this.authRepository.countExpired());
}
@Test
public void postCreatesSessionIfCorrect() throws Exception {
final long oldCount = this.authRepository.count();
final ObjectNode auth = AuthTests.mapper.createObjectNode();
auth.put("userId", "1");
auth.put("endPoint", "/");
final HttpUrl endpoint = HttpUrl.parse("http://localhost/auth/key").newBuilder().port(this.port).build();
final JsonNode response = AuthTests.mapper
.readTree(
AuthTests.client
.newCall(new Request.Builder().url(endpoint)
.post(RequestBody.create(AuthTests.mapper.writeValueAsBytes(auth),
MediaType.parse("application/json")))
.build())
.execute().body().byteStream());
Assert.assertTrue(Sets.newHashSet("accessKey", "accessSecret", "endpoint", "id", "createdAt",
"authorizationHeader", "validUntil", "time").equals(Sets.newHashSet(response.fieldNames())));
Assert.assertTrue((this.authRepository.count() - oldCount) == 1);
final AuthBean latest = this.authRepository.findById(response.get("id").asLong()).get();
Assert.assertTrue("Unexpected endpoint", "/".equals(latest.getEndpointBean().getEndpoint().trim()));
Assert.assertTrue("Incorrect validity",
ISODateTimeFormat.dateTime().parseDateTime(response.get("validUntil").asText())
.isAfter(DateTime.now().plusMinutes(9))
&& ISODateTimeFormat.dateTime().parseDateTime(response.get("validUntil").asText())
.isBefore(DateTime.now().plusMinutes(11)));
Assert.assertTrue("Incorrect createdAt - should be this instant",
Instant.now().getMillis() == response.get("createdAt").asLong());
Assert.assertTrue("Userid weird",
!response.has("userId") || this.userRepository.existsById(response.get("userId").asLong()));
}
}
package us.d8u.balance;
import java.io.IOException;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.context.SpringBootTest.WebEnvironment;
import org.springframework.boot.test.web.server.LocalServerPort;
import org.springframework.test.context.junit4.SpringRunner;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ObjectNode;
import com.google.common.collect.Sets;
import okhttp3.Authenticator;
import okhttp3.Credentials;
import okhttp3.HttpUrl;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
import okhttp3.Route;
@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT)
public class BalanceTests {
private static final OkHttpClient client = new OkHttpClient();
private static final ObjectMapper mapper = new ObjectMapper();
public static final String access_key = "603946abdd4225000f07acea";
public static final String secret_key = "0a199d067d9e3d3ad31a562ea52c35";
@LocalServerPort
private int port;
@Test
public void emptyBody() throws Exception {
HttpUrl url = HttpUrl.parse("http://localhost/bal");
JsonNode response = mapper
.readTree(client.newCall(new Request.Builder().url(url).build()).execute().body().charStream());
Assert.assertTrue(
response.get("error").asText().equals("Routing and account numbers required -- and not persisted"));
}
@Test
public void statusTest() throws Exception {
HttpUrl url = HttpUrl.parse("http://localhost/bal/status").newBuilder().port(port).build();
JsonNode response = mapper
.readTree(client.newCall(new Request.Builder().url(url).build()).execute().body().charStream());
Assert.assertTrue(Sets.newHashSet(true, false).contains(response.get("status").asBoolean()));
}
@Test
public void missingAccountNumber() throws Exception {
String user = "user_good";
String password = "pass_good";
ObjectNode body = mapper.createObjectNode();
body.put("class", "https://sandbox.plaid.com");
body.put("routingNumber", "021000021");
JsonNode response = mapper.readTree(client.newBuilder().authenticator(new Authenticator() {
@Override
public Request authenticate(Route arg0, Response arg1) throws IOException {
String credentials = Credentials.basic(user, password);
return arg1.request().newBuilder().header("Authorization", credentials).build();
}
}).build()
.newCall(new Request.Builder().url("http://localhost:" + port + "/bal")
.post(RequestBody.create(mapper.writeValueAsBytes(body), MediaType.parse("application/json")))
.build())
.execute().body().charStream());
Assert.assertTrue(response.get("error").asText().equals("Missing accountNumber"));
}
@Test
public void missingRoutingNumber() throws Exception {
String user = "user_good";
String password = "pass_good";
ObjectNode body = mapper.createObjectNode();
body.put("class", "sandbox");
body.put("account", "1111222233331111");
JsonNode response = mapper.readTree(client.newBuilder().authenticator(new Authenticator() {
@Override
public Request authenticate(Route arg0, Response arg1) throws IOException {
String credentials = Credentials.basic(user, password);
return arg1.request().newBuilder().header("Authorization", credentials).build();
}
}).build()
.newCall(new Request.Builder().url("http://localhost:" + port + "/bal")
.post(RequestBody.create(mapper.writeValueAsBytes(body), MediaType.parse("application/json")))
.build())
.execute().body().charStream());
Assert.assertTrue(response.get("error").asText().equals(
"Missing Routing Number, use the one on your cheque, call your institution, or look it up at https://routingnumber.aba.com/Search1.aspx"));
}
@Test
public void acceptanceTest() throws Exception {
String user = "user_good";
String password = "pass_good";
ObjectNode body = mapper.createObjectNode();
body.put("class", "sandbox");
body.put("routingNumber", "021000021");
body.put("account", "1111222233331111");
JsonNode response = mapper.readTree(client.newBuilder().authenticator(new Authenticator() {
@Override
public Request authenticate(Route arg0, Response arg1) throws IOException {
String credentials = Credentials.basic(user, password);
return arg1.request().newBuilder().header("Authorization", credentials).build();
}
}).build()
.newCall(new Request.Builder().url("http://localhost:" + port + "/bal")
.post(RequestBody.create(mapper.writeValueAsBytes(body), MediaType.parse("application/json")))
.build())
.execute().body().charStream());
Assert.assertTrue(response.get("institution").asText().equals("Houndstooth Bank"));
Assert.assertTrue(response.get("balance").asText().matches("^[0-9.]+$"));
}
}
package us.d8u.balance;
import java.io.IOException;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.context.SpringBootTest.WebEnvironment;
import org.springframework.boot.test.web.server.LocalServerPort;
import org.springframework.test.context.junit4.SpringRunner;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ObjectNode;
import com.google.common.collect.Sets;
import okhttp3.Authenticator;
import okhttp3.Credentials;
import okhttp3.HttpUrl;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
import okhttp3.Route;
@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT)
public class BankTests {
private static final OkHttpClient client = new OkHttpClient();
private static final ObjectMapper mapper = new ObjectMapper();
public static final String access_key = "603946abdd4225000f07acea";
public static final String secret_key = "0a199d067d9e3d3ad31a562ea52c35";
@LocalServerPort
private int port;
@Test
public void statusTest() throws Exception {
HttpUrl url = HttpUrl.parse("http://localhost/bal/status").newBuilder().port(port).build();
JsonNode response = mapper
.readTree(client.newCall(new Request.Builder().url(url).build()).execute().body().charStream());
Assert.assertTrue(Sets.newHashSet(true, false).contains(response.get("status").asBoolean()));
}
@Test
public void missingAccountNumber() throws Exception {
String user = "user_good";
String password = "pass_good";
ObjectNode body = mapper.createObjectNode();
body.put("class", "https://sandbox.plaid.com");
body.put("routingNumber", "021000021");
JsonNode response = mapper.readTree(client.newBuilder().authenticator(new Authenticator() {
@Override
public Request authenticate(Route arg0, Response arg1) throws IOException {
String credentials = Credentials.basic(user, password);
return arg1.request().newBuilder().header("Authorization", credentials).build();
}
}).build()
.newCall(new Request.Builder().url("http://localhost:" + port + "/bal")
.post(RequestBody.create(mapper.writeValueAsBytes(body), MediaType.parse("application/json")))
.build())
.execute().body().charStream());
Assert.assertTrue(response.get("error").asText().equals("Missing accountNumber"));
}
@Test
public void missingRoutingNumber() throws Exception {
String user = "user_good";
String password = "pass_good";
ObjectNode body = mapper.createObjectNode();
body.put("class", "sandbox");
body.put("account", "1111222233331111");
JsonNode response = mapper.readTree(client.newBuilder().authenticator(new Authenticator() {
@Override
public Request authenticate(Route arg0, Response arg1) throws IOException {
String credentials = Credentials.basic(user, password);
return arg1.request().newBuilder().header("Authorization", credentials).build();
}
}).build()
.newCall(new Request.Builder().url("http://localhost:" + port + "/bal")
.post(RequestBody.create(mapper.writeValueAsBytes(body), MediaType.parse("application/json")))
.build())
.execute().body().charStream());
Assert.assertTrue(response.get("error").asText().equals(
"Missing Routing Number, use the one on your cheque, call your institution, or look it up at https://routingnumber.aba.com/Search1.aspx"));
}
@Test
public void acceptanceTest() throws Exception {
String user = "user_good";
String password = "pass_good";
ObjectNode body = mapper.createObjectNode();
body.put("class", "sandbox");
body.put("routingNumber", "021000021");
body.put("account", "1111222233331111");
JsonNode response = mapper.readTree(client.newBuilder().authenticator(new Authenticator() {
@Override
public Request authenticate(Route arg0, Response arg1) throws IOException {
String credentials = Credentials.basic(user, password);
return arg1.request().newBuilder().header("Authorization", credentials).build();
}
}).build()
.newCall(new Request.Builder().url("http://localhost:" + port + "/bal")
.post(RequestBody.create(mapper.writeValueAsBytes(body), MediaType.parse("application/json")))
.build())
.execute().body().charStream());
Assert.assertTrue(response.get("institution").asText().equals("Houndstooth Bank"));
Assert.assertTrue(response.get("balance").asText().matches("^[0-9.]+$"));
}
}
package us.d8u.balance;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.context.SpringBootTest.WebEnvironment;
import org.springframework.boot.test.web.server.LocalServerPort;
import org.springframework.test.context.junit4.SpringRunner;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ObjectNode;
import com.google.common.base.Joiner;
import com.google.common.collect.Sets;
import okhttp3.HttpUrl;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT)
public class Base64Tests {
private static final OkHttpClient client = new OkHttpClient();
private static final ObjectMapper mapper = new ObjectMapper();
@LocalServerPort
int port;
@Test
public void stringMissingGivseFeedback() throws Exception {
HttpUrl underTest = HttpUrl.parse("http://localhost/base64").newBuilder().port(port).build();
JsonNode response = mapper
.readTree(client.newCall(new Request.Builder().url(underTest).build()).execute().body().charStream());
Assert.assertTrue("Unexpected keyset: " + Joiner.on(", ").join(response.fieldNames()),
Sets.newHashSet("status", "error").equals(Sets.newHashSet(response.fieldNames())));
}
@Test
public void validRequest() throws Exception {
HttpUrl underTest = HttpUrl.parse("http://localhost/base64").newBuilder().port(port).build();
ObjectNode requestBody = mapper.createObjectNode();
requestBody.put("string", "foo");
JsonNode response = mapper
.readTree(client
.newCall(
new Request.Builder().url(underTest)
.post(RequestBody.create(mapper.writeValueAsString(requestBody),
MediaType.parse("application/json")))
.build())
.execute().body().byteStream());
Assert.assertTrue("Unexpected output", "Wm05dg==".equals(response.get("output").asText()));
}
}
package us.d8u.balance;
import java.util.HashSet;
import java.util.Map;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
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.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.Maps;
import com.google.common.collect.Sets;
import okhttp3.HttpUrl;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT)
public class BaseTests {
private static final OkHttpClient client = new OkHttpClient();
@LocalServerPort
private int port;
HttpUrl url = HttpUrl.parse("http://localhost/base").newBuilder().port(this.port).build();
@Test
public void base64GivesErrorWithoutString() throws Exception {
final okhttp3.RequestBody body = okhttp3.RequestBody
.create(new ObjectMapper().writeValueAsString(Maps.newHashMap()), MediaType.parse("application/json"));
final HttpUrl endpoint = HttpUrl.parse("http://localhost:" + this.port + "/base64");
final Request request = new Request.Builder().url(endpoint).post(body).build();
final Response response = BaseTests.client.newCall(request).execute();
final 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 base64GivesIndeterminateStringWithSecure() throws Exception {
final Map<String, String> bodyMap = Maps.newHashMap();
bodyMap.put("string", "java");
bodyMap.put("secure", "1");
final okhttp3.RequestBody body = okhttp3.RequestBody.create(new ObjectMapper().writeValueAsString(bodyMap),
MediaType.parse("application/json"));
final HttpUrl endpoint = HttpUrl.parse("http://localhost:" + this.port + "/base64");
final Request request = new Request.Builder().url(endpoint).post(body).build();
final Response response = BaseTests.client.newCall(request).execute();
final Map<String, String> result = new ObjectMapper().readValue(response.body().bytes(),
new TypeReference<Map<String, String>>() {
});
final Map<String, String> expected = Maps.newHashMap();
expected.put("in", "java");
expected.put("timestamp", Long.toString(System.nanoTime()));
expected.put("output", Base64Utils.encodeToUrlSafeString(("java" + expected.get("timestamp")).getBytes()));
for (final String key : expected.keySet()) {
Assert.assertTrue(result.containsKey(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 {
final Map<String, String> bodyMap = Maps.newHashMap();
bodyMap.put("string", "java");
final okhttp3.RequestBody body = okhttp3.RequestBody.create(new ObjectMapper().writeValueAsString(bodyMap),
MediaType.parse("application/json"));
final HttpUrl endpoint = HttpUrl.parse("http://localhost:" + this.port + "/base64");
final Request request = new Request.Builder().url(endpoint).post(body).build();
final Response response = BaseTests.client.newCall(request).execute();
final Map<String, String> result = new ObjectMapper().readValue(response.body().bytes(),
new TypeReference<Map<String, String>>() {
});
final Map<String, String> expected = Maps.newHashMap();
expected.put("in", "java");
expected.put("output", Base64Utils.encodeToUrlSafeString("java".getBytes()));
Assert.assertEquals("Unexpected or missing keys", expected, result.keySet());
Assert.assertEquals("java", result.get("in"));
Assert.assertEquals("amF2YQ==", expected.get("output"));
Assert.assertFalse(result.containsKey("timestamp"));
}
@Test
public void convertFromBase16ToDecimalWorks() throws Exception {
this.url = this.url.newBuilder().addEncodedQueryParameter("from", "16").addEncodedQueryParameter("to", "10")
.addEncodedQueryParameter("number", "16").addEncodedQueryParameter("from", "16").build();
final JsonNode response = new ObjectMapper().readTree(
BaseTests.client.newCall(new Request.Builder().url(this.url).build()).execute().body().byteStream());
final HashSet<String> keysSet = Sets.newHashSet(response.fieldNames());
Assert.assertTrue(keysSet.equals(Sets.newHashSet("from", "to", "returningNumber", "incomingNumber")));
Assert.assertTrue(response.get("from").asInt() == 16);
Assert.assertTrue(response.get("to").asInt() == 10);
Assert.assertTrue(response.get("returningNum").asInt() == 16);
Assert.assertTrue(response.get("incomingNumber").asInt() == 10);
}
@Test
public void fromDefaultsTo10IfMissing() throws Exception {
this.url = this.url.newBuilder().addEncodedQueryParameter("to", "16").addEncodedQueryParameter("number", "10")
.build();
final JsonNode response = new ObjectMapper().readTree(
BaseTests.client.newCall(new Request.Builder().url(this.url).build()).execute().body().byteStream());
final String from = response.get("from").asText();
Assert.assertEquals(from, "10");
}
@Test
public void integersOnly() throws Exception {
this.url = this.url.newBuilder().addEncodedQueryParameter("from", "10.2").addEncodedQueryParameter("to", "10")
.addEncodedQueryParameter("number", "10").build();
final JsonNode response = new ObjectMapper().readTree(
BaseTests.client.newCall(new Request.Builder().url(this.url).build()).execute().body().byteStream());
final String error = response.get("error").asText();
Assert.assertEquals(error, "need from, to, and number as integers");
}
@Test
public void toDefaultsTo10IfMissing() throws Exception {
this.url = this.url.newBuilder().addEncodedQueryParameter("from", "16").addEncodedQueryParameter("number", "10")
.build();
final JsonNode response = new ObjectMapper().readTree(
BaseTests.client.newCall(new Request.Builder().url(this.url).build()).execute().body().byteStream());
final String to = response.get("to").asText();
Assert.assertEquals(to, "10");
}
}
package us.d8u.balance;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
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.test.context.junit4.SpringRunner;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import okhttp3.HttpUrl;
import okhttp3.OkHttpClient;
import okhttp3.Request;
@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT)
public class BcryptTests {
private static final OkHttpClient client = new OkHttpClient();
private final ObjectMapper mapper = new ObjectMapper();
@LocalServerPort
private int port;
@Test
public void nullString() throws Exception {
final HttpUrl location = HttpUrl.parse("http://localhost/bcrypt/").newBuilder().port(this.port).build();
final JsonNode response = this.mapper.readTree(
BcryptTests.client.newCall(new Request.Builder().url(location).build()).execute().body().byteStream());
Assert.assertTrue("blank string".equals(response.get("error").asText()));
}
@Test
public void parametersSupported() throws Exception {
final HttpUrl location = HttpUrl.parse("http://localhost/bcrypt/hello%20world").newBuilder().port(this.port)
.addEncodedQueryParameter("version", "2a").build();
final JsonNode response = this.mapper.readTree(
BcryptTests.client.newCall(new Request.Builder().url(location).build()).execute().body().byteStream());
Assert.assertTrue("hello world".equals(response.get("input").asText()));
Assert.assertTrue(response.get("version").asText().equals(location.queryParameter("version")));
}
/*
* According to https://en.wikipedia.org/wiki/Bcrypt, the differences between 2a
* and 2b is that OpenBSD uncovered a buffer-overflow bug. They fixed their
* implementation and bumped the version. I've included their test to verify
* this web service is immune.
*/
@Test
public void stringLongerThan72() throws Exception {
final HttpUrl location = HttpUrl.parse(
"http://localhost/bcrypt/xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx")
.newBuilder().port(this.port).build();
final JsonNode response = this.mapper.readTree(
BcryptTests.client.newCall(new Request.Builder().url(location).build()).execute().body().byteStream());
Assert.assertTrue("$2b$10$67srBmw35/M8n2EImcE5vuS020LBbhdu.aN9oAWJvFIZC1/f0MhWa"
.equals(response.get("encoded").asText()));
}
@Test
public void unsupportedVersion() throws Exception {
final HttpUrl location = HttpUrl.parse("http://localhost/bcrypt/hello%20world").newBuilder().port(this.port)
.addEncodedQueryParameter("version", "2xyz").build();
final JsonNode response = this.mapper.readTree(
BcryptTests.client.newCall(new Request.Builder().url(location).build()).execute().body().byteStream());
Assert.assertTrue("invalid version".equals(response.get("error").asText()));
}
}
package us.d8u.balance;
import java.net.HttpURLConnection;
import java.net.URL;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
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.test.context.junit4.SpringRunner;
import okhttp3.HttpUrl;
@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT)
public class BitbucketTests {
@LocalServerPort
private int port;
@Test
public void testGetSuccess() throws Exception {
final HttpUrl requestUrl = new HttpUrl.Builder().scheme("http").host("localhost").port(this.port)
.addPathSegment("bitbucket").build();
final HttpURLConnection conn = (HttpURLConnection) new URL(requestUrl.toString()).openConnection();
conn.connect();
final String location = conn.getHeaderField("Location");
Assert.assertTrue("Location incorrect " + location, "https://bitbucket.org/hd1".equals(location));
}
}
package us.d8u.balance;
import java.io.InputStreamReader;
import java.util.List;
import java.util.Set;
import org.apache.commons.compress.compressors.xz.XZCompressorInputStream;
import org.apache.commons.lang3.StringUtils;
import org.assertj.core.util.Sets;
import org.joda.time.DateTime;
import org.joda.time.format.ISODateTimeFormat;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
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.test.context.junit4.SpringRunner;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ObjectNode;
import com.google.common.collect.Lists;
import com.opencsv.CSVReader;
import okhttp3.HttpUrl;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT)
public class BmiTests {
private static final OkHttpClient client = new OkHttpClient();
private static final ObjectMapper mapper = new ObjectMapper();
@LocalServerPort
private int port;
@Test
public void bmiReportWorks() throws Exception {
final HttpUrl url = HttpUrl.parse("http://localhost/bmi/report").newBuilder().port(this.port)
.addEncodedQueryParameter("user", "me").addEncodedQueryParameter("pass", "p@ss").build();
List<String[]> report = null;
try (CSVReader reader = new CSVReader(new InputStreamReader(new XZCompressorInputStream(
BmiTests.client.newCall(new Request.Builder().url(url).build()).execute().body().byteStream())))) {
report = reader.readAll();
}
final CSVReader reader = new CSVReader(new InputStreamReader(
new XZCompressorInputStream(this.getClass().getResourceAsStream("bmiAuth.csv.xz"))));
final Set<String[]> usersFromDb = Sets.newHashSet(reader.readAll());
final Set<String> users = Sets.newHashSet();
for (final String[] stored : usersFromDb) {
users.add(stored[0]);
}
for (final String[] entry : report) {
Assert.assertTrue(entry.length == 3);
Assert.assertTrue("Date format invalid -- " + entry[0],
ISODateTimeFormat.dateParser().parseDateTime(entry[0]) != null);
Assert.assertTrue("User not found for " + entry[1], users.contains(entry[1]));
Assert.assertTrue("Reading not numeric" + entry[2], StringUtils.isNumeric(entry[2]));
}
}
@Test
public void getBmiReturnsCorrectly() throws Exception {
final HttpUrl url = HttpUrl.parse("http://localhost/bmi?m=1.51&kg=45").newBuilder().port(this.port).build();
final JsonNode response = BmiTests.mapper.readTree(
BmiTests.client.newCall(new Request.Builder().url(url).build()).execute().body().byteStream());
Assert.assertTrue("19.74".equals(response.get("bmi").asText()));
}
@Test
public void postBmiReturnsCorrectly() throws Exception {
final ObjectNode body = BmiTests.mapper.createObjectNode();
body.put("reading", 19.4);
body.put("date", ISODateTimeFormat.date().print(DateTime.now().plusDays(1)));
body.put("user", "me");
body.put("pass", "p@ss");
final HttpUrl url = HttpUrl.parse("http://localhost/bmi").newBuilder().port(this.port).build();
final RequestBody json = RequestBody.create(BmiTests.mapper.writeValueAsString(body),
MediaType.parse("application/json"));
final JsonNode response = BmiTests.mapper.readTree(BmiTests.client
.newCall(new Request.Builder().url(url).post(json).build()).execute().body().charStream());
for (final String k : Lists.newArrayList(response.fieldNames())) {
Assert.assertTrue(response.has(k));
}
Assert.assertTrue(StringUtils.isNumeric(response.get("id").asText()));
}
}
package us.d8u.balance;
import java.io.Reader;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
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 com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.common.base.CharMatcher;
import com.google.common.collect.Lists;
import okhttp3.HttpUrl;
import okhttp3.OkHttpClient;
import okhttp3.Request;
@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT)
public class CacheTests {
private static final OkHttpClient client = new OkHttpClient.Builder().followRedirects(false).build();
private static final ObjectMapper mapper = new ObjectMapper();
@LocalServerPort
private int port;
@Test
public void properKeysAndValues() throws Exception {
final HttpUrl url = HttpUrl.parse("http://localhost/cache").newBuilder().port(this.port).build();
final Request request = new Request.Builder().url(url).build();
final Reader jsonRaw = CacheTests.client.newCall(request).execute().body().charStream();
final JsonNode json = CacheTests.mapper.readTree(jsonRaw);
for (final String k : Lists.newArrayList(json.fieldNames())) {
Assert.assertTrue(k.startsWith("/"));
final JsonNode val = json.get(k);
Assert.assertTrue(
val.fieldNames().equals(Lists.newArrayList("hits", "misses", "filledPct", "totalSize").iterator()));
Assert.assertTrue(CharMatcher.inRange('0', '9').matchesAllOf(val.get("hits").asText()));
Assert.assertTrue(CharMatcher.inRange('0', '9').matchesAllOf(val.get("misses").asText()));
Assert.assertTrue("filledPct is greater than 100%", val.get("filledPct").asDouble() <= 1.0d);
}
}
@Test
public void tooManyParamtersReturnsError() throws Exception {
final HttpUrl url = HttpUrl.parse("http://localhost/cache").newBuilder().port(this.port)
.addQueryParameter("endpoint", "/summary").addEncodedQueryParameter("foo", "1").build();
final Request request = new Request.Builder().url(url).build();
final Reader jsonRaw = CacheTests.client.newCall(request).execute().body().charStream();
final JsonNode json = CacheTests.mapper.readTree(jsonRaw);
Assert.assertTrue(json.get("status").asInt() == HttpStatus.BAD_REQUEST.value());
Assert.assertTrue("too many parameters".equals(json.get("error").asText()));
}
}
package us.d8u.balance;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
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.test.context.junit4.SpringRunner;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ObjectNode;
import okhttp3.HttpUrl;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT)
public class CalcTests {
private static final OkHttpClient client = new OkHttpClient();
private static final ObjectMapper mapper = new ObjectMapper();
@LocalServerPort
private int port;
@Test
public void additionWorks() throws Exception {
ObjectNode body = mapper.createObjectNode();
body.put("expression", "1+1");
HttpUrl urlUnderTest = HttpUrl.parse("http://localhost/calc").newBuilder().port(port).build();
RequestBody httpBody = RequestBody.create(mapper.writeValueAsBytes(body), MediaType.parse("application/json"));
int result = mapper.readTree(client.newCall(new Request.Builder().post(httpBody).url(urlUnderTest).build())
.execute().body().byteStream()).get("result").asInt();
Assert.assertTrue("Sum not 2", result == 2);
}
@Test
public void multiplicationWorks() throws Exception {
ObjectNode body = mapper.createObjectNode();
body.put("expression", "1*1");
HttpUrl urlUnderTest = HttpUrl.parse("http://localhost/calc").newBuilder().port(port).build();
RequestBody httpBody = RequestBody.create(mapper.writeValueAsBytes(body), MediaType.parse("application/json"));
int result = mapper.readTree(client.newCall(new Request.Builder().post(httpBody).url(urlUnderTest).build())
.execute().body().byteStream()).get("result").asInt();
Assert.assertTrue("Product not 1", result == 1);
}
}
package us.d8u.balance;
import java.io.Reader;
import java.util.List;
import java.util.Map;
import java.util.TreeSet;
import org.joda.time.DateTime;
import org.joda.time.DateTimeComparator;
import org.joda.time.MutableDateTime;
import org.joda.time.format.DateTimeFormatter;
import org.joda.time.format.ISODateTimeFormat;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
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.test.context.junit4.SpringRunner;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.Iterators;
import com.google.common.collect.Lists;
import com.google.common.collect.Sets;
import okhttp3.HttpUrl;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT)
public class CalTests {
private static final OkHttpClient client = new OkHttpClient();
@LocalServerPort
private int port;
@Test
public void calReturnsOneEventOnly() throws Exception {
final HttpUrl url = HttpUrl.parse("http://localhost:" + this.port + "/cal");
final Response rawHttpResponse = CalTests.client.newCall(new Request.Builder().url(url).build()).execute();
final Reader rawResponse = rawHttpResponse.body().charStream();
final JsonNode response = new ObjectMapper().readTree(rawResponse);
Assert.assertTrue(!response.isArray() && response.isObject());
final Map<String, String> eventResponse = new ObjectMapper().readValue(rawResponse,
new TypeReference<Map<String, String>>() {
});
Assert.assertTrue(Sets.newHashSet("azimuth", "distance", "destination", "startTime", "event")
.equals(eventResponse.keySet()));
Assert.assertTrue(
ISODateTimeFormat.dateTime().parseDateTime(eventResponse.get("startTime")).isAfter(DateTime.now()));
Assert.assertTrue(Double.valueOf(eventResponse.get("distance")) > 0d);
Assert.assertTrue(Math.abs(Double.parseDouble(eventResponse.get("azimuth"))) < 360d);
}
@Test
public void calSlotsReturnsNextThreeDatesWithArrayOfTimes() throws Exception {
final TreeSet<DateTime> keys = new TreeSet<>(DateTimeComparator.getDateOnlyInstance());
final MutableDateTime today = MutableDateTime.now();
keys.add(today.toDateTime());
today.addDays(1);
keys.add(today.toDateTime());
today.addDays(1);
keys.add(today.toDateTime());
final HttpUrl url = HttpUrl.parse("http://localhost:" + this.port + "/cal/slots");
final Response rawHttpResponse = CalTests.client.newCall(new Request.Builder().url(url).build()).execute();
final Reader rawResponse = rawHttpResponse.body().charStream();
final JsonNode response = new ObjectMapper().readTree(rawResponse);
final List<String> outerKeys = Lists.newArrayList(response.fieldNames());
final String todayKey = ISODateTimeFormat.date().print(DateTime.now());
Assert.assertTrue(outerKeys.contains(todayKey));
final String tomorrowKey = ISODateTimeFormat.date().print(DateTime.now().plusDays(1));
Assert.assertTrue(outerKeys.contains(tomorrowKey));
final String lastKey = ISODateTimeFormat.date().print(DateTime.now().plusDays(2));
Assert.assertTrue(outerKeys.contains(lastKey));
Assert.assertTrue(response.size() == 3);
Assert.assertTrue(ImmutableSet.of(response.fieldNames()).equals(ImmutableSet.copyOf(keys)));
Assert.assertTrue(Iterators.size(response.fieldNames()) == 3);
final ImmutableSet<String> innerKeys = ImmutableSet.of("start", "end");
final DateTimeFormatter timeFormat = ISODateTimeFormat.hourMinute();
for (final String k : outerKeys) {
final JsonNode inner = response.get(k);
for (final String timeKey : Sets.newHashSet(inner.fieldNames())) {
Assert.assertTrue(inner.get(timeKey).size() == 2);
try {
timeFormat.parseDateTime(timeKey);
} catch (final Exception e) {
Assert.fail(e.getMessage());
}
try {
timeFormat.parseDateTime(timeKey);
} catch (final Exception e) {
Assert.fail(e.getMessage());
}
Assert.assertTrue(innerKeys.contains(inner.get(timeKey).asText()));
}
}
}
}
package us.d8u.balance;
import org.joda.time.DateTime;
import org.joda.time.format.ISODateTimeFormat;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
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 com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import okhttp3.HttpUrl;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT)
public class ClockTests {
private static final OkHttpClient client = new OkHttpClient();
@LocalServerPort
private int port;
@Test
public void defaultsToNow() throws Exception {
final HttpUrl endpointUnderTest = HttpUrl.parse("http://localhost:" + port + "/clock/PST8PDT/UTC");
final Request request = new Request.Builder().url(endpointUnderTest).build();
final Response response = client.newCall(request).execute();
final JsonNode returns = new ObjectMapper().readTree(response.body().bytes());
final String expected = ISODateTimeFormat.time().print(DateTime.now());
Assert.assertEquals(expected, returns.get("time"));
}
@Test
public void returnsOffset() throws Exception {
final HttpUrl endpointUnderTest = HttpUrl.parse("http://localhost:" + port + "/clock/PST8PDT/UTC");
final Request request = new Request.Builder().url(endpointUnderTest).build();
final Response response = client.newCall(request).execute();
final JsonNode returns = new ObjectMapper().readTree(response.body().bytes());
final Integer expected = returns.get("offset").asInt();
Assert.assertTrue(0 < expected && expected < 24);
}
@Test
public void unknownTimezoneReturnsError() throws Exception {
final HttpUrl endpointUnderTest = HttpUrl.parse("http://localhost:" + port + "/clock/PST8PDT/UTCx");
final Request request = new Request.Builder().url(endpointUnderTest).build();
final Response response = client.newCall(request).execute();
final JsonNode returns = new ObjectMapper().readTree(response.body().bytes());
final String expected = "Unknown timezone \"UTCx\"";
Assert.assertEquals(expected, returns.get("error").asText());
Assert.assertEquals(HttpStatus.PRECONDITION_FAILED.value(), returns.get("status").asInt());
}
}
package us.d8u.balance;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
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.test.context.junit4.SpringRunner;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import okhttp3.HttpUrl;
import okhttp3.OkHttpClient;
import okhttp3.Request;
@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT)
public class CloudTests {
private static final OkHttpClient client = new OkHttpClient();
public static final ObjectMapper mapper = new ObjectMapper();
@LocalServerPort
private int port;
@Value(value = "${api.dropbox.token}")
String DROPBOX_TOKEN;
@Before
public void define() {
System.setProperty("test", "1");
}
@Test
public void returnsResultsAsProperUrls() throws Exception {
final HttpUrl url = HttpUrl.parse("http://localhost/cloud").newBuilder().port(this.port)
.addEncodedPathSegment(this.DROPBOX_TOKEN).addQueryParameter("q", "amspresentationpub.pdf").build();
final JsonNode results = CloudTests.mapper.readTree(
CloudTests.client.newCall(new Request.Builder().url(url).build()).execute().body().charStream());
Assert.assertTrue("Missing top-level results key", results.has("results") && results.get("results").isArray());
for (final JsonNode result : results.get("results")) {
final HttpUrl resultLocation = HttpUrl.parse(result.asText());
Assert.assertTrue("invalid URL" + resultLocation, resultLocation != null);
}
}
}
package us.d8u.balance;
import java.util.Iterator;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
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.test.context.junit4.SpringRunner;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ArrayNode;
import okhttp3.HttpUrl;
import okhttp3.OkHttpClient;
import okhttp3.Request;
@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT)
public class ConfigTests {
private static final OkHttpClient client = new OkHttpClient();
private static final ObjectMapper mapper = new ObjectMapper();
@LocalServerPort
private int port;
@Test
public void configNoParamsReturnsSlashPrefixedList() throws Exception {
final HttpUrl underTest = HttpUrl.parse("http://localhost/config").newBuilder().port(this.port).build();
final ArrayNode response = (ArrayNode) ConfigTests.mapper.readTree(
ConfigTests.client.newCall(new Request.Builder().url(underTest).build()).execute().body().string())
.get("endponts");
final Iterator<JsonNode> iter = response.elements();
while (iter.hasNext()) {
final JsonNode valNode = iter.next();
final String val = valNode.asText();
Assert.assertTrue(val.startsWith("/"));
}
}
}
package us.d8u.balance;
import org.joda.time.DateTime;
import org.joda.time.format.ISODateTimeFormat;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
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.test.context.junit4.SpringRunner;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import okhttp3.HttpUrl;
import okhttp3.OkHttpClient;
import okhttp3.Request;
@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT)
public class CongressTests {
private static final OkHttpClient client = new OkHttpClient();
private static ObjectMapper mapper = new ObjectMapper();
@LocalServerPort
private int port;
@Test
public void congressionalBillIsCaseInsensitive() throws Exception {
final HttpUrl url = HttpUrl.parse("http://localhost/congress").newBuilder().port(this.port)
.addPathSegment("116").addQueryParameter("bill", "hr502").build();
final Request request = new Request.Builder().url(url).build();
final JsonNode response = CongressTests.mapper
.readTree(CongressTests.client.newCall(request).execute().body().byteStream());
Assert.assertTrue("Sponsor name incorrect", "Vargas, Juan".equals(response.get("sponsor").asText()));
Assert.assertTrue("Party incorrect", "Democratic".equals(response.get("party").asText()));
final HttpUrl link = HttpUrl.parse(response.get("link").asText());
Assert.assertTrue("hostname unexpected", "www.congress.gov".equals(link.host()));
final DateTime dt = ISODateTimeFormat.date().parseDateTime(response.get("introductionDate").asText());
Assert.assertTrue("Date incorrect",
(dt.getMonthOfYear() == 1) && (dt.getYear() == 2019) && (dt.getDayOfMonth() == 11));
Assert.assertTrue("district incorrect", "CA/51".equals(response.get("district").asText()));
}
}
package us.d8u.balance;
import java.util.Map;
import java.util.Set;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
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.test.context.junit4.SpringRunner;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.common.collect.Sets;
import okhttp3.HttpUrl;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT)
public class CostTests {
private static final OkHttpClient client = new OkHttpClient();
@LocalServerPort
private int port;
@Test
public void endpointCostCanBeUpdated() throws Exception {
final HttpUrl requestUrl = new HttpUrl.Builder().host("localhost").scheme("http").port(this.port)
.addPathSegment("cost").addQueryParameter("endpoint", "/").addQueryParameter("newCost", "0").build();
final Request request = new Request.Builder().url(requestUrl).patch(RequestBody.create("".getBytes(), null))
.build();
final Response rawResponse = CostTests.client.newCall(request).execute();
final String string = rawResponse.body().string();
final Map<String, String> response = new ObjectMapper().readValue(string,
new TypeReference<Map<String, String>>() {
});
final Set<String> expectedKeys = Sets.newHashSet("endpoint", "newCost");
for (final 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());
}
}
package us.d8u.balance;
import java.io.File;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
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 com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import okhttp3.HttpUrl;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT)
public class CovTests {
private static final OkHttpClient client = new OkHttpClient();
private static ObjectMapper mapper = new ObjectMapper();
@LocalServerPort
private int port;
@Test
public void returnsNotFoundInProduction() throws Exception {
final HttpUrl url = HttpUrl.parse("http://localhost/cov").newBuilder().port(this.port).build();
final Response rawResponse = CovTests.client.newCall(new Request.Builder().url(url).build()).execute();
final JsonNode response = CovTests.mapper.readTree(rawResponse.body().bytes());
final File testTree = new File("target/site/jacoco");
if (testTree.exists()) {
Assert.assertTrue("Redirect code failed", rawResponse.code() == HttpStatus.PERMANENT_REDIRECT.value());
} else {
Assert.assertTrue("not allowed on this server".equals(response.get("message").asText()));
}
}
}
package us.d8u.balance;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
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.test.context.junit4.SpringRunner;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT)
public class CvTests {
private static OkHttpClient client = new OkHttpClient();
@LocalServerPort
private int port;
@Test
public void redirectWorksWithSrcParameter() throws Exception {
Request request = new Request.Builder().url("http://localhost:" + port + "/cv?src=test").build();
Response response = client.newBuilder().followRedirects(false).build().newCall(request).execute();
Assert.assertTrue("Redirect location wrong", response.header("location").equals("https://hasan.d8u.us/CV.pdf"));
}
}
package us.d8u.balance;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
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.mock.web.MockMultipartFile;
import org.springframework.test.context.junit4.SpringRunner;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import okhttp3.MultipartBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT)
public class DetectTypeTests {
private static final OkHttpClient client = new OkHttpClient();
@LocalServerPort
private int port;
@Test
public void detectTypeReturnsProperKeys() throws Exception {
final MockMultipartFile multipartFile = new MockMultipartFile("file", "test.txt", "text/plain",
"Spring Boot".getBytes());
final RequestBody requestBody = new MultipartBody.Builder().setType(MultipartBody.FORM).addFormDataPart("file",
multipartFile.getOriginalFilename(), RequestBody.create(multipartFile.getBytes())).build();
final Request request = new Request.Builder().url("http://localhost:" + this.port + "/detectType")
.post(requestBody).build();
final Response rawResponse = DetectTypeTests.client.newCall(request).execute();
final JsonNode response = new ObjectMapper().readTree(rawResponse.body().bytes());
Assert.assertTrue("Invalid keys", response.has("default") && response.has("withMimeTypes")
&& response.has("withTypesDetector") && response.has("name"));
Assert.assertTrue("Type does not have a '/'",
response.get("default").asText().contains("/") && response.get("withMimeTypes").asText().contains("/")
&& response.get("withTypesDetector").asText().contains("/"));
Assert.assertTrue("test.txt".equals(response.get("name").asText()));
}
}
package us.d8u.balance;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.context.SpringBootTest.WebEnvironment;
import org.springframework.boot.test.web.server.LocalServerPort;
import org.springframework.test.context.junit4.SpringRunner;
import okhttp3.HttpUrl;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT)
public class DiffbotTests {
private static final OkHttpClient client = new OkHttpClient();
@LocalServerPort
private int port;
@Test
public void contentTypeCorrect() throws Exception {
HttpUrl url = HttpUrl.parse("http://localhost/diffbot").newBuilder().port(port).addQueryParameter("url",
"https://www.postgresonline.com/journal/archives/99-Quick-Intro-to-PLPython.html").build();
Response response = client.newCall(new Request.Builder().url(url).build()).execute();
Assert.assertTrue(response.header("content-type").equals("text/html"));
Assert.assertTrue(response.isSuccessful());
}
}
package us.d8u.balance;
import org.joda.time.DateTime;
import org.joda.time.format.ISODateTimeFormat;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
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.test.context.junit4.SpringRunner;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.ibm.icu.text.NumberFormat;
import okhttp3.HttpUrl;
import okhttp3.OkHttpClient;
import okhttp3.Request;
@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT)
public class DiffTimeTests {
private static final OkHttpClient client = new OkHttpClient();
private static final ObjectMapper mapper = new ObjectMapper();
@LocalServerPort
private int port;
@Test
public void moreThanOneHourReturnsHoursByDefault() throws Exception {
final String from = ISODateTimeFormat.dateTimeNoMillis().print(DateTime.now().plusHours(1).plusMinutes(1));
final String to = ISODateTimeFormat.dateTimeNoMillis().print(DateTime.now());
final HttpUrl url = HttpUrl.parse("http://localhost/diffttime").newBuilder().port(this.port)
.addQueryParameter("from", from).addQueryParameter("to", to).build();
final JsonNode response = DiffTimeTests.mapper.readTree(
DiffTimeTests.client.newCall(new Request.Builder().url(url).build()).execute().body().charStream());
Assert.assertTrue(response.get("from").asText().equals(from));
Assert.assertTrue(response.get("to").asText().equals(to));
Assert.assertTrue("1:01".equals(response.get("differenceInTime").asText()));
Assert.assertTrue(response.get("difference").asLong() == (ISODateTimeFormat.dateTimeNoMillis().parseMillis(to)
- ISODateTimeFormat.dateTimeNoMillis().parseMillis(from)));
}
@Test
public void withoutFrom() throws Exception {
final String from = ISODateTimeFormat.dateTimeNoMillis().print(DateTime.now().plusHours(1).plusMinutes(1));
final HttpUrl url = HttpUrl.parse("http://localhost/difftime").newBuilder().port(this.port)
.addQueryParameter("from", from).build();
final JsonNode response = DiffTimeTests.mapper.readTree(
DiffTimeTests.client.newCall(new Request.Builder().url(url).build()).execute().body().charStream());
Assert.assertTrue("From incorrect", response.get("from").asText().equals(from));
Assert.assertTrue("To incorrect format",
ISODateTimeFormat.dateTime().parseDateTime(response.get("to").asText()) != null);
Assert.assertTrue("difference not an integer",
NumberFormat.getInstance().parse(response.get("difference").asText()).longValue() > 0L);
}
@Test
public void withoutFromAndToYieldsError() throws Exception {
final HttpUrl url = HttpUrl.parse("http://localhost/difftime").newBuilder().port(this.port).build();
final JsonNode response = DiffTimeTests.mapper.readTree(
DiffTimeTests.client.newCall(new Request.Builder().url(url).build()).execute().body().charStream());
Assert.assertTrue(response.get("status").asInt() == 400);
Assert.assertTrue("Don't know what would make sense here".equals(response.get("error").asText()));
}
@Test
public void withoutTo() throws Exception {
final String to = ISODateTimeFormat.dateTimeNoMillis().print(DateTime.now().plusHours(1).plusMinutes(1));
final HttpUrl url = HttpUrl.parse("http://localhost/difftime").newBuilder().port(this.port)
.addQueryParameter("to", to).build();
final JsonNode response = DiffTimeTests.mapper.readTree(
DiffTimeTests.client.newCall(new Request.Builder().url(url).build()).execute().body().charStream());
Assert.assertTrue(response.get("to").asText().equals(to));
Assert.assertTrue(response.get("from").asText().equals(ISODateTimeFormat.dateTime().print(DateTime.now())));
Assert.assertTrue(NumberFormat.getInstance().parse(response.get("difference").asText()).longValue() > 0L);
}
}
package us.d8u.balance;
import java.util.Map;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
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.test.context.junit4.SpringRunner;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import okhttp3.HttpUrl;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT)
public class DistanceAndBearingTests {
private static final OkHttpClient client = new OkHttpClient();
@LocalServerPort
private int port;
ObjectMapper mapper = new ObjectMapper();
@Test
public void bearingReturnsZeroForIdenticalPoints() throws Exception {
final HttpUrl requestUrl = new HttpUrl.Builder().host("localhost").scheme("http").port(this.port)
.addPathSegment("bearing").addQueryParameter("point1", "0,0").addQueryParameter("point2", "0,0")
.build();
final Request request = new Request.Builder().url(requestUrl).get().build();
final String rawResponse = DistanceAndBearingTests.client.newCall(request).execute().body().string();
final Map<String, String> response = this.mapper.readValue(rawResponse,
new TypeReference<Map<String, String>>() {
});
Assert.assertEquals("0", response.get("bearingInDegreesFromEast"));
}
@Test
public void distanceBetweenPointAndItselfIsZeroMeters() throws Exception {
final HttpUrl url = new HttpUrl.Builder().addQueryParameter("point1", "0,0").addQueryParameter("point2", "0,0")
.host("localhost").port(this.port).scheme("http").addPathSegment("distance").build();
final Request request = new Request.Builder().url(url).build();
final Response response = DistanceAndBearingTests.client.newCall(request).execute();
final Map<String, String> responseMap = this.mapper.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("Incorect distance -- " + responseMap.get("distance"), "0.0", responseMap.get("distance"));
Assert.assertEquals("Incorrect bearing -- " + responseMap.get("bearing"), "0.0", responseMap.get("bearing"));
}
}
package us.d8u.balance;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.context.SpringBootTest.WebEnvironment;
import org.springframework.boot.test.web.server.LocalServerPort;
import org.springframework.test.context.junit4.SpringRunner;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import okhttp3.HttpUrl;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT)
public class DNSTests {
private static final OkHttpClient client = new OkHttpClient();
private static final ObjectMapper mapper = new ObjectMapper();
@LocalServerPort
private int port;
@Test
public void emptyParameters() throws Exception {
HttpUrl url = HttpUrl.parse("http://localhost/dns").newBuilder().port(port).build();
Response raw = client.newCall(new Request.Builder().url(url).build()).execute();
JsonNode response = mapper.readTree(raw.body().charStream());
Assert.assertTrue(response.get("error").asText().equals("host parameter required"));
}
@Test
public void unknownHost() throws Exception {
HttpUrl url = HttpUrl.parse("http://localhost/dns").newBuilder().port(port).addQueryParameter("host", "ibmx.cm")
.build();
Response raw = client.newCall(new Request.Builder().url(url).build()).execute();
JsonNode response = mapper.readTree(raw.body().charStream());
Assert.assertTrue(response.get("error").asText().equals("host ibmx.cm not found"));
}
@Test
public void workingForwardRequest() throws Exception {
HttpUrl url = HttpUrl.parse("http://localhost/dns").newBuilder().port(port)
.addQueryParameter("host", "www.rpi.edu").build();
Response raw = client.newCall(new Request.Builder().url(url).build()).execute();
JsonNode response = mapper.readTree(raw.body().charStream());
Assert.assertTrue(response.get("ipv4").asText().equals("128.113.0.2"));
Assert.assertTrue(response.get("ipv6").asText().equals("2620:0:2820:4::2"));
}
}
package us.d8u.balance;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
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 com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import okhttp3.HttpUrl;
import okhttp3.OkHttpClient;
import okhttp3.Request;
@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT)
public class EmailTests {
private static final OkHttpClient client = new OkHttpClient();
private static final ObjectMapper mapper = new ObjectMapper();
@LocalServerPort
int port;
@Test
public void invalidParameterReturnsError() throws Exception {
final HttpUrl url = HttpUrl.parse("http://localhost:" + this.port + "/email").newBuilder()
.addQueryParameter("eMail", "hd1@jsc.d8u.us").build();
final Request request = new Request.Builder().url(url).build();
final JsonNode response = EmailTests.mapper
.readTree(EmailTests.client.newCall(request).execute().body().bytes());
Assert.assertTrue("email should be the only parameter".equals(response.get("error").asText()));
Assert.assertTrue(response.get("status").asInt() == HttpStatus.BAD_GATEWAY.value());
}
@Test
public void returnsFalseForSyntacticallyInvalidEmail() throws Exception {
final HttpUrl url = HttpUrl.parse("http://localhost:" + this.port + "/email").newBuilder()
.addQueryParameter("email", "hd1").build();
final Request request = new Request.Builder().url(url).build();
final JsonNode response = EmailTests.mapper
.readTree(EmailTests.client.newCall(request).execute().body().bytes());
Assert.assertFalse(response.get("isValid").asBoolean());
}
@Test
public void returnsTrueForSyntacticallyValidEmail() throws Exception {
final HttpUrl url = HttpUrl.parse("http://localhost:" + this.port + "/email").newBuilder()
.addQueryParameter("email", "hd1@jsc.d8u.us").build();
final Request request = new Request.Builder().url(url).build();
final JsonNode response = EmailTests.mapper
.readTree(EmailTests.client.newCall(request).execute().body().bytes());
Assert.assertTrue(response.get("isValid").asBoolean());
}
}
package us.d8u.balance;
import java.io.IOException;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Base64;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.codehaus.plexus.util.StringUtils;
import org.joda.time.DateTime;
import org.joda.time.format.ISODateTimeFormat;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
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 com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.common.collect.Maps;
import com.google.common.collect.Sets;
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 EndpointTests {
private static final OkHttpClient client = new OkHttpClient();
@LocalServerPort
private int port;
public void getCreditLetsAccountBeUpdated() {
final String auth = "aaf5ba98-78a3-44a2-8370-7347052aa6cb:6017a423-6728-4e60-83b7-34b807d304fe";
final String authHeaderValue = new String(Base64.getEncoder().encode(("Bearer " + auth).getBytes()));
final DateTime dt = new DateTime().withDayOfMonth(1).withYear(2000).withMonthOfYear(1);
final 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");
final HttpUrl.Builder urlBuilder = new HttpUrl.Builder().scheme("http").host("localhost").port(this.port)
.addPathSegment("credit");
for (final String key : params.keySet()) {
urlBuilder.addQueryParameter(key, params.get(key));
}
final Request request = new Request.Builder().url(urlBuilder.build())
.addHeader("Authorization", authHeaderValue).build();
Response response = null;
try {
response = EndpointTests.client.newCall(request).execute();
} catch (final IOException 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 (final IOException 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 nonexistentUserReturnsNotFoundAndSentinelAmountForBalance() {
final Request request = new Request.Builder().url(new HttpUrl.Builder().host("localhost").port(this.port)
.scheme("http").addPathSegment("bal").addQueryParameter("user", "a@mailinator.com").build()).get()
.build();
Response res = null;
try {
res = EndpointTests.client.newCall(request).execute();
} catch (final IOException e) {
}
Map<String, BigDecimal> response = null;
try {
response = new ObjectMapper().readValue(res.body().string(), new TypeReference<Map<String, BigDecimal>>() {
});
} catch (final IOException e) {
}
final List<String> keys = new ArrayList<>(response.keySet());
Assert.assertTrue(keys.get(0).endsWith("not found"));
Assert.assertEquals("-999", response.get("a@mailinator.com not found").toPlainString());
Assert.assertEquals(HttpStatus.INTERNAL_SERVER_ERROR.value(), res.code());
}
@Test
public void routesAreTranslatedCorrectly() throws Exception {
final HttpUrl endpoint = HttpUrl.parse("http://localhost:" + this.port + "/underscores2dashes");
final Map<String, String> body = Maps.newHashMap();
body.put("inComing", "resources \"something_with_multiple_words\"");
final Request endpointRequest = new Request.Builder().post(
RequestBody.create(new ObjectMapper().writeValueAsString(body), MediaType.parse("application/json")))
.url(endpoint).build();
final Response endpointResponse = EndpointTests.client.newCall(endpointRequest).execute();
final Map<String, String> response = new ObjectMapper().readValue(endpointResponse.body().bytes(),
new TypeReference<Map<String, String>>() {
});
Assert.assertEquals("Unexpected or missing keys", Sets.newHashSet("result"), response.keySet());
Assert.assertEquals("resources \"something-with-multiple-words\"", response.get("translated"));
}
@Test
public void sdrReturnsCorrectFormat() throws Exception {
final HttpUrl requestUrl = new HttpUrl.Builder().host("localhost").scheme("http").port(this.port)
.addPathSegments("sdr").build();
final Request request = new Request.Builder().url(requestUrl).get().build();
final Response rawResponse = EndpointTests.client.newCall(request).execute();
final Map<String, String> response = new ObjectMapper().readValue(rawResponse.body().string(),
new TypeReference<Map<String, String>>() {
});
for (final Map.Entry<String, String> item : response.entrySet()) {
final String k = item.getKey();
Assert.assertEquals(k, StringUtils.capitalise(k));
final String v = item.getValue();
Assert.assertTrue(v.matches("^[0-9.,]+$"));
}
}
}
package us.d8u.balance;
import java.util.Map;
import org.apache.commons.lang3.math.NumberUtils;
import org.joda.time.DateTime;
import org.joda.time.format.DateTimeFormatter;
import org.joda.time.format.ISODateTimeFormat;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
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.test.context.junit4.SpringRunner;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.common.collect.Sets;
import okhttp3.HttpUrl;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT)
public class EpochTests {
private static final OkHttpClient client = new OkHttpClient();
private final ObjectMapper mapper = new ObjectMapper();
@LocalServerPort
private int port;
@Test
public void defaultIsNow() throws Exception {
final HttpUrl location = HttpUrl.parse("http://localhost/epoch").newBuilder().port(this.port).build();
final JsonNode response = this.mapper.readTree(
EpochTests.client.newCall(new Request.Builder().url(location).build()).execute().body().bytes());
Assert.assertTrue(response.get("epoch").asLong() <= System.currentTimeMillis());
Assert.assertTrue(ISODateTimeFormat.dateTimeNoMillis().parseDateTime(response.get("iso8601").asText()) != null);
}
@Test
public void epochIsNotIso() throws Exception {
final HttpUrl location = HttpUrl.parse("http://localhost/epoch").newBuilder().port(this.port)
.addQueryParameter("time", "nowIsTheTime forAllGoodMen 2 comeToTheAidOfTheirParty").build();
final JsonNode response = this.mapper.readTree(
EpochTests.client.newCall(new Request.Builder().url(location).build()).execute().body().bytes());
Assert.assertTrue(response.get("status").asText().equals(Integer.toString(400)));
Assert.assertTrue("Unable to parse".equals(response.get("error").asText()));
}
@Test
public void epochWorksWithIsoStrings() throws Exception {
final DateTimeFormatter dtf = ISODateTimeFormat.dateTimeNoMillis();
final DateTime dt = dtf.parseDateTime("2021-03-09T14:28:08-08:00");
final Long input = dt.getMillis() / 1000;
final Request request = new Request.Builder().url(HttpUrl.parse("http://localhost/epoch").newBuilder()
.port(this.port).addQueryParameter("time", Long.toString(input)).build()).build();
final Response response = EpochTests.client.newCall(request).execute();
final Map<String, String> resp = new ObjectMapper().readValue(response.body().string(),
new TypeReference<Map<String, String>>() {
});
Assert.assertEquals(Sets.newHashSet("epoch", "iso8601"), resp.keySet());
Assert.assertTrue(resp.get("epoch") + " is not numeric", NumberUtils.isParsable(resp.get("epoch")));
Assert.assertTrue(resp.get("epoch") + " is not correct, should be " + input,
Integer.valueOf(resp.get("epoch")).equals(1615328888));
Assert.assertTrue(resp.get("iso8601") + " not correct for " + resp.get("epoch") + "!",
"1970-01-19T08:42:08-08:00".equals(resp.get("iso8601")));
}
@Test
public void epochWorksWithNumbers() throws Exception {
final Integer l = 1610182324;
final Request request = new Request.Builder().url(HttpUrl.parse("http://localhost/epoch").newBuilder()
.port(this.port).addQueryParameter("time", Integer.toString(l)).build()).build();
final Response response = EpochTests.client.newCall(request).execute();
final Map<String, String> resp = new ObjectMapper().readValue(response.body().string(),
new TypeReference<Map<String, String>>() {
});
Assert.assertEquals(Sets.newHashSet("epoch", "iso8601"), resp.keySet());
Assert.assertTrue(
NumberUtils.isParsable(resp.get("epoch")) && resp.get("epoch").equalsIgnoreCase(Integer.toString(l)));
Assert.assertTrue(null != ISODateTimeFormat.dateTimeNoMillis().parseDateTime(resp.get("iso8601")));
}
@Test
public void nonDefault() throws Exception {
final HttpUrl location = HttpUrl.parse("http://localhost/epoch").newBuilder().port(this.port)
.addQueryParameter("time", "1969-12-31T16:00:00.000-08:00").build();
final JsonNode response = this.mapper.readTree(
EpochTests.client.newCall(new Request.Builder().url(location).build()).execute().body().bytes());
Assert.assertTrue(response.get("epoch").asInt() == 0);
}
}
package us.d8u.balance;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.junit.Assert;
import org.junit.BeforeClass;
import org.junit.Test;
import org.junit.runner.RunWith;
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.test.context.junit4.SpringRunner;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import okhttp3.HttpUrl;
import okhttp3.OkHttpClient;
import okhttp3.Request;
@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT)
public class ExcelTests {
private static final OkHttpClient client = new OkHttpClient();
private static final ObjectMapper mapper = new ObjectMapper();
static File temporary = null;
@LocalServerPort
private int port;
@Test
public void responseCorrect() throws Exception {
final String URL = "https://github.com/apache/poi/raw/trunk/test-data/spreadsheet/15375.xls";
final JsonNode response = ExcelTests.mapper
.readTree(ExcelTests.client
.newCall(new Request.Builder().url(HttpUrl.parse("http://localhost/word").newBuilder()
.port(this.port).addEncodedQueryParameter("url", URL).build()).build())
.execute().body().byteStream());
Assert.assertTrue(response.get("text").isContainerNode());
for (final JsonNode cell : response.get("text")) {
Assert.assertTrue(cell.isContainerNode());
}
Assert.assertTrue("36".equals(response.get("text").get("Java Books").get("1").get("2").asText()));
}
@BeforeClass
public void seedData() throws Exception {
try {
ExcelTests.temporary = File.createTempFile("units", ".xls");
ExcelTests.temporary.deleteOnExit();
} catch (final IOException exc1) {
}
final Object[][] bookData = { { "Head First Java", "Kathy Serria", 79 },
{ "Effective Java", "Joshua Bloch", 36 }, { "Clean Code", "Robert martin", 42 },
{ "Thinking in Java", "Bruce Eckel", 35 }, };
final XSSFWorkbook workbook = new XSSFWorkbook();
final XSSFSheet sheet = workbook.createSheet("Java Books");
int rowCount = 0;
for (final Object[] aBook : bookData) {
int columnCount = 0;
rowCount++;
final Row row = sheet.createRow(rowCount);
for (final Object field : aBook) {
columnCount++;
final Cell cell = row.createCell(columnCount);
if (field instanceof String) {
cell.setCellValue((String) field);
} else if (field instanceof Integer) {
cell.setCellValue((Integer) field);
}
}
}
try (FileOutputStream fos = new FileOutputStream("src/test/resources/" + ExcelTests.temporary.getName())) {
workbook.write(fos);
workbook.close();
} catch (final FileNotFoundException exc1) {
}
}
}
package us.d8u.balance;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
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.test.context.junit4.SpringRunner;
import okhttp3.HttpUrl;
import okhttp3.OkHttpClient;
import okhttp3.Request;
@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT)
public class FamilyTests {
private static final OkHttpClient client = new OkHttpClient();
private static final HttpUrl underTest = HttpUrl.parse("http://localhost/family");
@LocalServerPort
private int port;
@Test
public void logsProperly() throws Exception {
final HttpUrl telegramLoggingUrl = FamilyTests.underTest.newBuilder().port(this.port)
.addQueryParameter("src", "unitsTest").build();
final int originalLength = Controller.seenMsgs.size();
FamilyTests.client.newCall(new Request.Builder().url(telegramLoggingUrl).build()).execute();
Assert.assertTrue("not added to log", originalLength < Controller.seenMsgs.size());
}
@Test
public void redirectsProperly() throws Exception {
final OkHttpClient client1 = FamilyTests.client.newBuilder().addNetworkInterceptor(arg0 -> {
final Request request = arg0.request();
Assert.assertTrue("https://hd1.smugmug.com/Family/Diwans/".equals(request.header("location")));
return arg0.proceed(request);
}).build();
client1.newCall(new Request.Builder().url(FamilyTests.underTest.newBuilder().port(this.port).build()).build())
.execute();
}
}
package us.d8u.balance;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
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.test.context.junit4.SpringRunner;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import okhttp3.HttpUrl;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT)
public class FavIconTests {
private static final OkHttpClient client = new OkHttpClient();
@LocalServerPort
private int port;
ObjectMapper mapper = new ObjectMapper();
@Test
public void faviconIsNot404() throws Exception {
final HttpUrl endpoint = HttpUrl.parse("http://localhost:" + this.port + "/favicon.ico");
final Request request = new Request.Builder().url(endpoint).build();
final Response response = FavIconTests.client.newCall(request).execute();
Assert.assertEquals(200, response.code());
}
@Test
public void faviconReturnsCustomStatus() throws Exception {
final HttpUrl endpoint = new HttpUrl.Builder().scheme("http").host("localhost").port(this.port)
.addPathSegment("favicon.ico").addQueryParameter("code", "404").build();
final Request request = new Request.Builder().url(endpoint).build();
final JsonNode response = this.mapper
.readTree(FavIconTests.client.newCall(request).execute().body().byteStream());
Assert.assertEquals(404, response.get("code"));
}
}
package us.d8u.balance;
import java.text.NumberFormat;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
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.test.context.junit4.SpringRunner;
import okhttp3.HttpUrl;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT)
public class FeltTests {
private static final OkHttpClient client = new OkHttpClient();
@LocalServerPort
private int port;
@Test
public void withFeltParameterRetrievesAPositiveNumberOfQuakesOrZero() throws Exception {
final HttpUrl url = HttpUrl.parse("http://localhost:" + port + "/quake").newBuilder()
.addQueryParameter("felt", "1").build();
final Response rawResponse = client.newCall(new Request.Builder().url(url).build()).execute();
final NumberFormat fmt = NumberFormat.getIntegerInstance();
final String headerValue = rawResponse.header("X-Count");
Assert.assertTrue(fmt.parse(headerValue).intValue() > -1);
}
public void doesNotAllowDuplicates() throws Exception {
final HttpUrl url = HttpUrl.parse("http://localhost:" + port + "/quake").newBuilder()
.addQueryParameter("felt", "1").build();
Response rawResponse = client.newCall(new Request.Builder().url(url).build()).execute();
rawResponse = client.newCall(new Request.Builder().url(url).build()).execute();
final NumberFormat fmt = NumberFormat.getIntegerInstance();
Assert.assertTrue(fmt.parse(rawResponse.header("X-Count")).intValue() == 0);
}
}
package us.d8u.balance;
import static org.mockito.BDDMockito.given;
import static org.mockito.BDDMockito.then;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.multipart;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.header;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.mock.mockito.MockBean;
import org.springframework.mock.web.MockMultipartFile;
import org.springframework.test.web.servlet.MockMvc;
@AutoConfigureMockMvc
@SpringBootTest
public class FileUploadTests {
@Autowired
private MockMvc mvc;
@MockBean
private StorageService storageService;
@Test
public void shouldSaveUploadedFile() throws Exception {
final MockMultipartFile multipartFile = new MockMultipartFile("file",
"secring" + System.currentTimeMillis() + ".pgp", "application/pgp-keys", "Spring Framework".getBytes());
this.mvc.perform(multipart("/").file(multipartFile)).andExpect(status().isFound())
.andExpect(header().string("Location", "/"));
then(this.storageService).should().store(multipartFile);
}
@Test
public void should404WhenMissingFile() throws Exception {
given(this.storageService.loadAsResource("test.txt")).willThrow(Exception.class);
this.mvc.perform(get("/files/secring" + System.nanoTime() + ".pgp")).andExpect(status().isNotFound());
}
}
package us.d8u.balance;
import java.util.function.Consumer;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
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.test.context.junit4.SpringRunner;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ArrayNode;
import com.fasterxml.jackson.databind.node.ObjectNode;
import com.google.common.base.Splitter;
import okhttp3.HttpUrl;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT)
public class FitTests {
private static final OkHttpClient client = new OkHttpClient();
private static ObjectMapper mapper = new ObjectMapper();
@LocalServerPort
private int port;
@Test
public void customDegree() throws Exception {
final ObjectNode body = FitTests.mapper.createObjectNode();
final ArrayNode data = FitTests.mapper.createArrayNode();
final Consumer<String> foreachBody = t -> data.add(Double.parseDouble(t));
Splitter.on(",").trimResults().split("1,1,1,1,1").forEach(foreachBody);
body.set("data", data);
body.put("degree", 2);
final String json = FitTests.mapper.writeValueAsString(body);
final HttpUrl underTest = HttpUrl.parse("http://localhost/fit").newBuilder().port(this.port).build();
final Request underTestRequest = new Request.Builder().url(underTest)
.post(RequestBody.create(json, MediaType.parse("application/json"))).build();
final JsonNode response = FitTests.mapper
.readTree(FitTests.client.newCall(underTestRequest).execute().body().byteStream());
Assert.assertTrue(response.get("degree").asInt() == 2);
}
@Test
public void missingData() throws Exception {
final HttpUrl underTest = HttpUrl.parse("http://localhost/fit").newBuilder().port(this.port).build();
final Request underTestRequest = new Request.Builder().url(underTest)
.post(RequestBody.create("a", MediaType.parse("application/json"))).build();
final JsonNode response = FitTests.mapper
.readTree(FitTests.client.newCall(underTestRequest).execute().body().byteStream());
Assert.assertTrue("data missing", "need data".equals(response.get("status").asText()));
}
@Test
public void workingFit() throws Exception {
final ObjectNode body = FitTests.mapper.createObjectNode();
final ArrayNode data = FitTests.mapper.createArrayNode();
final Consumer<String> foreachBody = t -> data.add(Double.parseDouble(t));
Splitter.on(",").trimResults().split("1,1,1,1,1").forEach(foreachBody);
body.set("data", data);
final String json = FitTests.mapper.writeValueAsString(body);
final HttpUrl underTest = HttpUrl.parse("http://localhost/fit").newBuilder().port(this.port).build();
final Request underTestRequest = new Request.Builder().url(underTest)
.post(RequestBody.create(json, MediaType.parse("application/json"))).build();
final JsonNode response = FitTests.mapper
.readTree(FitTests.client.newCall(underTestRequest).execute().body().byteStream());
Assert.assertTrue("polynomial missing", response.has("polynomial"));
Assert.assertTrue("polynomial missing coefficients", response.get("polynomial").has("coefficients"));
final JsonNode polynomial = response.get("polynomial");
for (int i = 0; i != (polynomial.size() - 1); i++) {
final Double n = polynomial.get(i).asDouble();
Assert.assertTrue("polynomial coefficient " + n + " not numeric", !(n instanceof Double));
}
}
@Test
public void workingFitCustomSeparatorAndInvalidData() throws Exception {
final ObjectNode body = FitTests.mapper.createObjectNode();
final ArrayNode data = FitTests.mapper.createArrayNode();
final Consumer<String> foreachBody = t -> data.add(t);
Splitter.on(";").trimResults().split("1;a;1;1;1").forEach(foreachBody);
body.set("data", data);
body.put("separator", ";");
final String json = FitTests.mapper.writeValueAsString(body);
final HttpUrl underTest = HttpUrl.parse("http://localhost/fit").newBuilder().port(this.port).build();
final Request underTestRequest = new Request.Builder().url(underTest)
.post(RequestBody.create(json, MediaType.parse("application/json"))).build();
final JsonNode response = FitTests.mapper
.readTree(FitTests.client.newCall(underTestRequest).execute().body().byteStream());
Assert.assertTrue("warning not found", response.has("warning"));
Assert.assertTrue("invalid incorrect", "[\"a\"]".equals(response.get("invalid").asText()));
Assert.assertTrue("dropped size wrong", response.get("dropped").asInt() == response.get("invalid").size());
}
}
package us.d8u.balance;
import org.joda.time.DateTime;
import org.joda.time.format.ISODateTimeFormat;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
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.test.context.junit4.SpringRunner;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ObjectNode;
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 FlightCheckTests {
private static final OkHttpClient client = new OkHttpClient.Builder().followRedirects(false).build();
private static final ObjectMapper mapper = new ObjectMapper();
@LocalServerPort
private int port;
@Test
public void properRequest() throws Exception {
final ObjectNode expected = FlightCheckTests.mapper.createObjectNode();
expected.put("flight", "WN 1803");
final DateTime arrivalTime = DateTime.now().withHourOfDay(12).withMinuteOfHour(45);
final DateTime departureTime = arrivalTime.withMinuteOfHour(15);
if (DateTime.now().isBefore(arrivalTime)) {
expected.put("scheduledDdeparture", ISODateTimeFormat.dateTimeNoMillis().print(departureTime));
expected.put("scheduledArrival", ISODateTimeFormat.dateTimeNoMillis().print(arrivalTime));
} else {
expected.put("scheduledDeparture", ISODateTimeFormat.dateTimeNoMillis().print(departureTime.plusDays(1)));
expected.put("scheduledArrival", ISODateTimeFormat.dateTimeNoMillis().print(arrivalTime.plusDays(1)));
}
expected.put("departureAirport", "PHX");
expected.put("arrivalAirport", "LAX");
expected.put("departureTerminal", "4");
expected.put("departureGate", "C4");
expected.put("arrivalTerminal", "1");
expected.put("arrivalGate", "14");
final String json = FlightCheckTests.mapper.writeValueAsString(expected);
final HttpUrl url = HttpUrl.parse("http://localhost/flight/check").newBuilder().port(this.port).build();
final Response response = FlightCheckTests.client.newCall(new Request.Builder()
.post(RequestBody.create(json, MediaType.parse("application/json"))).url(url).build()).execute();
Assert.assertTrue(FlightCheckTests.mapper.readTree(response.body().string()).equals(expected));
}
}
package us.d8u.balance;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
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.test.context.junit4.SpringRunner;
import okhttp3.HttpUrl;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT)
public class FlightTests {
private static final OkHttpClient client = new OkHttpClient.Builder().followRedirects(false).build();
@LocalServerPort
private int port;
@Test
public void isCaseInsensitive() throws Exception {
final HttpUrl url = HttpUrl.parse("http://localhost/flight/swa678").newBuilder().port(this.port).build();
final Response response = FlightTests.client.newCall(new Request.Builder().url(url).build()).execute();
Assert.assertTrue("https://flightaware.com/live/flight/SWA678".equals(response.header("Location")));
}
@Test
public void redirectWithValidFlightWorks() throws Exception {
final HttpUrl url = HttpUrl.parse("http://localhost/flight/SWA678").newBuilder().port(this.port).build();
final Response response = FlightTests.client.newCall(new Request.Builder().url(url).build()).execute();
Assert.assertTrue("https://flightaware.com/live/flight/SWA678".equals(response.header("Location")));
}
}
package us.d8u.balance;
import java.text.NumberFormat;
import java.text.ParseException;
import java.util.HashMap;
import java.util.Map;
import org.joda.time.format.DateTimeFormatter;
import org.joda.time.format.ISODateTimeFormat;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
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.test.context.junit4.SpringRunner;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import okhttp3.HttpUrl;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT)
public class FredTests {
private static final OkHttpClient client = new OkHttpClient();
@LocalServerPort
private int port;
@Test
public void fredGetsSeries() throws Exception {
final HttpUrl testUrl = new HttpUrl.Builder().scheme("http").host("localhost").port(this.port)
.addPathSegment("fred").addQueryParameter("lookup", "false").addQueryParameter("series", "DEXUSUK")
.build();
final Request request = new Request.Builder().url(testUrl).build();
final Response response = FredTests.client.newCall(request).execute();
Assert.assertTrue(response.isSuccessful());
final Map<String, Map<String, String>> actual = new ObjectMapper().readValue(response.body().string(),
new TypeReference<Map<String, Map<String, String>>>() {
});
final Map<String, String> series = actual.get("series");
final DateTimeFormatter keyFormat = ISODateTimeFormat.dateParser();
for (final String date : series.keySet()) {
try {
keyFormat.parseDateTime(date);
} catch (final Exception e) {
Assert.fail(date + " failed to parse as a date");
}
try {
NumberFormat.getInstance().parse(series.get(date));
} catch (final ParseException e) {
Assert.fail("<" + date + ", " + series.get(date) + "> failed to parse as a number");
}
}
}
@Test
public void fredReturnsNonemptyForCanada() throws Exception {
final 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");
final HttpUrl testUrl = new HttpUrl.Builder().scheme("http").host("localhost").port(this.port)
.addPathSegment("fred").addQueryParameter("lookup", "true").addQueryParameter("series", "canada")
.build();
final Request request = new Request.Builder().url(testUrl).build();
final Response response = FredTests.client.newCall(request).execute();
Assert.assertTrue(response.isSuccessful());
final Map<String, Map<String, String>> actual = new ObjectMapper().readValue(response.body().string(),
new TypeReference<Map<String, Map<String, String>>>() {
});
for (final String result : results.keySet()) {
if (!actual.get("lookup").containsKey(result)) {
Assert.fail(result + " missing from " + results.keySet());
}
}
}
}
package us.d8u.balance;
import java.text.NumberFormat;
import java.text.ParseException;
import java.time.LocalDate;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import java.util.TreeMap;
import org.joda.time.DateTime;
import org.joda.time.format.ISODateTimeFormat;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
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 com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.common.collect.Sets;
import okhttp3.HttpUrl;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT)
public class FxTests {
private static final OkHttpClient client = new OkHttpClient();
@LocalServerPort
private int port;
public void fxCrpytoPrintsAmountAndNoRateIfAmountSpecified() throws Exception {
final HttpUrl endpoint = new HttpUrl.Builder().scheme("http").host("localhost").port(this.port)
.addPathSegment("fxCrypto").addPathSegment("xmr").addPathSegment("usd")
.addQueryParameter("amount", "15").build();
final Request request = new Request.Builder().url(endpoint).build();
final Response response = FxTests.client.newCall(request).execute();
Assert.assertTrue(response.isSuccessful());
final Map<String, String> actual = new ObjectMapper().readValue(response.body().string(),
new TypeReference<Map<String, String>>() {
});
final Set<String> expectedKeys = Sets.newHashSet("request", "requestTime", "amount", "time");
Assert.assertEquals(expectedKeys, actual.keySet());
Assert.assertEquals("XMR => USD", actual.get("request"));
Assert.assertTrue(actual.get("time").replace(" ms", "").matches("^[0-9.]+$"));
Assert.assertTrue("1".equals(actual.get("amountIn")));
Assert.assertTrue(actual.get("amount").matches("^[0-9.,]+$"));
}
public void fxCryptoPrintsAmountAndNoRateFor1CryptoIfNoAmountSpecified() throws Exception {
final HttpUrl endpoint = new HttpUrl.Builder().scheme("http").host("localhost").port(this.port)
.addPathSegment("fxCrypto").addPathSegment("xmr").addPathSegment("usd").build();
final Request request = new Request.Builder().url(endpoint).build();
final Response response = FxTests.client.newCall(request).execute();
Assert.assertTrue(response.isSuccessful());
final Map<String, String> actual = new ObjectMapper().readValue(response.body().string(),
new TypeReference<Map<String, String>>() {
});
final Set<String> expectedKeys = Sets.newHashSet("request", "requestTime", "amount", "time");
Assert.assertEquals(expectedKeys, actual.keySet());
Assert.assertEquals("XMR => USD", actual.get("request"));
Assert.assertTrue(actual.get("time").replace(" ms", "").matches("^[0-9.]+$"));
Assert.assertTrue(actual.get("amount").matches("^[0-9.,]+$"));
}
@Test
public void fxHasDatesAndRequestsUnlessAmountSpecified() throws Exception {
final HttpUrl endpoint = new HttpUrl.Builder().scheme("http").host("localhost").port(this.port)
.addPathSegment("fx").addPathSegment("gbp").addPathSegment("usd").build();
final Request request = new Request.Builder().url(endpoint).build();
final Response response = FxTests.client.newCall(request).execute();
Assert.assertTrue(response.isSuccessful());
final Map<String, String> actual = new ObjectMapper().readValue(response.body().string(),
new TypeReference<Map<String, String>>() {
});
Assert.assertTrue(actual.containsKey("requestTime"));
Assert.assertTrue(actual.containsKey("time"));
Assert.assertTrue(actual.get("time").replace(" ms", "").matches("^[0-9]+$"));
Assert.assertEquals("GBP => USD", actual.get("request"));
actual.remove("request");
actual.remove("time");
for (final String k : actual.keySet()) {
try {
LocalDate.parse(k);
} catch (final IllegalArgumentException e) {
Assert.fail(k + " is not a date");
}
try {
NumberFormat.getNumberInstance().parse(actual.get(k));
} catch (final ParseException e) {
Assert.fail("<" + k + ", " + actual.get(k) + "> is not a number");
}
}
}
@Test
public void fxPrintsAmountAndNoRateIfAmountSpecified() throws Exception {
final HttpUrl endpoint = new HttpUrl.Builder().scheme("http").host("localhost").port(this.port)
.addPathSegment("fx").addPathSegment("gbp").addPathSegment("usd").addQueryParameter("amount", "2")
.build();
final Request request = new Request.Builder().url(endpoint).build();
final Response response = FxTests.client.newCall(request).execute();
Assert.assertTrue(response.isSuccessful());
final Map<String, String> actual = new ObjectMapper().readValue(response.body().string(),
new TypeReference<Map<String, String>>() {
});
final Set<String> expectedKeys = Sets.newHashSet("request", "amount", "time");
Assert.assertEquals(expectedKeys, actual.keySet());
Assert.assertEquals("GBP => USD", actual.get("request"));
Assert.assertTrue(actual.get("time").replace(" ms", "").matches("^[0-9.]+$"));
Assert.assertTrue(actual.get("amount").matches("^[0-9.,]+$"));
}
@Test
public void fxReturnsErrorForNotFoundSymbols() throws Exception {
HttpUrl endpoint = new HttpUrl.Builder().scheme("http").host("localhost").port(this.port).addPathSegment("fx")
.addPathSegment("GBPX").addPathSegment("usd").build();
Request request = new Request.Builder().url(endpoint).build();
Response response = FxTests.client.newCall(request).execute();
Assert.assertTrue(response.isSuccessful());
final Map<String, String> actual = new ObjectMapper().readValue(response.body().string(),
new TypeReference<Map<String, String>>() {
});
Assert.assertTrue("Unknown Symbol GBPX".equals(actual.get("error")));
Assert.assertTrue(actual.get("status").equals(Integer.toString(HttpStatus.BAD_REQUEST.value())));
endpoint = new HttpUrl.Builder().scheme("http").host("localhost").port(this.port).addPathSegment("fx")
.addPathSegment("gbp").addPathSegment("USDX").build();
request = new Request.Builder().url(endpoint).build();
response = FxTests.client.newCall(request).execute();
Assert.assertTrue("Unknown Symbol USDX".equals(actual.get("error")));
Assert.assertTrue(actual.get("status").equals(Integer.toString(HttpStatus.BAD_REQUEST.value())));
}
@Test
public void fxReturnsSortedHistory() throws Exception {
final HttpUrl endpoint = new HttpUrl.Builder().scheme("http").host("localhost").port(this.port)
.addPathSegment("fx").addPathSegment("USD").addPathSegment("GBP").build();
final Request request = new Request.Builder().url(endpoint).build();
final Response response = FxTests.client.newCall(request).execute();
Assert.assertTrue(response.isSuccessful());
final Map<String, Map<String, String>> actual = new ObjectMapper().readValue(response.body().string(),
new TypeReference<Map<String, Map<String, String>>>() {
});
final Iterator<String> sortCheckIterator = new TreeMap<>(actual.get("history")).keySet().iterator();
while (sortCheckIterator.hasNext()) {
final String historyLine = sortCheckIterator.next();
final String historyLine2 = sortCheckIterator.next();
final DateTime history1 = ISODateTimeFormat.date().parseDateTime(historyLine);
final DateTime history2 = ISODateTimeFormat.date().parseDateTime(historyLine2);
Assert.assertTrue(history1.isAfter(history2));
}
}
}
package us.d8u.balance;
import java.io.Serializable;
import java.util.HashMap;
import java.util.Map;
import java.util.TreeMap;
import org.apache.commons.lang3.StringUtils;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
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 com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.common.collect.Sets;
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 GeocoderTests {
private static final OkHttpClient client = new OkHttpClient();
@LocalServerPort
private Integer port;
@Test
public void emptyParams() throws Exception {
final Request request = new Request.Builder().url(new HttpUrl.Builder().scheme("http").host("localhost")
.port(this.port).addPathSegment("geocode").build()).build();
final Response resp = GeocoderTests.client.newCall(request).execute();
final String rawResponse = resp.body().string();
final JsonNode actual = new ObjectMapper().readTree(rawResponse);
Assert.assertTrue("Unexpected status -- " + HttpStatus.valueOf(actual.get("status").asInt()),
actual.get("status").asInt() == HttpStatus.BAD_REQUEST.value());
}
@Test
public void forwardGeocodeWorks() throws Exception {
final Map<String, Serializable> parts = new HashMap<>();
final Map<String, String> params = new HashMap<>();
params.put("latitude", "41.3813934");
params.put("longitude", "2.1730637");
parts.putAll(params);
final RequestBody body = RequestBody.create(new ObjectMapper().writeValueAsString(params),
MediaType.parse("application/json"));
final Request request = new Request.Builder().url(new HttpUrl.Builder().scheme("http").host("localhost")
.port(this.port).addPathSegment("geocode").build()).post(body).build();
final Response resp = GeocoderTests.client.newCall(request).execute();
final String rawResponse = resp.body().string();
final Map<String, String> actual = new ObjectMapper().readValue(rawResponse,
new TypeReference<Map<String, String>>() {
});
Assert.assertTrue("Time is not numeric", StringUtils.isNumeric(actual.get("time")));
actual.remove("time");
actual.remove("location");
Assert.assertEquals(Controller.mapper.writeValueAsString(parts) + " does not equal "
+ Controller.mapper.writeValueAsString(actual), parts, actual);
}
@Test
public void reverseGeocodeWorks() throws Exception {
final TreeMap<String, String> expected = new TreeMap<>();
expected.put("location",
"Emerging Market Services, 2017, North Beverly Glen Boulevard, Beverly Glen, Beverly Crest, Los Angeles, Los Angeles County, California, 90077, United States");
final String paramsJson = "{\"latitude\": \"34.1056855\", \"longitude\": \"-118.446178\"}";
final RequestBody body = RequestBody.create(paramsJson, MediaType.parse("application/json"));
final HttpUrl requestingUrl = new HttpUrl.Builder().scheme("http").host("localhost").port(this.port)
.addPathSegment("geocode").build();
final Request request = new Request.Builder().url(requestingUrl).post(body).build();
final Response rawResponse = GeocoderTests.client.newCall(request).execute();
final Map<String, String> actual = new ObjectMapper().readValue(rawResponse.body().string(),
new TypeReference<Map<String, String>>() {
});
Assert.assertTrue("Not able to resolve", actual.get("location").equals(expected.get("location")));
}
@Test
public void successfulLookup() throws Exception {
final String bodySrc = "20 Greenwood Cove, Tiburon, 94920";
final HttpUrl url = HttpUrl.parse("http://localhost:" + this.port + "/geocode").newBuilder()
.addQueryParameter("location", bodySrc).build();
final Request request = new Request.Builder().url(url).build();
final Response rawResponse = new OkHttpClient().newCall(request).execute();
final Map<String, String> response = new ObjectMapper().readValue(rawResponse.body().bytes(),
new TypeReference<Map<String, String>>() {
});
Assert.assertEquals(
"Missing key -- " + Sets.difference(Sets.newHashSet("location", "time", "latitude", "longitude"),
response.keySet()),
Sets.newHashSet("location", "time", "latitude", "longitude"), response.keySet());
Assert.assertEquals("Latitude incorrect", "37.8980403", response.get("latitude"));
Assert.assertEquals("Longitude incorrect", "-122.5001078", response.get("longitude"));
}
}
package us.d8u.balance;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Map;
import org.joda.time.DateTime;
import org.joda.time.format.ISODateTimeFormat;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
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.test.context.junit4.SpringRunner;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import okhttp3.HttpUrl;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT)
public class GithubTests {
private static final OkHttpClient client = new OkHttpClient();
@LocalServerPort
private int port;
@Test
public void github() throws Exception {
final HttpUrl testUrl = new HttpUrl.Builder().scheme("http").host("localhost").port(this.port)
.addPathSegment("github").addPathSegment("rails|rails").build();
final Request request = new Request.Builder().url(testUrl).build();
final Response response = GithubTests.client.newCall(request).execute();
final Map<String, String> actual = new ObjectMapper().readValue(response.body().string(),
new TypeReference<Map<String, String>>() {
});
for (final String k : actual.keySet()) {
final String value = actual.get(k);
final String[] parts = value.split(":- ");
final String permalink = parts[1];
final HttpUrl commitLink = HttpUrl.parse(permalink);
Assert.assertEquals("api.github.com", commitLink.host());
Assert.assertEquals("https", commitLink.scheme());
try {
final DateTime date = ISODateTimeFormat.dateTimeNoMillis().parseDateTime(k);
Assert.assertTrue(date.isBeforeNow());
Assert.assertTrue(date.isAfter(new DateTime().minusHours(24)));
} catch (final Exception e) {
Assert.fail(k + " is not a date");
}
}
}
@Test
public void githubNoCommits() throws Exception {
final HttpUrl testUrl = new HttpUrl.Builder().scheme("http").host("localhost").port(this.port)
.addPathSegment("github").addPathSegment("hasandiwan|zsh").build();
final Request request = new Request.Builder().url(testUrl).build();
final Response response = GithubTests.client.newCall(request).execute();
final 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 {
final HttpUrl testUrl = new HttpUrl.Builder().scheme("http").host("localhost").port(this.port)
.addPathSegment("github").addPathSegment("hasandiwan|units").addQueryParameter("date", "0").build();
final Request request = new Request.Builder().url(testUrl).build();
final Response response = GithubTests.client.newCall(request).execute();
final Map<String, String> actual = new ObjectMapper().readValue(response.body().string(),
new TypeReference<Map<String, String>>() {
});
for (final String messageAndLink : actual.values()) {
if (messageAndLink.toLowerCase().startsWith("initial commit")) {
Assert.assertTrue("initial message not found", true);
}
}
}
@Test
public void testGetSuccess() throws Exception {
final HttpURLConnection conn = (HttpURLConnection) new URL("http://localhost:" + this.port + "/github")
.openConnection();
conn.connect();
final String location = conn.getHeaderField("Location");
Assert.assertTrue("Location incorrect -- " + location, "https://github.com/hasandiwan".equals(location));
}
}
package us.d8u.balance;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
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 com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ArrayNode;
import okhttp3.HttpUrl;
import okhttp3.OkHttpClient;
import okhttp3.Request;
@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT)
public class GmailTests {
private static final OkHttpClient client = new OkHttpClient();
private static final ObjectMapper mapper = new ObjectMapper();
@LocalServerPort
private int port;
private HttpUrl underTest = HttpUrl.parse("http://localhost/gmail/summary");
@Test
public void cleanupTest() throws Exception {
this.underTest = this.underTest.newBuilder().removePathSegment(this.underTest.pathSegments().size() - 1)
.build();
final Request headRequest = new Request.Builder().url(this.underTest).head().build();
final okhttp3.Response headResponse = GmailTests.client.newCall(headRequest).execute();
Assert.assertTrue("Thread ID missing!", null != headResponse.header("X-Thread-Id"));
}
@Test
public void minimumKeysForValidUser() throws Exception {
this.underTest = this.underTest.newBuilder().addQueryParameter("user", "hasan.diwan@gmail.com")
.addQueryParameter("password", "appSpecificPasswordForJavaMail").build();
final JsonNode response = GmailTests.mapper.readTree(GmailTests.client
.newCall(new Request.Builder().header("user-agent", "mozilla").url(this.underTest).build()).execute()
.body().byteStream());
Assert.assertTrue("Status is not " + HttpStatus.BAD_REQUEST.value(),
response.get("status").asInt() == HttpStatus.BAD_REQUEST.value());
}
@Test
public void validResponse() throws Exception {
if (System.getProperties().containsKey("us.d8u.balance.password")) {
throw new RuntimeException("need us.d8u.balance.password set");
}
final String password = System.getProperty("us.d8u.balance.password");
this.underTest = this.underTest.newBuilder()
.addQueryParameter("user",
(String) System.getProperties().getOrDefault("user", "hasan.diwan@gmail.com"))
.addQueryParameter("password", password).addQueryParameter("testing", "true").build();
final JsonNode response = GmailTests.mapper.readTree(GmailTests.client
.newCall(new Request.Builder().header("user-agent", "mozilla").url(this.underTest).build()).execute()
.body().byteStream());
Assert.assertTrue("messages missing", response.get("messages").isArray());
final ArrayNode messages = (ArrayNode) response.get("messages");
for (int i = 0; i != messages.size(); i++) {
final JsonNode message = messages.get(i);
final String fromAddr = message.get("from").get(0).asText();
try {
InternetAddress.parse(fromAddr, false);
} catch (final AddressException e) {
Assert.fail("failed to parse " + fromAddr);
}
Assert.assertTrue("Subject missing", message.has("subject"));
Assert.assertTrue("Summary missing", message.has("summary"));
}
}
}
package us.d8u.balance;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
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 okhttp3.HttpUrl;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT)
public class GoTests {
private static final OkHttpClient client = new OkHttpClient();
@LocalServerPort
private int port;
@Test
public void linkWorks() throws Exception {
final HttpUrl url = HttpUrl.parse("http://localhost/go/96").newBuilder().port(this.port).build();
final Request request = new Request.Builder().url(url).build();
final Response response = GoTests.client.newBuilder().followRedirects(false).build().newCall(request).execute();
Assert.assertTrue("Link resolution incorrect",
"https://www.reddit.com/r/bestof/comments/wx8beq/uramsesthepigeon_writes_some_hilarious_bdsm/"
.equals(response.header("location")));
}
@Test
public void linkNotFoundReturns404() throws Exception {
final HttpUrl url = HttpUrl.parse("http://localhost/go/BARBIE").newBuilder().port(this.port).build();
final Request request = new Request.Builder().url(url).build();
final Response response = GoTests.client.newBuilder().followRedirects(false).build().newCall(request).execute();
Assert.assertTrue("Shortcut not found doesn't yield 404", HttpStatus.NOT_FOUND.value() == response.code());
}
}
package us.d8u.balance;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import org.apache.tomcat.util.http.fileupload.IOUtils;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
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.core.io.InputStreamResource;
import org.springframework.http.HttpStatus;
import org.springframework.test.context.junit4.SpringRunner;
import okhttp3.HttpUrl;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT)
public class GraphTransTests {
@LocalServerPort
private int port;
OkHttpClient client = new OkHttpClient.Builder().build();
@Test
public void withPngReturnsJpeg() throws Exception {
final HttpUrl remoteUpstreamUrl = HttpUrl.parse("https://hasan.d8u.us/me.png");
final HttpUrl remote = HttpUrl.parse("http://localhost/graphtrans").newBuilder().port(this.port)
.addEncodedQueryParameter("url", remoteUpstreamUrl.toString()).build();
final Response response = this.client.newCall(new Request.Builder().url(remote).build()).execute();
Assert.assertTrue(response.code() == HttpStatus.CREATED.value());
final InputStream bs = response.body().byteStream();
final InputStreamResource inputStreamResource = new InputStreamResource(bs);
final ByteArrayOutputStream baos = new ByteArrayOutputStream();
IOUtils.copy(inputStreamResource.getInputStream(), baos);
final byte[] remoteUpstreamResponse = this.client.newCall(new Request.Builder().url(remoteUpstreamUrl).build())
.execute().body().bytes();
Assert.assertTrue(remoteUpstreamResponse != bs.readAllBytes());
}
}
package us.d8u.balance;
import java.util.Properties;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
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 com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ObjectNode;
import com.google.common.base.Splitter;
import com.google.common.collect.Sets;
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 Hack4LaTests {
private static final OkHttpClient client = new OkHttpClient();
private static final ObjectMapper mapper = new ObjectMapper();
@LocalServerPort
private int port;
@Test
public void sendMail() throws Exception {
final HttpUrl url = HttpUrl.parse("http://localhost/Hack4a").newBuilder().port(this.port).build();
final ObjectNode body = Hack4LaTests.mapper.createObjectNode();
body.put("body", "hello world");
body.put("recipients", "hasan@mailinator.com, diwan@mailinator.com");
final RequestBody jsonBody = RequestBody.create(Hack4LaTests.mapper.writeValueAsBytes(body),
MediaType.parse("application/json"));
final Properties systemProperties = new Properties();
systemProperties.load(this.getClass().getResourceAsStream("/application.properties"));
final Request request = new Request.Builder()
.addHeader("X-Authentication", systemProperties.getProperty("hack4la.auth")).post(jsonBody).url(url)
.build();
final Response rawResponse = Hack4LaTests.client.newCall(request).execute();
Assert.assertTrue(rawResponse.code() == HttpStatus.CREATED.value());
final JsonNode response = Hack4LaTests.mapper.readTree(rawResponse.body().byteStream());
Assert.assertTrue(response.size() == 1);
Assert.assertTrue("hack4la@mailinator.com".equals(response.get(0).get("to").asText()));
for (int c = 0; c != Sets.newHashSet(Splitter.on(",").split(body.get("recipients").asText()).iterator())
.size(); c++) {
Assert.assertTrue(
"Missing " + Sets.newHashSet(Splitter.on(",").split(body.get("recipients").asText())).toArray()[c],
Sets.newHashSet(Splitter.on(",").split(body.get("recipients").asText()))
.contains(response.get(c).get("bcc").asText()));
}
Assert.assertTrue("body incorrect", response.get("body").asText().equals(body.get("body").asText()));
}
}
package us.d8u.balance;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
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.test.context.junit4.SpringRunner;
import okhttp3.HttpUrl;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT)
public class HappyTests {
private static final OkHttpClient client = new OkHttpClient();
@LocalServerPort
private int port;
@Test
public void redirectsProperly() throws Exception {
final HttpUrl url = HttpUrl.parse("http://localhost/happy").newBuilder().port(this.port).build();
final Request request = new Request.Builder().url(url).build();
final Response rawResponse = HappyTests.client.newBuilder().followRedirects(false).build().newCall(request)
.execute();
Assert.assertTrue("Location incorrect",
rawResponse.header("location").equals("https://hd1.bitbucket.io/Happy.pdf"));
}
}
package us.d8u.balance;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
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.test.context.junit4.SpringRunner;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ObjectNode;
import okhttp3.HttpUrl;
import okhttp3.OkHttpClient;
import okhttp3.Request;
@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT)
public class HashTests {
private static final OkHttpClient client = new OkHttpClient();
private static ObjectMapper mapper = new ObjectMapper();
@LocalServerPort
private int port;
@Test
public void matchesPython() throws Exception {
final String expectedHash = "5676aaa0944af96f1692febe7e3350614fa95a71fede632624cb546f";
final ObjectNode expectedResponse = HashTests.mapper.createObjectNode();
expectedResponse.put("hash", expectedHash);
final ObjectNode realResponse = (ObjectNode) HashTests.mapper.readTree(HashTests.client
.newCall(new Request.Builder().url(HttpUrl.parse("http://localhost/hash").newBuilder().port(this.port)
.addQueryParameter("string", "I love Lean Liam").build()).build())
.execute().body().byteStream());
realResponse.remove("time");
Assert.assertTrue("Wrong hash", realResponse.equals(expectedResponse));
}
@Test
public void timeIsPositive() throws Exception {
final JsonNode realResponse = HashTests.mapper.readTree(HashTests.client
.newCall(new Request.Builder().url(HttpUrl.parse("http:/localhost/hash").newBuilder().port(this.port)
.addQueryParameter("string", "I love Lean Liam").build()).build())
.execute().body().byteStream());
Assert.assertTrue("time is not positive", realResponse.get("time").asLong() > 0);
}
}
package us.d8u.balance;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
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 com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.common.collect.Sets;
import okhttp3.HttpUrl;
import okhttp3.OkHttpClient;
import okhttp3.Request;
@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT)
public class HNTests {
private static final OkHttpClient client = new OkHttpClient();
private static final ObjectMapper mapper = new ObjectMapper();
@LocalServerPort
private int port;
@Test
public void responseIsCorrect() throws Exception {
final HttpUrl underTest = HttpUrl.parse("http://localhost/hn").newBuilder().port(this.port).build();
final JsonNode response = HNTests.mapper.readTree(
HNTests.client.newCall(new Request.Builder().url(underTest).build()).execute().body().charStream());
Assert.assertTrue("Time is not a positive number", response.get("time").asDouble() > 0.0d);
Assert.assertTrue("status invalid", Sets.newHashSet(HttpStatus.FOUND.value(), HttpStatus.NOT_FOUND.value())
.contains(response.get("status").asInt()));
}
}
package us.d8u.balance;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
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 com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import okhttp3.HttpUrl;
import okhttp3.OkHttpClient;
import okhttp3.Request;
@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT)
public class HtmlTests {
private static OkHttpClient client = new OkHttpClient();
private static ObjectMapper mapper = new ObjectMapper();
@LocalServerPort
private int port;
@Test
public void properOutput() throws Exception {
HttpUrl url = HttpUrl.parse("http://localhost/html").newBuilder().port(port).addQueryParameter("url",
"https://www.nytimes.com/2023/01/15/opinion/ai-chatgpt-lobbying-democracy.html").build();
JsonNode response = mapper
.readTree(client.newCall(new Request.Builder().url(url).build()).execute().body().byteStream());
Assert.assertTrue("deprecated key not found in /html", response.has("deprecated"));
url = HttpUrl.parse("http://localhost/web").newBuilder().port(port).addQueryParameter("url",
"https://www.nytimes.com/2023/01/15/opinion/ai-chatgpt-lobbying-democracy.html").build();
response = mapper
.readTree(client.newCall(new Request.Builder().url(url).build()).execute().body().byteStream());
Assert.assertTrue("Incorrect text -- " + response.get("text").asText(), response.get("text").asText().equals(
"Launched just weeks ago, ChatGPT is already threatening to upend how we draft everyday communications like emails, college essays and myriad other forms of writing.\\nCreated by the company OpenAI, ChatGPT is a chatbot that can automatically respond to written prompts in a manner that is sometimes eerily close to human.\\nBut for all the consternation over the potential for humans to be replaced by machines in formats like poetry and sitcom scripts, a far greater threat looms: artificial intelligence replacing humans in the democratic processes — not through voting, but through lobbying.\\nChatGPT could automatically compose comments submitted in regulatory processes. It could write letters to the editor for publication in local newspapers. It could comment on news articles, blog entries and social media posts millions of times every day. It could mimic the work that the Russian Internet Research Agency did in its attempt to influence our 2016 elections, but without the agency’s reported multimillion-dollar budget and hundreds of employees.\\nAutomatically generated comments aren’t a new problem. For some time, we have struggled with bots, machines that automatically post content. Five years ago, at least a million automatically drafted comments were believed to have been submitted to the Federal Communications Commission regarding proposed regulations on net neutrality. In 2019, a Harvard undergraduate, as a test, used a text-generation program to submit 1,001 comments in response to a government request for public input on a Medicaid issue. Back then, submitting comments was just a game of overwhelming numbers.\\nPlatforms have gotten better at removing “coordinated inauthentic behavior.” Facebook, for example, has been removing over a billion fake accounts a year. But such messages are just the beginning. Rather than flooding legislators’ inboxes with supportive emails, or dominating the Capitol switchboard with synthetic voice calls, an A.I. system with the sophistication of ChatGPT but trained on relevant data could selectively target key legislators and influencers to identify the weakest points in the policymaking system and ruthlessly exploit them through direct communication, public relations campaigns, horse trading or other points of leverage.\\nWhen we humans do these things, we call it lobbying. Successful agents in this sphere pair precision message writing with smart targeting strategies. Right now, the only thing stopping a ChatGPT-equipped lobbyist from executing something resembling a rhetorical drone warfare campaign is a lack of precision targeting. A.I. could provide techniques for that as well.\\nA system that can understand political networks, if paired with the textual-generation capabilities of ChatGPT, could identify the member of Congress with the most leverage over a particular policy area — say, corporate taxation or military spending. Like human lobbyists, such a system could target undecided representatives sitting on committees controlling the policy of interest and then focus resources on members of the majority party when a bill moves toward a floor vote.\\nOnce individuals and strategies are identified, an A.I. chatbot like ChatGPT could craft written messages to be used in letters, comments — anywhere text is useful. Human lobbyists could also target those individuals directly. It’s the combination that’s important: Editorial and social media comments only get you so far, and knowing which legislators to target isn’t itself enough.\\nThis ability to understand and target actors within a network would create a tool for A.I. hacking, exploiting vulnerabilities in social, economic and political systems with incredible speed and scope. Legislative systems would be a particular target, because the motive for attacking policymaking systems is so strong, because the data for training such systems is so widely available and because the use of A.I. may be so hard to detect — particularly if it is being used strategically to guide human actors.\\nThe data necessary to train such strategic targeting systems will only grow with time. Open societies generally make their democratic processes a matter of public record, and most legislators are eager — at least, performatively so — to accept and respond to messages that appear to be from their constituents.\\nMaybe an A.I. system could uncover which members of Congress have significant sway over leadership but still have low enough public profiles that there is only modest competition for their attention. It could then pinpoint the SuperPAC or public interest group with the greatest impact on that legislator’s public positions. Perhaps it could even calibrate the size of donation needed to influence that organization or direct targeted online advertisements carrying a strategic message to its members. For each policy end, the right audience; and for each audience, the right message at the right time.\\nWhat makes the threat of A.I.-powered lobbyists greater than the threat already posed by the high-priced lobbying firms on K Street is their potential for acceleration. Human lobbyists rely on decades of experience to find strategic solutions to achieve a policy outcome. That expertise is limited, and therefore expensive.\\nA.I. could, theoretically, do the same thing much more quickly and cheaply. Speed out of the gate is a huge advantage in an ecosystem in which public opinion and media narratives can become entrenched quickly, as is being nimble enough to shift rapidly in response to chaotic world events.\\nMoreover, the flexibility of A.I. could help achieve influence across many policies and jurisdictions simultaneously. Imagine an A.I.-assisted lobbying firm that can attempt to place legislation in every single bill moving in the U.S. Congress, or even across all state legislatures. Lobbying firms tend to work within one state only, because there are such complex variations in law, procedure and political structure. With A.I. assistance in navigating these variations, it may become easier to exert power across political boundaries.\\nJust as teachers will have to change how they give students exams and essay assignments in light of ChatGPT, governments will have to change how they relate to lobbyists.\\nTo be sure, there may also be benefits to this technology in the democracy space; the biggest one is accessibility. Not everyone can afford an experienced lobbyist, but a software interface to an A.I. system could be made available to anyone. If we’re lucky, maybe this kind of strategy-generating A.I. could revitalize the democratization of democracy by giving this kind of lobbying power to the powerless.\\nHowever, the biggest and most powerful institutions will likely use any A.I. lobbying techniques most successfully. After all, executing the best lobbying strategy still requires insiders — people who can walk the halls of the legislature — and money. Lobbying isn’t just about giving the right message to the right person at the right time; it’s also about giving money to the right person at the right time. And while an A.I. chatbot can identify who should be on the receiving end of those campaign contributions, humans will, for the foreseeable future, need to supply the cash. So while it’s impossible to predict what a future filled with A.I. lobbyists will look like, it will probably make the already influential and powerful even more so.\\nNathan E. Sanders is a data scientist affiliated with the Berkman Klein Center at Harvard University.\\nBruce Schneier is a security technologist and lecturer at Harvard Kennedy School. His new book is “A Hacker’s Mind: How the Powerful Bend Society’s Rules, and How to Bend Them Back.”\\nThe Times is committed to publishing a diversity of letters to the editor. We’d like to hear what you think about this or any of our articles. Here are some tips. And here’s our email: letters@nytimes.com."));
Assert.assertTrue("Incorrect HTML -- " + response.get("html"), response.get("html").asText().equals(
"<figure data-testid=\"VideoBlock\"><img alt=\"Cinemagraph\" src=\"https://static01.nyt.com/images/2023/01/15/autossell/15Sanders-FirstFrame/15Sanders-FirstFrame-square640.jpg\"></img><video data-testid=\"cinemagraph\" src=\"https://vp.nyt.com/video/2023/01/14/105564_1_15Sanders_wg_1080p.mp4\"></video><figcaption>CreditCredit...By David Szakaly</figcaption></figure>\\n<p>Launched just weeks ago, ChatGPT is already threatening to upend how we draft everyday communications like <a href=\"https://www.streak.com/post/how-to-use-ai-to-write-perfect-cold-emails\">emails</a>, <a href=\"https://www.theatlantic.com/technology/archive/2022/12/chatgpt-ai-writing-college-student-essays/672371/\">college essays</a> and myriad <a href=\"https://javascript.plainenglish.io/13-best-examples-of-chatgpt-on-the-internet-so-far-316876466d1c\">other forms</a> of writing.</p>\\n<p>Created by the company OpenAI, ChatGPT is a chatbot that can automatically respond to written prompts in a manner that is sometimes eerily close to human.</p>\\n<p>But for all the consternation over the potential for humans to be replaced by machines in formats like poetry and sitcom scripts, a far greater threat looms: artificial intelligence replacing humans in the democratic processes &mdash; not through voting, but through lobbying.</p>\\n<p>ChatGPT could <a href=\"https://www.washingtonpost.com/business/chatgpt-could-makedemocracy-even-more-messy/2022/12/06/e613edf8-756a-11ed-a199-927b334b939f_story.html\">automatically compose</a> comments submitted in regulatory processes. It could write letters to the editor for publication in local newspapers. It could comment on news articles, blog entries and social media posts millions of times every day. It could mimic the work that the Russian Internet Research Agency did in its attempt to influence our 2016 elections, but without the agency&rsquo;s reported <a href=\"https://www.businessinsider.com/russian-troll-farm-spent-millions-on-election-interference-2018-2\">multimillion-dollar budget</a> and <a href=\"https://www.justice.gov/file/1035477/download\">hundreds of employees.</a></p>\\n<p>Automatically generated comments aren&rsquo;t a new problem. For some time, we have struggled with bots, machines that automatically post content. Five years ago, at least a million automatically drafted comments were <a href=\"https://www.wired.com/story/bots-broke-fcc-public-comment-system/\">believed to have been submitted</a> to the Federal Communications Commission regarding proposed regulations on net neutrality. In 2019, a Harvard undergraduate, as a test, used a text-generation program to <a href=\"https://techscience.org/a/2019121801/\">submit</a> 1,001 comments in response to a government request for public input on a Medicaid issue. Back then, submitting comments was just a game of overwhelming numbers.</p>\\n<p>Platforms have gotten better at removing &ldquo;coordinated inauthentic behavior.&rdquo; Facebook, for example, has been <a href=\"https://about.fb.com/news/2022/05/community-standards-enforcement-report-q1-2022/\">removing</a> over a billion fake accounts a year. But such messages are just the beginning. Rather than flooding legislators&rsquo; inboxes with supportive emails, or dominating the Capitol switchboard with synthetic voice calls, an A.I. system with the sophistication of ChatGPT but trained on relevant data could selectively target key legislators and influencers to identify the weakest points in the policymaking system and ruthlessly exploit them through direct communication, public relations campaigns, horse trading or other points of leverage.</p>\\n<p>When we humans do these things, we call it lobbying. Successful agents in this sphere pair precision message writing with smart targeting strategies. Right now, the only thing stopping a ChatGPT-equipped lobbyist from executing something resembling a rhetorical drone warfare campaign is a lack of precision targeting. A.I. could provide techniques for that as well.</p>\\n<p>A system that can understand political networks, if paired with the textual-generation capabilities of ChatGPT, could identify the member of Congress with the most leverage over a particular policy area &mdash; say, corporate taxation or military spending. Like human lobbyists, such a system could target undecided representatives sitting on committees controlling the policy of interest and then focus resources on members of the majority party when a bill moves toward a floor vote.</p>\\n<p>Once individuals and strategies are identified, an A.I. chatbot like ChatGPT could craft written messages to be used in letters, comments &mdash; anywhere text is useful. Human lobbyists could also target those individuals directly. It&rsquo;s the combination that&rsquo;s important: Editorial and social media comments only get you so far, and knowing which legislators to target isn&rsquo;t itself enough.</p>\\n<p>This ability to understand and target actors within a network would create a tool for <a href=\"https://www.schneier.com/academic/archives/2021/04/the-coming-ai-hackers.html\">A.I. hacking</a>, exploiting vulnerabilities in social, economic and political systems with incredible speed and scope. Legislative systems would be a particular target, because the motive for attacking policymaking systems is so strong, because the data for training such systems is so widely available and because the use of A.I. may be so hard to detect &mdash; particularly if it is being used strategically to guide human actors.</p>\\n<p>The data necessary to train such strategic targeting systems will only grow with time. Open societies generally make their democratic processes a matter of public record, and most legislators are eager &mdash; at least, performatively so &mdash; to accept and respond to messages that appear to be from their constituents.</p>\\n<p>Maybe an A.I. system could uncover which members of Congress have significant sway over leadership but still have low enough public profiles that there is only modest competition for their attention. It could then pinpoint the SuperPAC or public interest group with the greatest impact on that legislator&rsquo;s public positions. Perhaps it could even calibrate the size of donation needed to influence that organization or direct targeted online advertisements carrying a strategic message to its members. For each policy end, the right audience; and for each audience, the right message at the right time.</p>\\n<p>What makes the threat of A.I.-powered lobbyists greater than the threat already posed by the high-priced lobbying firms on K Street is their potential for acceleration. Human lobbyists rely on decades of experience to find strategic solutions to achieve a policy outcome. That expertise is limited, and therefore expensive.</p>\\n<p>A.I. could, theoretically, do the same thing much more quickly and cheaply. Speed out of the gate is a huge advantage in an ecosystem in which public opinion and media narratives can become entrenched quickly, as is being nimble enough to shift rapidly in response to chaotic world events.</p>\\n<p>Moreover, the flexibility of A.I. could help achieve influence across many policies and jurisdictions simultaneously. Imagine an A.I.-assisted lobbying firm that can attempt to place legislation in every single bill moving in the U.S. Congress, or even across all state legislatures. Lobbying firms tend to work within one state only, because there are such complex variations in law, procedure and political structure. With A.I. assistance in navigating these variations, it may become easier to exert power across political boundaries.</p>\\n<p>Just as teachers will have to change how they give students exams and essay assignments in light of ChatGPT, governments will have to change how they relate to lobbyists.</p>\\n<p>To be sure, there may also be benefits to this technology in the democracy space; the biggest one is accessibility. Not everyone can afford an experienced lobbyist, but a software interface to an A.I. system could be made available to anyone. If we&rsquo;re lucky, maybe this kind of strategy-generating A.I. could revitalize the democratization of democracy by giving this kind of lobbying power to the powerless.</p>\\n<p>However, the biggest and most powerful institutions will likely use any A.I. lobbying techniques most successfully. After all, executing the best lobbying strategy still requires insiders &mdash; people who can walk the halls of the legislature &mdash; and money. Lobbying isn&rsquo;t just about giving the right message to the right person at the right time; it&rsquo;s also about giving money to the right person at the right time. And while an A.I. chatbot can identify who should be on the receiving end of those campaign contributions, humans will, for the foreseeable future, need to supply the cash. So while it&rsquo;s impossible to predict what a future filled with A.I. lobbyists will look like, it will probably make the already influential and powerful even more so.</p>\\n<p>Nathan E. Sanders is a data scientist affiliated with the Berkman Klein Center at Harvard University.</p>\\n<p>Bruce Schneier is a security technologist and lecturer at Harvard Kennedy School. His new book is &ldquo;A Hacker&rsquo;s Mind: How the Powerful Bend Society&rsquo;s Rules, and How to Bend Them Back.&rdquo;</p>"));
Assert.assertTrue("time is not greater than 0", response.get("time").asLong() > 0);
Assert.assertTrue("deprecated key found in /web", !response.has("deprecated"));
}
@Test
public void returnsErrorIfUrlNotProvided() throws Exception {
HttpUrl url = HttpUrl.parse("http://localhost/html").newBuilder().port(port).build();
JsonNode response = mapper
.readTree(client.newCall(new Request.Builder().url(url).build()).execute().body().byteStream());
Assert.assertTrue("Incorrect message -- " + response.get("error").asText(),
response.get("error").asText().equals("need a URL to process."));
Assert.assertTrue("Incorrect status -- " + response.get("status").asText(),
response.get("status").asInt() == HttpStatus.BAD_REQUEST.value());
}
}
package us.d8u.balance;
import java.util.HashMap;
import java.util.Map;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
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.test.context.junit4.SpringRunner;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import okhttp3.HttpUrl;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT)
public class IcmpTests {
private static final OkHttpClient client = new OkHttpClient();
@LocalServerPort
private int port;
@Test
public void icmpWithPort() throws Exception {
final HttpUrl url = new HttpUrl.Builder().scheme("http").host("localhost").port(this.port)
.addPathSegment("icmp").addPathSegment("localhost")
.addQueryParameter("port", Integer.toString(this.port)).build();
final Request request = new Request.Builder().url(url).build();
final Response response = IcmpTests.client.newCall(request).execute();
final Map<String, String> actual = new ObjectMapper().readValue(response.body().string(),
new TypeReference<Map<String, String>>() {
});
final 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 {
final HttpUrl endpoint = new HttpUrl.Builder().addPathSegment("icmp").addPathSegment("localhost")
.port(this.port).addQueryParameter("port", Integer.toString(this.port)).scheme("http").host("localhost")
.build();
final Request request = new Request.Builder().get().url(endpoint).build();
final Response response = IcmpTests.client.newCall(request).execute();
final Map<String, String> expected = new HashMap<>();
expected.put("host", "localhost");
expected.put("port", Integer.toString(this.port));
expected.put("path", "/");
expected.put("reachableSsl", "false");
final Map<String, String> actual = new ObjectMapper().readValue(response.body().string(),
new TypeReference<Map<String, String>>() {
});
Assert.assertTrue(response.isSuccessful());
Assert.assertEquals(expected, actual);
}
}
package us.d8u.balance;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
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.test.context.junit4.SpringRunner;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ObjectNode;
import okhttp3.HttpUrl;
import okhttp3.OkHttpClient;
import okhttp3.Request;
@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT)
public class IDNTests {
private static final OkHttpClient client = new OkHttpClient();
private final ObjectMapper mapper = new ObjectMapper();
@LocalServerPort
private int port;
@Test
public void conversionWorks() throws Exception {
final ObjectNode expected = this.mapper.createObjectNode();
expected.put("punyCode", "xn--1212-9iac64ad1033eea");
HttpUrl underTest = HttpUrl.parse("http://localhost:" + this.port + "/idn/��");
JsonNode actual = this.mapper.readTree(
IDNTests.client.newCall(new Request.Builder().url(underTest).build()).execute().body().byteStream());
Assert.assertTrue("Incorrect value for key ascii",
"xn--1212-9iac64ad1033eea".equals(actual.get("ascii").asText()));
Assert.assertTrue("Incoming request not in response", "��".equals(actual.get("request").asText()));
underTest = underTest.newBuilder().removePathSegment(underTest.pathSize() - 1)
.addPathSegment("xn--1212-9iac64ad1033eea").build();
actual = this.mapper.readTree(
IDNTests.client.newCall(new Request.Builder().url(underTest).build()).execute().body().byteStream());
Assert.assertTrue("Incorrect value for key punycode", "��".equals(actual.get("punycode").asText()));
}
}
package us.d8u.balance;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
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.test.context.junit4.SpringRunner;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.api.client.util.Joiner;
import okhttp3.HttpUrl;
import okhttp3.OkHttpClient;
import okhttp3.Request;
@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT)
public class ImageTests {
private static final OkHttpClient client = new OkHttpClient();
public static final ObjectMapper mapper = new ObjectMapper();
@LocalServerPort
private int port;
@Test
public void valid() throws Exception {
final HttpUrl underTest = HttpUrl.parse("http://localhost/image").newBuilder().port(this.port)
.addQueryParameter("text", "Copenhagen").build();
final JsonNode response = ImageTests.mapper.readTree(
ImageTests.client.newCall(new Request.Builder().url(underTest).build()).execute().body().byteStream());
Assert.assertTrue("Missing keys", response.has("original") && response.has("alpha0"));
Assert.assertTrue("Not a PNG",
Joiner.on('/').join(HttpUrl.parse(response.get("original").asText()).pathSegments()).endsWith(".png"));
Assert.assertTrue("Original Hostname not oaidalleapiprodscus.blob.core.windows.net",
"oaidalleapiprodscus.blob.core.windows.net"
.equals(HttpUrl.parse(response.get("original").asText()).host()));
Assert.assertTrue("New Hostname not on imgbb",
HttpUrl.parse(response.get("newUrl").asText()).host().contains("ibb.co"));
}
}
package us.d8u.balance;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
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.test.context.junit4.SpringRunner;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import okhttp3.HttpUrl;
import okhttp3.OkHttpClient;
import okhttp3.Request;
@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT)
public class IndexTests {
private static final OkHttpClient client = new OkHttpClient();
private static final ObjectMapper mapper = new ObjectMapper();
@LocalServerPort
private int port;
@Test
public void arrayReturnedInProperFormat() throws Exception {
final HttpUrl underTest = HttpUrl.parse("http://localhost/").newBuilder().port(this.port).build();
final JsonNode response = IndexTests.mapper.readTree(
IndexTests.client.newCall(new Request.Builder().url(underTest).build()).execute().body().byteStream());
Assert.assertTrue("endpoints missing", response.has("endpoints") && response.get("endpoints").isArray());
}
}
package us.d8u.balance;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
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.test.context.junit4.SpringRunner;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ObjectNode;
import okhttp3.HttpUrl;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT)
public class IntersectionTests {
private static final OkHttpClient client = new OkHttpClient();
private static ObjectMapper mapper = new ObjectMapper();
@LocalServerPort
private int port;
@Test
public void intersectSaydGoElsewhere() throws Exception {
final HttpUrl url = HttpUrl.parse("http://localhost/gis/intersects").newBuilder().port(this.port).build();
final ObjectNode body = IntersectionTests.mapper.createObjectNode();
body.put("p1", "0,0");
body.put("p2", "0,0");
final JsonNode response = IntersectionTests.mapper
.readTree(
IntersectionTests.client
.newCall(new Request.Builder().url(url)
.post(RequestBody.create(IntersectionTests.mapper.writeValueAsBytes(body),
MediaType.parse("application/json")))
.build())
.execute().body().bytes());
Assert.assertTrue(
("functionality moved to /sql -- body should be " + IntersectionTests.mapper.writeValueAsString(body)
+ " and Json will be returned, per /sql").equals(response.get("error").asText()));
}
}
package us.d8u.balance;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
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.test.context.junit4.SpringRunner;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ObjectNode;
import okhttp3.HttpUrl;
import okhttp3.OkHttpClient;
import okhttp3.Request;
@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT)
public class IpTests {
private static OkHttpClient client = new OkHttpClient();
private static ObjectMapper mapper = new ObjectMapper();
@LocalServerPort
private int port;
@Test
public void ipDefaultsToSourceAddress() throws Exception {
ObjectNode expected = mapper.createObjectNode();
expected.put("ip", "76.91.217.78");
String rawResponse = client.newCall(
new Request.Builder().url(HttpUrl.parse("http://localhost/ip").newBuilder().port(port).build()).build())
.execute().body().string();
JsonNode response = mapper.readTree(rawResponse);
Assert.assertTrue("Weird response " + rawResponse, response.equals(expected));
}
@Test
public void ipAcceptsXForwardedForAsHostname() throws Exception {
ObjectNode expected = mapper.createObjectNode();
expected.put("ip", "54.241.65.62");
JsonNode response = mapper.readTree(client
.newCall(new Request.Builder().url(HttpUrl.parse("http://localhost/ip").newBuilder().port(port).build())
.header("x-forwarded-for", "hasan.d8u.us").build())
.execute().body().byteStream());
Assert.assertTrue("IP returned for hasan.d8u.us -- " + response.get("ip").asText() + " -- incorrect!",
response.get("ip").asText().equals("54.241.65.62"));
}
@Test
public void ipAcceptsXFowardedForAsIpv4Address() throws Exception {
ObjectNode expected = mapper.createObjectNode();
expected.put("ip", "54.241.65.62");
JsonNode response = mapper.readTree(client
.newCall(new Request.Builder().header("x-forwarded-for", "54.241.65.62")
.url(HttpUrl.parse("http://localhost/ip").newBuilder().port(port).build()).build())
.execute().body().byteStream());
Assert.assertTrue("IP returned for 54.241.65.62 -- " + response.get("ip").asText() + " -- incorrect!",
response.get("ip").asText().equals("54.241.65.62"));
}
}
package us.d8u.balance;
import java.io.IOException;
import java.util.Iterator;
import java.util.List;
import java.util.Map.Entry;
import org.joda.time.format.ISODateTimeFormat;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
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 com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.common.collect.Lists;
import okhttp3.HttpUrl;
import okhttp3.Interceptor;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT)
public class IptvTest {
private static final OkHttpClient client = new OkHttpClient();
private static final ObjectMapper mapper = new ObjectMapper();
@LocalServerPort
private int port;
@Test
public void asteriskReturnsAll() throws Exception {
IptvTest.client.newCall(new Request.Builder().url(HttpUrl.parse("http://localhost:" + this.port + "/iptv")
.newBuilder().addQueryParameter("q", "*").build()).build()).execute();
}
@Test
public void containsTime() throws Exception {
final HttpUrl url = HttpUrl.parse("http://127.0.0.1/iptv?q=cheers").newBuilder().port(this.port).build();
final Request request = new Request.Builder().url(url).build();
final Response rawResponse = IptvTest.client.newCall(request).execute();
final JsonNode responseInJava = IptvTest.mapper.readValue(rawResponse.body().charStream(), JsonNode.class)
.get("match");
Assert.assertTrue("time missing", responseInJava.has("time"));
Assert.assertTrue("time units wrong", responseInJava.get("time").asText().endsWith("ms"));
Assert.assertTrue("time format wrong",
responseInJava.get("time").asText().replace(" ms", "").matches("^[0-9]+"));
}
@Test
public void containsUpdateDate() throws Exception {
final HttpUrl url = HttpUrl.parse("http://127.0.0.1/iptv?q=cheers").newBuilder().port(this.port).build();
final Request request = new Request.Builder().url(url).build();
final Response rawResponse = IptvTest.client.newCall(request).execute();
final JsonNode responseInJava = IptvTest.mapper.readValue(rawResponse.body().charStream(), JsonNode.class)
.get("match");
Assert.assertTrue("updatedAt missing", responseInJava.has("updatedAt"));
Assert.assertFalse("updatedAt wrong format",
ISODateTimeFormat.date().parseDateTime(responseInJava.get("updatedAt").asText()).equals(null));
}
@Test
public void paramReturnsUrl() throws Exception {
final Response rawResponse = IptvTest.client
.newCall(new Request.Builder().url(HttpUrl.parse("http://localhost:" + this.port + "/iptv").newBuilder()
.addQueryParameter("q", "TF1 FHD").build()).build())
.execute();
Assert.assertTrue(rawResponse.code() == HttpStatus.OK.value());
final JsonNode response = IptvTest.mapper.readTree(rawResponse.body().string()).get("match");
final boolean yes = false;
for (final JsonNode item : response) {
Assert.assertTrue("URL not valid",
item.get("url").asText().equals("http://line.iptveros.com:8000/54be55d5d0/811bf87116/506638"));
Assert.assertTrue("Logo incorrect",
item.get("logo").asText().equals("http://logo.protv.cc/picons/logos/tf1hd.png"));
Assert.assertTrue("Title incorrect", item.get("title").asText().equals("France Hd,Fr| Tf1 Hd"));
}
Assert.assertTrue("Not found", yes);
}
@Test
public void redirectIsCorrect() throws Exception {
IptvTest.client.newBuilder().addNetworkInterceptor(new Interceptor() {
@Override
public Response intercept(Chain chain) throws IOException {
Assert.assertTrue("Target URL incorrect", chain.request().url().toString().equals(
"http://line.iptveros.com/get.php?type=m3u_plus&output=ts&username=54be55d5d0&password=811bf87116"));
Assert.assertTrue("Final URL status is wrong", IptvTest.client
.newCall(new Request.Builder().url("http://localhost:" + IptvTest.this.port + "/iptv").build())
.execute().code() == HttpStatus.TEMPORARY_REDIRECT.value());
return chain.proceed(chain.request());
}
});
}
@Test
public void verifySortByTitle() throws Exception {
final HttpUrl url = HttpUrl.parse("http://127.0.0.1/iptv?q=cheers").newBuilder().port(this.port).build();
final Request request = new Request.Builder().url(url).build();
final Response rawResponse = IptvTest.client.newCall(request).execute();
final JsonNode responseInJava = IptvTest.mapper.readValue(rawResponse.body().charStream(), JsonNode.class)
.get("match");
Assert.assertTrue("Match count is not 540", Math.abs(responseInJava.get("match").size()) == 540);
final List<JsonNode> relevantResponse = Lists.newArrayList();
for (final JsonNode rawEpisode : Lists.newArrayList(responseInJava.iterator())) {
if (rawEpisode.size() == 2) {
final Iterator<Entry<String, JsonNode>> fieldsIter = rawEpisode.fields();
do {
final Entry<String, JsonNode> elt = fieldsIter.next();
final String title = elt.getKey();
if (title.startsWith("English Series,En - Cheers (1982) S")) {
relevantResponse.add(rawEpisode);
}
} while (fieldsIter.hasNext());
}
}
for (final JsonNode ep : relevantResponse) {
final Iterator<Entry<String, JsonNode>> episodes = ep.fields();
do {
final Entry<String, JsonNode> episode = episodes.next();
final Entry<String, JsonNode> next = episodes.next();
final String title = episode.getKey();
final String title2 = next.getKey();
Assert.assertTrue("List is not sorted!", title.hashCode() < title2.hashCode());
} while (episodes.hasNext());
}
}
}
package us.d8u.balance;
import java.util.Iterator;
import java.util.List;
import java.util.Map.Entry;
import org.joda.time.format.ISODateTimeFormat;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
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 com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.common.collect.Lists;
import okhttp3.HttpUrl;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT)
public class IptvTests {
private static final OkHttpClient client = new OkHttpClient();
private static final ObjectMapper mapper = new ObjectMapper();
@LocalServerPort
private int port;
@Test
public void asteriskReturnsAll() throws Exception {
IptvTests.client.newCall(new Request.Builder().url(HttpUrl.parse("http://localhost:" + this.port + "/iptv")
.newBuilder().addQueryParameter("q", "*").build()).build()).execute();
}
@Test
public void containsTime() throws Exception {
final HttpUrl url = HttpUrl.parse("http://127.0.0.1/iptv?q=cheers").newBuilder().port(this.port).build();
final Request request = new Request.Builder().url(url).build();
final Response rawResponse = IptvTests.client.newCall(request).execute();
final JsonNode responseInJava = IptvTests.mapper.readValue(rawResponse.body().charStream(), JsonNode.class)
.get("match");
Assert.assertTrue("time missing", responseInJava.has("time"));
Assert.assertTrue("time units wrong", responseInJava.get("time").asText().endsWith("ms"));
Assert.assertTrue("time format wrong",
responseInJava.get("time").asText().replace(" ms", "").matches("^[0-9]+"));
}
@Test
public void containsUpdateDate() throws Exception {
final HttpUrl url = HttpUrl.parse("http://127.0.0.1/iptv?q=cheers").newBuilder().port(this.port).build();
final Request request = new Request.Builder().url(url).build();
final Response rawResponse = IptvTests.client.newCall(request).execute();
final JsonNode responseInJava = IptvTests.mapper.readValue(rawResponse.body().charStream(), JsonNode.class)
.get("match");
Assert.assertTrue("updatedAt missing", responseInJava.has("updatedAt"));
Assert.assertFalse("updatedAt wrong format",
ISODateTimeFormat.date().parseDateTime(responseInJava.get("updatedAt").asText()).equals(null));
}
@Test
public void onlyWorksInProduction() throws Exception {
final HttpUrl url = HttpUrl.parse("http://localhost/iptv").newBuilder().port(this.port)
.addEncodedQueryParameter("q", "cnn").build();
final Request request = new Request.Builder().addHeader("x-forwarded-for", "54.193.214.117").url(url).build();
final JsonNode response = IptvTests.mapper
.readTree(IptvTests.client.newCall(request).execute().body().byteStream());
Assert.assertTrue("Error missing", response.has("error"));
Assert.assertTrue("Error message invaid",
"source ip \"54.193.214.117\" not allowed".equals(response.get("error").asText()));
}
@Test
public void paramReturnsUrl() throws Exception {
final Response rawResponse = IptvTests.client
.newCall(new Request.Builder().url(HttpUrl.parse("http://localhost:" + this.port + "/iptv").newBuilder()
.addQueryParameter("q", "TF1 FHD").build()).build())
.execute();
Assert.assertTrue(rawResponse.code() == HttpStatus.OK.value());
final JsonNode response = IptvTests.mapper.readTree(rawResponse.body().string()).get("match");
final boolean yes = false;
for (final JsonNode item : response) {
Assert.assertTrue("URL not valid",
"http://line.iptveros.com:8000/54be55d5d0/811bf87116/506638".equals(item.get("url").asText()));
Assert.assertTrue("Logo incorrect",
"http://logo.protv.cc/picons/logos/tf1hd.png".equals(item.get("logo").asText()));
Assert.assertTrue("Title incorrect", "France Hd,Fr| Tf1 Hd".equals(item.get("title").asText()));
}
Assert.assertTrue("Not found", yes);
}
@Test
public void redirectIsCorrect() throws Exception {
IptvTests.client.newBuilder().addNetworkInterceptor(chain -> {
Assert.assertTrue("Target URL incorrect",
"http://line.iptveros.com/get.php?type=m3u_plus&output=ts&username=54be55d5d0&password=811bf87116"
.equals(chain.request().url().toString()));
Assert.assertTrue("Final URL status is wrong", IptvTests.client
.newCall(new Request.Builder().url("http://localhost:" + IptvTests.this.port + "/iptv").build())
.execute().code() == HttpStatus.TEMPORARY_REDIRECT.value());
return chain.proceed(chain.request());
});
}
@Test
public void verifySortByTitle() throws Exception {
final HttpUrl url = HttpUrl.parse("http://127.0.0.1/iptv?q=cheers").newBuilder().port(this.port).build();
final Request request = new Request.Builder().url(url).build();
final Response rawResponse = IptvTests.client.newCall(request).execute();
final JsonNode responseInJava = IptvTests.mapper.readValue(rawResponse.body().charStream(), JsonNode.class)
.get("match");
Assert.assertTrue("Match count is not 540", Math.abs(responseInJava.get("match").size()) == 540);
final List<JsonNode> relevantResponse = Lists.newArrayList();
for (final JsonNode rawEpisode : Lists.newArrayList(responseInJava.iterator())) {
if (rawEpisode.size() == 2) {
final Iterator<Entry<String, JsonNode>> fieldsIter = rawEpisode.fields();
do {
final Entry<String, JsonNode> elt = fieldsIter.next();
final String title = elt.getKey();
if (title.startsWith("English Series,En - Cheers (1982) S")) {
relevantResponse.add(rawEpisode);
}
} while (fieldsIter.hasNext());
}
}
for (final JsonNode ep : relevantResponse) {
final Iterator<Entry<String, JsonNode>> episodes = ep.fields();
do {
final Entry<String, JsonNode> episode = episodes.next();
final Entry<String, JsonNode> next = episodes.next();
final String title = episode.getKey();
final String title2 = next.getKey();
Assert.assertTrue("List is not sorted!", title.hashCode() < title2.hashCode());
} while (episodes.hasNext());
}
}
}
package us.d8u.balance;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
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.test.context.junit4.SpringRunner;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import okhttp3.HttpUrl;
import okhttp3.OkHttpClient;
import okhttp3.Request;
@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT)
public class ISOTests {
private static final OkHttpClient client = new OkHttpClient();
private static ObjectMapper mapper = new ObjectMapper();
@LocalServerPort
private int port;
@Test
public void ad() throws Exception {
final HttpUrl url = HttpUrl.parse("http://localhost:" + this.port + "/iso/AD");
final Request request = new Request.Builder().url(url).build();
final JsonNode response = ISOTests.mapper
.readTree(ISOTests.client.newCall(request).execute().body().byteStream());
Assert.assertTrue("Andorra".equals(response.get("country").asText()));
}
@Test
public void andorra() throws Exception {
final HttpUrl url = HttpUrl.parse("http://localhost:" + this.port + "/iso/Andorra");
final Request request = new Request.Builder().url(url).build();
final JsonNode response = ISOTests.mapper
.readTree(ISOTests.client.newCall(request).execute().body().byteStream());
Assert.assertTrue("AD".equals(response.get("code").asText()));
}
@Test
public void noSuchCountry() throws Exception {
final HttpUrl url = HttpUrl.parse("http://localhost:" + this.port + "/iso/Buranda");
final Request request = new Request.Builder().url(url).build();
final JsonNode response = ISOTests.mapper
.readTree(ISOTests.client.newCall(request).execute().body().byteStream());
Assert.assertTrue("No such country, are you American?".equals(response.get("error").asText()));
}
}
package us.d8u.balance;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
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.test.context.junit4.SpringRunner;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import okhttp3.HttpUrl;
import okhttp3.OkHttpClient;
import okhttp3.Request;
@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT)
public class ItuTests {
private static final OkHttpClient client = new OkHttpClient();
private static final ObjectMapper mapper = new ObjectMapper();
@LocalServerPort
private int port;
@Test
public void countryForItu34IsSpain() throws Exception {
final HttpUrl requestUrl = new HttpUrl.Builder().host("localhost").scheme("http").port(this.port)
.addPathSegment("itu").addQueryParameter("cc", "34").build();
final Request request = new Request.Builder().url(requestUrl).get().build();
final String rawResponse = ItuTests.client.newCall(request).execute().body().string();
final JsonNode response = ItuTests.mapper.readTree(rawResponse);
Assert.assertEquals("Spain", response.get(0).get("English"));
Assert.assertEquals("+34", response.get(0).get("itu"));
}
}
package us.d8u.balance;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
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.test.context.junit4.SpringRunner;
import okhttp3.HttpUrl;
import okhttp3.OkHttpClient;
import okhttp3.Request;
@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT)
public class LockTests {
private static final OkHttpClient client = new OkHttpClient();
@LocalServerPort
private Integer port;
@Test
public void returnsFalseIfEntryLocked() throws Exception {
final HttpUrl url = HttpUrl.parse("http://localhost/locks").newBuilder().port(this.port)
.addQueryParameter("entry", "1").build();
final Request httpRequest = new Request.Builder().url(url).build();
LockTests.client.newCall(httpRequest).execute();
final String response = LockTests.client.newCall(httpRequest).execute().body().string();
Assert.assertTrue(response.equals("false"));
}
@Test
public void returnsTrueIfEntryNotLocked() throws Exception {
final String nanoTimeAsId = Long.toString(System.nanoTime());
final HttpUrl url = HttpUrl.parse("http://localhost/locks").newBuilder().port(this.port)
.addQueryParameter("entry", nanoTimeAsId).build();
final Request httpRequest = new Request.Builder().url(url).build();
LockTests.client.newCall(httpRequest).execute();
final String response = LockTests.client.newCall(httpRequest).execute().body().string();
Assert.assertTrue(response.equals("true"));
}
}
package us.d8u.balance;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
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.test.context.junit4.SpringRunner;
import okhttp3.HttpUrl;
import okhttp3.OkHttpClient;
import okhttp3.Request;
@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT)
public class LockTests {
private static final OkHttpClient client = new OkHttpClient();
@LocalServerPort
private Integer port;
@Test
public void returnsFalseIfEntryLocked() throws Exception {
final HttpUrl url = HttpUrl.parse("http://localhost/locks").newBuilder().port(this.port)
.addQueryParameter("entry", "1").build();
final Request httpRequest = new Request.Builder().url(url).build();
LockTests.client.newCall(httpRequest).execute();
final String response = LockTests.client.newCall(httpRequest).execute().body().string();
Assert.assertTrue("false".equals(response));
}
@Test
public void returnsTrueIfEntryNotLocked() throws Exception {
final String nanoTimeAsId = Long.toString(System.nanoTime());
final HttpUrl url = HttpUrl.parse("http://localhost/locks").newBuilder().port(this.port)
.addQueryParameter("entry", nanoTimeAsId).build();
final Request httpRequest = new Request.Builder().url(url).build();
LockTests.client.newCall(httpRequest).execute();
final String response = LockTests.client.newCall(httpRequest).execute().body().string();
Assert.assertTrue("true".equals(response));
}
}
package us.d8u.balance;
import java.net.InetAddress;
import org.joda.time.DateTime;
import org.joda.time.format.ISODateTimeFormat;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
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 com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import okhttp3.HttpUrl;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT)
public class LogTests {
private static final OkHttpClient client = new OkHttpClient();
@LocalServerPort
private int port;
@Test
public void canLogUsingEndpoint() throws Exception {
final HttpUrl url = HttpUrl.parse("https://units.d8u.us/log").newBuilder()
.addQueryParameter("endpoint", InetAddress.getLocalHost().getHostAddress()).build();
final Request request = new Request.Builder().url(url).build();
final JsonNode response = new ObjectMapper().readTree(client.newCall(request).execute().body().bytes());
Assert.assertTrue("Response from /log is not " + HttpStatus.CREATED.value() + ", rather is "
+ response.get("status").asInt(), response.get("status").asInt() == HttpStatus.CREATED.value());
Assert.assertTrue(response.get("telegram").get("sentStatus").asBoolean()
&& response.get("irc").get("sentStatus").asBoolean());
}
@Test
public void noEntryOlderThan24Hours() throws Exception {
final String source = HttpUrl.parse("https://units.d8u.us/log?op=view").toString();
final Response response = client.newCall(new Request.Builder().url(source).build()).execute();
final JsonNode json = new ObjectMapper().readTree(response.body().bytes());
for (final JsonNode stanza : json) {
final Long k = stanza.get("time").asLong();
Assert.assertTrue(
ISODateTimeFormat.dateTimeNoMillis().print(new DateTime(k)) + " is before "
+ ISODateTimeFormat.date().print(DateTime.now().minusDays(1)) + "!",
DateTime.now().minusDays(1).isBefore(new DateTime(k)));
}
}
}
package us.d8u.balance;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
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.test.context.junit4.SpringRunner;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.common.collect.Sets;
import okhttp3.HttpUrl;
import okhttp3.OkHttpClient;
import okhttp3.Request;
@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT)
public class LondonTests {
private static final OkHttpClient client = new OkHttpClient();
private static ObjectMapper mapper = new ObjectMapper();
@LocalServerPort
private int port;
@Test
public void home() throws Exception {
String homeLocation = "51.5102831,-0.186906";
JsonNode response = mapper
.readTree(client
.newCall(new Request.Builder().url(HttpUrl.parse("http://localhost/london").newBuilder()
.port(port).addQueryParameter("loc", homeLocation).build()).build())
.execute().body().charStream());
Assert.assertTrue(Sets.newHashSet("name", "latitude", "longitude", "line", "distance")
.equals(Sets.newHashSet(response.get("london").fieldNames())));
}
}
package us.d8u.balance;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
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.test.context.junit4.SpringRunner;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import okhttp3.HttpUrl;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT)
public class LTCSyncTests {
private static final OkHttpClient client = new OkHttpClient();
private static final ObjectMapper mapper = new ObjectMapper();
@LocalServerPort
private int port;
@Test
public void badRequest() throws Exception {
final JsonNode badRequest = LTCSyncTests.mapper.readTree("{}");
final HttpUrl url = HttpUrl.parse("http://localhost:" + this.port + "/discord2slack");
final RequestBody discordBody = RequestBody.create(LTCSyncTests.mapper.writeValueAsString(badRequest),
MediaType.parse("application/json"));
final Request request = new Request.Builder().url(url).post(discordBody).build();
final JsonNode response = LTCSyncTests.mapper
.readTree(LTCSyncTests.client.newCall(request).execute().body().charStream());
Assert.assertTrue("Need content or text".equals(response.get("error").asText()));
}
@Test
public void discordToSlack() throws Exception {
final JsonNode fromDiscord = LTCSyncTests.mapper.readTree(this.getClass().getResourceAsStream("/discord.json"));
final HttpUrl url = HttpUrl.parse("http://localhost:" + this.port + "/discord2slack");
final RequestBody discordBody = RequestBody.create(LTCSyncTests.mapper.writeValueAsString(fromDiscord),
MediaType.parse("application/json"));
final Request request = new Request.Builder().url(url).post(discordBody).build();
final JsonNode response = LTCSyncTests.mapper
.readTree(LTCSyncTests.client.newCall(request).execute().body().charStream());
Assert.assertTrue("200".equals(response.get("discord.status").asText()));
}
@Test
public void slackToDiscord() throws Exception {
final JsonNode fromSlack = LTCSyncTests.mapper.readTree(this.getClass().getResourceAsStream("/slack.json"));
final HttpUrl url = HttpUrl.parse("http://localhost:" + this.port + "/slack2discord");
final RequestBody slackBody = RequestBody.create(LTCSyncTests.mapper.writeValueAsString(fromSlack),
MediaType.parse("application/json"));
final Request request = new Request.Builder().url(url).post(slackBody).build();
final JsonNode response = LTCSyncTests.mapper
.readTree(LTCSyncTests.client.newCall(request).execute().body().charStream());
Assert.assertTrue("200".equals(response.get("slack.status").asText()));
}
}
package us.d8u.balance;
import org.apache.http.HttpStatus;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
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.test.context.junit4.SpringRunner;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT)
public class LTCTests {
private static final OkHttpClient client = new OkHttpClient();
@LocalServerPort
private int port;
@Test
public void ltcRedirectsProperly() throws Exception {
final Response response = LTCTests.client.newBuilder().followRedirects(false).build()
.newCall(new Request.Builder().url("/ltc").build()).execute();
final String location = response.header("location");
Assert.assertTrue("https://hd1.bitbucket.io/LTCTesting.pdf".equals(location));
Assert.assertTrue(response.code() == HttpStatus.SC_TEMPORARY_REDIRECT);
}
}
package us.d8u.balance;
import org.apache.commons.lang3.StringUtils;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
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.test.context.junit4.SpringRunner;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import okhttp3.HttpUrl;
import okhttp3.OkHttpClient;
import okhttp3.Request;
@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT)
public class MailStatsTests {
private static final OkHttpClient client = new OkHttpClient();
private final ObjectMapper mapper = new ObjectMapper();
@LocalServerPort
private int port;
@Test
public void properKeysAndTypesDefaults() throws Exception {
final HttpUrl endpoint = HttpUrl.parse("http://localhost/mailstats").newBuilder().port(this.port)
.addPathSegment("test@test.com").addEncodedQueryParameter("pwd", "tset").build();
final JsonNode response = this.mapper.readTree(MailStatsTests.client
.newCall(new Request.Builder().url(endpoint).build()).execute().body().charStream());
Assert.assertTrue("emailAddress incorrect", "test@test.com".equals(response.get("emailAddress").asText()));
Assert.assertTrue("count incorrect", response.get("messageCount").asInt() == 21);
Assert.assertTrue("folder incorrect", "INBOX".equals(response.get("folder").asText()));
Assert.assertTrue("time missing", StringUtils.isNumeric(response.get("time").asText()));
Assert.assertTrue("time out of range", response.get("time").asDouble() > 0d);
}
@Test
public void withFolderName() throws Exception {
final HttpUrl endpoint = HttpUrl.parse("http://localhost/mailstats").newBuilder().port(this.port)
.addPathSegment("test@test.com").addEncodedQueryParameter("pwd", "tset").addQueryParameter("f", "sent")
.build();
final JsonNode response = this.mapper.readTree(MailStatsTests.client
.newCall(new Request.Builder().url(endpoint).build()).execute().body().charStream());
Assert.assertTrue("folder name incorrect", response.get("folder").asText().contentEquals("sent"));
}
}
package us.d8u.balance;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Map;
import org.joda.time.DateTime;
import org.joda.time.format.DateTimeFormatter;
import org.joda.time.format.ISODateTimeFormat;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
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.test.context.junit4.SpringRunner;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.common.collect.Sets;
import okhttp3.HttpUrl;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT)
public class MarketPredTests {
private static final OkHttpClient client = new OkHttpClient();
@LocalServerPort
private int port;
@Test
public void checkTypesAndRanges() throws Exception {
final HttpUrl url = HttpUrl.parse("http://localhost:" + this.port + "/stock/info");
final Response rawResponse = MarketPredTests.client.newCall(new Request.Builder().url(url).build()).execute();
final JsonNode response = new ObjectMapper().readTree(rawResponse.body().bytes());
final DateTimeFormatter fmt = ISODateTimeFormat.date();
Assert.assertTrue(fmt.parseDateTime(response.get("date").asText()).isAfter(DateTime.now().minusDays(2))
&& fmt.parseDateTime(response.get("date").asText()).isBefore(DateTime.now().plusDays(2)));
Assert.assertTrue(Arrays.asList("up", "down", "no change").contains(response.get("prediction").asText()));
}
@Test
public void stockInfoWithoutSymReturnsPredictionForW5000() throws Exception {
final HashSet<String> expectedKeys = Sets.newHashSet("date", "prediction");
final HttpUrl requestUrl = new HttpUrl.Builder().scheme("http").host("localhost").port(this.port)
.addEncodedPathSegments("/stock/info").build();
final Request request = new Request.Builder().url(requestUrl).build();
final Response response = MarketPredTests.client.newCall(request).execute();
final Map<String, String> json = new ObjectMapper().readValue(response.body().bytes(),
new TypeReference<Map<String, String>>() {
});
Assert.assertEquals(expectedKeys, json.keySet());
final DateTimeFormatter futureDate = ISODateTimeFormat.date();
Assert.assertTrue(futureDate.parseDateTime(json.get("date")).plusDays(2).isAfter(DateTime.now())
&& futureDate.parseDateTime(json.get("date")).minusDays(1).isBefore(DateTime.now()));
Assert.assertTrue(Sets.newHashSet("up", "no change", "down").contains(json.get("prediction")));
Assert.assertTrue("^W5000".equals(json.get("symbol")));
}
@Test
public void stockWithoutIncorrectSymbolReturnsError() throws Exception {
final HttpUrl requestUrl = new HttpUrl.Builder().scheme("http").host("localhost").port(this.port)
.addEncodedPathSegments("/stock").addQueryParameter("sym", "RDSA").build();
final Request request = new Request.Builder().url(requestUrl).build();
final Response response = MarketPredTests.client.newCall(request).execute();
final Map<String, String> json = new ObjectMapper().readValue(response.body().bytes(),
new TypeReference<Map<String, String>>() {
});
Assert.assertEquals(json.get("status"), "404");
Assert.assertEquals(json.get("error"), "Symbol not found");
}
}
package us.d8u.balance;
import java.util.Map;
import org.junit.Assert;
import org.junit.Test;
import org.springframework.boot.web.server.LocalServerPort;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import okhttp3.HttpUrl;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
public class MavenTests {
private static final OkHttpClient client = new OkHttpClient();
@LocalServerPort
private int port;
@Test
public void pomXmlUrlReturnsJson() throws Exception {
final 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\\\"}]\"}";
final 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();
final Request requestToUpstream = new Request.Builder().url(url).build();
final Response responseFromUpstream = MavenTests.client.newCall(requestToUpstream).execute();
final Map<String, String> actual = new ObjectMapper().readValue(responseFromUpstream.body().charStream(),
new TypeReference<Map<String, String>>() {
});
final Map<String, String> expected = new ObjectMapper().readValue(expectedJson,
new TypeReference<Map<String, String>>() {
});
try {
Assert.assertEquals(actual.entrySet(), expected.entrySet());
} catch (final Throwable t) {
}
}
}
package us.d8u.balance;
import java.net.HttpURLConnection;
import java.net.URL;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
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.test.context.junit4.SpringRunner;
@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT)
public class MoatsTests {
@LocalServerPort
private int port;
@Test
public void redirectsProperly() throws Exception {
final HttpURLConnection conn = (HttpURLConnection) new URL("http://localhost:" + this.port + "/moats")
.openConnection();
conn.connect();
final String location = conn.getHeaderField("Location");
Assert.assertTrue("Location incorrect -- " + location, "https://paypal.me/georgegallowayuk".equals(location));
}
}
package us.d8u.balance;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import org.joda.time.DateTime;
import org.joda.time.format.DateTimeFormatter;
import org.joda.time.format.ISODateTimeFormat;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
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 com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ObjectNode;
import com.ibm.icu.text.NumberFormat;
import okhttp3.HttpUrl;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT)
public class MoneyTests {
static OkHttpClient client = new OkHttpClient.Builder().build();
static ObjectMapper mapper = new ObjectMapper();
@LocalServerPort
private int port;
@Test
public void belgianFrancIsNotValid() throws Exception {
final HttpUrl endpoint = new HttpUrl.Builder().scheme("http").host("localhost").port(this.port)
.addPathSegment("fx").addPathSegment("BEF").addPathSegment("USD").build();
final Request request = new Request.Builder().url(endpoint).build();
final Response response = MoneyTests.client.newCall(request).execute();
Assert.assertTrue(response.isSuccessful());
final Map<String, String> actual = new ObjectMapper().readValue(response.body().string(),
new TypeReference<Map<String, String>>() {
});
Assert.assertTrue(actual.get("status").equals(Integer.toString(HttpStatus.BAD_REQUEST.value())));
}
@Test
public void letsCommaOrDecimalBeSeparators() throws Exception {
HttpUrl url = HttpUrl.parse("http://localhost/money/2.1/usd/usd?adj=0.8").newBuilder().port(this.port).build();
final ObjectNode node1 = (ObjectNode) MoneyTests.mapper.readTree(
MoneyTests.client.newCall(new Request.Builder().url(url).build()).execute().body().byteStream());
node1.remove("time");
url = HttpUrl.parse("http://localhost/money/2,1/usd/usd?adj=0.8").newBuilder().port(this.port).build();
final ObjectNode node2 = (ObjectNode) MoneyTests.mapper.readTree(
MoneyTests.client.newCall(new Request.Builder().url(url).build()).execute().body().byteStream());
node2.remove("time");
Assert.assertTrue("Comma-separated currency value -- " + MoneyTests.mapper.writeValueAsString(node1)
+ " -- and decimal separated value -- " + MoneyTests.mapper.writeValueAsString(node2) + " -- not equal",
node2.equals(node1));
}
@Test
public void moneyHandlesAdjustmentFactor() throws Exception {
final HttpUrl url = HttpUrl.parse("http://localhost/money/2/usd/usd?adj=0.8").newBuilder().port(this.port)
.build();
final Request request = new Request.Builder().url(url).build();
final Response rawResponse = MoneyTests.client.newCall(request).execute();
final Map<String, String> response = new ObjectMapper().readValue(rawResponse.body().bytes(),
new TypeReference<Map<String, String>>() {
});
Assert.assertEquals("1.6",
NumberFormat.getCurrencyInstance(Locale.GERMANY).format(response.get("destinationAmount")).toString());
}
@Test
public void moneyIsCaseInsensitive() throws Exception {
final HttpUrl url = HttpUrl.parse("http://localhost/money/2/eur/eur").newBuilder().port(this.port).build();
final Request request = new Request.Builder().url(url).build();
final Response response = MoneyTests.client.newCall(request).execute();
Assert.assertEquals(200, response.code());
}
@Test
public void moneyReturnsErrorForInvalidSynbols() throws Exception {
final HttpUrl url = new HttpUrl.Builder().scheme("http").host("localhost").port(this.port)
.addEncodedPathSegments("money/2/UnitY/USD").build();
final Response rawResponse = MoneyTests.client.newCall(new Request.Builder().url(url).build()).execute();
final 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 moneySupportsEUR() throws Exception {
final HttpUrl url = HttpUrl.parse("http://localhost/money/2/EUR/EUR").newBuilder().port(this.port).build();
final Request request = new Request.Builder().url(url).build();
final Response response = MoneyTests.client.newCall(request).execute();
Assert.assertEquals(200, response.code());
}
@Test
public void moneySymbolsReturnsProperTypes() throws Exception {
final HttpUrl url = new HttpUrl.Builder().scheme("http").host("localhost").port(this.port)
.addPathSegment("money").addPathSegment("symbols").build();
final Request request = new Request.Builder().url(url).build();
final Response rawResponse = MoneyTests.client.newCall(request).execute();
final List<String> response = new ObjectMapper().readValue(rawResponse.body().string(),
new TypeReference<List<String>>() {
});
for (final String k : response) {
Assert.assertTrue(k.length() == 3);
Assert.assertTrue(k.equals(k.toUpperCase()));
}
}
@Test
public void noAmountReturnsCountry() throws Exception {
final HttpUrl url = new HttpUrl.Builder().host("localhost").scheme("http").port(this.port)
.addPathSegment("money").addPathSegment("AFN").build();
final Request requstObj = new Request.Builder().url(url).build();
final String rawResponse = MoneyTests.client.newCall(requstObj).execute().body().string();
final 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 twoDollarsEqualsTwoDollars() throws Exception {
final Request request = new Request.Builder().url("http://localhost:" + this.port + "/money/2/USD/USD").build();
final Response responseObj = MoneyTests.client.newBuilder().build().newCall(request).execute();
final String rawResponse = responseObj.body().string();
final Map<String, String> response = new ObjectMapper().readValue(rawResponse,
new TypeReference<Map<String, String>>() {
});
final DateTime today = DateTime.now();
final DateTimeFormatter fmt = ISODateTimeFormat.date();
final 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"));
}
}
package us.d8u.balance;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
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.test.context.junit4.SpringRunner;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import okhttp3.HttpUrl;
import okhttp3.OkHttpClient;
import okhttp3.Request;
@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT)
public class MsOfficeTests {
private static final OkHttpClient client = new OkHttpClient();
private static final ObjectMapper mapper = new ObjectMapper();
@LocalServerPort
private int port;
@Test
public void responseCorrectForUnsupportedFile() throws Exception {
final String URL = "https://hd1.bitbucket.io/wordcloud.html";
final JsonNode response = MsOfficeTests.mapper.readTree(MsOfficeTests.client
.newCall(new Request.Builder().url(HttpUrl.parse("http://localhost/msoffice").newBuilder()
.port(this.port).addEncodedQueryParameter("url", URL).build()).build())
.execute().body().byteStream());
Assert.assertTrue(response.get("error").asText() + " is not correct",
"wordcloud.html -- unsupported by this endpoint".equals(response.get("error").asText()));
}
}
package us.d8u.balance;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
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.test.context.junit4.SpringRunner;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ObjectNode;
import okhttp3.HttpUrl;
import okhttp3.OkHttpClient;
import okhttp3.Request;
@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT)
public class MyIpTests {
private static final OkHttpClient client = new OkHttpClient();
@LocalServerPort
private int port;
ObjectMapper mapper = new ObjectMapper();
@Test
public void homeIp() throws Exception {
final ObjectNode expected = this.mapper.createObjectNode();
expected.put("ip", "76.91.217.78");
final JsonNode real = this.mapper.readTree(MyIpTests.client
.newCall(new Request.Builder()
.url(HttpUrl.parse("http://localhost/myIp").newBuilder().port(this.port).build()).build())
.execute().body().charStream());
Assert.assertTrue("Invalid response", expected.equals(real));
}
}
package us.d8u.balance;
import java.math.BigDecimal;
import java.text.NumberFormat;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.Set;
import java.util.concurrent.TimeUnit;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.codec.digest.MessageDigestAlgorithms;
import org.apache.commons.lang3.StringUtils;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
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.test.context.junit4.SpringRunner;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.common.collect.Sets;
import okhttp3.HttpUrl;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT)
public class NearMeTests {
private static final OkHttpClient client = new OkHttpClient.Builder().followSslRedirects(false)
.followRedirects(false).connectTimeout(0, TimeUnit.SECONDS).readTimeout(0, TimeUnit.SECONDS).build();
private static ObjectMapper mapper = new ObjectMapper();
@LocalServerPort
private int port;
@Test
public void htmlRedirectsProperly() throws Exception {
final HttpUrl url = HttpUrl.parse("http://localhost/nearme.html").newBuilder().port(this.port).build();
final Response response = NearMeTests.client.newCall(new Request.Builder().url(url).build()).execute();
String location = response.header("location");
Assert.assertTrue("Wrong URL targetted from nearme.html -- " + location,
"https://hasan.d8u.us/nearme.html".equals(location));
final HttpUrl url2 = url.newBuilder().removePathSegment(0).addEncodedPathSegment("nearme.htm").build();
final Response resp2 = NearMeTests.client.newCall(new Request.Builder().url(url2).build()).execute();
location = resp2.header("location");
Assert.assertTrue("Wrong URL targetted from nearme.htm -- " + location,
"https://hasan.d8u.us/nearme.html".equals(location));
}
@Test
public void isSortedByDistance() throws Exception {
final HttpUrl url = HttpUrl.parse("http://localhost:" + this.port + "/nearme");
final JsonNode responses = NearMeTests.mapper.readTree(
NearMeTests.client.newCall(new Request.Builder().url(url).build()).execute().body().byteStream());
for (int response = 0; response != (responses.get("venues").size() - 1); response++) {
Assert.assertTrue("Error, not sorted properly", responses.get("venues").get(response).get("distance")
.asDouble() >= responses.get("venues").get(response + 1).get("distance").asDouble());
}
}
@Test
public void nearMeReturnsPlaceNamesDistancesBearingsForPlace() throws Exception {
final HttpUrl requestUrl = new HttpUrl.Builder().host("localhost").scheme("http").port(this.port)
.addPathSegment("nearme").addQueryParameter("lat", "41.3813934").addQueryParameter("lng", "2.1730637")
.build();
final Request request = new Request.Builder().url(requestUrl).get().build();
Response rawResponse = null;
try {
rawResponse = NearMeTests.client.newCall(request).execute();
} catch (final Exception e) {
Assert.fail(e.getMessage());
}
Assert.assertEquals(200, rawResponse.code());
final String string = rawResponse.body().string();
final List<Map<String, String>> response = new ObjectMapper().readValue(string,
new TypeReference<List<Map<String, String>>>() {
});
final Set<String> expectedKeys = Sets.newHashSet("venue", "distance", "bearing", "crowd", "latitude",
"longitude", "request");
for (final Map<String, String> result : response) {
try {
NumberFormat.getIntegerInstance().parse(result.get("crowd"));
} catch (final NumberFormatException e) {
Assert.fail("Expected integer. found " + result.get("crowd"));
}
try {
final 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 (final NumberFormatException e) {
Assert.fail("Expected number. found " + result.get("distance"));
}
try {
final 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 (final NumberFormatException e) {
Assert.fail("Expected number. found " + result.get("bearing"));
}
try {
final 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 (final NumberFormatException e) {
Assert.fail("Expected number. found " + result.get("latitude"));
}
try {
final 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 (final 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 nearmeReturnsProperKeysIfNoParametersGiven() throws Exception {
final HttpUrl url = HttpUrl.parse("http://localhost:" + this.port + "/nearme");
final JsonNode responses = NearMeTests.mapper.readTree(
NearMeTests.client.newCall(new Request.Builder().url(url).build()).execute().body().byteStream());
Assert.assertTrue("Time isn't numeric", StringUtils.isNumeric(responses.get("time").asText()));
for (final JsonNode response : responses.get("venues")) {
Assert.assertTrue(Sets.newHashSet(true, false).contains(response.get("isOpen").booleanValue()));
Assert.assertTrue(Integer.valueOf(response.get("distance").asInt()) >= 0);
Assert.assertTrue(Math.abs(response.get("bearing").asDouble()) < 360);
Assert.assertTrue("Phone number " + response.get("phoneNumber").asText() + " is not numeric",
response.get("phoneNumber").isNull()
|| StringUtils.isNumeric(response.get("phoneNumber").asText()));
}
}
@Test
public void uiUnchanged() throws Exception {
final HttpUrl url = HttpUrl.parse("https://hasan.d8u.us/nearme.html");
final Properties hashProperties = new Properties();
hashProperties.load(this.getClass().getResourceAsStream("/application.properties"));
final String EXPECTED = (String) hashProperties.get("nearme.html.sha224");
Assert.assertTrue(
"Hash incorrect -- \n"
+ new DigestUtils(MessageDigestAlgorithms.SHA_224).digestAsHex(NearMeTests.client
.newCall(new Request.Builder().url(url).build()).execute().body().bytes())
+ " -- expected\n" + EXPECTED,
EXPECTED.equals(new DigestUtils(MessageDigestAlgorithms.SHA_224).digestAsHex(
NearMeTests.client.newCall(new Request.Builder().url(url).build()).execute().body().bytes())));
}
}
package us.d8u.balance;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
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.test.context.junit4.SpringRunner;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.common.collect.Lists;
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 NerTests {
private static final OkHttpClient client = new OkHttpClient();
private static ObjectMapper mapper = new ObjectMapper();
private static String testString = "Hello I hope all is well. Here is the COA and quote Psyllium husk 95% 25kg@$18 per kilo ( FOB NJ) Please let me know if you need anything else? Thank you Regards, Eric Kantor Sales Representative Ecuadorian Rainforest, LLC. e: hd1@jsc.d8u.us, p: 973-759-2002 *direct: **(973) 500-6741* w: www.IntoTheRainforest.com<http://www.intotherainforest.com/> a:222 Getty Ave. Clifton, NJ 07011 <https://www.enmailer.com/sendy/subscription?f=g892vZbbQ7m4ct9t2A8NOsY0MNDcoVtBCx6QIUz8crCinaUj543TTPdE5TF3gFVsf5bUXDHuOWDXOaG0uIyUneSQ> Pleasevisit us at our upcoming shows: *IFT FIRST* – July 11-13 – Booth S4440 – McCormick Place, Chicago, Illinois *BIOFACH *– July 26 -29 – Hall 4A, Stand 4A-723 – Nürnberg Messe, Nuremberg, Germany";
@LocalServerPort
private int port;
final HttpUrl endpoint = HttpUrl.parse("http://localhost:" + this.port + "/ner");
@Test
public void getsEmail() throws Exception {
final Request postReq = new Request.Builder().url(this.endpoint)
.post(RequestBody.create(NerTests.testString, MediaType.parse("text/plain"))).build();
final JsonNode postResponse = NerTests.mapper
.readTree(NerTests.client.newCall(postReq).execute().body().charStream());
boolean foundEmail = false;
for (final JsonNode string : Lists.newArrayList(postResponse.get("emails").iterator())) {
if ("hd1@jsc.d8u.us".equals(string.asText().trim())) {
foundEmail = true;
}
}
Assert.assertTrue("email not found", foundEmail);
}
@Test
public void missingHelper() throws Exception {
final HttpUrl wrongHelperUrl = this.endpoint.newBuilder()
.addQueryParameter("url", "https://hd1-nlp.herokuapp.com/ner").build();
final Request postReq = new Request.Builder().url(wrongHelperUrl)
.post(RequestBody.create(NerTests.testString, MediaType.parse("text/plain"))).build();
final JsonNode postResponse = NerTests.mapper
.readTree(NerTests.client.newCall(postReq).execute().body().charStream());
Assert.assertTrue("https://hd1-nlp.herokuapp.com/ner unreachable".equals(postResponse.get("error").asText()));
}
@Test
public void postNer() throws Exception {
final HttpUrl testUrl = new HttpUrl.Builder().scheme("http").host("localhost").port(this.port)
.addPathSegment("ner").build();
final MediaType mediaType = MediaType.parse("text/plain");
final 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);
final Request request = new Request.Builder().url(testUrl).method("POST", body)
.addHeader("Content-Type", "text/plain").build();
final Response response = NerTests.client.newCall(request).execute();
final String rawResponse = response.body().string();
final 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());
}
}
package us.d8u.balance;
import java.io.ByteArrayInputStream;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.joda.time.DateTime;
import org.joda.time.format.DateTimeFormatter;
import org.joda.time.format.ISODateTimeFormat;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
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.test.context.junit4.SpringRunner;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.common.collect.Sets;
import com.rometools.rome.feed.synd.SyndEntry;
import com.rometools.rome.feed.synd.SyndFeed;
import com.rometools.rome.io.SyndFeedInput;
import com.rometools.rome.io.XmlReader;
import okhttp3.HttpUrl;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT)
public class NewsTests {
private static final OkHttpClient client = new OkHttpClient();
@LocalServerPort
private int port;
@Test
public void bsdIncludesNetOpenAndFreeRssFeedsOrderedByDate() throws Exception {
final HttpUrl requestUrl = new HttpUrl.Builder().host("localhost").scheme("http").port(this.port)
.addEncodedPathSegment("news").addPathSegment("bsd").build();
final Request request = new Request.Builder().url(requestUrl).build();
final Response rawResponse = NewsTests.client.newCall(request).execute();
final SyndFeed feed = new SyndFeedInput()
.build(new XmlReader(new ByteArrayInputStream(rawResponse.body().bytes())));
for (final SyndEntry entry : feed.getEntries().subList(0, feed.getEntries().size() - 1)) {
Assert.assertTrue(entry.getPublishedDate()
.after(feed.getEntries().get(feed.getEntries().indexOf(entry)).getPublishedDate()));
Assert.assertTrue(entry.getDescription().getValue().contains("ftp.openbsd.org")
|| entry.getLink().contains("freebsd.org") || entry.getLink().toLowerCase().contains("netbsd.org"));
Assert.assertTrue(null != entry.getAuthor());
Assert.assertTrue(Sets.newHashSet("OpenBSD", "FreeBSD", "NetBSD").contains(entry.getAuthor()));
Assert.assertTrue(null != entry.getLink());
}
Assert.assertTrue(feed.getEntries().size() > 3);
Assert.assertTrue("https://units.d8u.us/news/bsd".equals(feed.getLink()));
}
@Test
public void newsReturnsPieceWithParameters() throws Exception {
final Set<String> expected = Sets.newHashSet("author", "title", "publishedAt", "attribution", "link", "total");
final HttpUrl requestUrl = new HttpUrl.Builder().host("localhost").scheme("http").port(this.port)
.addPathSegment("news").addQueryParameter("q", "Boris Johnson").build();
final Request request = new Request.Builder().url(requestUrl).build();
final Response response = NewsTests.client.newCall(request).execute();
final List<Map<String, String>> responseObj = new ObjectMapper().readValue(response.body().string(),
new TypeReference<List<Map<String, String>>>() {
});
for (final Map<String, String> r : responseObj) {
final 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 {
final DateTimeFormatter df = ISODateTimeFormat.dateTimeNoMillis();
Assert.assertTrue(df.parseDateTime(r.get("publishedAt")).isBefore(DateTime.now()));
} catch (final Exception e) {
Assert.fail("Not a date -- " + r.get("publishedAt"));
}
}
}
@Test
public void newsReturnsSourcesWithNoParameters() throws Exception {
final Set<String> expected = Sets.newHashSet("name", "url", "country", "language", "attribution");
final HttpUrl requestUrl = new HttpUrl.Builder().host("localhost").scheme("http").port(this.port)
.addPathSegments("news").build();
final Request request = new Request.Builder().url(requestUrl).build();
final Response response = NewsTests.client.newCall(request).execute();
final List<Map<String, String>> responseObj = new ObjectMapper().readValue(response.body().string(),
new TypeReference<List<Map<String, String>>>() {
});
for (final Map<String, String> r : responseObj) {
final Set<String> actual = r.keySet();
Assert.assertEquals(expected, actual);
Assert.assertEquals("powered by NewsAPI.org", r.get("attribution"));
}
}
}
package us.d8u.balance;
import java.util.Map;
import org.junit.Assert;
import org.junit.BeforeClass;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.context.SpringBootTest.WebEnvironment;
import org.springframework.boot.test.web.server.LocalServerPort;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.datasource.DriverManagerDataSource;
import org.springframework.test.context.junit4.SpringRunner;
import com.aol.cyclops.streams.StreamUtils;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ArrayNode;
import com.fasterxml.jackson.databind.node.ObjectNode;
import com.google.common.collect.Maps;
import com.google.common.collect.Sets;
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 OneDriveTests {
private static final OkHttpClient client = new OkHttpClient();
private static ObjectMapper mapper = new ObjectMapper();
@LocalServerPort
private int port;
@BeforeClass
public void setUp() throws Exception {
String url = "https://1drv.ms/b/s!ArSglZTnZLNlcRRdO4Srt5Ja7Rc?e=jOotTI";
DriverManagerDataSource ds = new DriverManagerDataSource();
ds.setDriverClassName("org.sqlite.JDBC");
ds.setUrl("jdbc:sqlite:/Users/user/Developer/units/src/test/resources/onedrive.sqlite3");
JdbcTemplate tmpl = new JdbcTemplate(ds);
tmpl.batchUpdate(Sets.newHashSet("INSERT INTO onedrive (url, id) values (" + url + ", '1')",
"INSERT INTO tags (tag, id) VALUES ('pdf', 1)",
"INSERT INTO onedrive_tags (url_id, tag_id) values (1, 1)").toArray(new String[] { "" }));
}
@Test
public void getReturnsZeroUrlsWithNoMatches() throws Exception {
String tag = "bitch";
ArrayNode expectedResult = mapper.createArrayNode();
expectedResult.add(mapper.nullNode());
ObjectNode expectedResults = mapper.createObjectNode();
expectedResults.put("request", tag);
expectedResults.set("results", expectedResult);
JsonNode results = mapper.readTree(
client.newCall(new Request.Builder().url(HttpUrl.parse("http://localhost/onedrive").newBuilder()
.port(port).addQueryParameter("tag", tag).build()).build()).execute().body().bytes());
Assert.assertTrue("Unexpected results for bitch", results.equals(expectedResults));
}
@Test
public void getReturnsUrlWithMatch() throws Exception {
String url = "https://1drv.ms/b/s!ArSglZTnZLNlcRRdO4Srt5Ja7Rc?e=jOotTI";
ArrayNode results = (ArrayNode) mapper
.readTree(client
.newCall(new Request.Builder().url(HttpUrl.parse("http://localhost/onedrive").newBuilder()
.port(port).addQueryParameter("tag", "pdf").build()).build())
.execute().body().byteStream())
.get("results");
Assert.assertTrue(url + " not found", results.get(0).asText().equals(url));
Assert.assertTrue("More tyhan one result", results.size() == 1);
}
@Test
public void patchAddsTagToUrl() throws Exception {
String tag = "ruby";
String url = "https://1drv.ms/b/s!ArSglZTnZLNlcRRdO4Srt5Ja7Rc?e=jOotTI";
Response rawResponse = client
.newCall(new Request.Builder()
.url(HttpUrl.parse("http://localhost/onedrive").newBuilder().port(port)
.addQueryParameter("tag", tag).addQueryParameter("url", url).build())
.patch(RequestBody.create(new byte[0], null)).build())
.execute();
Assert.assertTrue("Wrong response code", rawResponse.code() == 201);
Map<String, String> sqlMap = Maps.newHashMap();
sqlMap.put("sql",
"SELECT u.url from tags t join onedrive_tags ot on t.id = ot.tag_id join urls u on ot.url_id = u.id where tag = 'ruby'");
sqlMap.put("driverClass", "org.sqlite.JDBC");
sqlMap.put("jdbcUrl", "jdbc:sqlite:/Users/user/Developer/units/src/test/resources/onedrive.sqlite3");
String sqlJson = mapper.writeValueAsString(sqlMap);
HttpUrl sqlUrl = HttpUrl.parse("http://localhost/sql").newBuilder().port(port).build();
RequestBody sqlBody = RequestBody.create(sqlJson, MediaType.parse("application/json"));
Request sqlRequest = new Request.Builder().url(sqlUrl).post(sqlBody).build();
ArrayNode results = (ArrayNode) mapper.readTree(client.newCall(sqlRequest).execute().body().byteStream())
.get("results");
Assert.assertTrue("Result not found",
StreamUtils.stream(results.spliterator()).anyMatch(p -> p.asText().equals(url)));
}
}
package us.d8u.balance;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
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.test.context.junit4.SpringRunner;
import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.dataformat.xml.XmlMapper;
import okhttp3.HttpUrl;
import okhttp3.OkHttpClient;
import okhttp3.Request;
@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT)
public class OsmTests {
private static final OkHttpClient client = new OkHttpClient();
@LocalServerPort
private int port;
XmlMapper mapper = new XmlMapper();
@Test
public void everyStanzaMustHaveLatLon() throws Exception {
final HttpUrl undertest = HttpUrl.parse("http://localhost/osm").newBuilder().port(this.port).build();
final JsonNode response = this.mapper.readTree(
OsmTests.client.newCall(new Request.Builder().url(undertest).build()).execute().body().string());
final String content = response.get("content").asText();
Assert.assertTrue("Impossible count", response.get("invalid").asInt() > -1);
final SAXParser parser = SAXParserFactory.newInstance().newSAXParser();
parser.parse(content, new DefaultHandler() {
@Override
public void startElement(String uri, String lName, String qName, Attributes attr) throws SAXException {
if ("node".equals(qName)) {
Assert.assertTrue("Missing id", attr.getValue("id") != null);
Assert.assertTrue("Non-nuneric id", attr.getValue("id").matches("^[0-9]+$"));
Assert.assertTrue("Missing lat", attr.getValue("lat") != null);
Assert.assertTrue("lat out of range", Math.abs(Double.parseDouble(attr.getValue("lat"))) < 181);
Assert.assertTrue("Missing lng", attr.getValue("lng") != null);
Assert.assertTrue("lat out of range", Math.abs(Double.parseDouble(attr.getValue("lng"))) < 91);
}
}
});
}
}
package us.d8u.balance;
import java.text.NumberFormat;
import java.util.Map;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
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 com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import okhttp3.HttpUrl;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT)
public class PasswordTests {
private static final OkHttpClient client = new OkHttpClient();
@LocalServerPort
private int port;
@Test
public void invalidUserReturnsUnauthorized() throws Exception {
final HttpUrl url = HttpUrl.parse("http://localhost:" + this.port + "/password").newBuilder()
.addQueryParameter("site", "google.com").addQueryParameter("user", "hd999@jsc.d8u.us").build();
final JsonNode response = new ObjectMapper().readTree(
PasswordTests.client.newCall(new Request.Builder().addHeader("authorization", "+").url(url).build())
.execute().body().bytes());
Assert.assertTrue(response.get("status").asInt() == HttpStatus.UNAUTHORIZED.value());
Assert.assertTrue("Invalid user".equals(response.get("error").asText()));
Assert.assertTrue(Long.valueOf(NumberFormat.getIntegerInstance().format(response.get("time"))) > 0L);
}
@Test
public void missingAuthHeaderReturnsUnauthorized() throws Exception {
final HttpUrl url = HttpUrl.parse("http://localhost:" + this.port + "/password").newBuilder()
.addQueryParameter("site", "google.com").build();
final JsonNode response = new ObjectMapper().readTree(
PasswordTests.client.newCall(new Request.Builder().url(url).build()).execute().body().bytes());
Assert.assertTrue(response.get("status").asInt() == HttpStatus.UNAUTHORIZED.value());
Assert.assertTrue("Missing user".equals(response.get("error").asText()));
Assert.assertTrue(Long.valueOf(NumberFormat.getIntegerInstance().format(response.get("time"))) > 0L);
}
@Test
public void missingKeyReturnsBadRequest() throws Exception {
final HttpUrl url = HttpUrl.parse("http://localhost:" + this.port + "/password").newBuilder()
.addQueryParameter("site", "google.com").build();
final JsonNode response = new ObjectMapper().readTree(
PasswordTests.client.newCall(new Request.Builder().url(url).build()).execute().body().bytes());
Assert.assertTrue(response.get("status").asInt() == HttpStatus.BAD_REQUEST.value());
Assert.assertTrue(Long.valueOf(NumberFormat.getIntegerInstance().format(response.get("time"))) > 0L);
Assert.assertTrue("Missing required parameters".equals(response.get("error").asText()));
}
@Test
public void noKeysReturnBadRequest() throws Exception {
final JsonNode response = new ObjectMapper().readTree(PasswordTests.client
.newCall(new Request.Builder().url("http://localhost:" + this.port + "/password").build()).execute()
.body().bytes());
Assert.assertTrue(response.get("status").asInt() == HttpStatus.BAD_REQUEST.value());
Assert.assertTrue("Missing required parameters".equals(response.get("error").asText()));
Assert.assertTrue(Long.valueOf(NumberFormat.getIntegerInstance().format(response.get("time"))) > 0L);
}
@Test
public void notFoundEntry() throws Exception {
final HttpUrl url = HttpUrl.parse("http://localhost:" + this.port + "/password").newBuilder()
.addQueryParameter("site", "google.com").addQueryParameter("user", "hd999@jsc.d8u.us").build();
final JsonNode response = new ObjectMapper().readTree(
PasswordTests.client.newCall(new Request.Builder().url(url).build()).execute().body().bytes());
Assert.assertTrue(response.get("status").asInt() == HttpStatus.NOT_FOUND.value());
Assert.assertTrue(response.get("error").asText().equals(HttpStatus.NOT_FOUND.getReasonPhrase()));
Assert.assertTrue(Long.valueOf(NumberFormat.getIntegerInstance().format(response.get("time"))) > 0L);
}
@Test
public void passwordWorks() throws Exception {
final HttpUrl requestUrl = new HttpUrl.Builder().host("localhost").scheme("http").port(this.port)
.addPathSegments("password").addQueryParameter("url", "https://cloud.gate.ac.uk").build();
final Request request = new Request.Builder().url(requestUrl).get().build();
final Response rawResponse = PasswordTests.client.newCall(request).execute();
final Map<String, String> response = new ObjectMapper().readValue(rawResponse.body().string(),
new TypeReference<Map<String, String>>() {
});
Assert.assertTrue("jsc".equals(response.get("username")));
Assert.assertTrue("^n'J#f;Fa{8\\72r/=)G!Y]".equals(response.get("password")));
}
}
package us.d8u.balance;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
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.test.context.junit4.SpringRunner;
import com.google.common.base.Joiner;
import okhttp3.HttpUrl;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT)
public class PasteTests {
private static final OkHttpClient client = new OkHttpClient();
@LocalServerPort
private int port;
private final HttpUrl underTest = HttpUrl.parse("http://localhost/paste");
@Test
public void noPathAccess() throws Exception {
final Response response = PasteTests.client.newBuilder().followRedirects(false).build()
.newCall(new Request.Builder().url(this.underTest.newBuilder().port(this.port).build()).build())
.execute();
Assert.assertTrue("Response is not redirect", response.isRedirect());
final String destinationSrc = response.header("Location");
final HttpUrl destination = HttpUrl.parse(destinationSrc);
Assert.assertTrue("hd1-paste.herokuapp.com".equals(destination.host()));
Assert.assertTrue("Destination path is not empty, but " + destination.encodedPath(),
"/".equals(destination.encodedPath()));
}
@Test
public void pathInvalid() throws Exception {
final Response response = PasteTests.client.newBuilder().followRedirects(false).build()
.newCall(new Request.Builder()
.url(this.underTest.newBuilder().port(this.port).addPathSegment("foo").build()).build())
.execute();
Assert.assertTrue(response.isRedirect());
final HttpUrl destination = response.request().url();
Assert.assertTrue("Path doesn't contain proper \"id\" parameter",
Joiner.on("/").join(destination.pathSegments()).endsWith("/foo"));
}
}
package us.d8u.balance;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
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 com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.common.collect.Sets;
import com.google.common.primitives.Ints;
import okhttp3.HttpUrl;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT)
public class PdfTests {
private static final OkHttpClient client = new OkHttpClient();
private static final ObjectMapper mapper = new ObjectMapper();
@LocalServerPort
private int port;
@Test
public void invalidSchemaGivesError() throws Exception {
final HttpUrl url = HttpUrl.parse("http://localhost/pdf").newBuilder().port(this.port)
.addQueryParameter("pdf", "httos://hd1.bitbucket.io/CV.pdf").build();
final Request request = new Request.Builder().url(url).build();
final Response response = PdfTests.client.newCall(request).execute();
final String rawResponse = response.body().string();
final JsonNode actual = PdfTests.mapper.readTree(rawResponse);
Assert.assertTrue(Sets.newHashSet("status", "error").iterator().equals(actual.fieldNames()));
Assert.assertTrue(actual.get("status").asInt() == HttpStatus.BAD_GATEWAY.value());
Assert.assertTrue(actual.get("error").asText().startsWith("Schemas supported are local filesnames, "));
}
@Test
public void noPdfSpecifiedGivesError() throws Exception {
final HttpUrl url = HttpUrl.parse("http://localhost/pdf").newBuilder().port(this.port).build();
final Request request = new Request.Builder().url(url).build();
final Response response = PdfTests.client.newCall(request).execute();
final String rawResponse = response.body().string();
final JsonNode actual = PdfTests.mapper.readTree(rawResponse);
Assert.assertTrue(Sets.newHashSet("status", "error").iterator().equals(actual.fieldNames()));
Assert.assertTrue(actual.get("status").asInt() == HttpStatus.BAD_REQUEST.value());
Assert.assertTrue("need URL".equals(actual.get("error").asText()));
}
@Test
public void validRequestKeysAndTypes() throws Exception {
final HttpUrl url = HttpUrl.parse("http://localhost/pdf").newBuilder().port(this.port)
.addQueryParameter("pdf", "httos://hd1.bitbucket.io/CV.pdf").build();
final Request request = new Request.Builder().url(url).header("X-PDF-key", System.getProperty("api.pdfkit", ""))
.build();
final Response response = PdfTests.client.newCall(request).execute();
final String rawResponse = response.body().string();
final JsonNode actual = PdfTests.mapper.readTree(rawResponse);
Assert.assertTrue("wordCount isn't a positive integer", Ints.tryParse(actual.get("wordCount").asText()) > 0);
Assert.assertTrue("pageCount isn't a positive integer", Ints.tryParse(actual.get("pageCount").asText()) > 0);
Assert.assertTrue("pageCount not positive", actual.get("pageCount").asInt() > 0);
Assert.assertTrue("fileSize isn't an integer", null != Ints.tryParse(actual.get("fileSize").asText()));
Assert.assertTrue("fileSize isn't positive", actual.get("fileSize").asInt() > 0);
Assert.assertTrue("Content isn't a string", actual.get("content").asText().length() > 0);
}
}
package us.d8u.balance;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
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.test.context.junit4.SpringRunner;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import okhttp3.HttpUrl;
import okhttp3.OkHttpClient;
import okhttp3.Request;
@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT)
public class PercentTests {
private static final OkHttpClient client = new OkHttpClient();
private static final ObjectMapper mapper = new ObjectMapper();
@LocalServerPort
private int port;
@Test
public void invalidParamsYieldsError() throws Exception {
final HttpUrl url = HttpUrl.parse("http://localhost/percent").newBuilder().port(this.port)
.addQueryParameter("encode", "https://i.ibb.co/XCfRYYd/image.png").build();
final JsonNode response = PercentTests.mapper.readTree(
PercentTests.client.newCall(new Request.Builder().url(url).build()).execute().body().charStream());
Assert.assertTrue(
"invalid key(s), valid ones are \"toEnc\" and \"encoded\"".equals(response.get("error").asText()));
}
@Test
public void percentDecodingWorks() throws Exception {
final HttpUrl url = HttpUrl.parse("http://localhost/percent").newBuilder().port(this.port)
.addQueryParameter("encoded", "https%3A%2F%2Fi.ibb.co%2FXCfRYYd%2Fimage.png").build();
final JsonNode response = PercentTests.mapper.readTree(
PercentTests.client.newCall(new Request.Builder().url(url).build()).execute().body().charStream());
Assert.assertTrue("https://i.ibb.co/XCfRYYd/image.png".equals(response.get("decoded").asText()));
}
@Test
public void percentEncodingUrlWorks() throws Exception {
final HttpUrl url = HttpUrl.parse("http://localhost/percent").newBuilder().port(this.port)
.addQueryParameter("toEnc", "https://i.ibb.co/XCfRYYd/image.png").build();
final JsonNode response = PercentTests.mapper.readTree(
PercentTests.client.newCall(new Request.Builder().url(url).build()).execute().body().charStream());
Assert.assertTrue("https%3A%2F%2Fi.ibb.co%2FXCfRYYd%2Fimage.png".equals(response.get("encoded").asText()));
}
}
package us.d8u.balance;
import java.util.Map;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
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.test.context.junit4.SpringRunner;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.common.collect.Maps;
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 PgpTests {
private static final OkHttpClient client = new OkHttpClient();
private static ObjectMapper mapper = new ObjectMapper();
@LocalServerPort
private int port;
private Map<String, String> fetchFromKeyserverReturnsValidKey(String param) throws Exception {
return PGPUtils.fetchFromKeyserver(param);
}
@Test
public void blankDoesNotThrowException() throws Exception {
final HttpUrl endpoint = HttpUrl.parse("http://localhost:" + this.port + "/pgp/verify");
final RequestBody body = RequestBody.create("{}", MediaType.parse("application/json"));
final Response rawResponse = PgpTests.client.newCall(new Request.Builder().url(endpoint).post(body).build())
.execute();
Assert.assertTrue(rawResponse.code() == 200);
final JsonNode response = PgpTests.mapper.readTree(rawResponse.body().byteStream());
Assert.assertTrue("'text' key required!".equals(response.get("error").asText()));
}
@Test
public void fetchInvalidKeyFromKeyserver() throws Exception {
final Map<String, String> actual = this.fetchFromKeyserverReturnsValidKey("hasan.diwan@gmail.com");
Assert.assertTrue(actual.containsKey("error"));
Assert.assertEquals(actual.get("error"), "Key not found");
Assert.assertTrue(actual.containsKey("request"));
Assert.assertEquals(actual.get("request"), "hasan.diwan@gmail.com");
}
@Test
public void fetchKeyFromKeyserverUsingFingerprint() throws Exception {
this.fetchFromKeyserverReturnsValidKey("44D0 5643 E391 4542 7702 E1E7 FEBA D7FF D041 BBA1");
}
@Test
public void fetchValidKeyFromKeyserver() throws Exception {
final Map<String, String> actual = this.fetchFromKeyserverReturnsValidKey("hasandiwan@gmail.com");
Assert.assertTrue(actual.containsKey("fingerprint"));
Assert.assertTrue(actual.containsKey("keyId"));
Assert.assertTrue(actual.containsKey("key"));
Assert.assertTrue(actual.containsKey("request"));
}
@Test
public void isValidSignatureIsBoolean() throws Exception {
final String signedText = "-----BEGIN PGP SIGNED MESSAGE-----\n" + "Hash: SHA256\n" + "\n" + "hello world\n"
+ "-----BEGIN PGP SIGNATURE-----\n" + "\n"
+ "iQIzBAEBCAAdFiEENROx5p50mTOovE9CwtUpwKaR7fcFAmBGmDwACgkQwtUpwKaR\n"
+ "7fdHuBAAxIKGhAY7pZEdmRNshjjiBNuG27tBE24cf2KCJYYUVTyw58IzPWIMOBPd\n"
+ "fKjHf6x6GEhfxfdPiX1s8p58VVkakRD6QE5jAMHtRB5n0OIUWTqoG0JEYRs/ZlLw\n"
+ "NZqEOirW3bI3I6p5kJ+ZMG4BVCnDNl/njonuSfihrgPBvvTxDjJyxQ5s4ib0RpVl\n"
+ "X2GxVNp5CP/WH3PoMC3aXnEISPuXU6AqpCndTzAA/W5sZzVy0KImDZhxSouoah35\n"
+ "E5eLLyik3lDggIiH0IlhNBzgBjDNrO8hSeTd9XytDBP+IOiooCeb0Fx77ZUXu93Y\n"
+ "8vIJyLT8dLEeqZH/VxcbVrhzO8VjreJol32OR67a4NkjtkCay0bbZcb41ZG1Bcr3\n"
+ "X8DwCsnTO8YYi5vxu9HArzhNgZ0VGAISaFFpmcAk4tQs2kHlCJZ4WDrXBc49NHko\n"
+ "/oALyOaD0AxcgfZpxoIaT/aSAVTrXo4+ZyEpEJtOtTNA5HBtogJRExFfznovm6io\n"
+ "ouF6cztKkWT9ImmbnIpfLlEMdmmBJUoAl3v9K1gmy4aYyytjBKUSQoZ+d9ofne7Y\n"
+ "C7uHA5wFnHDRjpWeTg3EiSFBovTMo/59+WvUxtzhaDdkWLd1mwcm+r2oEGp4r/fb\n"
+ "rXkeTzcHEX0h29paxMvQIOuYebMgZaCJkH5i3FGA2D06dFmfWSY=\n" + "=JATv\n"
+ "-----END PGP SIGNATURE-----\n";
final HttpUrl endpoint = HttpUrl.parse("http://localhost:" + this.port + "/pgp/verify");
final Response rawResponse = PgpTests.client.newCall(
new Request.Builder().url(endpoint).post(okhttp3.RequestBody.create(signedText.getBytes())).build())
.execute();
final JsonNode response = PgpTests.mapper.readValue(rawResponse.body().bytes(), JsonNode.class);
Assert.assertTrue(response.get("isValidSignature").asBoolean());
}
@Test
public void pgpSignIsCleartext() throws Exception {
final String plainText = "hello world";
final String keyId = "44D05643E39145427702E1E7FEBAD7FFD041BBA1";
final Map<String, String> params = Maps.newHashMap();
params.put("text", plainText);
params.put("key", keyId);
final HttpUrl endpoint = HttpUrl.parse("http://localhost:" + this.port + "/pgp/sign");
final Response rawResponse = PgpTests.client.newCall(new Request.Builder().url(endpoint)
.post(okhttp3.RequestBody.create(plainText.getBytes(), MediaType.parse("application/json"))).build())
.execute();
final String response = PgpTests.mapper.readValue(rawResponse.body().bytes(), String.class);
Assert.assertTrue(plainText + " missing from " + response, response.contains(plainText));
}
}
package us.d8u.balance;
import java.nio.charset.StandardCharsets;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
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 com.google.common.hash.Hashing;
import okhttp3.HttpUrl;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT)
public class PicTests {
@LocalServerPort
private int port;
@Test
public void picFound() throws Exception {
final HttpUrl url = HttpUrl.parse("https://hasan.d8u.us/me.png");
final OkHttpClient client = new OkHttpClient.Builder().build();
final Response response = client.newCall(new Request.Builder().url(url).build()).execute();
Assert.assertTrue(response.isSuccessful());
Assert.assertTrue(
"a6e92eeb42f29e9deac65a4dc4525842295d3abc73054a0a05a43ee92ae64f002b26060ab3db8e515f698194402d0b7e"
.equals(Hashing.goodFastHash(384).hashString(response.body().string(), StandardCharsets.UTF_8)
.toString()));
}
@Test
public void redirectsToCorrectPage() throws Exception {
final HttpUrl url = HttpUrl.parse("http://localhost:" + this.port + "/pic");
final OkHttpClient client = new OkHttpClient.Builder().followRedirects(false).build();
final Response response = client.newCall(new Request.Builder().url(url).build()).execute();
Assert.assertTrue(HttpStatus.TEMPORARY_REDIRECT.value() == response.code());
Assert.assertTrue("https://hasan,d8u.us/me.png".equals(response.header("Location")));
}
}
package us.d8u.balance;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.context.SpringBootTest.WebEnvironment;
import org.springframework.boot.test.web.server.LocalServerPort;
import org.springframework.test.context.junit4.SpringRunner;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import okhttp3.HttpUrl;
import okhttp3.OkHttpClient;
import okhttp3.Request;
@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT)
public class PlaceTests {
private static final OkHttpClient client = new OkHttpClient();
private static ObjectMapper mapper = new ObjectMapper();
@LocalServerPort
private int port;
@Test
public void latitudeOutOfBounds() throws Exception {
HttpUrl underTest = HttpUrl.parse("http://localhost/place/237.875291/-122.455503").newBuilder().port(port)
.build();
JsonNode response = mapper
.readTree(client.newCall(new Request.Builder().url(underTest).build()).execute().body().charStream());
Assert.assertTrue(response.get("error").asText().equals("latitude cannot be greater than 90 or less than -90"));
}
@Test
public void longitudeOutOfBounds() throws Exception {
HttpUrl underTest = HttpUrl.parse("http://localhost/place/37.875291/-1122.455503").newBuilder().port(port)
.build();
JsonNode response = mapper
.readTree(client.newCall(new Request.Builder().url(underTest).build()).execute().body().charStream());
Assert.assertTrue(
response.get("error").asText().equals("longitude cannot be greater than 180 or less than -180"));
}
@Test
public void pathParametersMustBeNumeric() throws Exception {
HttpUrl underTest = HttpUrl.parse("http://localhost/place/37.87529!/-122.455503").newBuilder().port(port)
.build();
JsonNode response = mapper
.readTree(client.newCall(new Request.Builder().url(underTest).build()).execute().body().charStream());
Assert.assertTrue(response.get("error").asText().equals("\"37.87529!\" not numeric"));
underTest = HttpUrl.parse("http://localhost/place/37.875291/-122.4555O3").newBuilder().port(port).build();
response = mapper
.readTree(client.newCall(new Request.Builder().url(underTest).build()).execute().body().charStream());
Assert.assertTrue(response.get("error").asText().equals("\"-122.4555O3\" is not numeric"));
}
@Test
public void properRequestWithoutType() throws Exception {
HttpUrl underTest = HttpUrl.parse("http://localhost/place/37.875291/-122.455503").newBuilder().port(port)
.build();
JsonNode response = mapper
.readTree(client.newCall(new Request.Builder().url(underTest).build()).execute().body().charStream());
Assert.assertTrue(response.get("bing").asText()
.equals("https://bing.com/maps/default.aspx?dir=0&cp=37.875291~-122.455503"));
Assert.assertTrue(response.get("google").asText()
.equals("https://www.google.com/maps/search/@37.875291,-122.455503,17z?hl=en"));
Assert.assertTrue(response.get("osmAsia").asText().equals("https://www.osmap.asia/#17/37.875291/-122.455503"));
}
@Test
public void properRequestWithType() throws Exception {
HttpUrl underTest = HttpUrl.parse("http://localhost/place/37.875291/-122.455503").newBuilder().port(port)
.addQueryParameter("type", "google").build();
String response = client.newCall(new Request.Builder().url(underTest).build()).execute().body().string();
Assert.assertTrue(
response.equals("forward:https://www.google.com/maps/search/@37.875291,-122.455503,17z?hl=en"));
}
@Test
public void placeNotFound() throws Exception {
HttpUrl underTest = HttpUrl.parse("http://localhost/place/0/0").newBuilder().port(port)
.addQueryParameter("type", "google").build();
String responseString = client.newCall(new Request.Builder().url(underTest).build()).execute().body().string();
JsonNode response = mapper.readTree(responseString);
Assert.assertTrue(response.get("error").asText().equals("Location not found"));
}
}
package us.d8u.balance;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.text.NumberFormat;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import org.joda.time.format.DateTimeFormatter;
import org.joda.time.format.ISODateTimeFormat;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
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 com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ObjectNode;
import com.google.common.collect.Maps;
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 PlusTests {
private static OkHttpClient client = new OkHttpClient();
private static ObjectMapper mapper = new ObjectMapper();
@LocalServerPort
private int port;
@Value(value = "${whereishasan.jdbc}")
private String WHEREISHASAN_JDBC;
@Before
public void _setup() {
System.setProperty("test", "1");
}
@Test
public void addrGivesProperGoogleLink() throws Exception {
final ObjectNode body = PlusTests.mapper.createObjectNode();
body.put("addr", "brecon, wales");
final HttpUrl url = new HttpUrl.Builder().scheme("http").host("localhost").port(this.port)
.addPathSegment("plus").build();
final Request request = new Request.Builder()
.url(url).addHeader("Content-type", "application/json").post(RequestBody
.create(PlusTests.mapper.writeValueAsString(body), MediaType.parse("application/json")))
.build();
final Response response = PlusTests.client.newCall(request).execute();
final Map<String, String> actual = PlusTests.mapper.readValue(response.body().string(),
new TypeReference<Map<String, String>>() {
});
Assert.assertTrue(
"https://www.google.com/maps/search/@51.9472048,-3.391696,17z?hl=en".equals(actual.get("google")));
}
@Test
public void authorizationHeaderWorksWithPlus() throws Exception {
final ObjectNode body = PlusTests.mapper.createObjectNode();
body.put("addr", "brecon, wales");
final HttpUrl url = new HttpUrl.Builder().scheme("http").host("localhost").port(this.port)
.addPathSegment("plus").build();
final Request request = new Request.Builder().header("authorization", "415690793").url(url)
.addHeader("Content-type", "application/json").post(RequestBody
.create(PlusTests.mapper.writeValueAsString(body), MediaType.parse("application/json")))
.build();
final Response response = PlusTests.client.newCall(request).execute();
Assert.assertTrue("Authorization error incorrect!",
response.body().string().equals("Use YmFzaWMgKzQxNTY5MDc5MzA6 as your authentication header!"));
}
@Test
public void authorizationHeaderWorks() throws Exception {
final ObjectNode body = PlusTests.mapper.createObjectNode();
body.put("addr", "brecon, wales");
final HttpUrl url = new HttpUrl.Builder().scheme("http").host("localhost").port(this.port)
.addPathSegment("plus").build();
final Request request = new Request.Builder().header("authorization", "415690793").url(url)
.addHeader("Content-type", "application/json").post(RequestBody
.create(PlusTests.mapper.writeValueAsString(body), MediaType.parse("application/json")))
.build();
final Response response = PlusTests.client.newCall(request).execute();
Assert.assertTrue("Authorization error incorrect!",
response.body().string().equals("Use YmFzaWMgKzQxNTY5MDc5MzA6 as your authentication header!"));
}
@Test
public void checkinNotAllowedWithInvalidNumbers() throws Exception {
final Map<String, String> ret = Maps.newHashMap();
ret.put("status", Integer.toString(HttpStatus.UNAUTHORIZED.value()));
ret.put("message", "user not allowed");
final Map<String, String> params = new HashMap<>();
params.put("latitude", "34.10638");
params.put("longitude", "-118.44858");
final HttpUrl url = new HttpUrl.Builder().scheme("http").host("localhost").port(this.port)
.addPathSegment("plus").build();
final Request request = new Request.Builder().addHeader("Authorization", "+3345428906").url(url)
.addHeader("Content-type", "application/json").post(RequestBody
.create(PlusTests.mapper.writeValueAsString(params), MediaType.parse("application/json")))
.build();
final Response response = PlusTests.client.newCall(request).execute();
final Map<String, String> actual = PlusTests.mapper.readValue(response.body().string(),
new TypeReference<Map<String, String>>() {
});
Assert.assertTrue("Error incorrect", ret.get("message").equals(actual.get("message")));
}
@Test
public void checkinWorks() throws Exception {
if (null == System.getProperty("plus.auth")) {
Assert.fail("Need to define plus.auth to make this test work");
}
final Map<String, String> params = new HashMap<>();
params.put("latitude", "-34.10638");
params.put("longitude", "118.44858");
final HttpUrl url = new HttpUrl.Builder().scheme("http").host("localhost").port(this.port)
.addPathSegment("plus").build();
final Request request = new Request.Builder().url(url).addHeader("Content-type", "application/json")
.addHeader("X-Authorization", System.getProperty("plus.auth")).post(RequestBody
.create(PlusTests.mapper.writeValueAsString(params), MediaType.parse("application/json")))
.build();
PlusTests.client.newCall(request).execute();
final HttpUrl checkUrl = HttpUrl.parse("https://whereishasan.herokuapp.com/api/0,0?test=1");
final JsonNode checkResp = PlusTests.mapper.readTree(
PlusTests.client.newCall(new Request.Builder().url(checkUrl).build()).execute().body().byteStream())
.get("data");
Assert.assertTrue("Latitude incorrect", checkResp.get("latitude").asText().equals(params.get("latitude")));
Assert.assertTrue("Longitude incorrect", checkResp.get("longitude").asText().equals(params.get("longitude")));
Assert.assertTrue("Timetamp negative", !checkResp.get("ago").asText().replace(" ms", "").startsWith("-"));
}
@Test
public void emptyBodyYieldsBooleanIsLocal() throws Exception {
final HttpUrl url = new HttpUrl.Builder().scheme("http").host("localhost").port(this.port)
.addPathSegment("plus").build();
final Request request = new Request.Builder()
.url(url).addHeader("Content-type", "application/json").post(RequestBody
.create(PlusTests.mapper.writeValueAsString("{}"), MediaType.parse("application/json")))
.build();
final Response response = PlusTests.client.newCall(request).execute();
final String actual = response.body().string();
Assert.assertTrue(Boolean.parseBoolean(actual) || !Boolean.parseBoolean(actual));
}
@Test
public void helpSupported() throws Exception {
final Map<String, String> body = Maps.newHashMap();
body.put("help", "");
final HttpUrl url = new HttpUrl.Builder().scheme("http").host("localhost").port(this.port)
.addPathSegment("plus").build();
final Request request = new Request.Builder()
.url(url).addHeader("Content-type", "application/json").post(RequestBody
.create(PlusTests.mapper.writeValueAsString(body), MediaType.parse("application/json")))
.build();
final Response response = PlusTests.client.newCall(request).execute();
final JsonNode jsonResponse = PlusTests.mapper.readTree(response.body().byteStream());
Assert.assertTrue("knownAddresses not found!", jsonResponse.has("knownAddresses"));
}
@Test
public void locationPostedToUi() throws Exception {
final Connection conn = DriverManager.getConnection(this.WHEREISHASAN_JDBC);
final ResultSet stored = conn.createStatement().executeQuery(
"SELECT latitude, longitude, to_json(timestamp)#>>'{}' as iso_timestamp from wherewashasan order by timestamp limit 1");
stored.next();
final String soupSource = PlusTests.client
.newCall(new Request.Builder().url("https://hasan.d8u.us/whereami.html").build()).execute().body()
.string();
final Document soup = Jsoup.parse(soupSource);
Element metaTag = soup.selectFirst("meta[name=locationLatitude]");
Assert.assertTrue("latitude incorrect", metaTag.attr("content").equals(stored.getString(1)));
metaTag = soup.selectFirst("meta[name=locationLongitude]");
Assert.assertTrue("longitude incorrect", metaTag.attr("content").equals(stored.getString(2)));
metaTag = soup.selectFirst("meta[name=timestamp]");
Assert.assertTrue("timestamp not ISO8601",
ISODateTimeFormat.dateTimeNoMillis().parseDateTime(metaTag.attr("content"))
.equals(ISODateTimeFormat.dateTimeNoMillis().parseDateTime(stored.getString(3))));
}
@Test
public void plusAcceptsGeohash() throws Exception {
final Map<String, String> expected = new HashMap<>();
expected.put("geohash", "9q8zkpgeud4d");
final RequestBody body = RequestBody.create(PlusTests.mapper.writeValueAsString(expected),
MediaType.parse("application/json"));
final Request request = new Request.Builder().url(
new HttpUrl.Builder().scheme("http").host("localhost").port(this.port).addPathSegment("plus").build())
.post(body).build();
final Response rawResponse = PlusTests.client.newCall(request).execute();
Map<String, String> realResponse = mapper.readValue(rawResponse.body().byteStream(),
new TypeReference<Map<String, String>>() {
});
expected.put("latitude", "37.88014096207917");
expected.put("longitude", "-122.51452809199691");
expected.put("plusCode", "849VVFJP+35");
for (String k : expected.keySet()) {
Assert.assertTrue(k + "incorrect", realResponse.get(k).equals(expected.get(k)));
}
}
@Test
public void plusAcceptsIp() throws Exception {
final Map<String, String> expected = new HashMap<>();
expected.put("ip", "8.8.8.8");
final RequestBody body = RequestBody.create(PlusTests.mapper.writeValueAsString(expected),
MediaType.parse("application/json"));
expected.put("request", "8.8.8.8");
expected.remove("ip");
expected.put("addr", "Ashburn, Virginia, United States");
final Request request = new Request.Builder().url(
new HttpUrl.Builder().scheme("http").host("localhost").port(this.port).addPathSegment("plus").build())
.post(body).build();
final Response rawResponse = PlusTests.client.newCall(request).execute();
final Map<String, String> response = PlusTests.mapper.readValue(rawResponse.body().bytes(),
new TypeReference<Map<String, String>>() {
});
final DateTimeFormatter fmt = ISODateTimeFormat.dateTimeNoMillis();
try {
fmt.parseDateTime(response.get("timestamp"));
} catch (final Exception e) {
Assert.fail(response.get("timestamp") + " is in the wrong format");
}
try {
NumberFormat.getIntegerInstance().parse(response.get("time"));
} catch (final Exception e) {
Assert.fail(response.get("time") + " isn't an integer");
}
response.remove("time");
response.remove("timestamp");
for (String k : expected.keySet()) {
Assert.assertTrue(k + "incorrect", response.get(k).equals(expected.get(k)));
}
}
@Test
public void plusEncodingLatLngWorks() throws Exception {
final Map<String, String> expected = new HashMap<>();
expected.put("plusCode", "85634H42+HH");
expected.put("time", "");
final Map<String, String> params = new HashMap<>();
params.put("latitude", "34.10638");
params.put("longitude", "-118.44858");
expected.putAll(params);
final HttpUrl url = new HttpUrl.Builder().scheme("http").host("localhost").port(this.port)
.addPathSegment("plus").build();
final Request request = new Request.Builder().url(url).post(
RequestBody.create(PlusTests.mapper.writeValueAsString(params), MediaType.parse("application/json")))
.build();
final Response response = PlusTests.client.newCall(request).execute();
final Map<String, String> actual = PlusTests.mapper.readValue(response.body().string(),
new TypeReference<Map<String, String>>() {
});
Assert.assertTrue("plusCode incorrect", actual.get("plusCode").equals(expected.get("plusCode")));
}
@Test
public void plusEncodingLocationWorks() throws Exception {
final Map<String, String> expected = new HashMap<>();
expected.put("plusCode", "85634H43+7G");
final HttpUrl url = new HttpUrl.Builder().scheme("http").host("localhost").port(this.port)
.addPathSegment("plus").build();
final Map<String, String> body = Maps.newHashMap();
body.put("latitude", "34.1056855");
body.put("longitude", "-118.4461788");
final MediaType contentType = MediaType.parse("application/json");
final String content = PlusTests.mapper.writeValueAsString(body);
final RequestBody params = RequestBody.create(content, contentType);
final Request request = new Request.Builder().url(url).post(params).build();
final Response response = PlusTests.client.newCall(request).execute();
final String actualSrc = response.body().string();
final Map<String, String> actual = PlusTests.mapper.readValue(actualSrc,
new TypeReference<Map<String, String>>() {
});
for (String k : expected.keySet()) {
Assert.assertTrue(k + " missing", actual.containsKey(k));
Assert.assertTrue(actual.get(k) + " not " + expected.get(k), actual.get(k).equals(expected.get(k)));
}
}
@Test
public void plusEncodingOsmUrlsWorks() throws Exception {
final String content = "https://www.openstreetmap.org/#map=18/34.10568/-118.44618";
final Map<String, String> params = Collections.singletonMap("url", content);
final RequestBody body = RequestBody.create(PlusTests.mapper.writeValueAsString(params),
MediaType.parse("application/json"));
final Request request = new Request.Builder().url(
new HttpUrl.Builder().host("localhost").port(this.port).scheme("http").addPathSegment("plus").build())
.post(body).build();
final Response resp = PlusTests.client.newCall(request).execute();
final Map<String, String> response = PlusTests.mapper.readValue(resp.body().string(),
new TypeReference<Map<String, String>>() {
});
Assert.assertEquals("85634H43+7G", response.get("plusCode"));
}
@Test
public void plusEncodingRequiresCodeOrGeohashOrLocationOrUrl() throws Exception {
final String message = "addr, plusCode, geohash, latitude and longitude, ip, loc, w3w, telegram, or url required as body";
final Map<String, String> expected = Collections.singletonMap("error", message);
final RequestBody body = RequestBody.create(PlusTests.mapper.writeValueAsString(expected),
MediaType.parse("application/json"));
final Request request = new Request.Builder().url(
new HttpUrl.Builder().scheme("http").host("localhost").port(this.port).addPathSegment("plus").build())
.post(body).build();
final Response response = PlusTests.client.newCall(request).execute();
JsonNode json = mapper.readTree(response.body().byteStream());
Assert.assertEquals(response.code(), HttpStatus.OK.value());
Assert.assertEquals(json.get("error").textValue(),
"addr, plusCode, geohash, latitude and longitude, ip, loc, w3w, telegram, or url required as body");
}
@Test
public void reversePlusEncodingWorks() throws Exception {
final Map<String, String> expected = PlusTests.mapper.readValue(
"{\"request\":\"849VRH2X+68\",\"latitude\":\"37.8005625\",\"radius\":\"1.7677669530250526E-4\",\"longitude\":\"-122.40168750000001\"} ",
new TypeReference<Map<String, String>>() {
});
final Map<String, String> body = Collections.singletonMap("plusCode", "849VRH2X+68");
final RequestBody requestBody = RequestBody.create(PlusTests.mapper.writeValueAsString(body),
MediaType.parse("application/json"));
final Request request = new Request.Builder().url("http://localhost:" + this.port + "/plus").post(requestBody)
.build();
final String actualSrc = PlusTests.client.newCall(request).execute().body().string();
final Map<String, String> actual = PlusTests.mapper.readValue(actualSrc,
new TypeReference<Map<String, String>>() {
});
Assert.assertTrue("Request not correct", actual.get("request").equals(expected.get("request")));
Assert.assertTrue("Radius not correct", actual.get("radius").equals(expected.get("radius")));
Assert.assertTrue("Latitude not correct", actual.get("latitude").equals(expected.get("latitude")));
Assert.assertTrue("Longitude not correct", actual.get("longitude").equals(expected.get("longitude")));
}
@Test
public void shorterPlusCodeReturnsBothOriginalAndResult() throws Exception {
Map<String, String> bodySrc = Collections.singletonMap("plusCode", "Q6QM+7H Stuttgart, Germany");
RequestBody requestBody = RequestBody.create(mapper.writeValueAsBytes(bodySrc),
MediaType.parse("application/json"));
HttpUrl url = HttpUrl.parse("http://localhost/plus").newBuilder().port(port).build();
Request postRequest = new Request.Builder().url(url).post(requestBody).build();
JsonNode response = mapper.readTree(client.newCall(postRequest).execute().body().bytes());
Assert.assertTrue("Missing keys", response.has("plusCode") && response.has("shortPlusCode"));
Assert.assertTrue("plusCode incorrect", response.get("plusCode").asText().equals("8FWFQ6QM+7H"));
}
}
package us.d8u.balance;
import java.math.BigDecimal;
import java.util.Base64;
import java.util.Map;
import org.assertj.core.util.Lists;
import org.joda.time.DateTime;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.context.SpringBootTest.WebEnvironment;
import org.springframework.boot.web.server.LocalServerPort;
import org.springframework.test.context.junit4.SpringRunner;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.rometools.rome.feed.synd.SyndEnclosure;
import com.rometools.rome.feed.synd.SyndEnclosureImpl;
import com.rometools.rome.feed.synd.SyndEntry;
import com.rometools.rome.feed.synd.SyndEntryImpl;
import com.rometools.rome.feed.synd.SyndFeed;
import com.rometools.rome.feed.synd.SyndFeedImpl;
import com.rometools.rome.io.FeedException;
import com.rometools.rome.io.SyndFeedOutput;
import okhttp3.Headers;
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 PodcastTests {
@Autowired
private AuthRepository authRepository;
@LocalServerPort
private int port;
@Autowired
private UserRepository userRepository;
@Test
public void addPodcastWorks() throws Exception {
final HttpUrl url = HttpUrl.parse("http://localhost:" + this.port + "/podcast");
final Request request = new Request.Builder()
.addHeader("authorization", "aHdXSTQzVFBTakpFQzY4ZjoyejQwZlAzdU9uMkJSMGZYSTA1dkhjaVM=")
.patch(RequestBody.create("{}", MediaType.parse("text/json"))).url(url).build();
final Response response = new OkHttpClient.Builder().build().newCall(request).execute();
Assert.assertEquals(204, response.code());
}
@Test
public void podcastDefaultsToRecentEntriesOnly() throws Exception {
final SyndFeed feed = new SyndFeedImpl();
feed.setFeedType("atom_0.3");
feed.setLink("https://units.d8u.us/podcast");
feed.setAuthor("Units Podcast feed");
feed.setTitle("Podcasts for hdiwan");
final SyndEnclosure enc = new SyndEnclosureImpl();
enc.setUrl("http://example.com/hello.mp3");
final SyndEntry entry = new SyndEntryImpl();
entry.setTitle("hello world");
entry.setPublishedDate(DateTime.now().toDate());
entry.setEnclosures(Lists.newArrayList(enc));
feed.setEntries(Lists.newArrayList(entry));
final SyndFeedOutput out = new SyndFeedOutput();
String expected = null;
try {
expected = out.outputString(feed);
} catch (final FeedException e) {
Assert.fail(e.getLocalizedMessage());
}
UserBean myTestUser = new UserBean();
myTestUser.setName("hdiwan@mailinator.com");
myTestUser.setNumber("+12125551212");
this.userRepository.saveAndFlush(myTestUser);
final AuthBean authBean = new AuthBean();
authBean.setUser(myTestUser);
authBean.setEndpointBean(new EndpointBean("/podcast", BigDecimal.ZERO));
authBean.setAccessKey(null);
authBean.setAccessSecret(null);
final UserBean myTestUserToBeUpd8d = this.userRepository.findById(myTestUser.getUserId()).get();
myTestUserToBeUpd8d.setKeys(Lists.newArrayList(authBean));
myTestUser = this.userRepository.save(myTestUserToBeUpd8d);
final Map<String, String> data = new ObjectMapper().readValue(authBean.getData(),
new TypeReference<Map<String, String>>() {
});
if (data.isEmpty()) {
data.put("podcast.last_access", "-1");
data.put("podcast.password", "waw@wiw@");
authBean.setData(new ObjectMapper().writeValueAsString(data));
}
this.authRepository.saveAndFlush(authBean);
final Headers headers = new Headers.Builder()
.add("Authorization", new String(Base64.getEncoder().encode("hdiwan:waw@wiw@".getBytes()), "utf-8"))
.build();
final Request request = new Request.Builder().url("http://localhost:" + this.port + "/podcast").headers(headers)
.build();
final Response response = new OkHttpClient().newCall(request).execute();
Assert.assertEquals("application/atom+xml", response.header("Content-Type"));
Assert.assertEquals(expected, response.body().string());
final AuthBean finalAuth = this.authRepository.findById(authBean.getAuthId()).get();
final Map<String, String> finalData = new ObjectMapper().readValue(finalAuth.getData(),
new TypeReference<Map<String, String>>() {
});
Assert.assertTrue(!finalData.get("podcast.last_access").equals(data.get("podcast.last_access")));
this.userRepository.deleteById(myTestUser.getUserId());
this.authRepository.deleteById(authBean.getAuthId());
}
}
package us.d8u.balance;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
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.test.context.junit4.SpringRunner;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import okhttp3.HttpUrl;
import okhttp3.OkHttpClient;
import okhttp3.Request;
@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT)
public class PowerpointTests {
private static final OkHttpClient client = new OkHttpClient();
private static final ObjectMapper mapper = new ObjectMapper();
@LocalServerPort
private int port;
@Test
public void responseCorrect() throws Exception {
final HttpUrl url = HttpUrl.parse("http://localhost/powerpoint").newBuilder()
.addQueryParameter("url", "https://hd1.bitbucket.io/observer.pptx").port(this.port).build();
final JsonNode response = PowerpointTests.mapper.readTree(
PowerpointTests.client.newCall(new Request.Builder().url(url).build()).execute().body().byteStream());
Assert.assertTrue(response.get("slideCount").asInt() == 15);
Assert.assertTrue(response.get("fileSize").asLong() > 0L);
Assert.assertTrue(response.get("text").isArray() && (response.get("text").size() == 15));
}
}
package us.d8u.balance;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import org.apache.poi.xslf.usermodel.XMLSlideShow;
import org.apache.poi.xslf.usermodel.XSLFSlide;
import org.apache.poi.xslf.usermodel.XSLFTextBox;
import org.apache.poi.xslf.usermodel.XSLFTextParagraph;
import org.apache.poi.xslf.usermodel.XSLFTextRun;
import org.junit.After;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
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.test.context.junit4.SpringRunner;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import okhttp3.HttpUrl;
import okhttp3.OkHttpClient;
import okhttp3.Request;
@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT)
public class PptTests {
private static final OkHttpClient client = new OkHttpClient();
private static final ObjectMapper mapper = new ObjectMapper();
@LocalServerPort
private int port;
private File temporary;
@After
public void cleanup() {
new File("src/test/resources/" + this.temporary.getName()).delete();
}
@Before
public void createPptxPresentation() {
try {
this.temporary = File.createTempFile("units", ".pptx");
} catch (final IOException exc1) {
}
FileOutputStream fos = null;
try {
fos = new FileOutputStream("src/test/resources/" + this.temporary.getName());
this.temporary.delete();
} catch (final FileNotFoundException exc1) {
}
final XMLSlideShow ppt = new XMLSlideShow();
final XSLFSlide blankSlide = ppt.createSlide();
final XSLFTextBox shape = blankSlide.createTextBox();
final XSLFTextParagraph p = shape.addNewTextParagraph();
final XSLFTextRun r1 = p.addNewTextRun();
r1.setText("Hello world.");
try {
ppt.write(fos);
} catch (final IOException exc) {
} finally {
try {
fos.close();
ppt.close();
} catch (final IOException exc) {
}
}
}
@Test
public void textCorrect() throws Exception {
final HttpUrl url = HttpUrl.parse("http://localhost/powerpoint").newBuilder().port(this.port)
.addEncodedQueryParameter("url", "http://localhost:" + this.port + "/" + this.temporary.getName())
.build();
final JsonNode response = PptTests.mapper.readTree(
PptTests.client.newCall(new Request.Builder().url(url).build()).execute().body().byteStream());
Assert.assertTrue("Hello world.".equals(response.get("text").get(0).asText()));
Assert.assertTrue(response.get("wordCount").asInt() == 2);
Assert.assertTrue(response.get("phraseCount").asInt() == 1);
}
}
package us.d8u.balance;
import java.util.Map;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
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.test.context.junit4.SpringRunner;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.common.collect.Maps;
import okhttp3.HttpUrl;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT)
public class PrimeCheckTests {
private static final OkHttpClient client = new OkHttpClient();
@LocalServerPort
private int port;
@Test
public void compositeNumbersShowPrimeFactorization() throws Exception {
final Request request = new Request.Builder()
.url(HttpUrl.parse("http://localhost/primeCheck/25").newBuilder().port(this.port).build()).build();
final Map<String, String> response = new ObjectMapper().readValue(
PrimeCheckTests.client.newCall(request).execute().body().bytes(),
new TypeReference<Map<String, String>>() {
});
Assert.assertTrue("false".equals(response.get("isPrime")));
Assert.assertTrue("5 * 5".equals(response.get("primeFactorization")));
}
@Test
public void primeNumbersShowTrue() throws Exception {
final Request request = new Request.Builder()
.url(HttpUrl.parse("http://localhost/primeCheck/25").newBuilder().port(this.port).build()).build();
final Map<String, String> response = new ObjectMapper().readValue(
PrimeCheckTests.client.newCall(request).execute().body().bytes(),
new TypeReference<Map<String, String>>() {
});
Assert.assertTrue("true".equals(response.get("isPrime")));
}
@Test
public void sixShouldNotBePrimeAndHaveItsPrimeFactorizationReturned() throws Exception {
final Map<String, String> expected = Maps.newHashMap();
expected.put("number", "6");
expected.put("isPrime", "false");
expected.put("primeFactorization", "2, 3");
final Request request = new Request.Builder().url(new HttpUrl.Builder().scheme("http").host("localhost")
.port(this.port).addPathSegments("primeCheck/6").build()).build();
final Response response = new OkHttpClient().newCall(request).execute();
final Map<String, String> actual = new ObjectMapper().readValue(response.body().string(),
new TypeReference<Map<String, String>>() {
});
Assert.assertTrue(
actual.get("time").endsWith(" ns") && actual.get("time").replace(" ns", "").matches("[0-9]+"));
actual.remove("time");
Assert.assertEquals(expected, actual);
}
@Test
public void twoShouldBePrime() throws Exception {
final Map<String, String> expected = Maps.newHashMap();
expected.put("isPrime", "true");
expected.put("number", "2");
final Request request = new Request.Builder().url(new HttpUrl.Builder().scheme("http").host("localhost")
.port(this.port).addPathSegments("primeCheck/2").build()).build();
final Response response = new OkHttpClient().newCall(request).execute();
final Map<String, String> actual = new ObjectMapper().readValue(response.body().string(),
new TypeReference<Map<String, String>>() {
});
Assert.assertEquals(expected, actual);
}
}
package us.d8u.balance;
import java.util.Map;
import java.util.Set;
import org.apache.http.HttpStatus;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
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.test.context.junit4.SpringRunner;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ObjectNode;
import com.google.common.collect.Maps;
import com.google.common.collect.Sets;
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 QrTests {
private static final OkHttpClient client = new OkHttpClient();
private static ObjectMapper mapper = new ObjectMapper();
@LocalServerPort
private int port;
@Test
public void canDecode() throws Exception {
final HttpUrl requestUrl = HttpUrl.parse("http://localhost/qr").newBuilder().port(this.port)
.addQueryParameter("url", "https://i.ibb.co/XCfRYYd/image.png").build();
final Request request = new Request.Builder().url(requestUrl).build();
final Response rawResponse = QrTests.client.newCall(request).execute();
final JsonNode response = QrTests.mapper.readTree(rawResponse.body().string());
Assert.assertTrue("I love you in a 笶、次塾beat!".equals(response.get("text").asText()));
}
@Test
public void postQrWithText() throws Exception {
final HttpUrl requestUrl = new HttpUrl.Builder().host("localhost").scheme("http").port(this.port)
.addPathSegment("qr").build();
final Map<String, String> requestBody = Maps.newConcurrentMap();
requestBody.put("text", "foo");
final okhttp3.RequestBody body = okhttp3.RequestBody.create(new ObjectMapper().writeValueAsString(requestBody),
MediaType.parse("application/json"));
final Request request = new Request.Builder().url(requestUrl).post(body).build();
final Response rawResponse = QrTests.client.newCall(request).execute();
final String string = rawResponse.body().string();
final Map<String, String> response = QrTests.mapper.readValue(string, new TypeReference<Map<String, String>>() {
});
final Set<String> expectedKeys = Sets.newHashSet("url", "text", "time");
Assert.assertEquals(expectedKeys, response.keySet());
try {
Long.valueOf(response.get("time"));
} catch (final IllegalArgumentException e) {
Assert.fail(response.get("time") + " is not an integer.");
}
final HttpUrl imgbbUrl = HttpUrl.parse(response.get("location"));
Assert.assertTrue(imgbbUrl != null);
Assert.assertTrue("i.ibb.co".equals(imgbbUrl.host()));
Assert.assertTrue("https".equals(imgbbUrl.scheme()));
Assert.assertTrue("foo".equals(response.get("text")));
}
@Test
public void qrReturnsAppropriateResponseWithInvalidBody() throws Exception {
final HttpUrl requestUrl = HttpUrl.parse("http://localhost/qr").newBuilder().port(this.port).build();
ObjectNode body = QrTests.mapper.createObjectNode();
body.put("giveMe", "food");
final String json = QrTests.mapper.writeValueAsString(body);
final RequestBody requestBody = RequestBody.create(json, MediaType.parse("application/json"));
final Request request = new Request.Builder().url(requestUrl).post(requestBody).build();
final Response rawResponse = QrTests.client.newCall(request).execute();
body = (ObjectNode) QrTests.mapper.readTree(rawResponse.body().bytes());
Assert.assertTrue(
"Wrong status code, " + body.get("status").asText() + ", expected " + HttpStatus.SC_BAD_REQUEST,
body.get("status").asInt() == HttpStatus.SC_BAD_REQUEST);
Assert.assertTrue(
"Unexpected error message -- " + body.get("error") + ", expected \"" + body.get("error").asText()
+ "\"",
"Missing body, need \"text\" or \"tweet\" (number or twitter permalink)"
.equals(body.get("error").asText()));
}
@Test
public void qrWithInvalidUrlYieldsError() throws Exception {
final HttpUrl requestUrl = HttpUrl.parse("http://localhost/qr").newBuilder().port(this.port).build();
final Map<String, String> body = Maps.newHashMap();
body.put("url", "I love my ARFFie");
final String json = QrTests.mapper.writeValueAsString(body);
final RequestBody requestBody = RequestBody.create(json, MediaType.parse("application/json"));
final Request request = new Request.Builder().url(requestUrl).post(requestBody).build();
final Response rawResponse = QrTests.client.newCall(request).execute();
final JsonNode response = QrTests.mapper.readTree(rawResponse.body().bytes());
Assert.assertTrue(response.get("status").asInt() == 422);
Assert.assertTrue("url expected".equals(response.get("error").asText()));
}
@Test
public void qrWithTweet() throws Exception {
final HttpUrl requestUrl = HttpUrl.parse("http://localhost/qr").newBuilder().port(this.port).build();
final Map<String, String> body = Maps.newHashMap();
body.put("tweet", "1250650485205241857");
final Request request = new Request.Builder().url(requestUrl)
.post(RequestBody.create(QrTests.mapper.writeValueAsBytes(body), MediaType.parse("application/json")))
.build();
final Response rawResponse = QrTests.client.newCall(request).execute();
final JsonNode response = QrTests.mapper.readTree(rawResponse.body().bytes());
Assert.assertTrue(
"Expected \"Mapped to https://twitter.com/HasanDiwan2/status/1250650485205241857, whose text is \\\"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.\", but was "
+ response.get("text").asText(),
"Mapped to https://twitter.com/HasanDiwan2/status/1250650485205241857, whose text is \"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.\""
.equals(response.get("text").asText()));
}
@Test
public void qrWithTwitterUrl() throws Exception {
final HttpUrl requestUrl = HttpUrl.parse("http://localhost/qr").newBuilder().port(this.port).build();
final Map<String, String> body = Maps.newHashMap();
body.put("tweet", "https://twitter.com/HasanDiwan2/status/1250650485205241857");
final String json = QrTests.mapper.writeValueAsString(body);
final RequestBody requestBody = RequestBody.create(json, MediaType.parse("application/json"));
final Request request = new Request.Builder().url(requestUrl).post(requestBody).build();
final Response rawResponse = QrTests.client.newCall(request).execute();
final JsonNode response = QrTests.mapper.readTree(rawResponse.body().bytes());
Assert.assertTrue(
"Expected \"Mapped to https://twitter.com/HasanDiwan2/status/1250650485205241857, whose text is \\\"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.\", but was \"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.\"",
"Mapped to https://twitter.com/HasanDiwan2/status/1250650485205241857, whose text is \"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.\""
.equals(response.get("text").asText()));
}
@Test
public void qrWithUrlDecodes() throws Exception {
final HttpUrl requestUrl = HttpUrl.parse("http://localhost/qr").newBuilder().port(this.port).build();
final Map<String, String> body = Maps.newHashMap();
body.put("url", "https://i1.wp.com/techtutorialsx.com/wp-content/uploads/2019/12/testQRCode-1.png?w=410&ssl=1");
final String json = QrTests.mapper.writeValueAsString(body);
final RequestBody requestBody = RequestBody.create(json, MediaType.parse("application/json"));
final Request request = new Request.Builder().url(requestUrl).post(requestBody).build();
final Response rawResponse = QrTests.client.newCall(request).execute();
final JsonNode response = QrTests.mapper.readTree(rawResponse.body().bytes());
Assert.assertTrue("Use your camera for reading a QR code".equals(response.get("error").asText()));
}
@Test
public void returnsAppropriatelyForInvalidUrl() throws Exception {
final HttpUrl requestUrl = HttpUrl.parse("http://localhost/qr").newBuilder().port(this.port)
.addQueryParameter("url", "https://www.google.com").build();
final Request request = new Request.Builder().url(requestUrl).build();
final Response rawResponse = QrTests.client.newCall(request).execute();
final JsonNode response = QrTests.mapper.readTree(rawResponse.body().bytes());
Assert.assertTrue("Invalid message", "unsupported image type".equals(response.get("message").asText()));
}
}
package us.d8u.balance;
import java.util.List;
import java.util.Map;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
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.test.context.junit4.SpringRunner;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import okhttp3.HttpUrl;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT)
public class QuakeTests {
private static final OkHttpClient client = new OkHttpClient();
@LocalServerPort
private int port;
@Test
public void quakeReturnsPlusCodeGeohashAndLatLon() throws Exception {
final HttpUrl requestUrl = new HttpUrl.Builder().host("localhost").scheme("http").port(this.port)
.addPathSegment("quake").build();
final Request request = new Request.Builder().url(requestUrl).get().build();
final Response rawResponse = QuakeTests.client.newCall(request).execute();
final Map<String, List<Map<String, String>>> response = new ObjectMapper()
.readValue(rawResponse.body().string(), new TypeReference<Map<String, List<Map<String, String>>>>() {
});
for (final Map<String, String> quake : response.get("results")) {
Assert.assertTrue(quake.containsKey("plusCode") && quake.get("plusCode").startsWith("+"));
Assert.assertTrue(quake.containsKey("geohash"));
Assert.assertTrue(
quake.containsKey("latitude") && (Math.abs(Double.parseDouble(quake.get("latitude"))) < 90.0d));
Assert.assertTrue(
quake.containsKey("longitude") && (Math.abs(Double.parseDouble(quake.get("longitude"))) < 180.0d));
}
}
}
package us.d8u.balance;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Map;
import org.apache.commons.validator.routines.InetAddressValidator;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
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.test.context.junit4.SpringRunner;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.common.collect.Sets;
import com.google.common.net.InetAddresses;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT)
public class RandomTests {
private static final OkHttpClient client = new OkHttpClient();
@LocalServerPort
private int port;
@Test
public void randomGivesIntegerGaussianStringWithDefaultLengthOf10() throws Exception {
final Request request = new Request.Builder().url("http://localhost:" + this.port + "/random").build();
final Response response = RandomTests.client.newCall(request).execute();
final Map<String, String> responseMap = new ObjectMapper().readValue(response.body().string(),
new TypeReference<Map<String, String>>() {
});
Assert.assertTrue(responseMap.containsKey("integer"));
Assert.assertTrue(Long.valueOf(responseMap.get("integer")) < 10000000000L);
Assert.assertTrue(responseMap.containsKey("gaussian"));
Assert.assertTrue(responseMap.containsKey("string"));
Assert.assertEquals(10, responseMap.get("string").length());
}
@Test
public void randomGivesIntegerGaussianStringWithLengthParameter() throws Exception {
final int LENGTH = 22;
final Request request = new Request.Builder().url("http://localhost:" + this.port + "/random?length=" + LENGTH)
.build();
final Response response = RandomTests.client.newCall(request).execute();
final 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(22, responseMap.get("string").length());
}
@Test
public void randomWithAddrGivesAddressOnly() throws Exception {
final Request request = new Request.Builder().url("http://localhost:" + this.port + "/random?type=address")
.build();
final Response response = RandomTests.client.newCall(request).execute();
final Map<String, String> responseMap = new ObjectMapper().readValue(response.body().string(),
new TypeReference<Map<String, String>>() {
});
Assert.assertTrue(responseMap.keySet().equals(new HashSet<>(Arrays.asList("address"))));
}
@Test
public void randomWithBitcoin() throws Exception {
final Request request = new Request.Builder().url("http://localhost:" + this.port + "/random?type=bitcoin")
.build();
final Response response = RandomTests.client.newCall(request).execute();
final Map<String, Map<String, String>> responseMap = new ObjectMapper().readValue(response.body().string(),
new TypeReference<Map<String, Map<String, String>>>() {
});
Assert.assertTrue(responseMap.keySet().equals(new HashSet<>(Arrays.asList("btc"))));
Assert.assertTrue(responseMap.get("btc").keySet().equals(Sets.newHashSet("address", "testnetAddress")));
Assert.assertTrue(null != responseMap.get("btc").get("address"));
Assert.assertTrue(null != responseMap.get("btc").get("testnetAddress"));
}
@Test
public void randomWithDNSReturnsDomainOnly() throws Exception {
final Request request = new Request.Builder().url("http://localhost:" + this.port + "/random?type=domain")
.build();
final Response response = RandomTests.client.newCall(request).execute();
final Map<String, String> responseMap = new ObjectMapper().readValue(response.body().string(),
new TypeReference<Map<String, String>>() {
});
Assert.assertTrue(responseMap.containsKey("domain"));
Assert.assertTrue(responseMap.get("domain").getClass().equals(String.class));
Assert.assertFalse("Domain contains space", responseMap.get("domain").matches("[[:space:]]"));
Assert.assertTrue(responseMap.containsKey("ipv4"));
Assert.assertTrue(InetAddresses.isInetAddress(responseMap.get("ipv4")));
Assert.assertTrue(responseMap.containsKey("ipv6"));
Assert.assertTrue(new InetAddressValidator().isValidInet6Address(responseMap.get("ipv6")));
}
@Test
public void randomWithEmailGivesEmailOnly() throws Exception {
final Request request = new Request.Builder().url("http://localhost:" + this.port + "/random?type=email")
.build();
final Response response = RandomTests.client.newCall(request).execute();
final JsonNode responseMap = new ObjectMapper().readTree(response.body().bytes());
Assert.assertTrue(responseMap.has("email") && responseMap.get("email").asText().contains("@example."));
}
@Test
public void randomWithPhoneGivesPhoneOnly() throws Exception {
final Request request = new Request.Builder().url("http://localhost:" + this.port + "/random?type=phone")
.build();
final Response response = RandomTests.client.newCall(request).execute();
final JsonNode responseMap = new ObjectMapper().readTree(response.body().bytes());
Assert.assertTrue("key \"phone\" not found", responseMap.has("phone"));
Assert.assertTrue(responseMap.get("phone").asText() + " does not match regex",
responseMap.get("phone").asText().matches("^[-0-9. x]+$"));
}
}
package us.d8u.balance;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
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.test.context.junit4.SpringRunner;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import okhttp3.HttpUrl;
import okhttp3.OkHttpClient;
import okhttp3.Request;
@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT)
public class ReceiptTests {
static OkHttpClient client = new OkHttpClient.Builder().build();
@LocalServerPort
private int port;
@Test
public void missingAuthenticationReturnsError() throws Exception {
final HttpUrl endpoint = HttpUrl.parse("http://localhost:" + this.port + "/receipt");
final JsonNode response = new ObjectMapper().readTree(
ReceiptTests.client.newCall(new Request.Builder().url(endpoint).build()).execute().body().string());
Assert.assertTrue(response.get("status").intValue() == 401);
}
}
package us.d8u.balance;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
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.test.context.junit4.SpringRunner;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import okhttp3.HttpUrl;
import okhttp3.OkHttpClient;
import okhttp3.Request;
@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT)
public class RedditAndroidTests {
private static final OkHttpClient client = new OkHttpClient();
private static ObjectMapper mapper = new ObjectMapper();
@LocalServerPort
private int port;
@Test
public void correctMessageWithPaidLink() throws Exception {
HttpUrl underTest = HttpUrl
.parse("http://localhost/reddit/android/ukbsy5?free=com.wakdev.nfctools&paid=com.wakdev.nfctools.pro")
.newBuilder().port(this.port).build();
final JsonNode response = RedditAndroidTests.mapper.readTree(RedditAndroidTests.client
.newCall(new Request.Builder().url(underTest).build()).execute().body().byteStream());
Assert.assertTrue(
"Play Store [link](https://play.google.com/store/apps/details?id=com.wakdev.nfctools) and [paid version](https://play.google.com/store/apps/details?id=com.wakdev.nfctools.pro"
.equals(response.get("text").asText()));
underTest = HttpUrl.parse(response.get("reddit").asText());
Assert.assertNotNull(underTest);
Assert.assertTrue("www.reddit.com".equals(underTest.host()));
Assert.assertTrue("https".equals(underTest.scheme()));
Assert.assertTrue(underTest.encodedPath().startsWith("r/Android/comments/"));
}
// FIXME figure out how to test this?
@Test
public void helperOffline() throws Exception {
}
@Test
public void missingFreeKey() throws Exception {
final HttpUrl underTest = HttpUrl.parse("http://localhost/reddit/android/ukbsy5").newBuilder().port(this.port)
.build();
final JsonNode response = RedditAndroidTests.mapper.readTree(RedditAndroidTests.client
.newCall(new Request.Builder().url(underTest).build()).execute().body().byteStream());
Assert.assertTrue("free link required".equals(response.get("error").asText()));
}
}
package us.d8u.balance;
import org.apache.commons.lang3.StringUtils;
import org.joda.time.format.ISODateTimeFormat;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
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.test.context.junit4.SpringRunner;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.common.base.Joiner;
import com.google.common.collect.Sets;
import okhttp3.HttpUrl;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT)
public class RedditCommentTests {
private static final OkHttpClient client = new OkHttpClient();
@LocalServerPort
private int port;
@Test
public void commentCheckReportsWithoutAuth() throws Exception {
final HttpUrl commentCheckUrl = HttpUrl.parse("http://localhost/reddit/comments").newBuilder().port(this.port)
.addQueryParameter("user", "gabriot").build();
final Request commentCheckRequest = new Request.Builder().url(commentCheckUrl).build();
final JsonNode response = new ObjectMapper()
.readTree(RedditCommentTests.client.newCall(commentCheckRequest).execute().body().string());
Assert.assertTrue("Length parameter must be positive", response.get("length").asInt() > -1);
Assert.assertTrue("\"data\" is not a array", response.get("data").isContainerNode());
for (int i = 0; i != response.get("length").asInt(); i++) {
Assert.assertTrue("Element missing keys",
Sets.newHashSet("title", "date", "score", "content", "url", "id", "subreddit")
.equals(Sets.newHashSet(response.get("data").get(i).fieldNames())));
Assert.assertTrue("Not a url " + response.get("data").get(i).get("url").asText(),
(HttpUrl.parse(response.get("data").get(i).get("url").asText()) != null));
Assert.assertTrue("Host is incorrect",
"www.reddit.com".equals(HttpUrl.parse(response.get("data").get(i).get("url").asText()).host()));
final String path = Joiner.on('/')
.join(HttpUrl.parse(response.get("data").get(i).get("url").asText()).pathSegments());
Assert.assertTrue("Path is incorrect", path.contains("r/") && path.contains("/comments/"));
Assert.assertTrue("Title shouldn't be empty", response.get("data").get(i).get("title").asText() != null);
Assert.assertTrue("Date is not in the past", ISODateTimeFormat.dateTime()
.parseDateTime(response.get("data").get(i).get("date").asText()).isBeforeNow());
Assert.assertTrue("Score " + response.get("data").get(i).get("score").asInt() + " isn't valid",
response.get("data").get(i).get("score").asInt() < 1);
Assert.assertTrue("Time " + response.get("time").asText() + " is not in correct format",
response.get("time").asText().matches("^[0-9.]+$"));
}
}
@Test
public void commentCheckRequiresUser() throws Exception {
final HttpUrl commentCheckUrl = HttpUrl.parse("http://localhost/reddit/comments").newBuilder().port(this.port)
.build();
final Request commentCheckRequest = new Request.Builder().url(commentCheckUrl).build();
final JsonNode commentCheckResponse = new ObjectMapper()
.readTree(RedditCommentTests.client.newCall(commentCheckRequest).execute().body().string());
Assert.assertTrue("status should be 422, not " + commentCheckResponse.get("status").asInt(),
422 == commentCheckResponse.get("status").asInt());
Assert.assertTrue("\"error\" incorrect",
"comment id or username required".equals(commentCheckResponse.get("error").asText()));
}
@Test
public void commentDeleteRequestWithUserRemovesFromAskReddit() throws Exception {
if (!System.getProperties().containsKey("reddit.auth")) {
Assert.fail("need to define reddit.auth to your units' authkey");
}
if (!System.getProperties().containsKey("reddit.secret")) {
Assert.fail("need to define reddit.secret to your units' authsecret");
}
final HttpUrl commentCheckUrl = HttpUrl.parse("http://localhost/reddit/comments").newBuilder().port(this.port)
.addQueryParameter("user", "LiteratureOk7716").build();
final Request deleteRequest = new Request.Builder().url(commentCheckUrl)
.addHeader("X-Authorization",
Joiner.on(":").join(System.getProperty("reddit.auth"), System.getProperty("reddit.secret")))
.get().build();
final Response deleteResponse = RedditCommentTests.client.newCall(deleteRequest).execute();
Assert.assertTrue("X-Count header not numeric", StringUtils.isNumeric(deleteResponse.header("X-Count")));
Assert.assertTrue("X-Count value not positive",
Math.abs(Integer.parseInt(deleteResponse.header("X-Count"))) == Integer
.parseInt(deleteResponse.header("X-Count")));
}
@Test
public void commentWithIdReturnsUrlOfPostSubredditAuthorTimestampAndBody() throws Exception {
final HttpUrl commentCheckUrl = HttpUrl.parse("http://localhost/reddit/comments").newBuilder().port(this.port)
.addQueryParameter("id", "dpxi39l").build();
final Request commentCheckRequest = new Request.Builder().url(commentCheckUrl).build();
final JsonNode response = new ObjectMapper()
.readTree(RedditCommentTests.client.newCall(commentCheckRequest).execute().body().string());
Assert.assertTrue("Subreddit " + response.get("subreddit").asText() + " unexpected, expected \"MensRights\"",
"MensRights".equals(response.get("subreddit").asText()));
Assert.assertTrue("Url " + response.get("url").asText()
+ " unexpected, expected https://www.reddit.com/r/MensRights/comments/7dfz79/compulsory_military_service_in_austria/",
"https://www.reddit.com/r/MensRights/comments/7dfz79/compulsory_military_service_in_austria/"
.equals(response.get("url").asText()));
Assert.assertTrue("Author " + response.get("author").asText() + " unexpedcted, expected \"meh613\"",
"meh613".equals(response.get("author").asText()));
Assert.assertTrue(
"Date " + response.get("date").asText() + " unexpected, expected \"2017-11-16T14:23:54.000-08:00\"",
"2017-11-16T14:23:54.000-08:00".equals(response.get("date").asText()));
}
}
package us.d8u.balance;
import java.util.Arrays;
import java.util.Map;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
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 com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.common.base.Joiner;
import com.google.common.collect.Maps;
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 RedditMultiTests {
private static final OkHttpClient client = new OkHttpClient();
@LocalServerPort
private int port;
ObjectMapper mapper = new ObjectMapper();
@Test
public void multiAskRedirectsCorrectly() throws Exception {
final HttpUrl url = HttpUrl.parse("http://localhost/reddit/multi?s=ask").newBuilder().port(this.port).build();
final Request request = new Request.Builder().url(url).build();
final Response response = RedditMultiTests.client.newBuilder().followRedirects(false).build().newCall(request)
.execute();
Assert.assertTrue(
("https://www.reddit.com/r/"
+ Joiner.on("+")
.join(Arrays.asList("AskAnAmerican", "AskScience", "AskHistorians", "AskAstronomy",
"AskHistory", "AskEconomics", "askCulinary")))
.equals(response.header("Location")));
}
@Test
public void multiAuthenticatedRedirectsCorrectly() throws Exception {
final HttpUrl url = HttpUrl.parse("http://localhost/reddit/multi").newBuilder().port(this.port)
.addEncodedQueryParameter("user", "me").addEncodedQueryParameter("password", "test")
.addEncodedQueryParameter("s", "def").build();
final Response rawResponse = RedditMultiTests.client.newBuilder().followRedirects(false).build()
.newCall(new Request.Builder().url(url).build()).execute();
Assert.assertTrue("0".equals(rawResponse.header("x-last-access")));
Assert.assertTrue(rawResponse.isRedirect());
Assert.assertTrue("https://reddit.com/r/android+iphone/new".equals(rawResponse.header("location")));
}
@Test
public void multiDefReturnsRedirectsCorrectly() throws Exception {
final HttpUrl url = HttpUrl.parse("http://localhost/reddit/multi?s=def").newBuilder().port(this.port).build();
final Request request = new Request.Builder().url(url).build();
final Response response = RedditMultiTests.client.newBuilder().followRedirects(false).build().newCall(request)
.execute();
Assert.assertTrue(("https://www.reddit.com/r/"
+ Joiner.on("+").join(Arrays.asList("bestof", "depthhub", "longreads", "askReddit", "goodlongreads"))
+ "/new").equals(response.header("Location")));
Assert.assertTrue(response.code() == 302);
}
@Test
public void multiFirstRREdirectsCorrectly() throws Exception {
final HttpUrl url = HttpUrl.parse("http://localhost/reddit/multi").newBuilder().addQueryParameter("s", "First")
.port(this.port).build();
final Request request = new Request.Builder().url(url).build();
final Response response = RedditMultiTests.client.newBuilder().followRedirects(false).build().newCall(request)
.execute();
Assert.assertTrue(("https://www.reddit.com/r/" + Joiner.on("+").join(Arrays.asList("askReddit")))
.equals(response.header("Location")));
}
@Test
public void multiLaRedirectsCorrectly() throws Exception {
final HttpUrl url = HttpUrl.parse("http://localhost/reddit/multi?stored=la").newBuilder().port(this.port)
.build();
final Request request = new Request.Builder().url(url).build();
final OkHttpClient newClient = RedditMultiTests.client.newBuilder().followRedirects(false).build();
final Response response = newClient.newCall(request).execute();
Assert.assertTrue("https://www.reddit.com/r/losangeles+lalist+lar4r/new".equals(response.header("Location")));
Assert.assertTrue(response.code() == 302);
}
@Test
public void multiMobileRedirectsCorrectly() throws Exception {
final HttpUrl url = HttpUrl.parse("http://localhost/reddit/multi?s=mobile").newBuilder().port(this.port)
.build();
final Request request = new Request.Builder().url(url).build();
final OkHttpClient newClient = RedditMultiTests.client.newBuilder().followRedirects(false).build();
final Response response = newClient.newCall(request).execute();
Assert.assertTrue(
"https://www.reddit.com/r/ios+android+AndroidQuestions+tasker/new".equals(response.header("Location")));
Assert.assertTrue(response.code() == 302);
}
@Test
public void multiPostAddsToList() throws Exception {
final Map<String, String> newSub = Maps.newHashMap();
newSub.put("sub", "depthHub");
final HttpUrl url = HttpUrl.parse("http://localhost/reddit/multi/").newBuilder().port(this.port).build();
final RequestBody postBody = RequestBody.create(new ObjectMapper().writeValueAsBytes(newSub),
MediaType.parse("application/json"));
final Request postRequest = new Request.Builder().url(url).addHeader("x-authorization", "me@example.com:p@ss")
.post(postBody).build();
final Response postRawResponse = RedditMultiTests.client.newCall(postRequest).execute();
Assert.assertTrue(postRawResponse.code() == HttpStatus.OK.value());
final JsonNode postResponse = new ObjectMapper().readTree(postRawResponse.body().bytes());
Assert.assertTrue(postResponse.get("status").asInt() == HttpStatus.CREATED.value());
}
@Test
public void multiPostNeedsValidAuth() throws Exception {
final Map<String, String> newSub = Maps.newHashMap();
newSub.put("sub", "depthHub");
final HttpUrl url = HttpUrl.parse("http://localhost/reddit/multi/").newBuilder().port(this.port).build();
final RequestBody postBody = RequestBody.create(new ObjectMapper().writeValueAsBytes(newSub),
MediaType.parse("application/json"));
final Request postRequest = new Request.Builder().url(url).post(postBody).build();
final Response postRawResponse = RedditMultiTests.client.newCall(postRequest).execute();
Assert.assertTrue(postRawResponse.code() == HttpStatus.OK.value());
final JsonNode postResponse = new ObjectMapper().readTree(postRawResponse.body().bytes());
Assert.assertTrue(postResponse.get("status").asInt() == HttpStatus.UNAUTHORIZED.value());
Assert.assertTrue("x-authentication header required".equals(postResponse.get("error").asText()));
}
@Test
public void multiReturnsCreatedIfLocal() throws Exception {
final HttpUrl url = HttpUrl.parse("http://localhost/reddit/multi").newBuilder()
.addQueryParameter("user", "me@example.com").addQueryParameter("password", "p@ss")
.addEncodedQueryParameter("password", "p@ss").port(this.port).build();
final Request request = new Request.Builder().url(url).head().build();
final Response response = RedditMultiTests.client.newCall(request).execute();
final String status = response.header("x-response-status");
Assert.assertTrue("201 CREATED".equals(status));
}
@Test
public void multiReturnsErrorForNonexistentAlias() throws Exception {
final HttpUrl url = HttpUrl.parse("http://localhost/reddit/multi?stored=xxxSocialxxx").newBuilder()
.port(this.port).build();
final Request request = new Request.Builder().url(url).build();
final JsonNode response = new ObjectMapper()
.readTree(RedditMultiTests.client.newCall(request).execute().body().charStream());
String expectationFailMsg = "Unexpected status code, expected " + HttpStatus.NOT_FOUND.value()
+ ", but received " + response.get("status").asInt();
Assert.assertTrue(expectationFailMsg, response.get("status").asInt() != HttpStatus.NOT_FOUND.value());
expectationFailMsg = "\"xxxSocialxxx\" is an invalid alias on this server.";
Assert.assertTrue("invalid error message", expectationFailMsg.equals(response.get("message").asText()));
}
@Test
public void multiReturnsUnauthorizedIfNotLocal() throws Exception {
final HttpUrl url = HttpUrl.parse("http://localhost/reddit/multi?stored=xxxSocialxxx").newBuilder()
.port(this.port).build();
final Request request = new Request.Builder().url(url).header("x-forwarded-for", "me").head().build();
final Response response = RedditMultiTests.client.newCall(request).execute();
final String status = response.header("x-response-status");
Assert.assertTrue("401 UNAUTHORIZED".equals(status));
}
@Test
public void multiSexRedirectsProperly() throws Exception {
final HttpUrl url = HttpUrl.parse("http://localhost/reddit/multi?stored=sex").newBuilder().port(this.port)
.build();
final Request request = new Request.Builder().url(url).build();
final Response response = RedditMultiTests.client.newBuilder().followRedirects(false).build().newCall(request)
.execute();
Assert.assertTrue("https://www.reddit.com/r/dirtyPenpals/new".equals(response.header("Location")));
}
@Test
public void multiSocialRedirectsCorrectly() throws Exception {
final HttpUrl url = HttpUrl.parse("http://localhost/reddit/multi?stored=social").newBuilder().port(this.port)
.build();
final Request request = new Request.Builder().url(url).build();
final Response response = RedditMultiTests.client.newBuilder().followRedirects(false).build().newCall(request)
.execute();
Assert.assertTrue(
"https://www.reddit.com/r/CasualConversation+LAr4r+MakeNewFriendsHere+MeetPeople+SeriousConversation/new"
.equals(response.header("Location")));
Assert.assertTrue(response.code() == 302);
}
@Test
public void multiSportRedirectsCorrectly() throws Exception {
final HttpUrl url = HttpUrl.parse("http://localhost/reddit/multi?stored=sport").newBuilder().port(this.port)
.build();
final Request request = new Request.Builder().url(url).build();
final Response response = RedditMultiTests.client.newBuilder().followRedirects(false).build().newCall(request)
.execute();
Assert.assertTrue(("https://www.reddit.com/r/"
+ Joiner.on("+").join(
Arrays.asList("nufc", "gunners", "49ers", "warriors", "celticfc", "barca", "ajaxamsterdam"))
+ "/new").equals(response.header("Location")));
Assert.assertTrue(response.code() == 302);
}
@Test
public void rRedirectsToIndividualSubreddit() throws Exception {
final HttpUrl url = HttpUrl.parse("http://localhost/reddit/multi?r=ask").newBuilder().port(this.port).build();
final Request request = new Request.Builder().url(url).build();
final Response response = RedditMultiTests.client.newBuilder().followRedirects(false).build().newCall(request)
.execute();
Assert.assertTrue("https://www.reddit.com/r/ask/new".equals(response.header("Location")));
}
@Before
public void setup() {
System.setProperty("testing", "1");
}
}
package us.d8u.balance;
import java.io.File;
import java.util.Collections;
import java.util.Iterator;
import java.util.Map;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
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 com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ObjectNode;
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 RedditRemindTests {
private static final OkHttpClient client = new OkHttpClient();
private static final ObjectMapper mapper = new ObjectMapper();
@LocalServerPort
private int port;
@Test
public void deleteRemovesWatchedLinks() throws Exception {
ObjectNode body = mapper.createObjectNode();
body.put("url", "https://www.reddit.com/r/Barca/comments/ypxojw/match_thread_osasuna_vs_barcelona_laliga/");
RequestBody postBody = RequestBody.create(mapper.writeValueAsString(body), MediaType.parse("application/json"));
HttpUrl postUrl = HttpUrl.parse("http://localhost/reddit/remind").newBuilder().port(this.port).build();
Request postRequest = new Request.Builder().url(postUrl).post(postBody).build();
if (!client.newCall(postRequest).execute().isSuccessful()) {
Assert.fail("post failed");
}
HttpUrl deleteUrl = HttpUrl.parse("http://localhost/reddit/remind").newBuilder().port(this.port).build();
Request deleteRequest = new Request.Builder().url(deleteUrl).delete(postBody).build();
Response deleteResponse = client.newCall(deleteRequest).execute();
Assert.assertTrue("Delete failed", deleteResponse.code() == HttpStatus.NO_CONTENT.value());
deleteResponse = client.newCall(deleteRequest).execute();
Assert.assertTrue("Delete successsful", !deleteResponse.isSuccessful());
}
@Test
public void changedAndUnchangedCountsReturnedInGetRequest() throws Exception {
final HttpUrl requestUrl = HttpUrl.parse("http://localhost/reddit/remind").newBuilder().port(this.port).build();
final Request request = new Request.Builder().url(requestUrl)
.post(RequestBody.create("{}", MediaType.parse("application/json"))).build();
Response response = RedditRemindTests.client.newCall(request).execute();
Assert.assertTrue("X-OldCount missing", response.header("X-OldCount") != null);
Assert.assertTrue("X-NewCount missing", response.header("X-NewCount") != null);
Assert.assertTrue("X-OldCount not numeric", Integer.parseInt(response.header("X-OldCount")) >= 0);
Assert.assertTrue("X-NewCount not numeric", Integer.parseInt(response.header("X-NewCount")) >= 0);
}
@Test
public void remindNewUrlCleansUp() throws Exception {
String filePath = "/var/tmp/reminder.json.xz";
ObjectNode ourBody = mapper.createObjectNode();
ourBody.put("url", "https://www.reddit.com/r/Barca/comments/ypxojw/match_thread_osasuna_vs_barcelona_laliga/");
RequestBody requestBody = RequestBody.create(mapper.writeValueAsString(ourBody),
MediaType.parse("application/json"));
final HttpUrl requestUrl = HttpUrl.parse("http://localhost/reddit/remind").newBuilder().port(this.port).build();
final Request request = new Request.Builder().url(requestUrl).post(requestBody).build();
RedditRemindTests.client.newCall(request).execute();
Assert.assertTrue(filePath + " exists and shouldn't", !!new File(filePath).exists());
}
@Test
public void remindReturnsOldAndNewIfLinkFound() throws Exception {
final HttpUrl requestUrl = HttpUrl.parse("http://localhost/reddit/remind").newBuilder().port(this.port).build();
Map<String, String> requestMap = Collections.singletonMap("url",
"https://www.reddit.com/r/Barca/comments/ypxojw/match_thread_osasuna_vs_barcelona_laliga/");
final Request request = new Request.Builder().url(requestUrl)
.post(RequestBody.create(mapper.writeValueAsBytes(requestMap), MediaType.parse("application/json")))
.build();
final Response rawResponse = RedditRemindTests.client.newCall(request).execute();
final JsonNode response = mapper.readTree(rawResponse.body().charStream());
Assert.assertTrue(
"https://www.reddit.com/r/Barca/comments/ypxojw/match_thread_osasuna_vs_barcelona_laliga/ not found, but requested",
response.get("changedUrls")
.has("https://www.reddit.com/r/Barca/comments/ypxojw/match_thread_osasuna_vs_barcelona_laliga/")
|| response.get("unchangedUrls").has(
"https://www.reddit.com/r/Barca/comments/ypxojw/match_thread_osasuna_vs_barcelona_laliga/"));
}
@Test
public void remindWithEmptyBodyChecksForChanges() throws Exception {
final HttpUrl requestUrl = HttpUrl.parse("http://localhost/reddit/remind").newBuilder().port(this.port).build();
String json = "{}";
final Request request = new Request.Builder().url(requestUrl)
.post(RequestBody.create(json, MediaType.parse("application/json"))).build();
final Response rawResponse = RedditRemindTests.client.newCall(request).execute();
final JsonNode response = mapper.readTree(rawResponse.body().charStream());
Iterator<String> urlNames = response.fieldNames();
while (urlNames.hasNext()) {
String url = urlNames.next();
Assert.assertTrue(url + " isn't a proper URL", HttpUrl.parse(url) != null);
Assert.assertTrue("host isn't reddit", HttpUrl.parse(url).host().equals("www.reddit.com"));
Assert.assertTrue("comment count for " + url + "is not positive", response.get(url).asInt() > 0);
}
}
}
package us.d8u.balance;
import org.apache.commons.lang3.StringUtils;
import org.joda.time.format.ISODateTimeFormat;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.context.SpringBootTest.WebEnvironment;
import org.springframework.boot.test.web.server.LocalServerPort;
import org.springframework.test.context.junit4.SpringRunner;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ArrayNode;
import com.google.common.base.Joiner;
import com.google.common.collect.Sets;
import okhttp3.HttpUrl;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT)
public class RedditSearchTests {
private static final OkHttpClient client = new OkHttpClient();
private final ObjectMapper mapper = new ObjectMapper();
@LocalServerPort
private int port;
@Test
public void commentCheckReportsWithoutAuth() throws Exception {
final HttpUrl commentCheckUrl = HttpUrl.parse("http://localhost/reddit/search").newBuilder().port(this.port)
.addQueryParameter("user", "gabriot").build();
final Request commentCheckRequest = new Request.Builder().url(commentCheckUrl).build();
final JsonNode response = mapper
.readTree(RedditSearchTests.client.newCall(commentCheckRequest).execute().body().string());
Assert.assertTrue("Length parameter must be positive", response.get("length").asInt() > -1);
Assert.assertTrue("\"data\" is not a array", response.get("data").isContainerNode());
for (int i = 0; i != response.get("length").asInt(); i++) {
Assert.assertTrue("Element missing keys",
Sets.newHashSet("title", "date", "score", "content", "url", "id", "subreddit")
.equals(Sets.newHashSet(response.get("data").get(i).fieldNames())));
Assert.assertTrue("Not a url " + response.get("data").get(i).get("url").asText(),
(HttpUrl.parse(response.get("data").get(i).get("url").asText()) != null));
Assert.assertTrue("Host is incorrect",
"www.reddit.com".equals(HttpUrl.parse(response.get("data").get(i).get("url").asText()).host()));
final String path = Joiner.on('/')
.join(HttpUrl.parse(response.get("data").get(i).get("url").asText()).pathSegments());
Assert.assertTrue("Path is incorrect", path.contains("r/") && path.contains("/comments/"));
Assert.assertTrue("Title shouldn't be empty", response.get("data").get(i).get("title").asText() != null);
Assert.assertTrue("Date is not in the past", ISODateTimeFormat.dateTime()
.parseDateTime(response.get("data").get(i).get("date").asText()).isBeforeNow());
Assert.assertTrue("Score " + response.get("data").get(i).get("score").asInt() + " isn't valid",
response.get("data").get(i).get("score").asInt() < 1);
Assert.assertTrue("Time " + response.get("time").asText() + " is not in correct format",
response.get("time").asText().matches("^[0-9.]+$"));
}
}
@Test
public void commentCheckRequiresUser() throws Exception {
final HttpUrl commentCheckUrl = HttpUrl.parse("http://localhost/reddit/search").newBuilder().port(this.port)
.build();
final Request commentCheckRequest = new Request.Builder().url(commentCheckUrl).build();
final JsonNode commentCheckResponse = mapper
.readTree(RedditSearchTests.client.newCall(commentCheckRequest).execute().body().string());
Assert.assertTrue("status should be 422, not " + commentCheckResponse.get("status").asInt(),
422 == commentCheckResponse.get("status").asInt());
Assert.assertTrue("\"error\" incorrect",
"comment id or username required".equals(commentCheckResponse.get("error").asText()));
}
@Test
public void commentDeleteRequestWithUserRemovesFromAskReddit() throws Exception {
if (!System.getProperties().containsKey("reddit.auth")) {
Assert.fail("need to define reddit.auth to your units' authkey");
}
if (!System.getProperties().containsKey("reddit.secret")) {
Assert.fail("need to define reddit.secret to your units' authsecret");
}
final HttpUrl commentCheckUrl = HttpUrl.parse("http://localhost/reddit/search").newBuilder().port(this.port)
.addQueryParameter("user", "LiteratureOk7716").build();
final Request deleteRequest = new Request.Builder().url(commentCheckUrl)
.addHeader("X-Authorization",
Joiner.on(":").join(System.getProperty("reddit.auth"), System.getProperty("reddit.secret")))
.delete().build();
final Response deleteResponse = RedditSearchTests.client.newCall(deleteRequest).execute();
Assert.assertTrue("X-Count header not numeric", StringUtils.isNumeric(deleteResponse.header("X-Count")));
Assert.assertTrue("X-Count value not positive",
Math.abs(Integer.parseInt(deleteResponse.header("X-Count"))) == Integer
.parseInt(deleteResponse.header("X-Count")));
}
@Test
public void commentWithIdReturnsUrlOfPostSubredditAuthorTimestampAndBody() throws Exception {
final HttpUrl commentCheckUrl = HttpUrl.parse("http://localhost/reddit/search").newBuilder().port(this.port)
.addQueryParameter("id", "dpxi39l").build();
final Request commentCheckRequest = new Request.Builder().url(commentCheckUrl).build();
final JsonNode response = mapper
.readTree(RedditSearchTests.client.newCall(commentCheckRequest).execute().body().string());
Assert.assertTrue("Subreddit " + response.get("subreddit").asText() + " unexpected, expected \"MensRights\"",
"MensRights".equals(response.get("subreddit").asText()));
Assert.assertTrue("Url " + response.get("url").asText()
+ " unexpected, expected https://www.reddit.com/r/MensRights/comments/7dfz79/compulsory_military_service_in_austria/",
"https://www.reddit.com/r/MensRights/comments/7dfz79/compulsory_military_service_in_austria/"
.equals(response.get("url").asText()));
Assert.assertTrue("Author " + response.get("author").asText() + " unexpedcted, expected \"meh613\"",
"meh613".equals(response.get("author").asText()));
Assert.assertTrue(
"Date " + response.get("date").asText() + " unexpected, expected \"2017-11-16T14:23:54.000-08:00\"",
"2017-11-16T14:23:54.000-08:00".equals(response.get("date").asText()));
}
@Test
public void idReturnsIndividualPost() throws Exception {
HttpUrl idUrl = HttpUrl.parse("http://localhost/reddit/search").newBuilder().port(port)
.addQueryParameter("id", "t3_10x4ke8").build();
Request idRequest = new Request.Builder().url(idUrl).build();
JsonNode response = mapper.readTree(client.newCall(idRequest).execute().body().charStream());
Assert.assertTrue("Author not AutoModerator", response.get("author").asText().equals("AutoModerator"));
Assert.assertTrue("subreddit not AskHistorians", response.get("subreddit").asText().equals("AskHistorians"));
Assert.assertTrue("Date not in ISO format",
ISODateTimeFormat.dateTimeNoMillis().parseDateTime(response.get("date").asText()) != null);
Assert.assertTrue("url not valid", HttpUrl.parse(response.get("url").asText()) != null);
}
@Test
public void isSortedByDate() throws Exception {
final HttpUrl commentCheckUrl = HttpUrl.parse("http://localhost/reddit/search").newBuilder().port(this.port)
.addQueryParameter("user", "gabriot").build();
final Request commentCheckRequest = new Request.Builder().url(commentCheckUrl).build();
final JsonNode response = mapper
.readTree(RedditSearchTests.client.newCall(commentCheckRequest).execute().body().string());
ArrayNode usersSubmissions = (ArrayNode) response.get("response");
for (int i = 0; i != usersSubmissions.size() - 1; i++) {
JsonNode thisNode = usersSubmissions.get(i);
JsonNode nextNode = usersSubmissions.get(i + 1);
org.joda.time.DateTime thisDate = ISODateTimeFormat.dateTimeNoMillis()
.parseDateTime(thisNode.get("date").asText());
org.joda.time.DateTime nextDate = ISODateTimeFormat.dateTimeNoMillis()
.parseDateTime(nextNode.get("date").asText());
Assert.assertTrue(thisNode.get("date").asText() + " is not after " + nextNode.get("date").asText(),
thisDate.isAfter(nextDate));
}
}
}
package us.d8u.balance;
import java.util.Iterator;
import java.util.Map;
import java.util.regex.Pattern;
import org.assertj.core.util.Lists;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
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.test.context.junit4.SpringRunner;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ArrayNode;
import com.google.common.collect.Sets;
import okhttp3.HttpUrl;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT)
public class RedditTests {
private static final OkHttpClient client = new OkHttpClient();
@LocalServerPort
private int port;
@Test
public void headRequest() throws Exception {
final HttpUrl requestUrl = new HttpUrl.Builder().host("localhost").scheme("http").port(this.port)
.addPathSegment("reddit").build();
final Request request = new Request.Builder().url(requestUrl).head().build();
final Response response = RedditTests.client.newCall(request).execute();
final JsonNode responseObj = new ObjectMapper().readValue(response.body().string(), JsonNode.class);
Assert.assertTrue("responseObj is not valid!",
!responseObj.isNull() || responseObj.has("expired") || responseObj.has("changed"));
if (responseObj.has("expired")) {
ArrayNode expiredNodes = (ArrayNode) responseObj.get("expired");
Iterator<JsonNode> urlsIterator = expiredNodes.elements();
do {
String url = urlsIterator.next().asText();
Assert.assertTrue(url + "is ont a valid url", HttpUrl.parse(url) != null);
} while (urlsIterator.hasNext());
}
if (responseObj.has("changed")) {
ArrayNode changedNodes = (ArrayNode) responseObj.get("changed");
Iterator<JsonNode> urlsIterator = changedNodes.elements();
do {
String url = urlsIterator.next().asText();
Assert.assertTrue(url + "is ont a valid url", HttpUrl.parse(url) != null);
} while (urlsIterator.hasNext());
}
}
@Test
public void redditTopLevelApiKeysStartWithNumbersLackUnderscores() throws Exception {
final HttpUrl requestUrl = new HttpUrl.Builder().host("localhost").scheme("http").port(this.port)
.addPathSegment("reddit").build();
final Request request = new Request.Builder().url(requestUrl).build();
final Response response = RedditTests.client.newCall(request).execute();
final JsonNode responseObj = new ObjectMapper().readValue(response.body().string(), JsonNode.class);
final Pattern pattern = Pattern.compile("^(\\d+.*)");
for (final String k : Lists.newArrayList(responseObj.fieldNames())) {
Assert.assertFalse("snake case found at " + k, k.contains("_"));
if (k == "request") {
continue;
}
Assert.assertTrue(k + " does not begin with a digit", pattern.matcher(k).matches());
}
}
@Test
public void subredditDoesNotExist() throws Exception {
final HttpUrl requestUrl = new HttpUrl.Builder().host("localhost").scheme("http").port(this.port)
.addPathSegment("reddit").addPathSegment("q").build();
final Request request = new Request.Builder().url(requestUrl).build();
final Response rawResponse = RedditTests.client.newCall(request).execute();
final String string = rawResponse.body().string();
final 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 subredditStatusForDepthhub() throws Exception {
final HttpUrl requestUrl = new HttpUrl.Builder().host("localhost").scheme("http").port(this.port)
.addPathSegment("reddit").addPathSegment("depthhub").build();
final Request request = new Request.Builder().url(requestUrl).build();
final Response rawResponse = RedditTests.client.newCall(request).execute();
final String string = rawResponse.body().string();
final 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 subredditStatusForFroenlegzos() throws Exception {
final HttpUrl requestUrl = new HttpUrl.Builder().host("localhost").scheme("http").port(this.port)
.addPathSegment("reddit").addPathSegment("froenlegzos").build();
final Request request = new Request.Builder().url(requestUrl).build();
final Response rawResponse = RedditTests.client.newCall(request).execute();
final String string = rawResponse.body().string();
final 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 {
final HttpUrl requestUrl = new HttpUrl.Builder().host("localhost").scheme("http").port(this.port)
.addPathSegment("reddit").addPathSegment("GreatAwakening").build();
final Request request = new Request.Builder().url(requestUrl).build();
final Response rawResponse = RedditTests.client.newCall(request).execute();
final String string = rawResponse.body().string();
final 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 subredditStatusForOperationGetSmash() throws Exception {
final HttpUrl requestUrl = new HttpUrl.Builder().host("localhost").scheme("http").port(this.port)
.addPathSegment("reddit").addPathSegment("the_donald").build();
final Request request = new Request.Builder().url(requestUrl).build();
final Response rawResponse = RedditTests.client.newCall(request).execute();
final String string = rawResponse.body().string();
final 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 {
final HttpUrl requestUrl = new HttpUrl.Builder().host("localhost").scheme("http").port(this.port)
.addPathSegment("reddit").addPathSegment("the_donald").build();
final Request request = new Request.Builder().url(requestUrl).build();
final Response rawResponse = RedditTests.client.newCall(request).execute();
final String string = rawResponse.body().string();
final 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"));
}
}
package us.d8u.balance;
import org.joda.time.DateTime;
import org.joda.time.MutableDateTime;
import org.joda.time.format.DateTimeFormat;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
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.test.context.junit4.SpringRunner;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import okhttp3.HttpUrl;
import okhttp3.OkHttpClient;
import okhttp3.Request;
@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT)
public class RemindTests {
private static final OkHttpClient client = new OkHttpClient();
@LocalServerPort
private int port;
@Test
public void fromCustomMessage() throws Exception {
final HttpUrl url = HttpUrl.parse("http://localhost/remind").newBuilder().port(this.port)
.addQueryParameter("message", "hello world").addQueryParameter("testing", "1").build();
final Request request = new Request.Builder().url(url).build();
final JsonNode response = new ObjectMapper()
.readTree(RemindTests.client.newCall(request).execute().body().string());
final MutableDateTime remindmeTime = MutableDateTime.now();
Assert.assertTrue(response.get("date").asText()
.equals(DateTimeFormat.forPattern("dd MM yyyy HH:mm").print(remindmeTime.toDateTime())));
Assert.assertTrue(
response.get("description").asText().equals("You have an event, \"hello world\", in 15 minutes"));
}
@Test
public void fromCustomTime() throws Exception {
final HttpUrl url = HttpUrl.parse("http://localhost/remind").newBuilder().port(this.port)
.addQueryParameter("time", "15").addQueryParameter("testing", "1").build();
final Request request = new Request.Builder().url(url).build();
final JsonNode response = new ObjectMapper()
.readTree(RemindTests.client.newCall(request).execute().body().string());
final MutableDateTime remindmeTime = MutableDateTime.now();
Assert.assertTrue(response.get("date").asText()
.equals(DateTimeFormat.forPattern("dd MM yyyy HH:mm").print(remindmeTime.toDateTime())));
Assert.assertTrue(response.get("description").asText().equals("You have an event in 15 minutes"));
}
@Test
public void fromDefaults() throws Exception {
final HttpUrl url = HttpUrl.parse("http://localhost/remind").newBuilder().port(this.port)
.addEncodedQueryParameter("when", "2021-11-06T17:00").addEncodedQueryParameter("testing", "1").build();
final Request request = new Request.Builder().url(url).build();
final JsonNode response = new ObjectMapper()
.readTree(RemindTests.client.newCall(request).execute().body().string());
final DateTime remindmeTime = DateTime.now();
Assert.assertTrue(response.get("date").asText()
.equals(DateTimeFormat.forPattern("dd MM yyyy HH:mm").print(remindmeTime.plusMinutes(5).toDateTime())));
Assert.assertTrue(response.get("description").asText().equals("You have an event in 5 minutes"));
}
}
package us.d8u.balance;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
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 okhttp3.HttpUrl;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT)
public class ResumeTests {
private static final OkHttpClient client = new OkHttpClient();
@LocalServerPort
private int port;
@Test
public void locationAndResponseCodeCorrectForCv() throws Exception {
final HttpUrl urlUnderTest = HttpUrl.parse("http://localhost/cv").newBuilder().port(this.port).build();
Response response = ResumeTests.client.newBuilder().followRedirects(false).build()
.newCall(new Request.Builder().url(urlUnderTest).build()).execute();
Assert.assertTrue("Status code " + response.code() + " unexpected",
HttpStatus.TEMPORARY_REDIRECT.value() == response.code());
final String location = response.header("Location");
Assert.assertTrue("Location \"" + location + "\" is not expected",
"https://hd1.bitbucket.io/CV.pdf".equals(location));
response = ResumeTests.client.newCall(new Request.Builder().url(location).build()).execute();
Assert.assertTrue("URL " + location + " invalid!", response.isSuccessful());
}
@Test
public void locationAndResponseCodeCorrectForResume() throws Exception {
final HttpUrl urlUnderTest = HttpUrl.parse("http://localhost/resume").newBuilder().port(this.port).build();
Response response = ResumeTests.client.newBuilder().followRedirects(false).build()
.newCall(new Request.Builder().url(urlUnderTest).build()).execute();
Assert.assertTrue("Status code " + response.code() + " unexpected",
HttpStatus.TEMPORARY_REDIRECT.value() == response.code());
final String location = response.header("Location");
Assert.assertTrue("Location \"" + location + "\" is not expected",
"https://hd1.bitbucket.io/zaf.pdf".equals(location));
response = ResumeTests.client.newCall(new Request.Builder().url(location).build()).execute();
Assert.assertTrue("URL " + location + " invalid!", response.isSuccessful());
}
}
package us.d8u.balance;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
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.test.context.junit4.SpringRunner;
import okhttp3.HttpUrl;
import okhttp3.OkHttpClient;
import okhttp3.Request;
@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT)
public class RobotsTxtTests {
static final OkHttpClient client = new OkHttpClient();
@LocalServerPort
int port;
@Test
public void working() throws Exception {
final String expected = "User-agent: *\nDisallow: /";
final HttpUrl url = HttpUrl.parse("http://localhost:" + this.port + "/robots.txt");
final String actual = RobotsTxtTests.client.newCall(new Request.Builder().url(url).build()).execute().body()
.string();
Assert.assertTrue(expected.equals(actual));
}
}
package us.d8u.balance;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
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 com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import okhttp3.HttpUrl;
import okhttp3.OkHttpClient;
import okhttp3.Request;
@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT)
public class RoutableTests {
private static final OkHttpClient client = new OkHttpClient();
private static final ObjectMapper mapper = new ObjectMapper();
@LocalServerPort
private int port;
@Test
public void invalidParameters() throws Exception {
final HttpUrl url = HttpUrl.parse("http://localhost/isRoutable").newBuilder().port(this.port).build();
final JsonNode response = RoutableTests.mapper.readTree(
RoutableTests.client.newCall(new Request.Builder().url(url).build()).execute().body().byteStream());
Assert.assertTrue("Missing or invalid ip address".equals(response.get("error").asText()));
Assert.assertTrue(response.get("status").asText().equals(Integer.toString(HttpStatus.BAD_REQUEST.value())));
}
@Test
public void ipv4WithoutSubnet() throws Exception {
final HttpUrl url = HttpUrl.parse("http://localhost/isRoutable").newBuilder().port(this.port)
.addQueryParameter("ipv4", "54.193.214.117").build();
final JsonNode response = RoutableTests.mapper.readTree(
RoutableTests.client.newCall(new Request.Builder().url(url).build()).execute().body().byteStream());
Assert.assertTrue("netmask missing".equals(response.get("error").asText()));
Assert.assertTrue(response.get("status").asText().equals(Integer.toString(HttpStatus.BAD_REQUEST.value())));
}
@Test
public void ipv6ReturnsPending() throws Exception {
final HttpUrl url = HttpUrl.parse("http://localhost/isRoutable").newBuilder().port(this.port)
.addQueryParameter("ipv6", "0:0:0:0:0:0").build();
final JsonNode response = RoutableTests.mapper.readTree(
RoutableTests.client.newCall(new Request.Builder().url(url).build()).execute().body().byteStream());
Assert.assertTrue("Functionality not yet implemented".equals(response.get("error").asText()));
Assert.assertTrue(response.get("status").asText().equals(Integer.toString(HttpStatus.NOT_IMPLEMENTED.value())));
}
@Test
public void properRequest() throws Exception {
final HttpUrl url = HttpUrl.parse("http://localhost/isRoutable").newBuilder().port(this.port)
.addQueryParameter("ipv4", "54.193.214.117").addEncodedQueryParameter("netmask", "255.255.255.221")
.build();
final JsonNode response = RoutableTests.mapper.readTree(
RoutableTests.client.newCall(new Request.Builder().url(url).build()).execute().body().byteStream());
Assert.assertTrue("2".equals(response.get("addressCount").asText()));
Assert.assertTrue("[\"54.193.214.117\",\"54.193.214.118\"]".equals(response.get("addresses").asText()));
Assert.assertTrue("54.193.214.117-54.193.214.118".equals(response.get("subnetRange").asText()));
}
}
package us.d8u.balance;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
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.test.context.junit4.SpringRunner;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.common.collect.Sets;
import okhttp3.HttpUrl;
import okhttp3.OkHttpClient;
import okhttp3.Request;
@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT)
public class RoutingTests {
private static final OkHttpClient client = new OkHttpClient();
public static final ObjectMapper mapper = new ObjectMapper();
@LocalServerPort
private int port;
@Test
public void nonnumericPointsGiveError() throws Exception {
final var urlUnderTest = HttpUrl.parse("http://localhost/directions").newBuilder().port(this.port)
.addQueryParameter("p1", "13.388860,52.517037")
.addQueryParameter("p2", "37 Lagoon Vista Rd, Riburon, California 94920, USA").build();
final var directions = RoutingTests.mapper.readTree(RoutingTests.client
.newCall(new Request.Builder().url(urlUnderTest).build()).execute().body().byteStream());
Assert.assertTrue("numerical points supported".equals(directions.get("error").asText()));
}
@Test
public void withLatLng() throws Exception {
final var urlUnderTest = HttpUrl.parse("http://localhost/directions").newBuilder().port(this.port)
.addQueryParameter("p1", "13.388860,52.517037").addQueryParameter("p2", "13.385983,52.496891").build();
final var directions = RoutingTests.mapper.readTree(RoutingTests.client
.newCall(new Request.Builder().url(urlUnderTest).build()).execute().body().byteStream());
Assert.assertTrue("Missing key - \"steps\"", directions.has("steps") && directions.get("steps").isArray());
for (final JsonNode step : directions.get("steps")) {
Assert.assertTrue("street missing", step.has("street") && !step.get("street").isNull());
Assert.assertTrue("start coordinte missing", step.has("startLocation"));
Assert.assertTrue("start coordinte misformatted",
step.get("startLocation").asText().matches("^[0-9.]+,[0-9.]+$"));
Assert.assertTrue("distance missing", step.has("distance"));
Assert.assertTrue("distance misformatted", step.get("distance").isIntegralNumber());
Assert.assertTrue("bearing missing", step.has("bearing"));
Assert.assertTrue("bearing misformatted", Math.abs(step.get("bearing").asDouble()) < 360);
Assert.assertTrue("time missing", step.has("time"));
Assert.assertTrue("time misformatted", step.get("time").isIntegralNumber());
Assert.assertTrue("turns missing", step.has("turns") && step.get("turns").isArray());
Assert.assertTrue("extra keys found",
Sets.newHashSet("startLocation", "distance", "bearing", "turns", "time").iterator()
.equals(step.fieldNames()));
}
}
}
package us.d8u.balance;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
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 com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import net.fortuna.ical4j.data.CalendarBuilder;
import okhttp3.HttpUrl;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT)
public class Rss2IcalTests {
private static final OkHttpClient client = new OkHttpClient();
static ObjectMapper mapper = new ObjectMapper();
@LocalServerPort
private int port;
@Test
public void bbcnewsWorks() throws Exception {
final HttpUrl url = HttpUrl.parse("http://localhost:" + this.port + "/rss2calendar").newBuilder()
.addQueryParameter("url", "https://www.bbc.co.uk/blogs/theeditors/rss.xml").build();
final Response response = Rss2IcalTests.client.newCall(new Request.Builder().url(url).build()).execute();
final String responseAsVcal = response.body().string();
new CalendarBuilder();
Assert.assertTrue(responseAsVcal.contains("SUMMARY:The Editors' blog is moving"));
Assert.assertTrue(responseAsVcal.contains(
"DESCRIPTION:As of Thursday\\, the Editors' blog will move to a different address on the BBC News website. While this page will no longer be updated\\, it will stay here for reference."));
}
@Test
public void invalidUrlSaysAsMuch() throws Exception {
final HttpUrl url = HttpUrl.parse("http://localhost:" + this.port + "/rss2calendar").newBuilder()
.addQueryParameter("url", "ye fuckin' fool, I ain't no URL").build();
final Response rawResponse = Rss2IcalTests.client.newCall(new Request.Builder().url(url).build()).execute();
final JsonNode response = Rss2IcalTests.mapper.readTree(rawResponse.body().bytes());
Assert.assertTrue(response.get("status").asInt() == HttpStatus.BAD_REQUEST.value());
}
}
package us.d8u.balance;
import org.apache.http.HttpStatus;
import org.joda.time.DateTime;
import org.joda.time.format.ISODateTimeFormat;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
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.test.context.junit4.SpringRunner;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ObjectNode;
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 ScheduleTests {
private final OkHttpClient client = new OkHttpClient.Builder().build();
private final ObjectMapper mapper = new ObjectMapper();
@LocalServerPort
private int port;
@Test
public void postScheduleWorksProperly() throws Exception {
final HttpUrl url = HttpUrl.parse("http://localhost:" + this.port + "/schedule");
final ObjectNode bodySrc = this.mapper.createObjectNode();
bodySrc.put("when", ISODateTimeFormat.dateTimeNoMillis().print(DateTime.now().plusMinutes(15)));
bodySrc.put("what", "test appointment");
bodySrc.put("who", "myself@mailinator.com");
bodySrc.put("where", "1600 Penssylvania Avenue");
final String body = this.mapper.writeValueAsString(bodySrc);
final Request rawRequest = new Request.Builder().url(url)
.post(RequestBody.create(body, MediaType.parse("application/json"))).build();
final JsonNode response = this.mapper.readTree(this.client.newCall(rawRequest).execute().body().charStream());
Assert.assertTrue(!response.isNull());
}
@Test
public void scheduleWorksProperly() throws Exception {
final HttpUrl url = HttpUrl.parse("http://localhost:" + this.port + "/schedule");
final Response rawHttpResponse = this.client.newCall(new Request.Builder().url(url).build()).execute();
Assert.assertTrue("Wrong response code -- " + rawHttpResponse.code(),
rawHttpResponse.code() == HttpStatus.SC_OK);
Assert.assertTrue("Wrong location header -- " + rawHttpResponse.request().url().toString(),
"https://whereishasan.herokuapp.com/schedule".equals(rawHttpResponse.request().url().toString()));
this.client.newCall(new Request.Builder().url(url).build()).execute();
}
@Test
public void scheduleWorksProperlyWithSrcParameter() throws Exception {
final HttpUrl url = HttpUrl.parse("http://localhost:" + this.port + "/schedule?src=home");
final Response rawHttpResponse = this.client.newCall(new Request.Builder().url(url).build()).execute();
Assert.assertTrue("Wrong response code -- " + rawHttpResponse.code(),
rawHttpResponse.code() == HttpStatus.SC_OK);
Assert.assertTrue("Wrong location header -- " + rawHttpResponse.request().url().toString(),
"https://whereishasan.herokuapp.com/schedule".equals(rawHttpResponse.request().url().toString()));
this.client.newCall(new Request.Builder().url(url).build()).execute();
}
}
package us.d8u.balance;
import java.util.Map;
import org.codehaus.plexus.util.StringUtils;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
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.test.context.junit4.SpringRunner;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import okhttp3.HttpUrl;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT)
public class SDRTests {
private static final OkHttpClient client = new OkHttpClient();
private static ObjectMapper mapper = new ObjectMapper();
@LocalServerPort
private int port;
@Test
public void sdrReturnsCorrectFormat() throws Exception {
final HttpUrl requestUrl = new HttpUrl.Builder().host("localhost").scheme("http").port(this.port)
.addPathSegments("sdr").build();
final Request request = new Request.Builder().url(requestUrl).get().build();
final Response rawResponse = SDRTests.client.newCall(request).execute();
final Map<String, String> response = SDRTests.mapper.readValue(rawResponse.body().string(),
new TypeReference<Map<String, String>>() {
});
for (final Map.Entry<String, String> item : response.entrySet()) {
final String k = item.getKey();
Assert.assertEquals(k, StringUtils.capitalise(k));
final String v = item.getValue();
Assert.assertTrue(v.matches("^[0-9.,]+$"));
}
}
}
package us.d8u.balance;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
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.test.context.junit4.SpringRunner;
import okhttp3.HttpUrl;
import okhttp3.OkHttpClient;
import okhttp3.Request;
@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT)
public class SfPythonTests {
private static final OkHttpClient client = new OkHttpClient.Builder().followRedirects(false)
.followSslRedirects(false).build();
@LocalServerPort
private int port;
@Test
public void noparamsYieldsSlack() throws Exception {
final HttpUrl url = HttpUrl.parse("http://localhost/sfpython").newBuilder().port(this.port).build();
final String locationHdr = SfPythonTests.client.newCall(new Request.Builder().url(url).build()).execute()
.header("location");
Assert.assertTrue("https://sfpythonmeetup.slack.com/".equals(locationHdr));
}
@Test
public void remoParamYieldsRemo() throws Exception {
final HttpUrl url = HttpUrl.parse("http://localhost/sfpython").newBuilder().port(this.port)
.addEncodedQueryParameter("svc", "remo").build();
final String locationHdr = SfPythonTests.client.newCall(new Request.Builder().url(url).build()).execute()
.header("location");
Assert.assertTrue(locationHdr.startsWith("https://live.remo.co/e/sf-python-"));
}
}
package us.d8u.balance;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.text.NumberFormat;
import java.text.ParseException;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import org.apache.commons.lang3.ArrayUtils;
import org.joda.time.DateTime;
import org.joda.time.format.ISODateTimeFormat;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
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 com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ObjectNode;
import com.google.common.base.Splitter;
import com.google.common.collect.Iterables;
import com.google.common.collect.Maps;
import com.google.common.collect.Sets;
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 SharedTests {
static OkHttpClient client = new OkHttpClient();
static ObjectMapper mapper = new ObjectMapper();
private final Integer CLICKS_POSITION = 0, EMAIL_POSITION = 1, URL_POSITION = 2, TIME_POSITION = 3;
@Value("${api.links.helper}")
private String LINKS_DB;
@LocalServerPort
private int port;
@Value(value = "${api.diffbot}")
private String TOKEN_FOR_DIFFBOT;
@Test
public void dailyReportConstructedProperly() throws Exception {
final HttpUrl url = HttpUrl.parse("http://localhost:" + this.port + "/shared").newBuilder().build();
final Request request = new Request.Builder().url(url).head().addHeader("x-testing", "1").build();
final Response response = SharedTests.client.newCall(request).execute();
Assert.assertTrue(
"https://twitter.com/HasanDiwan2/status/1420932148811296768".equals(response.header("x-twitter-link")));
Assert.assertTrue(response.header("x-twitter-tweet")
.matches("On " + ISODateTimeFormat.date().print(DateTime.now().minusDays(1))
+ ", I shared [0-9] links to [0-9] people, of which [0-9] were clicked."));
}
@Test
public void deleteReturnsCountsWithoutLinkId() throws Exception {
HttpUrl url = HttpUrl.parse("http://localhost:" + this.port + "/shared").newBuilder().build();
Request request = new Request.Builder().url(url).delete().build();
Response response = SharedTests.client.newCall(request).execute();
Assert.assertTrue(Integer.valueOf(response.header("X-Count")) > -1);
final String sql = "SELECT COUNT(id) as count FROM applicationlogs WHERE read_on < now() - interval '90 days'";
url = url.newBuilder().encodedPath("/sql").addQueryParameter("jdbcUrl", this.LINKS_DB)
.addQueryParameter("driverClass", "org.postgresql.Driver").addQueryParameter("stmt", sql).build();
request = new Request.Builder().url(url).get().build();
response = SharedTests.client.newCall(request).execute();
final String responseAsJson = response.body().string();
final JsonNode json = SharedTests.mapper.readTree(responseAsJson);
Assert.assertTrue(json.get("results").get("count").asInt() > -1);
}
@Test
public void deleteReturnsZeroCountIfLinkIdNotValid() throws Exception {
final HttpUrl url = HttpUrl.parse("http://localhost:" + this.port + "/shared").newBuilder()
.addQueryParameter("link", "-1").build();
final Request request = new Request.Builder().url(url).delete().addHeader("x-forwarded-for", "107.184.228.7")
.build();
final Response response = SharedTests.client.newCall(request).execute();
final String responseAsJson = response.body().string();
final JsonNode json = SharedTests.mapper.readTree(responseAsJson);
Assert.assertTrue("-1".equals(json.get("entryId").asText()));
Assert.assertTrue(json.get("count").asInt() == 0);
}
@Test
public void deleteShareReturnsTotalCountForGreaterThanMonthsAgo() throws Exception {
Integer expectedThreeMonthOldCount = null;
Connection heroku = null;
try {
heroku = DriverManager.getConnection(
"jdbc:postgresql://ec2-174-129-253-174.compute-1.amazonaws.com/dfgnf32vnkq9bg?ssl=true",
"hqocfzgmvbuzhn", "3e53d6c65b40fd1d2e5c5479ab0efbe5e544116de0f821a82f856ec3c595d3b9");
final ResultSet herokuResults = heroku.createStatement().executeQuery(
"select count(id) from applicationlogs where metadata->>'app_id' = 'balance' or read_on < 'now'::timestamp -'3 month'::interval");
expectedThreeMonthOldCount = herokuResults.getInt(1);
heroku.close();
} catch (final SQLException e) {
Assert.fail("Can't get to logging database on heroku");
} finally {
if (null != heroku) {
heroku.close();
}
}
final HttpUrl endpoint = HttpUrl.parse("http://localhost:" + this.port + "/shared/");
final Request request = new Request.Builder().url(endpoint).build();
final Response rawResponse = SharedTests.client.newCall(request).execute();
final String realThreeMonthOldCount = rawResponse.header("X-Count");
Assert.assertEquals("Default delete doesn't work", expectedThreeMonthOldCount,
Integer.valueOf(realThreeMonthOldCount));
}
@Test
public void diffbotWithOkHttp() throws Exception {
final HttpUrl baseUrl = HttpUrl.parse("https://api.diffbot.com/v3/article").newBuilder()
.addEncodedQueryParameter("discussion", "false").addEncodedQueryParameter("paging", "false")
.addEncodedQueryParameter("timeout", "50000").addQueryParameter("token", this.TOKEN_FOR_DIFFBOT)
.addQueryParameter("url", "https://thebulwark.com/what-the-hell-happened-to-the-claremont-institute/")
.build();
final okhttp3.Request request = new okhttp3.Request.Builder().url(baseUrl).get().build();
final okhttp3.Response rawResponse = SharedTests.client.newCall(request).execute();
final JsonNode response = SharedTests.mapper.readTree(rawResponse.body().charStream());
Assert.assertTrue(!response.get("objects").get(0).get("html").isNull());
}
@Test
public void domainlessEmailThrowsError() throws Exception {
final ObjectNode body = SharedTests.mapper.createObjectNode();
body.put("recipient", "reddhimitragmail.com");
body.put("link",
"https://www.reddit.com/r/AskLosAngeles/comments/wkdr7d/recommendations_for_the_best_wagyu_place/");
final HttpUrl url = HttpUrl.parse("http://localhost:" + this.port + "/shared").newBuilder().build();
final Request request = new Request.Builder().url(url)
.post(RequestBody.create(SharedTests.mapper.writeValueAsBytes(body))).build();
final JsonNode response = SharedTests.mapper
.readTree(SharedTests.client.newCall(request).execute().body().charStream());
Assert.assertTrue("status not correct " + response.get("status"),
response.get("status").asInt() == HttpStatus.BAD_REQUEST.value());
Assert.assertTrue("error message not correct -- " + response.get("error"),
"email address invalid".equals(response.get("error").asText()));
}
@Test
public void getDoesNotReturnNoLinks() throws Exception {
final HttpUrl url = HttpUrl.parse("http://localhost:" + this.port + "/shared?fmt=json");
final Request request = new Request.Builder().url(url).delete().build();
final JsonNode response = SharedTests.mapper
.readTree(SharedTests.client.newCall(request).execute().body().bytes());
Assert.assertTrue(!response.isNull());
}
@Test
public void getReturnsCsvWithoutRecipientsIfUnauthorized() throws Exception {
final HttpUrl url = HttpUrl.parse("http://localhost:" + this.port + "/shared").newBuilder()
.addQueryParameter("port", Integer.toString(this.port)).build();
final Request request = new Request.Builder().url(url).build();
final Response response = SharedTests.client.newCall(request).execute();
final String body = response.body().string();
Assert.assertTrue("time not found", NumberFormat.getIntegerInstance().parse(body.split(" ")[0]).intValue() > 0);
final String[] lines = Iterables.toArray(
Splitter.on("\n").split(body.substring(body.indexOf(System.lineSeparator()) + 1)), String.class);
Assert.assertTrue("\"Click Count\",\"Recipient\",\"Target\",\"Minutes Since Sending\"".equals(lines[0]));
for (final String line : ArrayUtils.subarray(lines, 1, lines.length)) {
if ("".equals(line)) {
break;
}
final List<String> parts = Splitter.on(",").splitToList(line.replace("\"", ""));
Assert.assertTrue(parts.get(this.CLICKS_POSITION) + " is a number less than 0",
NumberFormat.getIntegerInstance().parse(parts.get(this.CLICKS_POSITION)).intValue() > -1);
Assert.assertTrue(parts.get(this.EMAIL_POSITION) + " is an unmasked email address",
parts.get(this.EMAIL_POSITION).matches("^[*]*@[*]*$"));
Assert.assertTrue(parts.get(this.URL_POSITION) + " isn't a URL",
HttpUrl.parse(parts.get(this.URL_POSITION)) != null);
Assert.assertTrue(parts.get(this.TIME_POSITION) + " is too old", ISODateTimeFormat.dateTimeNoMillis()
.parseDateTime(parts.get(this.TIME_POSITION)).isAfter(DateTime.now().minusHours(24)));
}
}
@Test
public void getReturnsJsonIfSpecified() throws Exception {
final HttpUrl url = HttpUrl.parse("http://localhost:" + this.port + "/shared").newBuilder()
.addQueryParameter("port", Integer.toString(this.port)).addQueryParameter("fmt", "json").build();
final Request request = new Request.Builder().url(url).build();
final Response rawResponse = SharedTests.client.newCall(request).execute();
final byte[] body = rawResponse.body().bytes();
final List<Map<String, String>> response = SharedTests.mapper.readValue(body,
new TypeReference<List<Map<String, String>>>() {
});
for (final Map<String, String> line : response) {
Assert.assertTrue(NumberFormat.getIntegerInstance().parse(line.get("id")).intValue() > 1);
Assert.assertTrue(line.get("target") + " didn't parse as a URL", HttpUrl.parse(line.get("target")) != null);
Assert.assertTrue(line.get("read_on") + " is too old", ISODateTimeFormat.dateTimeNoMillis()
.parseDateTime(line.get("read_on")).isAfter(DateTime.now().minusHours(24)));
Assert.assertTrue(line.get("to") + " is not an unmasked email address",
line.get("to").matches("********@********"));
Assert.assertTrue(line.get("shortlink") + " is not a URL", HttpUrl.parse(line.get("shortlink")) != null);
Assert.assertTrue(line.get("clicked") + " is not a positive number",
NumberFormat.getIntegerInstance().parse(line.get("clicked")).intValue() > -1);
}
}
@Test
public void getShareWorksWithAuthorization() throws Exception {
final HttpUrl endpoint = HttpUrl.parse("http://localhost:" + this.port + "/shared/52756");
final Request request = new Request.Builder().url(endpoint).addHeader("X-Authorization", "view1").build();
final Response rawResponse = SharedTests.client.newCall(request).execute();
final Map<String, String> response = SharedTests.mapper.readValue(rawResponse.body().bytes(),
new TypeReference<Map<String, String>>() {
});
Assert.assertEquals("Unexpected or missing keys", Sets.newHashSet("clicks", "recipient", "link"),
response.keySet());
try {
final int clickCount = NumberFormat.getIntegerInstance().parse(response.get("clicks")).intValue();
Assert.assertTrue("Clicks is not positive", clickCount > -1);
} catch (final ParseException e) {
Assert.fail(response.get("clicks") + " is not an integer");
}
Assert.assertEquals("Invalid recipient " + response.get("recipient"), "ajenck@gmail.com",
response.get("recipient"));
Assert.assertTrue("Link is not url",
"https://www.cnet.com/personal-finance/new-600-stimulus-checks-for-californians-who-is-eligible-and-what-we-know-so-far/"
.equals(response.get("link")));
}
@Test
public void getShareWorksWithFromIfAuthorized() throws Exception {
final HttpUrl endpoint = HttpUrl.parse("http://localhost:" + this.port + "/shared/").newBuilder()
.addQueryParameter("from", "-7").build();
final Request request = new Request.Builder().url(endpoint).addHeader("Authorization", "viewMany").build();
final Response rawResponse = SharedTests.client.newCall(request).execute();
final Map<String, Map<String, String>> response = SharedTests.mapper.readValue(rawResponse.body().bytes(),
new TypeReference<Map<String, Map<String, String>>>() {
});
for (final String k : response.keySet()) {
Assert.assertTrue("Not keyed by date", Long.valueOf(k) > 0);
final DateTime dt = new DateTime(Long.valueOf(k));
Assert.assertTrue(dt.isAfter(dt.minusDays(7)));
}
}
@Test
public void getShareWorksWithoutAuthorization() throws Exception {
final HttpUrl endpoint = HttpUrl.parse("http://localhost:" + this.port + "/shared/52756");
final Request request = new Request.Builder().url(endpoint).build();
final Response rawResponse = SharedTests.client.newCall(request).execute();
final Map<String, String> response = SharedTests.mapper.readValue(rawResponse.body().bytes(),
new TypeReference<Map<String, String>>() {
});
Assert.assertEquals("Unexpected or missing keys", Sets.newHashSet("clicks", "recipient", "link"),
response.keySet());
try {
final int clickCount = NumberFormat.getIntegerInstance().parse(response.get("clicks")).intValue();
Assert.assertTrue("Clicks is not positive", clickCount > -1);
} catch (final ParseException e) {
Assert.fail(response.get("clicks") + " is not an integer");
}
Assert.assertEquals("Invalid recipient " + response.get("recipient"), "***@mailinator.com",
response.get("recipient"));
Assert.assertTrue("Link is not url",
"https://www.cnet.com/personal-finance/new-600-stimulus-checks-for-californians-who-is-eligible-and-what-we-know-so-far/"
.equals(response.get("link")));
}
@Test
public void getShareWorksWithToIfAuthorized() throws Exception {
final HttpUrl endpoint = HttpUrl.parse("http://localhost:" + this.port + "/shared/").newBuilder()
.addQueryParameter("to", "-2").build();
final Request request = new Request.Builder().url(endpoint).addHeader("Authorization", "viewMany").build();
final Response rawResponse = SharedTests.client.newCall(request).execute();
final Map<String, Map<String, String>> response = SharedTests.mapper.readValue(rawResponse.body().bytes(),
new TypeReference<Map<String, Map<String, String>>>() {
});
for (final String k : response.keySet()) {
Assert.assertTrue("Not keyed by date", Long.valueOf(k) > 0);
final DateTime dt = new DateTime(Long.valueOf(k));
Assert.assertTrue(dt.isBefore(dt.plusDays(2)));
}
}
@Test
public void misformattedLink() throws Exception {
final String expectedMessage = "Bad link 'hhttps://syrianews.cc/breaking-news-israel-bombs-damascus-and-homs-from-over-beirut/?utm_campaign=shareaholic&utm_medium=reddit&utm_source=news'";
final HttpUrl endpoint = HttpUrl.parse("http://localhost:" + this.port + "/share/");
final Request request = new Request.Builder().url(endpoint).build();
final Response rawResponse = SharedTests.client.newCall(request).execute();
final JsonNode response = SharedTests.mapper.readTree(rawResponse.body().byteStream());
Assert.assertTrue(expectedMessage.equals(response.get("error").asText()));
}
@Test
public void postDoesNotLogMailinator() throws Exception {
final Map<String, String> params = Maps.newHashMap();
final Properties props = new Properties();
props.load(this.getClass().getResourceAsStream("/application.properties"));
params.put("jdbcUrl", props.getProperty("whereishasan.jdbc"));
params.put("stmt", "select count(id) as cnt from applicationlogs where metadata->app_id='units'");
params.put("driverClass", "org.postgresql.Driver");
final String paramsAsJson = SharedTests.mapper.writeValueAsString(params);
final RequestBody requestBody = RequestBody.create(paramsAsJson, MediaType.parse("application/json"));
final String requestUrl = "http://localhost:" + this.port + "/sql";
Request request = new Request.Builder().url(requestUrl).post(requestBody).build();
Response rawResponse = new OkHttpClient().newCall(request).execute();
JsonNode result = SharedTests.mapper.readValue(rawResponse.body().bytes(), ObjectNode.class);
final int oldCount = result.get("cnt").asInt();
final ObjectNode body = SharedTests.mapper.createObjectNode();
body.put("link", "https://www.theleaguesf.org/voter_guides");
body.put("recipient", "raydee326@mailinator.com");
final HttpUrl endpoint = HttpUrl.parse("http://localhost:" + this.port + "/shared");
request = new Request.Builder().url(endpoint)
.post(RequestBody.create(SharedTests.mapper.writeValueAsBytes(body))).build();
rawResponse = SharedTests.client.newCall(request).execute();
result = SharedTests.mapper.readTree(rawResponse.body().charStream());
Assert.assertTrue(result.get("status").asInt() == 200);
request = new Request.Builder().url(requestUrl).post(requestBody).build();
rawResponse = new OkHttpClient().newCall(request).execute();
result = SharedTests.mapper.readValue(rawResponse.body().bytes(), ObjectNode.class);
Assert.assertFalse(result.get("cnt").asInt() != oldCount);
}
@Test
public void postReturnsAppropriateKeys() throws Exception {
final HashSet<String> expected = Sets.newHashSet("link", "recipient", "summary", "title", "status", "url",
"time");
final ObjectNode body = SharedTests.mapper.createObjectNode();
body.put("link", "https://www.theleaguesf.org/voter_guides");
body.put("recipient", "raydee326@mailinator.com");
final HttpUrl endpoint = HttpUrl.parse("http://localhost:" + this.port + "/shared");
final Request request = new Request.Builder().url(endpoint)
.post(RequestBody.create(SharedTests.mapper.writeValueAsBytes(body))).build();
final Response rawResponse = SharedTests.client.newCall(request).execute();
final Map<String, String> response = SharedTests.mapper.readValue(rawResponse.body().bytes(),
new TypeReference<Map<String, String>>() {
});
Assert.assertTrue(response.keySet().equals(expected));
Assert.assertTrue(response.get("twitterStatus").startsWith("https://twitter.com/HasanDiwan2/"));
Assert.assertTrue("Voter Guide - San Francisco League of Pissed Off Voters".equals(response.get("title")));
Assert.assertTrue("200".equals(response.get("status")));
Assert.assertTrue(response.get("time").endsWith(" ms"));
Assert.assertTrue("URL missing", response.get("url").equals(body.get("link").asText()));
}
@Test
public void verifiedReturnsFalseIfMessageMisformatted() throws Exception {
final HttpUrl url = HttpUrl.parse("http://localhost:" + this.port + "/shared/verify");
final Map<String, String> body = Maps.newHashMap();
body.put("key",
"-----BEGIN PGP PRIVATE KEY BLOCK-----\n\nlQdGBFRVgakBEADH0oLj4e2j4eoed2KSjYWecT1fniWzQuuXKE12HGStZDS6lPmV\nDuweS+E6k/FyD7Jw9tFMRxZ83A6JsTqJW0SrhqEiNYq/df1C80SMhncBqgjIrvRL\nB2STKO8MFJGbaoVJ+JHh2pS0caHPxPrIPDLRhxSK/EC9BzbD+w15hEpwo1nehrCv\nqjGdil7cKMOLqJgWawQ/4q1/Fb30pGOXg6HzkuL7AaI3mQr5xgzpL3XIGG5IH7oG\n+2sihfAIivBqe45sja9Xn4EwX5X5DWXSMi3Fsy7q0aDBHJAGybailG6DHLmS0tIU\neOiNsCnFlA5beU/FXEEXTX4yYAeJ0TMNlu/2h6e7vHntv0T/uP9gBY32VWUny1NI\nxyVgeKCg7OG6az8hMiPTdgNeH1j7QeSS1IOx903wpW96xQg5WNjRY0XsoX3zV4Zp\nSzwxFb2FK7DG23Bd5WvbEjXNvNxye5VP3yRw3sF++6N/ehCwZjFv31DjaEtpKsjm\n1PVm/ioGcuj2Js2XShsnD8KFzA5wEBeNwXWyMSP1nYxOxKxDVekWDX7r0d68bwhd\nYYL+ojqMSlCo09RyPyueqXhN9ySXEh4WJoD4XhTLjhqypxmyS/vMkJxvHQARAQAB\n/gcDAkHlklVTgRCF8kdncV0yiilvIpJ/hvzBd8ufJl1+PtYBZT2JABvAjCJ7bISn\nvPyGxT3WiYltWQcR5pEnRpbUu8+lEuc04jHaJw3AV1qjgWSEAkCDPEJMFxci64nW\nrG7p0gc5Oi29irulnyKMBIq2cGuf3XVc0R2rPJaTltirmm+31qz3z8yamwBGu6Zv\npoWdc3YgE/xbqqSVWe7rY/MeNuQ90hBJUw5vi78Ztd8j1/kqijZWppJAHFMtod1f\nCoVvnXdysvS0Glr3pJPmKPkaBQrw4PnOzjRUa2BVQ//In9WcfY4osHMrb01tYhLZ\nBtN3/y3hg9XoTTa0GoFvAxUgf+RP5AeA4aRqI3TUsazNixgF487PA9Biiw1cA+Ca\nYAc/suCzzgzIBiItTwlyxymF+WQGN2DtaxgRESkvrwBdocW78gIJKykI262XweZo\neG4QJ2fFpb/OtGk0MVsZDhZWf8gLiTYLJVTlzq2upJT1eBlK0y0fMYsl9nOuWpeq\nv3QMBAY9M3jKAJDeJqo4laokEgzID1yL4A9M/RhY4BEjrgn9Nvs6IREIzlrHvE64\nhDHjlg7jC22Skt8mD6BoCFA2jfQj0qAPV2qLFlwRUr/W+rYA/l0vzELLZ7AkSg+B\nYmm6w+KG1LN976qdE5bMMk7I7uUIl5vm/Gcg7tIBxe+vhz3dhc6pu9OlujTZFq/f\n3ZrvizysLaq3mvBVgwoxWO2Uu3dRpxODS9ZzRPOEJaRt27sLNc22mppmkfhmYEyc\nkI4QT6c8ClvrS1ZH2ETycvN8uTdd8FXgOBcWJ9yjytnNEc0aYOdcrbiH6UWy9hRC\nIsQ5U/oSB94SpJpPCN+mT4o6G8UuykPUzz25nlfVK58s5MJuCZx2ozcxEbiNqDnh\nPm59zmrO/9a/DylSlJrMeZRKSsE6DX6UQz0KunHqseizQdtyKr6Hnvfk1Iv8vjyN\n8h7Xyy6ioNIYlbj+59qGbkYQdYoGB+Z0mMZx6igb+pyXZapoupPHVuEC2c200KWb\nlKAfvDnjAEPXncMoie4uORprovj9Ss9ZEvi1sYSYEBpS7fweZcCYTd4/s3TjE9Mr\npTeACEheI+b90uf4DBgorm8nGRhC55zftiJvOBuze7vel57OqFFZeUTuI2j77RM+\nUuzrSD/CbvdwbtpQDC3HFCU1J/84xkok8ofppp658ojD8sSxwtCFdZfD4lp7K8Lv\naTOFgaqxAo8ZSXv+gw46OJnM0lCQLA2DgYNAHeaIO0s6fRqwbNZ1kVS0XYjU7sb9\n7Py9HgI3EG1KMCFo8DU6CR1x/JMmnJ9ljraLqPoW/tkcMugkK7uSD1T7PVOoI0U5\ngFHfS0gRiX1aFrmNpzeoWbrVzdp+mrohU+ipLvEzAl305Pym4XgouaNtBkzGwV9c\neGJyfo3v6/IIkcVc6RNTMbc7zKGhYH3yGMDf5D1MGwXJqS8oxsYV7rZWoKKcMNgC\nd6/hTmegejhA744jTMbd1LUue3mnhAKt6bY6tNoDRGWLOT6mmdny++/QDHaZlNMe\nh046MRtH/5rh5QnZxjprlYqHzhxCmOIVcfiDGfycHQT2eDWyGALJ3sne9Xo1DDu3\netZHikMZDi5j9lxaN5Mx1rMjahXGvE7iIBgbbxNsQE4q9B11UsxK7eObbCNHW03B\nYk7KSmj1BgiPKHLje8UGZNE0wtV4IAcP+teTmbeaEri6r5AYpTfwGRq0Nkhhc2Fu\nIERpd2FuIChTaGFyZVBpZWNlLnB5IGtleSkgPGhhc2FuZGl3YW5AZ21haWwuY29t\nPokCNwQTAQoAIQUCVFWBqQIbAwULCQgHAwUVCgkICwUWAwIBAAIeAQIXgAAKCRDC\n1SnAppHt9w+YEACKBDICobj9aImOBVspWNs3xjCaGbN9ikq8vWk2t1VAOmwgcjFF\nsazw+emv3bIf3ApMwcsDYrqlg6SexwiWVrve8/RosGJCRVmXal4rCcgw+EyPNEoR\n9UYIR7DD/nRX6qvOJ3hVM9N/Yvm6hV94h1fLmS32thyy3UDR6aSoZ+pGcjQUgcNh\nOvdspyg8kQV4uL9erm0upPhayDwXaTyktrqg9Bc5q7+pOYf/wzKMjBiJV+MCffTi\ntUOesocKVtemYi+eKyMgug/TdFn3KA502fe1GnGxdscZN073JXOMboUkyHeJYoFb\n6177owCemwtqVlYuSPCHRujGIMtPRKGA46UdKlN2QrkbhC/UqtJA3h1OwP/pdjfx\nDv9UEhOESJWvQF3g2vGCOprRLZUW5UOLj1JLYFoE6//Ca40NYu6MrEX7dwswZaFY\nOhIEs57wWNTIG80PAe1psYv+0ns043dKDOZO5jrcxx/rBTi5vdYG1Jqtbsf+FXAP\nJz4bjHrrM96lCTH/xRoUcqKd22ie861RGGmRKnJN8AasYDaNhrfE8UJ1ir96dvpS\npplEjL/uDYiO0Mndw3uBl8qGNWRhmlOfVqJKqlRwIp2iPTfIHWTNo2pcI1uZQ6jA\nMvpjnLXpUqCIyAy04qn/uwuYsPP4USAW6cZN5XEIg7T6oXx4mlNioyCt3IkCIAQQ\nAQoACgUCV+d+cwMFA3gACgkQ/rrX/9BBu6Gr4BAAoGWLdhr4Pmz1FoUo+OCF/sG/\nlV8kfLXPzAZF9NEvhhHhnsZ9P+73kDcNuNeU0eq5z/MO5m5+nOBjY8eHUwlbxfcD\n6nMLkf/3XbIGy+7CD2Abk/OolWJHEVdbbGqCz7tHY3dPeW96W6r1uPbj+Bq/dF/h\nx91VqIJCrnFWRQaLPxiugy2u1UBRsVy6To1g4xSY2Nh2d+lxmSyEhXXsIJl8cb2p\n2477xjc3FRQ2ITqE/Rh8AoEGuKt2a5ljB8bkUImyQw3vyUilrao8Z+uNjQT2ZqP3\nTryiw+/GU3KbuST7hiYMZ89RSaMp5S9eROLldXOSIQH96A4vr8/FZouh6h5lCbRT\nX2lt4YwZZpa/8UoQdQb2q5Du3h3wMFnb17U/dBUjTV+kxaFYtT8KwMchuhWWPqng\ne8FoKGO79ETfKZ/pgH6HgjAV4nHqVR3xv1LfgAeL5HZOjruc9+OwWzPJehoqAjnh\n3mU6iu9XxvAZBVsZLHWdLZtIyKmXNDBEp8kESQ24CaGWwX89uL6WH8jY83Rli+8U\nDUg+n8mZvdKXxAc8GD8Qc+/6uWIDjl6iVksw7NbMbf8a1xrCatyj5KJ7mz2a9K1y\nmWmONHMKV6NabYRHejHmc6oi+fljyawDNEnMN+Hegd3BVv1iaqMYs90yhdnbudJ4\nYxFpK50fwPcXh/qJj5A=\n=ye4x\n-----END PGP PRIVATE KEY BLOCK----");
body.put("text",
"-----BEGIN PGP SIGNED MESSAGE-----\nHash: SHA256\n\na\n-----BEGIN PGP SIGNATURE-----\n\niQIzBAEBCAAdFiEENROx5p50mTOovE9CwtUpwKaR7fcFAmB7siYACgkQwtUpwKaR\n7fcixA/+LmmJsj8yCPWP139SyyZPQ1wC2M+eNwgWZpqGjb1Vi+gdekxGmHOHW8eI\nChx8svyqBRWgh5+JWDDkBfUeRaqsMVBKnAodMVYhOWpqlKZuC4oXaMlFwVs8Kny1\ngM5qXNfRA4MIXsy3jRYjaTE2qT5be+y8U7On/rITZ8G41qBK4NEXvgIJfCejYXar\nZaES1BXnVxugIEOJWQ0l8p0RwxxOPfcBv6UsW9kfxWmitdFBFmGWl1AYIMwdI/WI\nD7KTPq2LeRYRYiDVzTxWKKvNVELl9n1Tqb0MnKM0By++QR4VdMx6ROQiKSvlaXF0\nKU5m5GkRPZkaWRP6lkjXssNXcAI/PMoySWvAMQb1Fil0iTp/eM5Bm6Y7qKU+TQFl\n30SKmv4DWCuL808AB2YXKdw2uM85q7u8DYo36lVHU8aFeMp8LPQIH0drwdBTdm3e\n6LW0SrwrP2LF/r+IH+4tXFu6mmnDcCNx1a/D1nyxD4s7F/vqbkHkqBxaIE/M2GiV\newQr9NW9QaEbzC9ZSi777a62Nk2g4BtQVOCIzyOZFwqiANazpVxS2Y4yGuMrxU6j\nX739U+KJTRQhO+VU5DYs2aKyHafSND9rv6Fdxn/mtzeGdGJ5TlqAc/wBUfKc7sfr\nCNq2RsUFP+nsTBKvvC+C6tky/gVW7aMLnuF+Er7eQVARmNnvDzg=\n=Iju/\n-----END PGP SIGNATURE----");
final Request verified = new Request.Builder().url(url)
.post(RequestBody.create(SharedTests.mapper.writeValueAsBytes(body))).build();
final Response rawResponse = SharedTests.client.newCall(verified).execute();
final Map<String, String> response = SharedTests.mapper.readValue(rawResponse.body().bytes(),
new TypeReference<Map<String, String>>() {
});
Assert.assertTrue("false".equals(response.get("verified")));
}
@Test
public void verifiedReturnsFalseIfSignatureMisformatted() throws Exception {
final HttpUrl url = HttpUrl.parse("http://localhost:" + this.port + "/shared/verify");
final Map<String, String> body = Maps.newHashMap();
body.put("key",
"-----BEGIN PGP PRIVATE KEY BLOCK-----\n\nlQdGBFRVgakBEADH0oLj4e2j4eoed2KSjYWecT1fniWzQuuXKE12HGStZDS6lPmV\nDuweS+E6k/FyD7Jw9tFMRxZ83A6JsTqJW0SrhqEiNYq/df1C80SMhncBqgjIrvRL\nB2STKO8MFJGbaoVJ+JHh2pS0caHPxPrIPDLRhxSK/EC9BzbD+w15hEpwo1nehrCv\nqjGdil7cKMOLqJgWawQ/4q1/Fb30pGOXg6HzkuL7AaI3mQr5xgzpL3XIGG5IH7oG\n+2sihfAIivBqe45sja9Xn4EwX5X5DWXSMi3Fsy7q0aDBHJAGybailG6DHLmS0tIU\neOiNsCnFlA5beU/FXEEXTX4yYAeJ0TMNlu/2h6e7vHntv0T/uP9gBY32VWUny1NI\nxyVgeKCg7OG6az8hMiPTdgNeH1j7QeSS1IOx903wpW96xQg5WNjRY0XsoX3zV4Zp\nSzwxFb2FK7DG23Bd5WvbEjXNvNxye5VP3yRw3sF++6N/ehCwZjFv31DjaEtpKsjm\n1PVm/ioGcuj2Js2XShsnD8KFzA5wEBeNwXWyMSP1nYxOxKxDVekWDX7r0d68bwhd\nYYL+ojqMSlCo09RyPyueqXhN9ySXEh4WJoD4XhTLjhqypxmyS/vMkJxvHQARAQAB\n/gcDAkHlklVTgRCF8kdncV0yiilvIpJ/hvzBd8ufJl1+PtYBZT2JABvAjCJ7bISn\nvPyGxT3WiYltWQcR5pEnRpbUu8+lEuc04jHaJw3AV1qjgWSEAkCDPEJMFxci64nW\nrG7p0gc5Oi29irulnyKMBIq2cGuf3XVc0R2rPJaTltirmm+31qz3z8yamwBGu6Zv\npoWdc3YgE/xbqqSVWe7rY/MeNuQ90hBJUw5vi78Ztd8j1/kqijZWppJAHFMtod1f\nCoVvnXdysvS0Glr3pJPmKPkaBQrw4PnOzjRUa2BVQ//In9WcfY4osHMrb01tYhLZ\nBtN3/y3hg9XoTTa0GoFvAxUgf+RP5AeA4aRqI3TUsazNixgF487PA9Biiw1cA+Ca\nYAc/suCzzgzIBiItTwlyxymF+WQGN2DtaxgRESkvrwBdocW78gIJKykI262XweZo\neG4QJ2fFpb/OtGk0MVsZDhZWf8gLiTYLJVTlzq2upJT1eBlK0y0fMYsl9nOuWpeq\nv3QMBAY9M3jKAJDeJqo4laokEgzID1yL4A9M/RhY4BEjrgn9Nvs6IREIzlrHvE64\nhDHjlg7jC22Skt8mD6BoCFA2jfQj0qAPV2qLFlwRUr/W+rYA/l0vzELLZ7AkSg+B\nYmm6w+KG1LN976qdE5bMMk7I7uUIl5vm/Gcg7tIBxe+vhz3dhc6pu9OlujTZFq/f\n3ZrvizysLaq3mvBVgwoxWO2Uu3dRpxODS9ZzRPOEJaRt27sLNc22mppmkfhmYEyc\nkI4QT6c8ClvrS1ZH2ETycvN8uTdd8FXgOBcWJ9yjytnNEc0aYOdcrbiH6UWy9hRC\nIsQ5U/oSB94SpJpPCN+mT4o6G8UuykPUzz25nlfVK58s5MJuCZx2ozcxEbiNqDnh\nPm59zmrO/9a/DylSlJrMeZRKSsE6DX6UQz0KunHqseizQdtyKr6Hnvfk1Iv8vjyN\n8h7Xyy6ioNIYlbj+59qGbkYQdYoGB+Z0mMZx6igb+pyXZapoupPHVuEC2c200KWb\nlKAfvDnjAEPXncMoie4uORprovj9Ss9ZEvi1sYSYEBpS7fweZcCYTd4/s3TjE9Mr\npTeACEheI+b90uf4DBgorm8nGRhC55zftiJvOBuze7vel57OqFFZeUTuI2j77RM+\nUuzrSD/CbvdwbtpQDC3HFCU1J/84xkok8ofppp658ojD8sSxwtCFdZfD4lp7K8Lv\naTOFgaqxAo8ZSXv+gw46OJnM0lCQLA2DgYNAHeaIO0s6fRqwbNZ1kVS0XYjU7sb9\n7Py9HgI3EG1KMCFo8DU6CR1x/JMmnJ9ljraLqPoW/tkcMugkK7uSD1T7PVOoI0U5\ngFHfS0gRiX1aFrmNpzeoWbrVzdp+mrohU+ipLvEzAl305Pym4XgouaNtBkzGwV9c\neGJyfo3v6/IIkcVc6RNTMbc7zKGhYH3yGMDf5D1MGwXJqS8oxsYV7rZWoKKcMNgC\nd6/hTmegejhA744jTMbd1LUue3mnhAKt6bY6tNoDRGWLOT6mmdny++/QDHaZlNMe\nh046MRtH/5rh5QnZxjprlYqHzhxCmOIVcfiDGfycHQT2eDWyGALJ3sne9Xo1DDu3\netZHikMZDi5j9lxaN5Mx1rMjahXGvE7iIBgbbxNsQE4q9B11UsxK7eObbCNHW03B\nYk7KSmj1BgiPKHLje8UGZNE0wtV4IAcP+teTmbeaEri6r5AYpTfwGRq0Nkhhc2Fu\nIERpd2FuIChTaGFyZVBpZWNlLnB5IGtleSkgPGhhc2FuZGl3YW5AZ21haWwuY29t\nPokCNwQTAQoAIQUCVFWBqQIbAwULCQgHAwUVCgkICwUWAwIBAAIeAQIXgAAKCRDC\n1SnAppHt9w+YEACKBDICobj9aImOBVspWNs3xjCaGbN9ikq8vWk2t1VAOmwgcjFF\nsazw+emv3bIf3ApMwcsDYrqlg6SexwiWVrve8/RosGJCRVmXal4rCcgw+EyPNEoR\n9UYIR7DD/nRX6qvOJ3hVM9N/Yvm6hV94h1fLmS32thyy3UDR6aSoZ+pGcjQUgcNh\nOvdspyg8kQV4uL9erm0upPhayDwXaTyktrqg9Bc5q7+pOYf/wzKMjBiJV+MCffTi\ntUOesocKVtemYi+eKyMgug/TdFn3KA502fe1GnGxdscZN073JXOMboUkyHeJYoFb\n6177owCemwtqVlYuSPCHRujGIMtPRKGA46UdKlN2QrkbhC/UqtJA3h1OwP/pdjfx\nDv9UEhOESJWvQF3g2vGCOprRLZUW5UOLj1JLYFoE6//Ca40NYu6MrEX7dwswZaFY\nOhIEs57wWNTIG80PAe1psYv+0ns043dKDOZO5jrcxx/rBTi5vdYG1Jqtbsf+FXAP\nJz4bjHrrM96lCTH/xRoUcqKd22ie861RGGmRKnJN8AasYDaNhrfE8UJ1ir96dvpS\npplEjL/uDYiO0Mndw3uBl8qGNWRhmlOfVqJKqlRwIp2iPTfIHWTNo2pcI1uZQ6jA\nMvpjnLXpUqCIyAy04qn/uwuYsPP4USAW6cZN5XEIg7T6oXx4mlNioyCt3IkCIAQQ\nAQoACgUCV+d+cwMFA3gACgkQ/rrX/9BBu6Gr4BAAoGWLdhr4Pmz1FoUo+OCF/sG/\nlV8kfLXPzAZF9NEvhhHhnsZ9P+73kDcNuNeU0eq5z/MO5m5+nOBjY8eHUwlbxfcD\n6nMLkf/3XbIGy+7CD2Abk/OolWJHEVdbbGqCz7tHY3dPeW96W6r1uPbj+Bq/dF/h\nx91VqIJCrnFWRQaLPxiugy2u1UBRsVy6To1g4xSY2Nh2d+lxmSyEhXXsIJl8cb2p\n2477xjc3FRQ2ITqE/Rh8AoEGuKt2a5ljB8bkUImyQw3vyUilrao8Z+uNjQT2ZqP3\nTryiw+/GU3KbuST7hiYMZ89RSaMp5S9eROLldXOSIQH96A4vr8/FZouh6h5lCbRT\nX2lt4YwZZpa/8UoQdQb2q5Du3h3wMFnb17U/dBUjTV+kxaFYtT8KwMchuhWWPqng\ne8FoKGO79ETfKZ/pgH6HgjAV4nHqVR3xv1LfgAeL5HZOjruc9+OwWzPJehoqAjnh\n3mU6iu9XxvAZBVsZLHWdLZtIyKmXNDBEp8kESQ24CaGWwX89uL6WH8jY83Rli+8U\nDUg+n8mZvdKXxAc8GD8Qc+/6uWIDjl6iVksw7NbMbf8a1xrCatyj5KJ7mz2a9K1y\nmWmONHMKV6NabYRHejHmc6oi+fljyawDNEnMN+Hegd3BVv1iaqMYs90yhdnbudJ4\nYxFpK50fwPcXh/qJj5A=\n=ye4x\n-----END PGP PRIVATE KEY BLOCK----");
body.put("text",
"-----BEGIN PGP SIGNED MESSAGE-----\nHash: SHA256\n\na\n-----BEGIN PGP SIGNATURE-----\n\niQIzBAEBCAAdFiEENROx5p50mTOovE9CwtUpwKaR7fcFAmB7siYACgkQwtUpwKaR\n7fcixA/+LmmJsj8yCPWP139SyyZPQ1wC2M+eNwgWZpqGjb1Vi+gdekxGmHOHW8eI\nChx8svyqBRWgh5+JWDDkBfUeRaqsMVBKnAodMVYhOWpqlKZuC4oXaMlFwVs8Kny1\ngM5qXNfRA4MIXsy3jRYjaTE2qT5be+y8U7On/rITZ8G41qBK4NEXvgIJfCejYXar\nZaES1BXnVxugIEOJWQ0l8p0RwxxOPfcBv6UsW9kfxWmitdFBFmGWl1AYIMwdI/WI\nD7KTPq2LeRYRYiDVzTxWKKvNVELl9n1Tqb0MnKM0By++QR4VdMx6ROQiKSvlaXF0\nKU5m5GkRPZkaWRP6lkjXssNXcAI/PMoySWvAMQb1Fil0iTp/eM5Bm6Y7qKU+TQFl\n30SKmv4DWCuL808AB2YXKdw2uM85q7u8DYo36lVHU8aFeMp8LPQIH0drwdBTdm3e\n6LW0SrwrP2LF/r+IH+4tXFu6mmnDcCNx1a/D1nyxD4s7F/vqbkHkqBxaIE/M2GiV\newQr9NW9QaEbzC9ZSi777a62Nk2g4BtQVOCIzyOZFwqiANazpVxS2Y4yGuMrxU6j\nX739U+KJTRQhO+VU5DYs2aKyHafSND9rv6Fdxn/mtzeGdGJ5TlqAc/wBUfKc7sfr\nCNq2RsUFP+nsTBKvvC+C6tky/gVW7aMLnuF+Er7eQVARmNnvDzg=\n=Iju/\n-----END PGP SIGNATURE-----\n");
final Request verified = new Request.Builder().url(url)
.post(RequestBody.create(SharedTests.mapper.writeValueAsBytes(body))).build();
final Response rawResponse = SharedTests.client.newCall(verified).execute();
final Map<String, String> response = SharedTests.mapper.readValue(rawResponse.body().bytes(),
new TypeReference<Map<String, String>>() {
});
Assert.assertTrue("false".equals(response.get("verified")));
}
@Test
public void verifyReturnsFalseIfHelperNotConfigured() throws Exception {
final String saved = System.getProperty("openpgp.helper");
System.getProperties().remove("openpgp.helper");
final HttpUrl url = HttpUrl.parse("http://localhost:" + this.port + "/shared/verify");
final Map<String, String> body = Maps.newHashMap();
body.put("key",
"-----BEGIN PGP PRIVATE KEY BLOCK-----\n\nlQdGBFRVgakBEADH0oLj4e2j4eoed2KSjYWecT1fniWzQuuXKE12HGStZDS6lPmV\nDuweS+E6k/FyD7Jw9tFMRxZ83A6JsTqJW0SrhqEiNYq/df1C80SMhncBqgjIrvRL\nB2STKO8MFJGbaoVJ+JHh2pS0caHPxPrIPDLRhxSK/EC9BzbD+w15hEpwo1nehrCv\nqjGdil7cKMOLqJgWawQ/4q1/Fb30pGOXg6HzkuL7AaI3mQr5xgzpL3XIGG5IH7oG\n+2sihfAIivBqe45sja9Xn4EwX5X5DWXSMi3Fsy7q0aDBHJAGybailG6DHLmS0tIU\neOiNsCnFlA5beU/FXEEXTX4yYAeJ0TMNlu/2h6e7vHntv0T/uP9gBY32VWUny1NI\nxyVgeKCg7OG6az8hMiPTdgNeH1j7QeSS1IOx903wpW96xQg5WNjRY0XsoX3zV4Zp\nSzwxFb2FK7DG23Bd5WvbEjXNvNxye5VP3yRw3sF++6N/ehCwZjFv31DjaEtpKsjm\n1PVm/ioGcuj2Js2XShsnD8KFzA5wEBeNwXWyMSP1nYxOxKxDVekWDX7r0d68bwhd\nYYL+ojqMSlCo09RyPyueqXhN9ySXEh4WJoD4XhTLjhqypxmyS/vMkJxvHQARAQAB\n/gcDAkHlklVTgRCF8kdncV0yiilvIpJ/hvzBd8ufJl1+PtYBZT2JABvAjCJ7bISn\nvPyGxT3WiYltWQcR5pEnRpbUu8+lEuc04jHaJw3AV1qjgWSEAkCDPEJMFxci64nW\nrG7p0gc5Oi29irulnyKMBIq2cGuf3XVc0R2rPJaTltirmm+31qz3z8yamwBGu6Zv\npoWdc3YgE/xbqqSVWe7rY/MeNuQ90hBJUw5vi78Ztd8j1/kqijZWppJAHFMtod1f\nCoVvnXdysvS0Glr3pJPmKPkaBQrw4PnOzjRUa2BVQ//In9WcfY4osHMrb01tYhLZ\nBtN3/y3hg9XoTTa0GoFvAxUgf+RP5AeA4aRqI3TUsazNixgF487PA9Biiw1cA+Ca\nYAc/suCzzgzIBiItTwlyxymF+WQGN2DtaxgRESkvrwBdocW78gIJKykI262XweZo\neG4QJ2fFpb/OtGk0MVsZDhZWf8gLiTYLJVTlzq2upJT1eBlK0y0fMYsl9nOuWpeq\nv3QMBAY9M3jKAJDeJqo4laokEgzID1yL4A9M/RhY4BEjrgn9Nvs6IREIzlrHvE64\nhDHjlg7jC22Skt8mD6BoCFA2jfQj0qAPV2qLFlwRUr/W+rYA/l0vzELLZ7AkSg+B\nYmm6w+KG1LN976qdE5bMMk7I7uUIl5vm/Gcg7tIBxe+vhz3dhc6pu9OlujTZFq/f\n3ZrvizysLaq3mvBVgwoxWO2Uu3dRpxODS9ZzRPOEJaRt27sLNc22mppmkfhmYEyc\nkI4QT6c8ClvrS1ZH2ETycvN8uTdd8FXgOBcWJ9yjytnNEc0aYOdcrbiH6UWy9hRC\nIsQ5U/oSB94SpJpPCN+mT4o6G8UuykPUzz25nlfVK58s5MJuCZx2ozcxEbiNqDnh\nPm59zmrO/9a/DylSlJrMeZRKSsE6DX6UQz0KunHqseizQdtyKr6Hnvfk1Iv8vjyN\n8h7Xyy6ioNIYlbj+59qGbkYQdYoGB+Z0mMZx6igb+pyXZapoupPHVuEC2c200KWb\nlKAfvDnjAEPXncMoie4uORprovj9Ss9ZEvi1sYSYEBpS7fweZcCYTd4/s3TjE9Mr\npTeACEheI+b90uf4DBgorm8nGRhC55zftiJvOBuze7vel57OqFFZeUTuI2j77RM+\nUuzrSD/CbvdwbtpQDC3HFCU1J/84xkok8ofppp658ojD8sSxwtCFdZfD4lp7K8Lv\naTOFgaqxAo8ZSXv+gw46OJnM0lCQLA2DgYNAHeaIO0s6fRqwbNZ1kVS0XYjU7sb9\n7Py9HgI3EG1KMCFo8DU6CR1x/JMmnJ9ljraLqPoW/tkcMugkK7uSD1T7PVOoI0U5\ngFHfS0gRiX1aFrmNpzeoWbrVzdp+mrohU+ipLvEzAl305Pym4XgouaNtBkzGwV9c\neGJyfo3v6/IIkcVc6RNTMbc7zKGhYH3yGMDf5D1MGwXJqS8oxsYV7rZWoKKcMNgC\nd6/hTmegejhA744jTMbd1LUue3mnhAKt6bY6tNoDRGWLOT6mmdny++/QDHaZlNMe\nh046MRtH/5rh5QnZxjprlYqHzhxCmOIVcfiDGfycHQT2eDWyGALJ3sne9Xo1DDu3\netZHikMZDi5j9lxaN5Mx1rMjahXGvE7iIBgbbxNsQE4q9B11UsxK7eObbCNHW03B\nYk7KSmj1BgiPKHLje8UGZNE0wtV4IAcP+teTmbeaEri6r5AYpTfwGRq0Nkhhc2Fu\nIERpd2FuIChTaGFyZVBpZWNlLnB5IGtleSkgPGhhc2FuZGl3YW5AZ21haWwuY29t\nPokCNwQTAQoAIQUCVFWBqQIbAwULCQgHAwUVCgkICwUWAwIBAAIeAQIXgAAKCRDC\n1SnAppHt9w+YEACKBDICobj9aImOBVspWNs3xjCaGbN9ikq8vWk2t1VAOmwgcjFF\nsazw+emv3bIf3ApMwcsDYrqlg6SexwiWVrve8/RosGJCRVmXal4rCcgw+EyPNEoR\n9UYIR7DD/nRX6qvOJ3hVM9N/Yvm6hV94h1fLmS32thyy3UDR6aSoZ+pGcjQUgcNh\nOvdspyg8kQV4uL9erm0upPhayDwXaTyktrqg9Bc5q7+pOYf/wzKMjBiJV+MCffTi\ntUOesocKVtemYi+eKyMgug/TdFn3KA502fe1GnGxdscZN073JXOMboUkyHeJYoFb\n6177owCemwtqVlYuSPCHRujGIMtPRKGA46UdKlN2QrkbhC/UqtJA3h1OwP/pdjfx\nDv9UEhOESJWvQF3g2vGCOprRLZUW5UOLj1JLYFoE6//Ca40NYu6MrEX7dwswZaFY\nOhIEs57wWNTIG80PAe1psYv+0ns043dKDOZO5jrcxx/rBTi5vdYG1Jqtbsf+FXAP\nJz4bjHrrM96lCTH/xRoUcqKd22ie861RGGmRKnJN8AasYDaNhrfE8UJ1ir96dvpS\npplEjL/uDYiO0Mndw3uBl8qGNWRhmlOfVqJKqlRwIp2iPTfIHWTNo2pcI1uZQ6jA\nMvpjnLXpUqCIyAy04qn/uwuYsPP4USAW6cZN5XEIg7T6oXx4mlNioyCt3IkCIAQQ\nAQoACgUCV+d+cwMFA3gACgkQ/rrX/9BBu6Gr4BAAoGWLdhr4Pmz1FoUo+OCF/sG/\nlV8kfLXPzAZF9NEvhhHhnsZ9P+73kDcNuNeU0eq5z/MO5m5+nOBjY8eHUwlbxfcD\n6nMLkf/3XbIGy+7CD2Abk/OolWJHEVdbbGqCz7tHY3dPeW96W6r1uPbj+Bq/dF/h\nx91VqIJCrnFWRQaLPxiugy2u1UBRsVy6To1g4xSY2Nh2d+lxmSyEhXXsIJl8cb2p\n2477xjc3FRQ2ITqE/Rh8AoEGuKt2a5ljB8bkUImyQw3vyUilrao8Z+uNjQT2ZqP3\nTryiw+/GU3KbuST7hiYMZ89RSaMp5S9eROLldXOSIQH96A4vr8/FZouh6h5lCbRT\nX2lt4YwZZpa/8UoQdQb2q5Du3h3wMFnb17U/dBUjTV+kxaFYtT8KwMchuhWWPqng\ne8FoKGO79ETfKZ/pgH6HgjAV4nHqVR3xv1LfgAeL5HZOjruc9+OwWzPJehoqAjnh\n3mU6iu9XxvAZBVsZLHWdLZtIyKmXNDBEp8kESQ24CaGWwX89uL6WH8jY83Rli+8U\nDUg+n8mZvdKXxAc8GD8Qc+/6uWIDjl6iVksw7NbMbf8a1xrCatyj5KJ7mz2a9K1y\nmWmONHMKV6NabYRHejHmc6oi+fljyawDNEnMN+Hegd3BVv1iaqMYs90yhdnbudJ4\nYxFpK50fwPcXh/qJj5A=\n=ye4x\n-----END PGP PRIVATE KEY BLOCK-----");
body.put("text",
"-----BEGIN PGP SIGNED MESSAGE-----\nHash: SHA256\n\na\n-----BEGIN PGP SIGNATURE-----\n\niQIzBAEBCAAdFiEENROx5p50mTOovE9CwtUpwKaR7fcFAmB7siYACgkQwtUpwKaR\n7fcixA/+LmmJsj8yCPWP139SyyZPQ1wC2M+eNwgWZpqGjb1Vi+gdekxGmHOHW8eI\nChx8svyqBRWgh5+JWDDkBfUeRaqsMVBKnAodMVYhOWpqlKZuC4oXaMlFwVs8Kny1\ngM5qXNfRA4MIXsy3jRYjaTE2qT5be+y8U7On/rITZ8G41qBK4NEXvgIJfCejYXar\nZaES1BXnVxugIEOJWQ0l8p0RwxxOPfcBv6UsW9kfxWmitdFBFmGWl1AYIMwdI/WI\nD7KTPq2LeRYRYiDVzTxWKKvNVELl9n1Tqb0MnKM0By++QR4VdMx6ROQiKSvlaXF0\nKU5m5GkRPZkaWRP6lkjXssNXcAI/PMoySWvAMQb1Fil0iTp/eM5Bm6Y7qKU+TQFl\n30SKmv4DWCuL808AB2YXKdw2uM85q7u8DYo36lVHU8aFeMp8LPQIH0drwdBTdm3e\n6LW0SrwrP2LF/r+IH+4tXFu6mmnDcCNx1a/D1nyxD4s7F/vqbkHkqBxaIE/M2GiV\newQr9NW9QaEbzC9ZSi777a62Nk2g4BtQVOCIzyOZFwqiANazpVxS2Y4yGuMrxU6j\nX739U+KJTRQhO+VU5DYs2aKyHafSND9rv6Fdxn/mtzeGdGJ5TlqAc/wBUfKc7sfr\nCNq2RsUFP+nsTBKvvC+C6tky/gVW7aMLnuF+Er7eQVARmNnvDzg=\n=Iju/\n-----END PGP SIGNATURE-----\n");
final Request verified = new Request.Builder().url(url)
.post(RequestBody.create(SharedTests.mapper.writeValueAsBytes(body))).build();
final Response rawResponse = SharedTests.client.newCall(verified).execute();
final Map<String, String> response = SharedTests.mapper.readValue(rawResponse.body().bytes(),
new TypeReference<Map<String, String>>() {
});
Assert.assertTrue("true".equals(response.get("verified")) || "false".equals(response.get("verified")));
System.setProperty("openpgp.helper", saved);
}
}
package us.d8u.balance;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.text.NumberFormat;
import java.text.ParseException;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import org.apache.commons.lang3.ArrayUtils;
import org.joda.time.DateTime;
import org.joda.time.format.ISODateTimeFormat;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
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 com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ObjectNode;
import com.google.common.base.Splitter;
import com.google.common.collect.Iterables;
import com.google.common.collect.Maps;
import com.google.common.collect.Sets;
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 ShareTests {
static OkHttpClient client = new OkHttpClient();
static ObjectMapper mapper = new ObjectMapper();
private final Integer CLICKS_POSITION = 0, EMAIL_POSITION = 1, URL_POSITION = 2, TIME_POSITION = 3;
@Value("${api.links.helper}")
private String LINKS_DB;
@LocalServerPort
private int port;
@Value(value = "${api.diffbot}")
private String TOKEN_FOR_DIFFBOT;
@Test
public void dailyReportConstructedProperly() throws Exception {
final HttpUrl url = HttpUrl.parse("http://localhost:" + this.port + "/shared").newBuilder().build();
final Request request = new Request.Builder().url(url).head().addHeader("x-testing", "1").build();
final Response response = ShareTests.client.newCall(request).execute();
Assert.assertTrue(
"https://twitter.com/HasanDiwan2/status/1420932148811296768".equals(response.header("x-twitter-link")));
Assert.assertTrue(response.header("x-twitter-tweet")
.matches("On " + ISODateTimeFormat.date().print(DateTime.now().minusDays(1))
+ ", I shared [0-9] links to [0-9] people, of which [0-9] were clicked."));
}
@Test
public void deleteReturnsCountsWithoutLinkId() throws Exception {
HttpUrl url = HttpUrl.parse("http://localhost:" + this.port + "/shared").newBuilder().build();
Request request = new Request.Builder().url(url).delete().build();
Response response = ShareTests.client.newCall(request).execute();
Assert.assertTrue(Integer.valueOf(response.header("X-Count")) > -1);
final String sql = "SELECT COUNT(id) as count FROM applicationlogs WHERE read_on < now() - interval '90 days'";
url = url.newBuilder().encodedPath("/sql").addQueryParameter("jdbcUrl", this.LINKS_DB)
.addQueryParameter("driverClass", "org.postgresql.Driver").addQueryParameter("stmt", sql).build();
request = new Request.Builder().url(url).get().build();
response = ShareTests.client.newCall(request).execute();
final String responseAsJson = response.body().string();
final JsonNode json = ShareTests.mapper.readTree(responseAsJson);
Assert.assertTrue(json.get("results").get("count").asInt() > -1);
}
@Test
public void deleteReturnsZeroCountIfLinkIdNotValid() throws Exception {
final HttpUrl url = HttpUrl.parse("http://localhost:" + this.port + "/shared").newBuilder()
.addQueryParameter("link", "-1").build();
final Request request = new Request.Builder().url(url).delete().addHeader("x-forwarded-for", "107.184.228.7")
.build();
final Response response = ShareTests.client.newCall(request).execute();
final String responseAsJson = response.body().string();
final JsonNode json = ShareTests.mapper.readTree(responseAsJson);
Assert.assertTrue("-1".equals(json.get("entryId").asText()));
Assert.assertTrue(json.get("count").asInt() == 0);
}
@Test
public void deleteShareReturnsTotalCountForGreaterThanMonthsAgo() throws Exception {
Integer expectedThreeMonthOldCount = null;
Connection heroku = null;
try {
heroku = DriverManager.getConnection(
"jdbc:postgresql://ec2-174-129-253-174.compute-1.amazonaws.com/dfgnf32vnkq9bg?ssl=true",
"hqocfzgmvbuzhn", "3e53d6c65b40fd1d2e5c5479ab0efbe5e544116de0f821a82f856ec3c595d3b9");
final ResultSet herokuResults = heroku.createStatement().executeQuery(
"select count(id) from applicationlogs where metadata->>'app_id' = 'balance' or read_on < 'now'::timestamp -'3 month'::interval");
expectedThreeMonthOldCount = herokuResults.getInt(1);
heroku.close();
} catch (final SQLException e) {
Assert.fail("Can't get to logging database on heroku");
} finally {
if (null != heroku) {
heroku.close();
}
}
final HttpUrl endpoint = HttpUrl.parse("http://localhost:" + this.port + "/shared/");
final Request request = new Request.Builder().url(endpoint).build();
final Response rawResponse = ShareTests.client.newCall(request).execute();
final String realThreeMonthOldCount = rawResponse.header("X-Count");
Assert.assertEquals("Default delete doesn't work", expectedThreeMonthOldCount,
Integer.valueOf(realThreeMonthOldCount));
}
@Test
public void diffbotWithOkHttp() throws Exception {
final HttpUrl baseUrl = HttpUrl.parse("https://api.diffbot.com/v3/article").newBuilder()
.addEncodedQueryParameter("discussion", "false").addEncodedQueryParameter("paging", "false")
.addEncodedQueryParameter("timeout", "50000").addQueryParameter("token", this.TOKEN_FOR_DIFFBOT)
.addQueryParameter("url", "https://thebulwark.com/what-the-hell-happened-to-the-claremont-institute/")
.build();
final okhttp3.Request request = new okhttp3.Request.Builder().url(baseUrl).get().build();
final okhttp3.Response rawResponse = ShareTests.client.newCall(request).execute();
final JsonNode response = ShareTests.mapper.readTree(rawResponse.body().charStream());
Assert.assertTrue(!response.get("objects").get(0).get("html").isNull());
}
@Test
public void domainlessEmailThrowsError() throws Exception {
final ObjectNode body = ShareTests.mapper.createObjectNode();
body.put("recipient", "reddhimitragmail.com");
body.put("link",
"https://www.reddit.com/r/AskLosAngeles/comments/wkdr7d/recommendations_for_the_best_wagyu_place/");
final HttpUrl url = HttpUrl.parse("http://localhost:" + this.port + "/shared").newBuilder().build();
final Request request = new Request.Builder().url(url)
.post(RequestBody.create(ShareTests.mapper.writeValueAsBytes(body))).build();
final JsonNode response = ShareTests.mapper
.readTree(ShareTests.client.newCall(request).execute().body().charStream());
Assert.assertTrue("status not correct " + response.get("status"),
response.get("status").asInt() == HttpStatus.BAD_REQUEST.value());
Assert.assertTrue("error message not correct -- " + response.get("error"),
"email address invalid".equals(response.get("error").asText()));
}
@Test
public void getDoesNotReturnNoLinks() throws Exception {
final HttpUrl url = HttpUrl.parse("http://localhost:" + this.port + "/shared?fmt=json");
final Request request = new Request.Builder().url(url).delete().build();
final JsonNode response = ShareTests.mapper
.readTree(ShareTests.client.newCall(request).execute().body().bytes());
Assert.assertTrue(!response.isNull());
}
@Test
public void getReturnsCsvWithoutRecipientsIfUnauthorized() throws Exception {
final HttpUrl url = HttpUrl.parse("http://localhost:" + this.port + "/shared").newBuilder()
.addQueryParameter("port", Integer.toString(this.port)).build();
final Request request = new Request.Builder().url(url).build();
final Response response = ShareTests.client.newCall(request).execute();
final String body = response.body().string();
Assert.assertTrue("time not found", NumberFormat.getIntegerInstance().parse(body.split(" ")[0]).intValue() > 0);
final String[] lines = Iterables.toArray(
Splitter.on("\n").split(body.substring(body.indexOf(System.lineSeparator()) + 1)), String.class);
Assert.assertTrue("\"Click Count\",\"Recipient\",\"Target\",\"Minutes Since Sending\"".equals(lines[0]));
for (final String line : ArrayUtils.subarray(lines, 1, lines.length)) {
if ("".equals(line)) {
break;
}
final List<String> parts = Splitter.on(",").splitToList(line.replace("\"", ""));
Assert.assertTrue(parts.get(this.CLICKS_POSITION) + " is a number less than 0",
NumberFormat.getIntegerInstance().parse(parts.get(this.CLICKS_POSITION)).intValue() > -1);
Assert.assertTrue(parts.get(this.EMAIL_POSITION) + " is an unmasked email address",
parts.get(this.EMAIL_POSITION).matches("^[*]*@[*]*$"));
Assert.assertTrue(parts.get(this.URL_POSITION) + " isn't a URL",
HttpUrl.parse(parts.get(this.URL_POSITION)) != null);
Assert.assertTrue(parts.get(this.TIME_POSITION) + " is too old", ISODateTimeFormat.dateTimeNoMillis()
.parseDateTime(parts.get(this.TIME_POSITION)).isAfter(DateTime.now().minusHours(24)));
}
}
@Test
public void getReturnsJsonIfSpecified() throws Exception {
final HttpUrl url = HttpUrl.parse("http://localhost:" + this.port + "/shared").newBuilder()
.addQueryParameter("port", Integer.toString(this.port)).addQueryParameter("fmt", "json").build();
final Request request = new Request.Builder().url(url).build();
final Response rawResponse = ShareTests.client.newCall(request).execute();
final byte[] body = rawResponse.body().bytes();
final List<Map<String, String>> response = ShareTests.mapper.readValue(body,
new TypeReference<List<Map<String, String>>>() {
});
for (final Map<String, String> line : response) {
Assert.assertTrue(NumberFormat.getIntegerInstance().parse(line.get("id")).intValue() > 1);
Assert.assertTrue(line.get("target") + " didn't parse as a URL", HttpUrl.parse(line.get("target")) != null);
Assert.assertTrue(line.get("read_on") + " is too old", ISODateTimeFormat.dateTimeNoMillis()
.parseDateTime(line.get("read_on")).isAfter(DateTime.now().minusHours(24)));
Assert.assertTrue(line.get("to") + " is not an unmasked email address",
line.get("to").matches("********@********"));
Assert.assertTrue(line.get("shortlink") + " is not a URL", HttpUrl.parse(line.get("shortlink")) != null);
Assert.assertTrue(line.get("clicked") + " is not a positive number",
NumberFormat.getIntegerInstance().parse(line.get("clicked")).intValue() > -1);
}
}
@Test
public void getShareWorksWithAuthorization() throws Exception {
final HttpUrl endpoint = HttpUrl.parse("http://localhost:" + this.port + "/shared/52756");
final Request request = new Request.Builder().url(endpoint).addHeader("X-Authorization", "view1").build();
final Response rawResponse = ShareTests.client.newCall(request).execute();
final Map<String, String> response = ShareTests.mapper.readValue(rawResponse.body().bytes(),
new TypeReference<Map<String, String>>() {
});
Assert.assertEquals("Unexpected or missing keys", Sets.newHashSet("clicks", "recipient", "link"),
response.keySet());
try {
final int clickCount = NumberFormat.getIntegerInstance().parse(response.get("clicks")).intValue();
Assert.assertTrue("Clicks is not positive", clickCount > -1);
} catch (final ParseException e) {
Assert.fail(response.get("clicks") + " is not an integer");
}
Assert.assertEquals("Invalid recipient " + response.get("recipient"), "ajenck@gmail.com",
response.get("recipient"));
Assert.assertTrue("Link is not url",
"https://www.cnet.com/personal-finance/new-600-stimulus-checks-for-californians-who-is-eligible-and-what-we-know-so-far/"
.equals(response.get("link")));
}
@Test
public void getShareWorksWithFromIfAuthorized() throws Exception {
final HttpUrl endpoint = HttpUrl.parse("http://localhost:" + this.port + "/shared/").newBuilder()
.addQueryParameter("from", "-7").build();
final Request request = new Request.Builder().url(endpoint).addHeader("Authorization", "viewMany").build();
final Response rawResponse = ShareTests.client.newCall(request).execute();
final Map<String, Map<String, String>> response = ShareTests.mapper.readValue(rawResponse.body().bytes(),
new TypeReference<Map<String, Map<String, String>>>() {
});
for (final String k : response.keySet()) {
Assert.assertTrue("Not keyed by date", Long.valueOf(k) > 0);
final DateTime dt = new DateTime(Long.valueOf(k));
Assert.assertTrue(dt.isAfter(dt.minusDays(7)));
}
}
@Test
public void getShareWorksWithoutAuthorization() throws Exception {
final HttpUrl endpoint = HttpUrl.parse("http://localhost:" + this.port + "/shared/52756");
final Request request = new Request.Builder().url(endpoint).build();
final Response rawResponse = ShareTests.client.newCall(request).execute();
final Map<String, String> response = ShareTests.mapper.readValue(rawResponse.body().bytes(),
new TypeReference<Map<String, String>>() {
});
Assert.assertEquals("Unexpected or missing keys", Sets.newHashSet("clicks", "recipient", "link"),
response.keySet());
try {
final int clickCount = NumberFormat.getIntegerInstance().parse(response.get("clicks")).intValue();
Assert.assertTrue("Clicks is not positive", clickCount > -1);
} catch (final ParseException e) {
Assert.fail(response.get("clicks") + " is not an integer");
}
Assert.assertEquals("Invalid recipient " + response.get("recipient"), "***@mailinator.com",
response.get("recipient"));
Assert.assertTrue("Link is not url",
"https://www.cnet.com/personal-finance/new-600-stimulus-checks-for-californians-who-is-eligible-and-what-we-know-so-far/"
.equals(response.get("link")));
}
@Test
public void getShareWorksWithToIfAuthorized() throws Exception {
final HttpUrl endpoint = HttpUrl.parse("http://localhost:" + this.port + "/shared/").newBuilder()
.addQueryParameter("to", "-2").build();
final Request request = new Request.Builder().url(endpoint).addHeader("Authorization", "viewMany").build();
final Response rawResponse = ShareTests.client.newCall(request).execute();
final Map<String, Map<String, String>> response = ShareTests.mapper.readValue(rawResponse.body().bytes(),
new TypeReference<Map<String, Map<String, String>>>() {
});
for (final String k : response.keySet()) {
Assert.assertTrue("Not keyed by date", Long.valueOf(k) > 0);
final DateTime dt = new DateTime(Long.valueOf(k));
Assert.assertTrue(dt.isBefore(dt.plusDays(2)));
}
}
@Test
public void misformattedLink() throws Exception {
final String expectedMessage = "Bad link 'hhttps://syrianews.cc/breaking-news-israel-bombs-damascus-and-homs-from-over-beirut/?utm_campaign=shareaholic&utm_medium=reddit&utm_source=news'";
final HttpUrl endpoint = HttpUrl.parse("http://localhost:" + this.port + "/share/");
final Request request = new Request.Builder().url(endpoint).build();
final Response rawResponse = ShareTests.client.newCall(request).execute();
final JsonNode response = ShareTests.mapper.readTree(rawResponse.body().byteStream());
Assert.assertTrue(expectedMessage.equals(response.get("error").asText()));
}
@Test
public void postDoesNotLogMailinator() throws Exception {
final Map<String, String> params = Maps.newHashMap();
final Properties props = new Properties();
props.load(this.getClass().getResourceAsStream("/application.properties"));
params.put("jdbcUrl", props.getProperty("whereishasan.jdbc"));
params.put("stmt", "select count(id) as cnt from applicationlogs where metadata->app_id='units'");
params.put("driverClass", "org.postgresql.Driver");
final String paramsAsJson = ShareTests.mapper.writeValueAsString(params);
final RequestBody requestBody = RequestBody.create(paramsAsJson, MediaType.parse("application/json"));
final String requestUrl = "http://localhost:" + this.port + "/sql";
Request request = new Request.Builder().url(requestUrl).post(requestBody).build();
Response rawResponse = new OkHttpClient().newCall(request).execute();
JsonNode result = ShareTests.mapper.readValue(rawResponse.body().bytes(), ObjectNode.class);
final int oldCount = result.get("cnt").asInt();
final ObjectNode body = ShareTests.mapper.createObjectNode();
body.put("link", "https://www.theleaguesf.org/voter_guides");
body.put("recipient", "raydee326@mailinator.com");
final HttpUrl endpoint = HttpUrl.parse("http://localhost:" + this.port + "/shared");
request = new Request.Builder().url(endpoint)
.post(RequestBody.create(ShareTests.mapper.writeValueAsBytes(body))).build();
rawResponse = ShareTests.client.newCall(request).execute();
result = ShareTests.mapper.readTree(rawResponse.body().charStream());
Assert.assertTrue(result.get("status").asInt() == 200);
request = new Request.Builder().url(requestUrl).post(requestBody).build();
rawResponse = new OkHttpClient().newCall(request).execute();
result = ShareTests.mapper.readValue(rawResponse.body().bytes(), ObjectNode.class);
Assert.assertFalse(result.get("cnt").asInt() != oldCount);
}
@Test
public void postReturnsAppropriateKeys() throws Exception {
final HashSet<String> expected = Sets.newHashSet("link", "recipient", "summary", "title", "status", "url",
"time");
final ObjectNode body = ShareTests.mapper.createObjectNode();
body.put("link", "https://www.theleaguesf.org/voter_guides");
body.put("recipient", "raydee326@mailinator.com");
final HttpUrl endpoint = HttpUrl.parse("http://localhost:" + this.port + "/shared");
final Request request = new Request.Builder().url(endpoint)
.post(RequestBody.create(ShareTests.mapper.writeValueAsBytes(body))).build();
final Response rawResponse = ShareTests.client.newCall(request).execute();
final Map<String, String> response = ShareTests.mapper.readValue(rawResponse.body().bytes(),
new TypeReference<Map<String, String>>() {
});
Assert.assertTrue(response.keySet().equals(expected));
Assert.assertTrue(response.get("twitterStatus").startsWith("https://twitter.com/HasanDiwan2/"));
Assert.assertTrue("Voter Guide - San Francisco League of Pissed Off Voters".equals(response.get("title")));
Assert.assertTrue("200".equals(response.get("status")));
Assert.assertTrue(response.get("time").endsWith(" ms"));
Assert.assertTrue("URL missing", response.get("url").equals(body.get("link").asText()));
}
@Test
public void verifiedReturnsFalseIfMessageMisformatted() throws Exception {
final HttpUrl url = HttpUrl.parse("http://localhost:" + this.port + "/shared/verify");
final Map<String, String> body = Maps.newHashMap();
body.put("key",
"-----BEGIN PGP PRIVATE KEY BLOCK-----\n\nlQdGBFRVgakBEADH0oLj4e2j4eoed2KSjYWecT1fniWzQuuXKE12HGStZDS6lPmV\nDuweS+E6k/FyD7Jw9tFMRxZ83A6JsTqJW0SrhqEiNYq/df1C80SMhncBqgjIrvRL\nB2STKO8MFJGbaoVJ+JHh2pS0caHPxPrIPDLRhxSK/EC9BzbD+w15hEpwo1nehrCv\nqjGdil7cKMOLqJgWawQ/4q1/Fb30pGOXg6HzkuL7AaI3mQr5xgzpL3XIGG5IH7oG\n+2sihfAIivBqe45sja9Xn4EwX5X5DWXSMi3Fsy7q0aDBHJAGybailG6DHLmS0tIU\neOiNsCnFlA5beU/FXEEXTX4yYAeJ0TMNlu/2h6e7vHntv0T/uP9gBY32VWUny1NI\nxyVgeKCg7OG6az8hMiPTdgNeH1j7QeSS1IOx903wpW96xQg5WNjRY0XsoX3zV4Zp\nSzwxFb2FK7DG23Bd5WvbEjXNvNxye5VP3yRw3sF++6N/ehCwZjFv31DjaEtpKsjm\n1PVm/ioGcuj2Js2XShsnD8KFzA5wEBeNwXWyMSP1nYxOxKxDVekWDX7r0d68bwhd\nYYL+ojqMSlCo09RyPyueqXhN9ySXEh4WJoD4XhTLjhqypxmyS/vMkJxvHQARAQAB\n/gcDAkHlklVTgRCF8kdncV0yiilvIpJ/hvzBd8ufJl1+PtYBZT2JABvAjCJ7bISn\nvPyGxT3WiYltWQcR5pEnRpbUu8+lEuc04jHaJw3AV1qjgWSEAkCDPEJMFxci64nW\nrG7p0gc5Oi29irulnyKMBIq2cGuf3XVc0R2rPJaTltirmm+31qz3z8yamwBGu6Zv\npoWdc3YgE/xbqqSVWe7rY/MeNuQ90hBJUw5vi78Ztd8j1/kqijZWppJAHFMtod1f\nCoVvnXdysvS0Glr3pJPmKPkaBQrw4PnOzjRUa2BVQ//In9WcfY4osHMrb01tYhLZ\nBtN3/y3hg9XoTTa0GoFvAxUgf+RP5AeA4aRqI3TUsazNixgF487PA9Biiw1cA+Ca\nYAc/suCzzgzIBiItTwlyxymF+WQGN2DtaxgRESkvrwBdocW78gIJKykI262XweZo\neG4QJ2fFpb/OtGk0MVsZDhZWf8gLiTYLJVTlzq2upJT1eBlK0y0fMYsl9nOuWpeq\nv3QMBAY9M3jKAJDeJqo4laokEgzID1yL4A9M/RhY4BEjrgn9Nvs6IREIzlrHvE64\nhDHjlg7jC22Skt8mD6BoCFA2jfQj0qAPV2qLFlwRUr/W+rYA/l0vzELLZ7AkSg+B\nYmm6w+KG1LN976qdE5bMMk7I7uUIl5vm/Gcg7tIBxe+vhz3dhc6pu9OlujTZFq/f\n3ZrvizysLaq3mvBVgwoxWO2Uu3dRpxODS9ZzRPOEJaRt27sLNc22mppmkfhmYEyc\nkI4QT6c8ClvrS1ZH2ETycvN8uTdd8FXgOBcWJ9yjytnNEc0aYOdcrbiH6UWy9hRC\nIsQ5U/oSB94SpJpPCN+mT4o6G8UuykPUzz25nlfVK58s5MJuCZx2ozcxEbiNqDnh\nPm59zmrO/9a/DylSlJrMeZRKSsE6DX6UQz0KunHqseizQdtyKr6Hnvfk1Iv8vjyN\n8h7Xyy6ioNIYlbj+59qGbkYQdYoGB+Z0mMZx6igb+pyXZapoupPHVuEC2c200KWb\nlKAfvDnjAEPXncMoie4uORprovj9Ss9ZEvi1sYSYEBpS7fweZcCYTd4/s3TjE9Mr\npTeACEheI+b90uf4DBgorm8nGRhC55zftiJvOBuze7vel57OqFFZeUTuI2j77RM+\nUuzrSD/CbvdwbtpQDC3HFCU1J/84xkok8ofppp658ojD8sSxwtCFdZfD4lp7K8Lv\naTOFgaqxAo8ZSXv+gw46OJnM0lCQLA2DgYNAHeaIO0s6fRqwbNZ1kVS0XYjU7sb9\n7Py9HgI3EG1KMCFo8DU6CR1x/JMmnJ9ljraLqPoW/tkcMugkK7uSD1T7PVOoI0U5\ngFHfS0gRiX1aFrmNpzeoWbrVzdp+mrohU+ipLvEzAl305Pym4XgouaNtBkzGwV9c\neGJyfo3v6/IIkcVc6RNTMbc7zKGhYH3yGMDf5D1MGwXJqS8oxsYV7rZWoKKcMNgC\nd6/hTmegejhA744jTMbd1LUue3mnhAKt6bY6tNoDRGWLOT6mmdny++/QDHaZlNMe\nh046MRtH/5rh5QnZxjprlYqHzhxCmOIVcfiDGfycHQT2eDWyGALJ3sne9Xo1DDu3\netZHikMZDi5j9lxaN5Mx1rMjahXGvE7iIBgbbxNsQE4q9B11UsxK7eObbCNHW03B\nYk7KSmj1BgiPKHLje8UGZNE0wtV4IAcP+teTmbeaEri6r5AYpTfwGRq0Nkhhc2Fu\nIERpd2FuIChTaGFyZVBpZWNlLnB5IGtleSkgPGhhc2FuZGl3YW5AZ21haWwuY29t\nPokCNwQTAQoAIQUCVFWBqQIbAwULCQgHAwUVCgkICwUWAwIBAAIeAQIXgAAKCRDC\n1SnAppHt9w+YEACKBDICobj9aImOBVspWNs3xjCaGbN9ikq8vWk2t1VAOmwgcjFF\nsazw+emv3bIf3ApMwcsDYrqlg6SexwiWVrve8/RosGJCRVmXal4rCcgw+EyPNEoR\n9UYIR7DD/nRX6qvOJ3hVM9N/Yvm6hV94h1fLmS32thyy3UDR6aSoZ+pGcjQUgcNh\nOvdspyg8kQV4uL9erm0upPhayDwXaTyktrqg9Bc5q7+pOYf/wzKMjBiJV+MCffTi\ntUOesocKVtemYi+eKyMgug/TdFn3KA502fe1GnGxdscZN073JXOMboUkyHeJYoFb\n6177owCemwtqVlYuSPCHRujGIMtPRKGA46UdKlN2QrkbhC/UqtJA3h1OwP/pdjfx\nDv9UEhOESJWvQF3g2vGCOprRLZUW5UOLj1JLYFoE6//Ca40NYu6MrEX7dwswZaFY\nOhIEs57wWNTIG80PAe1psYv+0ns043dKDOZO5jrcxx/rBTi5vdYG1Jqtbsf+FXAP\nJz4bjHrrM96lCTH/xRoUcqKd22ie861RGGmRKnJN8AasYDaNhrfE8UJ1ir96dvpS\npplEjL/uDYiO0Mndw3uBl8qGNWRhmlOfVqJKqlRwIp2iPTfIHWTNo2pcI1uZQ6jA\nMvpjnLXpUqCIyAy04qn/uwuYsPP4USAW6cZN5XEIg7T6oXx4mlNioyCt3IkCIAQQ\nAQoACgUCV+d+cwMFA3gACgkQ/rrX/9BBu6Gr4BAAoGWLdhr4Pmz1FoUo+OCF/sG/\nlV8kfLXPzAZF9NEvhhHhnsZ9P+73kDcNuNeU0eq5z/MO5m5+nOBjY8eHUwlbxfcD\n6nMLkf/3XbIGy+7CD2Abk/OolWJHEVdbbGqCz7tHY3dPeW96W6r1uPbj+Bq/dF/h\nx91VqIJCrnFWRQaLPxiugy2u1UBRsVy6To1g4xSY2Nh2d+lxmSyEhXXsIJl8cb2p\n2477xjc3FRQ2ITqE/Rh8AoEGuKt2a5ljB8bkUImyQw3vyUilrao8Z+uNjQT2ZqP3\nTryiw+/GU3KbuST7hiYMZ89RSaMp5S9eROLldXOSIQH96A4vr8/FZouh6h5lCbRT\nX2lt4YwZZpa/8UoQdQb2q5Du3h3wMFnb17U/dBUjTV+kxaFYtT8KwMchuhWWPqng\ne8FoKGO79ETfKZ/pgH6HgjAV4nHqVR3xv1LfgAeL5HZOjruc9+OwWzPJehoqAjnh\n3mU6iu9XxvAZBVsZLHWdLZtIyKmXNDBEp8kESQ24CaGWwX89uL6WH8jY83Rli+8U\nDUg+n8mZvdKXxAc8GD8Qc+/6uWIDjl6iVksw7NbMbf8a1xrCatyj5KJ7mz2a9K1y\nmWmONHMKV6NabYRHejHmc6oi+fljyawDNEnMN+Hegd3BVv1iaqMYs90yhdnbudJ4\nYxFpK50fwPcXh/qJj5A=\n=ye4x\n-----END PGP PRIVATE KEY BLOCK----");
body.put("text",
"-----BEGIN PGP SIGNED MESSAGE-----\nHash: SHA256\n\na\n-----BEGIN PGP SIGNATURE-----\n\niQIzBAEBCAAdFiEENROx5p50mTOovE9CwtUpwKaR7fcFAmB7siYACgkQwtUpwKaR\n7fcixA/+LmmJsj8yCPWP139SyyZPQ1wC2M+eNwgWZpqGjb1Vi+gdekxGmHOHW8eI\nChx8svyqBRWgh5+JWDDkBfUeRaqsMVBKnAodMVYhOWpqlKZuC4oXaMlFwVs8Kny1\ngM5qXNfRA4MIXsy3jRYjaTE2qT5be+y8U7On/rITZ8G41qBK4NEXvgIJfCejYXar\nZaES1BXnVxugIEOJWQ0l8p0RwxxOPfcBv6UsW9kfxWmitdFBFmGWl1AYIMwdI/WI\nD7KTPq2LeRYRYiDVzTxWKKvNVELl9n1Tqb0MnKM0By++QR4VdMx6ROQiKSvlaXF0\nKU5m5GkRPZkaWRP6lkjXssNXcAI/PMoySWvAMQb1Fil0iTp/eM5Bm6Y7qKU+TQFl\n30SKmv4DWCuL808AB2YXKdw2uM85q7u8DYo36lVHU8aFeMp8LPQIH0drwdBTdm3e\n6LW0SrwrP2LF/r+IH+4tXFu6mmnDcCNx1a/D1nyxD4s7F/vqbkHkqBxaIE/M2GiV\newQr9NW9QaEbzC9ZSi777a62Nk2g4BtQVOCIzyOZFwqiANazpVxS2Y4yGuMrxU6j\nX739U+KJTRQhO+VU5DYs2aKyHafSND9rv6Fdxn/mtzeGdGJ5TlqAc/wBUfKc7sfr\nCNq2RsUFP+nsTBKvvC+C6tky/gVW7aMLnuF+Er7eQVARmNnvDzg=\n=Iju/\n-----END PGP SIGNATURE----");
final Request verified = new Request.Builder().url(url)
.post(RequestBody.create(ShareTests.mapper.writeValueAsBytes(body))).build();
final Response rawResponse = ShareTests.client.newCall(verified).execute();
final Map<String, String> response = ShareTests.mapper.readValue(rawResponse.body().bytes(),
new TypeReference<Map<String, String>>() {
});
Assert.assertTrue("false".equals(response.get("verified")));
}
@Test
public void verifiedReturnsFalseIfSignatureMisformatted() throws Exception {
final HttpUrl url = HttpUrl.parse("http://localhost:" + this.port + "/shared/verify");
final Map<String, String> body = Maps.newHashMap();
body.put("key",
"-----BEGIN PGP PRIVATE KEY BLOCK-----\n\nlQdGBFRVgakBEADH0oLj4e2j4eoed2KSjYWecT1fniWzQuuXKE12HGStZDS6lPmV\nDuweS+E6k/FyD7Jw9tFMRxZ83A6JsTqJW0SrhqEiNYq/df1C80SMhncBqgjIrvRL\nB2STKO8MFJGbaoVJ+JHh2pS0caHPxPrIPDLRhxSK/EC9BzbD+w15hEpwo1nehrCv\nqjGdil7cKMOLqJgWawQ/4q1/Fb30pGOXg6HzkuL7AaI3mQr5xgzpL3XIGG5IH7oG\n+2sihfAIivBqe45sja9Xn4EwX5X5DWXSMi3Fsy7q0aDBHJAGybailG6DHLmS0tIU\neOiNsCnFlA5beU/FXEEXTX4yYAeJ0TMNlu/2h6e7vHntv0T/uP9gBY32VWUny1NI\nxyVgeKCg7OG6az8hMiPTdgNeH1j7QeSS1IOx903wpW96xQg5WNjRY0XsoX3zV4Zp\nSzwxFb2FK7DG23Bd5WvbEjXNvNxye5VP3yRw3sF++6N/ehCwZjFv31DjaEtpKsjm\n1PVm/ioGcuj2Js2XShsnD8KFzA5wEBeNwXWyMSP1nYxOxKxDVekWDX7r0d68bwhd\nYYL+ojqMSlCo09RyPyueqXhN9ySXEh4WJoD4XhTLjhqypxmyS/vMkJxvHQARAQAB\n/gcDAkHlklVTgRCF8kdncV0yiilvIpJ/hvzBd8ufJl1+PtYBZT2JABvAjCJ7bISn\nvPyGxT3WiYltWQcR5pEnRpbUu8+lEuc04jHaJw3AV1qjgWSEAkCDPEJMFxci64nW\nrG7p0gc5Oi29irulnyKMBIq2cGuf3XVc0R2rPJaTltirmm+31qz3z8yamwBGu6Zv\npoWdc3YgE/xbqqSVWe7rY/MeNuQ90hBJUw5vi78Ztd8j1/kqijZWppJAHFMtod1f\nCoVvnXdysvS0Glr3pJPmKPkaBQrw4PnOzjRUa2BVQ//In9WcfY4osHMrb01tYhLZ\nBtN3/y3hg9XoTTa0GoFvAxUgf+RP5AeA4aRqI3TUsazNixgF487PA9Biiw1cA+Ca\nYAc/suCzzgzIBiItTwlyxymF+WQGN2DtaxgRESkvrwBdocW78gIJKykI262XweZo\neG4QJ2fFpb/OtGk0MVsZDhZWf8gLiTYLJVTlzq2upJT1eBlK0y0fMYsl9nOuWpeq\nv3QMBAY9M3jKAJDeJqo4laokEgzID1yL4A9M/RhY4BEjrgn9Nvs6IREIzlrHvE64\nhDHjlg7jC22Skt8mD6BoCFA2jfQj0qAPV2qLFlwRUr/W+rYA/l0vzELLZ7AkSg+B\nYmm6w+KG1LN976qdE5bMMk7I7uUIl5vm/Gcg7tIBxe+vhz3dhc6pu9OlujTZFq/f\n3ZrvizysLaq3mvBVgwoxWO2Uu3dRpxODS9ZzRPOEJaRt27sLNc22mppmkfhmYEyc\nkI4QT6c8ClvrS1ZH2ETycvN8uTdd8FXgOBcWJ9yjytnNEc0aYOdcrbiH6UWy9hRC\nIsQ5U/oSB94SpJpPCN+mT4o6G8UuykPUzz25nlfVK58s5MJuCZx2ozcxEbiNqDnh\nPm59zmrO/9a/DylSlJrMeZRKSsE6DX6UQz0KunHqseizQdtyKr6Hnvfk1Iv8vjyN\n8h7Xyy6ioNIYlbj+59qGbkYQdYoGB+Z0mMZx6igb+pyXZapoupPHVuEC2c200KWb\nlKAfvDnjAEPXncMoie4uORprovj9Ss9ZEvi1sYSYEBpS7fweZcCYTd4/s3TjE9Mr\npTeACEheI+b90uf4DBgorm8nGRhC55zftiJvOBuze7vel57OqFFZeUTuI2j77RM+\nUuzrSD/CbvdwbtpQDC3HFCU1J/84xkok8ofppp658ojD8sSxwtCFdZfD4lp7K8Lv\naTOFgaqxAo8ZSXv+gw46OJnM0lCQLA2DgYNAHeaIO0s6fRqwbNZ1kVS0XYjU7sb9\n7Py9HgI3EG1KMCFo8DU6CR1x/JMmnJ9ljraLqPoW/tkcMugkK7uSD1T7PVOoI0U5\ngFHfS0gRiX1aFrmNpzeoWbrVzdp+mrohU+ipLvEzAl305Pym4XgouaNtBkzGwV9c\neGJyfo3v6/IIkcVc6RNTMbc7zKGhYH3yGMDf5D1MGwXJqS8oxsYV7rZWoKKcMNgC\nd6/hTmegejhA744jTMbd1LUue3mnhAKt6bY6tNoDRGWLOT6mmdny++/QDHaZlNMe\nh046MRtH/5rh5QnZxjprlYqHzhxCmOIVcfiDGfycHQT2eDWyGALJ3sne9Xo1DDu3\netZHikMZDi5j9lxaN5Mx1rMjahXGvE7iIBgbbxNsQE4q9B11UsxK7eObbCNHW03B\nYk7KSmj1BgiPKHLje8UGZNE0wtV4IAcP+teTmbeaEri6r5AYpTfwGRq0Nkhhc2Fu\nIERpd2FuIChTaGFyZVBpZWNlLnB5IGtleSkgPGhhc2FuZGl3YW5AZ21haWwuY29t\nPokCNwQTAQoAIQUCVFWBqQIbAwULCQgHAwUVCgkICwUWAwIBAAIeAQIXgAAKCRDC\n1SnAppHt9w+YEACKBDICobj9aImOBVspWNs3xjCaGbN9ikq8vWk2t1VAOmwgcjFF\nsazw+emv3bIf3ApMwcsDYrqlg6SexwiWVrve8/RosGJCRVmXal4rCcgw+EyPNEoR\n9UYIR7DD/nRX6qvOJ3hVM9N/Yvm6hV94h1fLmS32thyy3UDR6aSoZ+pGcjQUgcNh\nOvdspyg8kQV4uL9erm0upPhayDwXaTyktrqg9Bc5q7+pOYf/wzKMjBiJV+MCffTi\ntUOesocKVtemYi+eKyMgug/TdFn3KA502fe1GnGxdscZN073JXOMboUkyHeJYoFb\n6177owCemwtqVlYuSPCHRujGIMtPRKGA46UdKlN2QrkbhC/UqtJA3h1OwP/pdjfx\nDv9UEhOESJWvQF3g2vGCOprRLZUW5UOLj1JLYFoE6//Ca40NYu6MrEX7dwswZaFY\nOhIEs57wWNTIG80PAe1psYv+0ns043dKDOZO5jrcxx/rBTi5vdYG1Jqtbsf+FXAP\nJz4bjHrrM96lCTH/xRoUcqKd22ie861RGGmRKnJN8AasYDaNhrfE8UJ1ir96dvpS\npplEjL/uDYiO0Mndw3uBl8qGNWRhmlOfVqJKqlRwIp2iPTfIHWTNo2pcI1uZQ6jA\nMvpjnLXpUqCIyAy04qn/uwuYsPP4USAW6cZN5XEIg7T6oXx4mlNioyCt3IkCIAQQ\nAQoACgUCV+d+cwMFA3gACgkQ/rrX/9BBu6Gr4BAAoGWLdhr4Pmz1FoUo+OCF/sG/\nlV8kfLXPzAZF9NEvhhHhnsZ9P+73kDcNuNeU0eq5z/MO5m5+nOBjY8eHUwlbxfcD\n6nMLkf/3XbIGy+7CD2Abk/OolWJHEVdbbGqCz7tHY3dPeW96W6r1uPbj+Bq/dF/h\nx91VqIJCrnFWRQaLPxiugy2u1UBRsVy6To1g4xSY2Nh2d+lxmSyEhXXsIJl8cb2p\n2477xjc3FRQ2ITqE/Rh8AoEGuKt2a5ljB8bkUImyQw3vyUilrao8Z+uNjQT2ZqP3\nTryiw+/GU3KbuST7hiYMZ89RSaMp5S9eROLldXOSIQH96A4vr8/FZouh6h5lCbRT\nX2lt4YwZZpa/8UoQdQb2q5Du3h3wMFnb17U/dBUjTV+kxaFYtT8KwMchuhWWPqng\ne8FoKGO79ETfKZ/pgH6HgjAV4nHqVR3xv1LfgAeL5HZOjruc9+OwWzPJehoqAjnh\n3mU6iu9XxvAZBVsZLHWdLZtIyKmXNDBEp8kESQ24CaGWwX89uL6WH8jY83Rli+8U\nDUg+n8mZvdKXxAc8GD8Qc+/6uWIDjl6iVksw7NbMbf8a1xrCatyj5KJ7mz2a9K1y\nmWmONHMKV6NabYRHejHmc6oi+fljyawDNEnMN+Hegd3BVv1iaqMYs90yhdnbudJ4\nYxFpK50fwPcXh/qJj5A=\n=ye4x\n-----END PGP PRIVATE KEY BLOCK----");
body.put("text",
"-----BEGIN PGP SIGNED MESSAGE-----\nHash: SHA256\n\na\n-----BEGIN PGP SIGNATURE-----\n\niQIzBAEBCAAdFiEENROx5p50mTOovE9CwtUpwKaR7fcFAmB7siYACgkQwtUpwKaR\n7fcixA/+LmmJsj8yCPWP139SyyZPQ1wC2M+eNwgWZpqGjb1Vi+gdekxGmHOHW8eI\nChx8svyqBRWgh5+JWDDkBfUeRaqsMVBKnAodMVYhOWpqlKZuC4oXaMlFwVs8Kny1\ngM5qXNfRA4MIXsy3jRYjaTE2qT5be+y8U7On/rITZ8G41qBK4NEXvgIJfCejYXar\nZaES1BXnVxugIEOJWQ0l8p0RwxxOPfcBv6UsW9kfxWmitdFBFmGWl1AYIMwdI/WI\nD7KTPq2LeRYRYiDVzTxWKKvNVELl9n1Tqb0MnKM0By++QR4VdMx6ROQiKSvlaXF0\nKU5m5GkRPZkaWRP6lkjXssNXcAI/PMoySWvAMQb1Fil0iTp/eM5Bm6Y7qKU+TQFl\n30SKmv4DWCuL808AB2YXKdw2uM85q7u8DYo36lVHU8aFeMp8LPQIH0drwdBTdm3e\n6LW0SrwrP2LF/r+IH+4tXFu6mmnDcCNx1a/D1nyxD4s7F/vqbkHkqBxaIE/M2GiV\newQr9NW9QaEbzC9ZSi777a62Nk2g4BtQVOCIzyOZFwqiANazpVxS2Y4yGuMrxU6j\nX739U+KJTRQhO+VU5DYs2aKyHafSND9rv6Fdxn/mtzeGdGJ5TlqAc/wBUfKc7sfr\nCNq2RsUFP+nsTBKvvC+C6tky/gVW7aMLnuF+Er7eQVARmNnvDzg=\n=Iju/\n-----END PGP SIGNATURE-----\n");
final Request verified = new Request.Builder().url(url)
.post(RequestBody.create(ShareTests.mapper.writeValueAsBytes(body))).build();
final Response rawResponse = ShareTests.client.newCall(verified).execute();
final Map<String, String> response = ShareTests.mapper.readValue(rawResponse.body().bytes(),
new TypeReference<Map<String, String>>() {
});
Assert.assertTrue("false".equals(response.get("verified")));
}
@Test
public void verifyReturnsFalseIfHelperNotConfigured() throws Exception {
final String saved = System.getProperty("openpgp.helper");
System.getProperties().remove("openpgp.helper");
final HttpUrl url = HttpUrl.parse("http://localhost:" + this.port + "/shared/verify");
final Map<String, String> body = Maps.newHashMap();
body.put("key",
"-----BEGIN PGP PRIVATE KEY BLOCK-----\n\nlQdGBFRVgakBEADH0oLj4e2j4eoed2KSjYWecT1fniWzQuuXKE12HGStZDS6lPmV\nDuweS+E6k/FyD7Jw9tFMRxZ83A6JsTqJW0SrhqEiNYq/df1C80SMhncBqgjIrvRL\nB2STKO8MFJGbaoVJ+JHh2pS0caHPxPrIPDLRhxSK/EC9BzbD+w15hEpwo1nehrCv\nqjGdil7cKMOLqJgWawQ/4q1/Fb30pGOXg6HzkuL7AaI3mQr5xgzpL3XIGG5IH7oG\n+2sihfAIivBqe45sja9Xn4EwX5X5DWXSMi3Fsy7q0aDBHJAGybailG6DHLmS0tIU\neOiNsCnFlA5beU/FXEEXTX4yYAeJ0TMNlu/2h6e7vHntv0T/uP9gBY32VWUny1NI\nxyVgeKCg7OG6az8hMiPTdgNeH1j7QeSS1IOx903wpW96xQg5WNjRY0XsoX3zV4Zp\nSzwxFb2FK7DG23Bd5WvbEjXNvNxye5VP3yRw3sF++6N/ehCwZjFv31DjaEtpKsjm\n1PVm/ioGcuj2Js2XShsnD8KFzA5wEBeNwXWyMSP1nYxOxKxDVekWDX7r0d68bwhd\nYYL+ojqMSlCo09RyPyueqXhN9ySXEh4WJoD4XhTLjhqypxmyS/vMkJxvHQARAQAB\n/gcDAkHlklVTgRCF8kdncV0yiilvIpJ/hvzBd8ufJl1+PtYBZT2JABvAjCJ7bISn\nvPyGxT3WiYltWQcR5pEnRpbUu8+lEuc04jHaJw3AV1qjgWSEAkCDPEJMFxci64nW\nrG7p0gc5Oi29irulnyKMBIq2cGuf3XVc0R2rPJaTltirmm+31qz3z8yamwBGu6Zv\npoWdc3YgE/xbqqSVWe7rY/MeNuQ90hBJUw5vi78Ztd8j1/kqijZWppJAHFMtod1f\nCoVvnXdysvS0Glr3pJPmKPkaBQrw4PnOzjRUa2BVQ//In9WcfY4osHMrb01tYhLZ\nBtN3/y3hg9XoTTa0GoFvAxUgf+RP5AeA4aRqI3TUsazNixgF487PA9Biiw1cA+Ca\nYAc/suCzzgzIBiItTwlyxymF+WQGN2DtaxgRESkvrwBdocW78gIJKykI262XweZo\neG4QJ2fFpb/OtGk0MVsZDhZWf8gLiTYLJVTlzq2upJT1eBlK0y0fMYsl9nOuWpeq\nv3QMBAY9M3jKAJDeJqo4laokEgzID1yL4A9M/RhY4BEjrgn9Nvs6IREIzlrHvE64\nhDHjlg7jC22Skt8mD6BoCFA2jfQj0qAPV2qLFlwRUr/W+rYA/l0vzELLZ7AkSg+B\nYmm6w+KG1LN976qdE5bMMk7I7uUIl5vm/Gcg7tIBxe+vhz3dhc6pu9OlujTZFq/f\n3ZrvizysLaq3mvBVgwoxWO2Uu3dRpxODS9ZzRPOEJaRt27sLNc22mppmkfhmYEyc\nkI4QT6c8ClvrS1ZH2ETycvN8uTdd8FXgOBcWJ9yjytnNEc0aYOdcrbiH6UWy9hRC\nIsQ5U/oSB94SpJpPCN+mT4o6G8UuykPUzz25nlfVK58s5MJuCZx2ozcxEbiNqDnh\nPm59zmrO/9a/DylSlJrMeZRKSsE6DX6UQz0KunHqseizQdtyKr6Hnvfk1Iv8vjyN\n8h7Xyy6ioNIYlbj+59qGbkYQdYoGB+Z0mMZx6igb+pyXZapoupPHVuEC2c200KWb\nlKAfvDnjAEPXncMoie4uORprovj9Ss9ZEvi1sYSYEBpS7fweZcCYTd4/s3TjE9Mr\npTeACEheI+b90uf4DBgorm8nGRhC55zftiJvOBuze7vel57OqFFZeUTuI2j77RM+\nUuzrSD/CbvdwbtpQDC3HFCU1J/84xkok8ofppp658ojD8sSxwtCFdZfD4lp7K8Lv\naTOFgaqxAo8ZSXv+gw46OJnM0lCQLA2DgYNAHeaIO0s6fRqwbNZ1kVS0XYjU7sb9\n7Py9HgI3EG1KMCFo8DU6CR1x/JMmnJ9ljraLqPoW/tkcMugkK7uSD1T7PVOoI0U5\ngFHfS0gRiX1aFrmNpzeoWbrVzdp+mrohU+ipLvEzAl305Pym4XgouaNtBkzGwV9c\neGJyfo3v6/IIkcVc6RNTMbc7zKGhYH3yGMDf5D1MGwXJqS8oxsYV7rZWoKKcMNgC\nd6/hTmegejhA744jTMbd1LUue3mnhAKt6bY6tNoDRGWLOT6mmdny++/QDHaZlNMe\nh046MRtH/5rh5QnZxjprlYqHzhxCmOIVcfiDGfycHQT2eDWyGALJ3sne9Xo1DDu3\netZHikMZDi5j9lxaN5Mx1rMjahXGvE7iIBgbbxNsQE4q9B11UsxK7eObbCNHW03B\nYk7KSmj1BgiPKHLje8UGZNE0wtV4IAcP+teTmbeaEri6r5AYpTfwGRq0Nkhhc2Fu\nIERpd2FuIChTaGFyZVBpZWNlLnB5IGtleSkgPGhhc2FuZGl3YW5AZ21haWwuY29t\nPokCNwQTAQoAIQUCVFWBqQIbAwULCQgHAwUVCgkICwUWAwIBAAIeAQIXgAAKCRDC\n1SnAppHt9w+YEACKBDICobj9aImOBVspWNs3xjCaGbN9ikq8vWk2t1VAOmwgcjFF\nsazw+emv3bIf3ApMwcsDYrqlg6SexwiWVrve8/RosGJCRVmXal4rCcgw+EyPNEoR\n9UYIR7DD/nRX6qvOJ3hVM9N/Yvm6hV94h1fLmS32thyy3UDR6aSoZ+pGcjQUgcNh\nOvdspyg8kQV4uL9erm0upPhayDwXaTyktrqg9Bc5q7+pOYf/wzKMjBiJV+MCffTi\ntUOesocKVtemYi+eKyMgug/TdFn3KA502fe1GnGxdscZN073JXOMboUkyHeJYoFb\n6177owCemwtqVlYuSPCHRujGIMtPRKGA46UdKlN2QrkbhC/UqtJA3h1OwP/pdjfx\nDv9UEhOESJWvQF3g2vGCOprRLZUW5UOLj1JLYFoE6//Ca40NYu6MrEX7dwswZaFY\nOhIEs57wWNTIG80PAe1psYv+0ns043dKDOZO5jrcxx/rBTi5vdYG1Jqtbsf+FXAP\nJz4bjHrrM96lCTH/xRoUcqKd22ie861RGGmRKnJN8AasYDaNhrfE8UJ1ir96dvpS\npplEjL/uDYiO0Mndw3uBl8qGNWRhmlOfVqJKqlRwIp2iPTfIHWTNo2pcI1uZQ6jA\nMvpjnLXpUqCIyAy04qn/uwuYsPP4USAW6cZN5XEIg7T6oXx4mlNioyCt3IkCIAQQ\nAQoACgUCV+d+cwMFA3gACgkQ/rrX/9BBu6Gr4BAAoGWLdhr4Pmz1FoUo+OCF/sG/\nlV8kfLXPzAZF9NEvhhHhnsZ9P+73kDcNuNeU0eq5z/MO5m5+nOBjY8eHUwlbxfcD\n6nMLkf/3XbIGy+7CD2Abk/OolWJHEVdbbGqCz7tHY3dPeW96W6r1uPbj+Bq/dF/h\nx91VqIJCrnFWRQaLPxiugy2u1UBRsVy6To1g4xSY2Nh2d+lxmSyEhXXsIJl8cb2p\n2477xjc3FRQ2ITqE/Rh8AoEGuKt2a5ljB8bkUImyQw3vyUilrao8Z+uNjQT2ZqP3\nTryiw+/GU3KbuST7hiYMZ89RSaMp5S9eROLldXOSIQH96A4vr8/FZouh6h5lCbRT\nX2lt4YwZZpa/8UoQdQb2q5Du3h3wMFnb17U/dBUjTV+kxaFYtT8KwMchuhWWPqng\ne8FoKGO79ETfKZ/pgH6HgjAV4nHqVR3xv1LfgAeL5HZOjruc9+OwWzPJehoqAjnh\n3mU6iu9XxvAZBVsZLHWdLZtIyKmXNDBEp8kESQ24CaGWwX89uL6WH8jY83Rli+8U\nDUg+n8mZvdKXxAc8GD8Qc+/6uWIDjl6iVksw7NbMbf8a1xrCatyj5KJ7mz2a9K1y\nmWmONHMKV6NabYRHejHmc6oi+fljyawDNEnMN+Hegd3BVv1iaqMYs90yhdnbudJ4\nYxFpK50fwPcXh/qJj5A=\n=ye4x\n-----END PGP PRIVATE KEY BLOCK-----");
body.put("text",
"-----BEGIN PGP SIGNED MESSAGE-----\nHash: SHA256\n\na\n-----BEGIN PGP SIGNATURE-----\n\niQIzBAEBCAAdFiEENROx5p50mTOovE9CwtUpwKaR7fcFAmB7siYACgkQwtUpwKaR\n7fcixA/+LmmJsj8yCPWP139SyyZPQ1wC2M+eNwgWZpqGjb1Vi+gdekxGmHOHW8eI\nChx8svyqBRWgh5+JWDDkBfUeRaqsMVBKnAodMVYhOWpqlKZuC4oXaMlFwVs8Kny1\ngM5qXNfRA4MIXsy3jRYjaTE2qT5be+y8U7On/rITZ8G41qBK4NEXvgIJfCejYXar\nZaES1BXnVxugIEOJWQ0l8p0RwxxOPfcBv6UsW9kfxWmitdFBFmGWl1AYIMwdI/WI\nD7KTPq2LeRYRYiDVzTxWKKvNVELl9n1Tqb0MnKM0By++QR4VdMx6ROQiKSvlaXF0\nKU5m5GkRPZkaWRP6lkjXssNXcAI/PMoySWvAMQb1Fil0iTp/eM5Bm6Y7qKU+TQFl\n30SKmv4DWCuL808AB2YXKdw2uM85q7u8DYo36lVHU8aFeMp8LPQIH0drwdBTdm3e\n6LW0SrwrP2LF/r+IH+4tXFu6mmnDcCNx1a/D1nyxD4s7F/vqbkHkqBxaIE/M2GiV\newQr9NW9QaEbzC9ZSi777a62Nk2g4BtQVOCIzyOZFwqiANazpVxS2Y4yGuMrxU6j\nX739U+KJTRQhO+VU5DYs2aKyHafSND9rv6Fdxn/mtzeGdGJ5TlqAc/wBUfKc7sfr\nCNq2RsUFP+nsTBKvvC+C6tky/gVW7aMLnuF+Er7eQVARmNnvDzg=\n=Iju/\n-----END PGP SIGNATURE-----\n");
final Request verified = new Request.Builder().url(url)
.post(RequestBody.create(ShareTests.mapper.writeValueAsBytes(body))).build();
final Response rawResponse = ShareTests.client.newCall(verified).execute();
final Map<String, String> response = ShareTests.mapper.readValue(rawResponse.body().bytes(),
new TypeReference<Map<String, String>>() {
});
Assert.assertTrue("true".equals(response.get("verified")) || "false".equals(response.get("verified")));
System.setProperty("openpgp.helper", saved);
}
}
package us.d8u.balance;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;
import org.apache.http.HttpStatus;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
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.test.context.junit4.SpringRunner;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ObjectNode;
import com.rometools.rome.io.impl.Base64;
import okhttp3.HttpUrl;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
// Sender id: 18445195959
@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT)
public class SmsTests {
private static final OkHttpClient client = new OkHttpClient();
private static final Logger LOG = LogManager.getLogger(SmsTests.class);
private static final ObjectMapper mapper = new ObjectMapper();
private static final Properties settings = new Properties();
@LocalServerPort
private int port;
@Test
public void postSmsTakesEmail() throws Exception {
final ObjectNode body = SmsTests.mapper.createObjectNode();
final String authHeader = "Basic " + Base64.encode("test:");
body.put("text", "hello world");
body.put("destination", "hasan.diwan@gmail.com");
final HttpUrl url = HttpUrl.parse("http://localhost/sms").newBuilder().port(this.port).build();
final Request request = new Request.Builder().url(url).addHeader("authorization", authHeader)
.post(RequestBody.create(SmsTests.mapper.writeValueAsBytes(body), MediaType.parse("application/json")))
.build();
final Response rawResponse = SmsTests.client.newCall(request).execute();
Assert.assertTrue(rawResponse.code() == HttpStatus.SC_CREATED);
}
@Test
public void postSmsTakesValidNumber() throws Exception {
final String authHeader = "Basic " + Base64.encode("test:");
final ObjectNode body = SmsTests.mapper.createObjectNode();
body.put("text", "hello world");
body.put("destination", "+8615555555555");
final HttpUrl url = HttpUrl.parse("http://localhost/sms").newBuilder().port(this.port).build();
final Request request = new Request.Builder().url(url).addHeader("authorization", authHeader)
.post(RequestBody.create(SmsTests.mapper.writeValueAsBytes(body), MediaType.parse("application/json")))
.build();
final Response rawResponse = SmsTests.client.newCall(request).execute();
Assert.assertTrue(rawResponse.code() == HttpStatus.SC_CREATED);
}
@Before
public void setup() {
final InputStream path = this.getClass().getResourceAsStream("/application.properties");
try {
SmsTests.settings.load(path);
} catch (final IOException e) {
SmsTests.LOG.error(e.getLocalizedMessage());
}
}
@Test
public void textAndDestinationAreRequired() throws Exception {
final String authHeader = "Basic " + Base64.encode("test:");
final ObjectNode body = SmsTests.mapper.createObjectNode();
body.put("text", "hello world");
final HttpUrl url = HttpUrl.parse("http://localhost/sms").newBuilder().port(this.port).build();
final Request request = new Request.Builder().url(url).addHeader("authorization", authHeader)
.post(RequestBody.create(SmsTests.mapper.writeValueAsBytes(body), MediaType.parse("application/json")))
.build();
final Response rawResponse = SmsTests.client.newCall(request).execute();
final JsonNode response = SmsTests.mapper.readTree(rawResponse.body().bytes());
Assert.assertTrue("text key corresponding to message required; destination containing phone number required"
.equals(response.get("error").asText()));
}
@Test
public void wrongAuthReturns401() throws Exception {
final String authHeader = "Basic " + Base64.encode("testInvalid:");
final ObjectNode body = SmsTests.mapper.createObjectNode();
body.put("text", "hello world");
body.put("destination", "+61422222222");
final HttpUrl url = HttpUrl.parse("http://localhost/sms").newBuilder().port(this.port).build();
final Request request = new Request.Builder().url(url).addHeader("authorization", authHeader)
.post(RequestBody.create(SmsTests.mapper.writeValueAsBytes(body), MediaType.parse("application/json")))
.build();
final Response rawResponse = SmsTests.client.newCall(request).execute();
final JsonNode response = SmsTests.mapper.readTree(rawResponse.body().bytes());
Assert.assertTrue(response.get("status").asInt() == HttpStatus.SC_UNAUTHORIZED);
}
}
package us.d8u.balance;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
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.test.context.junit4.SpringRunner;
import okhttp3.HttpUrl;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT)
public class SpaCyTests {
private static final OkHttpClient client = new OkHttpClient.Builder().followRedirects(false).build();
@LocalServerPort
private int port;
@Test
public void spaCyRedirectsProperly() throws Exception {
final HttpUrl url = HttpUrl.parse("http://localhost:" + this.port + "/spaCy");
final Response response = SpaCyTests.client.newCall(new Request.Builder().url(url).build()).execute();
Assert.assertTrue("Location incorrect", "https://hasan.dd8u.us/spaCy.pdf".equals(response.header("Location")));
}
}
package us.d8u.balance;
import java.util.Collections;
import java.util.Map;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
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.test.context.junit4.SpringRunner;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
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 SpellTest {
private static final OkHttpClient client = new OkHttpClient();
@LocalServerPort
private int port;
@Test
public void testSpellingCorrection() throws Exception {
final String mispelt = "the quikc brown fox jumped over the lazy dog";
final String expected = "the quick brown fox jumped over the lazy dog";
final Map<String, String> sending = Collections.singletonMap("text", mispelt);
final String json = new ObjectMapper().writeValueAsString(sending);
final RequestBody jsonSrc = RequestBody.create(json, MediaType.parse("application/json"));
final Request spellRequest = new Request.Builder().url("http://localhost:" + this.port + "/spell").post(jsonSrc)
.build();
final Response rawResponse = SpellTest.client.newCall(spellRequest).execute();
final JsonNode response = new ObjectMapper().readTree(rawResponse.body().string());
final String text = response.asText();
Assert.assertTrue(expected.equals(text));
}
}
package us.d8u.balance;
import java.io.File;
import java.sql.Date;
import java.util.Calendar;
import java.util.Collections;
import java.util.Map;
import org.joda.time.DateTime;
import org.joda.time.format.DateTimeFormatter;
import org.joda.time.format.ISODateTimeFormat;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
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.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.simple.SimpleJdbcInsert;
import org.springframework.jdbc.datasource.DriverManagerDataSource;
import org.springframework.test.context.junit4.SpringRunner;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ObjectNode;
import com.google.common.collect.Maps;
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 SQLTests {
static OkHttpClient client = new OkHttpClient();
static ObjectMapper mapper = new ObjectMapper();
@LocalServerPort
private Integer port;
JdbcTemplate jdbcTemplate;
@Test
public void booleansAreTrueOrFalse() throws Exception {
final String jdbcUrl = "jdbc:postgresql://localhost/template1?username=user&password=Wonju777";
final DriverManagerDataSource dataSource = new DriverManagerDataSource();
dataSource.setUrl(jdbcUrl);
dataSource.setDriverClassName("org.postgresql.Driver");
dataSource.setUsername("user");
dataSource.setPassword("Wonju777");
this.jdbcTemplate = new JdbcTemplate(dataSource);
this.jdbcTemplate.execute("DROP TABLE IF EXISTS temporarytbl; CREATE TABLE temporaryTbl (col1 boolean)");
final SimpleJdbcInsert simpleJdbcInsert = new SimpleJdbcInsert(dataSource).withTableName("temporaryTbl");
simpleJdbcInsert.execute(Collections.singletonMap("col1", "true"));
final Map<String, String> params = Maps.newHashMap();
params.put("stmt", "select col1 from temporaryTbl");
params.put("jdbcUrl", jdbcUrl);
params.put("driverClass", "org.postgresql.Driver");
final String paramsAsJson = new ObjectMapper().writeValueAsString(params);
final RequestBody requestBody = RequestBody.create(paramsAsJson, MediaType.parse("application/json"));
final String requestUrl = "http://localhost:" + this.port + "/sql";
final Request request = new Request.Builder().url(requestUrl).post(requestBody).build();
final JsonNode response = SQLTests.mapper
.readTree(new OkHttpClient.Builder().build().newCall(request).execute().body().bytes());
Assert.assertTrue("t".equals(response.get("results").get(0).get("col1").asText().replace("\"", "")));
this.jdbcTemplate.execute("drop table temporarytbl");
}
@Test
public void canConnectToOnion() throws Exception {
final String jdbcUrl = "jdbc:postgresql://o25y5ku5gmhonfyv5mln7jxhjpzl2i2lj3vprxwn5f3xbv4zg6ftuvad.onion:5432/template1?username=user";
final Map<String, String> params = Maps.newHashMap();
params.put("stmt", "select 1*1 as res");
params.put("jdbcUrl", jdbcUrl);
params.put("driverClass", "org.postgresql.Driver");
final String paramsAsJson = new ObjectMapper().writeValueAsString(params);
final RequestBody requestBody = RequestBody.create(paramsAsJson, MediaType.parse("application/json"));
final String requestUrl = "http://localhost:" + this.port + "/sql";
final Request request = new Request.Builder().url(requestUrl).post(requestBody).build();
final JsonNode response = SQLTests.mapper
.readTree(new OkHttpClient.Builder().build().newCall(request).execute().body().bytes());
Assert.assertTrue(response.get("results").get(0).get("res").asInt() == 1);
}
@Test
public void datesAreISO8601Format() throws Exception {
final String jdbcUrl = "jdbc:postgresql://localhost/template1?username=user&password=Wonju777";
final DriverManagerDataSource dataSource = new DriverManagerDataSource();
dataSource.setUrl(jdbcUrl);
dataSource.setDriverClassName("org.postgresql.Driver");
dataSource.setUsername("user");
dataSource.setPassword("Wonju777");
this.jdbcTemplate = new JdbcTemplate(dataSource);
this.jdbcTemplate.execute("DROP TABLE IF EXISTS temporarytbl;CREATE TABLE temporaryTbl (col1 DATE)");
final SimpleJdbcInsert simpleJdbcInsert = new SimpleJdbcInsert(dataSource).withTableName("temporaryTbl");
simpleJdbcInsert.execute(Collections.singletonMap("col1", new Date(DateTime.now().getMillis())));
final Map<String, String> params = Maps.newHashMap();
params.put("stmt", "select col1 from temporaryTbl");
params.put("jdbcUrl", jdbcUrl);
params.put("driverClass", "org.postgresql.Driver");
final String paramsAsJson = new ObjectMapper().writeValueAsString(params);
final RequestBody requestBody = RequestBody.create(paramsAsJson, MediaType.parse("application/json"));
final String requestUrl = "http://localhost:" + this.port + "/sql";
final Request request = new Request.Builder().url(requestUrl).post(requestBody).build();
final JsonNode response = SQLTests.mapper
.readTree(new OkHttpClient.Builder().build().newCall(request).execute().body().bytes());
final DateTimeFormatter fmt = ISODateTimeFormat.date();
Assert.assertTrue("Not ISO Format",
fmt.parseDateTime(response.get("results").get(0).get("col1").asText().replace("\"", "")) != null);
this.jdbcTemplate.execute("DROP TABLE temporaryTbl");
}
@Test
public void driverAutoRetrieved() throws Exception {
final String jdbcUrl = "jdbc:postgresql://localhost/template1?username=user&password=Wonju777";
final DriverManagerDataSource dataSource = new DriverManagerDataSource();
dataSource.setUrl(jdbcUrl);
dataSource.setDriverClassName("org.postgresql.Driver");
dataSource.setUsername("user");
dataSource.setPassword("Wonju777");
this.jdbcTemplate = new JdbcTemplate(dataSource);
this.jdbcTemplate.execute(
"DROP TABLE IF EXISTS temporarytbl;CREATE TABLE temporaryTbl (col1 int, col2 float, col3 smallint)");
final Map<String, Object> params = Maps.newHashMap();
params.put("col1", 1);
params.put("col2", 1.4f);
params.put("col3", 1);
final SimpleJdbcInsert simpleJdbcInsert = new SimpleJdbcInsert(dataSource).withTableName("temporaryTbl");
simpleJdbcInsert.execute(params);
params.clear();
params.put("stmt", "select col1, col2, col3 from temporaryTbl");
params.put("jdbcUrl", jdbcUrl);
final String paramsAsJson = new ObjectMapper().writeValueAsString(params);
final RequestBody requestBody = RequestBody.create(paramsAsJson, MediaType.parse("application/json"));
final String requestUrl = "http://localhost:" + this.port + "/sql";
final Request request = new Request.Builder().url(requestUrl).post(requestBody).build();
final JsonNode response = SQLTests.mapper
.readTree(new OkHttpClient.Builder().build().newCall(request).execute().body().string());
Assert.assertTrue(
"org.postgresql.jdbc.PgConnection".equals(response.get("incoming").get("driverClass").asText()));
}
@Test
public void incorrectAuthenticationReturnsGracefully() throws Exception {
final String jdbcUrl = "jdbc:postgresql://localhost/template1?username=use&password=Wonju777";
final DriverManagerDataSource dataSource = new DriverManagerDataSource();
dataSource.setUrl(jdbcUrl);
dataSource.setDriverClassName("org.postgresql.Driver");
dataSource.setUsername("user");
dataSource.setPassword("Wonju777");
this.jdbcTemplate = new JdbcTemplate(dataSource);
this.jdbcTemplate.execute("DROP TABLE IF EXISTS temporarytbl; CREATE TABLE temporaryTbl (col1 boolean)");
final SimpleJdbcInsert simpleJdbcInsert = new SimpleJdbcInsert(dataSource).withTableName("temporaryTbl");
simpleJdbcInsert.execute(Collections.singletonMap("col1", "true"));
final Map<String, String> params = Maps.newHashMap();
params.put("stmt", "select col1 from temporaryTbl");
params.put("jdbcUrl", jdbcUrl);
params.put("driverClass", "org.postgresql.Driver");
final String paramsAsJson = new ObjectMapper().writeValueAsString(params);
final RequestBody requestBody = RequestBody.create(paramsAsJson, MediaType.parse("application/json"));
final String requestUrl = "http://localhost:" + this.port + "/sql";
final Request request = new Request.Builder().url(requestUrl).post(requestBody).build();
final JsonNode response = SQLTests.mapper
.readTree(new OkHttpClient.Builder().build().newCall(request).execute().body().bytes());
Assert.assertTrue(response.get("results").get("status").asInt() == 500);
}
@Test
public void invalidStatementReturnsException() throws Exception {
final File databaseLocation = File.createTempFile("sqlite3-temp", ".sqlite3");
final String jdbcUrl = "jdbc:sqlite:" + databaseLocation.getAbsolutePath();
final String stmt = "select * from wherewashasana";
final String driverClass = "org.sqlite.JDBC";
final Map<String, String> params = Maps.newHashMap();
params.put("jdbcUrl", jdbcUrl);
params.put("stmt", stmt);
params.put("driverClass", driverClass);
final String paramsAsJson = new ObjectMapper().writeValueAsString(params);
final RequestBody requestBody = RequestBody.create(paramsAsJson, MediaType.parse("application/json"));
final String requestUrl = "http://localhost:" + this.port + "/sql";
final Request request = new Request.Builder().url(requestUrl).post(requestBody).build();
final Response rawResponse = SQLTests.client.newCall(request).execute();
final JsonNode results = new ObjectMapper().readTree(rawResponse.body().bytes());
Assert.assertEquals(results.get("results").get("status").asInt(), 500);
}
@Test(expected = RuntimeException.class)
public void invalidUrlForSqlThrowsException() throws Exception {
final String stmt = "SELECT 1+1 AS result";
final String driverClass = "org.postgresql.Driver";
final Map<String, String> params = Maps.newHashMap();
params.put("stmt", stmt);
params.put("driverClass", driverClass);
final String paramsAsJson = SQLTests.mapper.writeValueAsString(params);
final RequestBody requestBody = RequestBody.create(paramsAsJson, MediaType.parse("application/json"));
final String requestUrl = "http://localhost:" + this.port + "/sql";
final Request request = new Request.Builder().url(requestUrl).post(requestBody).build();
SQLTests.client.newCall(request).execute();
}
@Test
public void missingPasswordGivesError() throws Exception {
final String jdbcUrl = "jdbc:postgresql://localhost/template1?username=me";
final String stmt = "select 1";
final String driverClass = "org.postgresql.Driver";
final Map<String, String> params = Maps.newHashMap();
params.put("jdbcUrl", jdbcUrl);
params.put("stmt", stmt);
params.put("driverClass", driverClass);
final String paramsAsJson = new ObjectMapper().writeValueAsString(params);
final RequestBody requestBody = RequestBody.create(paramsAsJson, MediaType.parse("application/json"));
final String requestUrl = "http://localhost:" + this.port + "/sql";
final Request request = new Request.Builder().url(requestUrl).post(requestBody).build();
final Response rawResponse = SQLTests.client.newCall(request).execute();
final ObjectNode result = new ObjectMapper().readValue(rawResponse.body().bytes(), ObjectNode.class);
Assert.assertTrue("missing password yields" + result.get("error").asText(),
"missing password".equals(result.get("error").asText()));
}
@Test
public void missingUsernameGivesError() throws Exception {
final String jdbcUrl = "jdbc:postgresql://localhost/template1";
final String stmt = "select 1";
final String driverClass = "org.postgresql.Driver";
final Map<String, String> params = Maps.newHashMap();
params.put("jdbcUrl", jdbcUrl);
params.put("stmt", stmt);
params.put("driverClass", driverClass);
final String paramsAsJson = new ObjectMapper().writeValueAsString(params);
final RequestBody requestBody = RequestBody.create(paramsAsJson, MediaType.parse("application/json"));
final String requestUrl = "http://localhost:" + this.port + "/sql";
final Request request = new Request.Builder().url(requestUrl).post(requestBody).build();
final Response rawResponse = SQLTests.client.newCall(request).execute();
final ObjectNode result = new ObjectMapper().readValue(rawResponse.body().bytes(), ObjectNode.class);
Assert.assertTrue("missing username yields" + result.get("error").asText(),
"missing username".equals(result.get("error").asText()));
}
@Test
public void numbersAreNumbers() throws Exception {
final String jdbcUrl = "jdbc:postgresql://localhost/template1?username=user&password=Wonju777";
final DriverManagerDataSource dataSource = new DriverManagerDataSource();
dataSource.setUrl(jdbcUrl);
dataSource.setDriverClassName("org.postgresql.Driver");
dataSource.setUsername("user");
dataSource.setPassword("Wonju777");
this.jdbcTemplate = new JdbcTemplate(dataSource);
this.jdbcTemplate.execute(
"DROP TABLE IF EXISTS temporarytbl;CREATE TABLE temporaryTbl (col1 int, col2 float, col3 smallint)");
final Map<String, Object> params = Maps.newHashMap();
params.put("col1", 1);
params.put("col2", 1.4f);
params.put("col3", 1);
final SimpleJdbcInsert simpleJdbcInsert = new SimpleJdbcInsert(dataSource).withTableName("temporaryTbl");
simpleJdbcInsert.execute(params);
params.clear();
params.put("stmt", "select col1, col2, col3 from temporaryTbl");
params.put("jdbcUrl", jdbcUrl);
params.put("driverClass", "org.postgresql.Driver");
final String paramsAsJson = new ObjectMapper().writeValueAsString(params);
final RequestBody requestBody = RequestBody.create(paramsAsJson, MediaType.parse("application/json"));
final String requestUrl = "http://localhost:" + this.port + "/sql";
final Request request = new Request.Builder().url(requestUrl).post(requestBody).build();
final JsonNode response = SQLTests.mapper
.readTree(new OkHttpClient.Builder().build().newCall(request).execute().body().string());
Assert.assertTrue("Integer not formatted correctly", response.get("results").get(0).get("col3").asInt() == 1);
Assert.assertTrue("Float not formatted correctly",
response.get("results").get(0).get("col2").floatValue() == 1.4f);
}
@Test
public void onionRequiresPort() throws Exception {
final String jdbcUrl = "jdbc:postgresql://o25y5ku5gmhonfyv5mln7jxhjpzl2i2lj3vprxwn5f3xbv4zg6ftuvad.onion/template1?username=user";
final Map<String, String> params = Maps.newHashMap();
params.put("stmt", "select 1*1 as res");
params.put("jdbcUrl", jdbcUrl);
params.put("driverClass", "org.postgresql.Driver");
final String paramsAsJson = new ObjectMapper().writeValueAsString(params);
final RequestBody requestBody = RequestBody.create(paramsAsJson, MediaType.parse("application/json"));
final String requestUrl = "http://localhost:" + this.port + "/sql";
final Request request = new Request.Builder().url(requestUrl).post(requestBody).build();
final JsonNode response = SQLTests.mapper
.readTree(new OkHttpClient.Builder().build().newCall(request).execute().body().bytes());
Assert.assertTrue("Port required".equals(response.get("error").asText()));
}
@Test
public void queryReturns() throws Exception {
final var stmt = "SELECT concat('https://hd1-logging.herokuapp.com/go/', id) as shortlink, id, coalesce(metadata->>'clicked', '-1')::integer as clicked, metadata->>'To' as to, metadata ->> 'Link' as target, (read_on at time zone 'utc')::date as read_on from applicationlogs order by read_on";
final String jdbcUrl = "postgres://rbtoqdtclfgghv:74f78a1f9b642657ea31dbfdf05beec86b72ddb1fd29fc5f93bf9b32fffcb7ae@ec2-174-129-253-146.compute-1.amazonaws.com:5432/d66osk0an34pip";
final String driverName = "org.postgresql.Driver";
final ObjectNode params = SQLTests.mapper.createObjectNode();
params.put("driverClass", driverName);
params.put("jdbcUrl", jdbcUrl);
params.put("stmt", stmt);
final String paramsAsJson = new ObjectMapper().writeValueAsString(params);
final RequestBody requestBody = RequestBody.create(paramsAsJson, MediaType.parse("application/json"));
final String requestUrl = "http://localhost:" + this.port + "/sql";
final Request request = new Request.Builder().url(requestUrl).post(requestBody).build();
final Response rawResponse = SQLTests.client.newCall(request).execute();
final JsonNode results = new ObjectMapper().readTree(rawResponse.body().bytes());
Assert.assertTrue("results is not array", results.get("results").isArray());
Assert.assertTrue(results.get("results").size() > 0);
Assert.assertTrue("Statement not found", stmt.equals(results.get("metadata").get("stmt").asText()));
Assert.assertTrue("URL not found", jdbcUrl.equals(results.get("metdata").get("jdbcUrl").asText()));
Assert.assertTrue("driver not found", driverName.equals(results.get("metadata").get("driverClass").asText()));
}
@Test
public void timesAreISO8601Format() throws Exception {
final String jdbcUrl = "jdbc:postgresql://localhost/template1?username=user&password=Wonju777";
final DriverManagerDataSource dataSource = new DriverManagerDataSource();
dataSource.setUrl(jdbcUrl);
dataSource.setDriverClassName("org.postgresql.Driver");
dataSource.setUsername("user");
dataSource.setPassword("Wonju777");
this.jdbcTemplate = new JdbcTemplate(dataSource);
this.jdbcTemplate.execute("DROP TABLE IF EXISTS temporarytbl;CREATE TABLE temporaryTbl (col1 TIME)");
final SimpleJdbcInsert simpleJdbcInsert = new SimpleJdbcInsert(dataSource).withTableName("temporaryTbl");
simpleJdbcInsert.execute(Collections.singletonMap("col1", new Date(DateTime.now().getMillis())));
final Map<String, String> params = Maps.newHashMap();
params.put("stmt", "select col1 from temporaryTbl");
params.put("jdbcUrl", jdbcUrl);
params.put("driverClass", "org.postgresql.Driver");
final String paramsAsJson = new ObjectMapper().writeValueAsString(params);
final RequestBody requestBody = RequestBody.create(paramsAsJson, MediaType.parse("application/json"));
final String requestUrl = "http://localhost:" + this.port + "/sql";
final Request request = new Request.Builder().url(requestUrl).post(requestBody).build();
final JsonNode response = SQLTests.mapper
.readTree(new OkHttpClient.Builder().build().newCall(request).execute().body().bytes());
final DateTimeFormatter fmt = ISODateTimeFormat.timeNoMillis();
Assert.assertTrue("Not ISO Format",
fmt.parseDateTime(response.get("results").get(0).get("col1").asText()) != null);
}
@Test
public void timestampsAreISO8601Format() throws Exception {
final String jdbcUrl = "jdbc:postgresql://localhost/template1?username=user&password=Wonju777";
final DriverManagerDataSource dataSource = new DriverManagerDataSource();
dataSource.setUrl(jdbcUrl);
dataSource.setDriverClassName("org.postgresql.Driver");
dataSource.setUsername("user");
dataSource.setPassword("Wonju777");
this.jdbcTemplate = new JdbcTemplate(dataSource);
this.jdbcTemplate.execute("DROP TABLE IF EXISTS temporarytbl;CREATE TABLE temporaryTbl (col1 TIMESTAMP)");
final SimpleJdbcInsert simpleJdbcInsert = new SimpleJdbcInsert(dataSource).withTableName("temporaryTbl");
simpleJdbcInsert.execute(Collections.singletonMap("col1", Calendar.getInstance().getTime()));
final Map<String, String> params = Maps.newHashMap();
params.put("stmt", "select col1 from temporaryTbl");
params.put("jdbcUrl", jdbcUrl);
params.put("driverClass", "org.postgresql.Driver");
final String paramsAsJson = new ObjectMapper().writeValueAsString(params);
final RequestBody requestBody = RequestBody.create(paramsAsJson, MediaType.parse("application/json"));
final String requestUrl = "http://localhost:" + this.port + "/sql";
final Request request = new Request.Builder().url(requestUrl).post(requestBody).build();
final JsonNode response = SQLTests.mapper
.readTree(new OkHttpClient.Builder().build().newCall(request).execute().body().bytes());
final DateTimeFormatter fmt = ISODateTimeFormat.dateTime();
final String timestampCandid8 = response.get("results").get(0).get("col1").asText();
try {
fmt.parseDateTime(timestampCandid8);
} catch (final RuntimeException e) {
Assert.fail("timestamp not formatted correctly " + timestampCandid8);
}
}
@Test
public void validStatementReturnsJson() throws Exception {
final String jdbcUrl = "jdbc:postgresql:///template1?username=user&password=Wonju777";
final String stmt = "select 1-1 as difference";
final String driverClass = "org.postgresql.Driver";
final Map<String, String> params = Maps.newHashMap();
params.put("jdbcUrl", jdbcUrl);
params.put("stmt", stmt);
params.put("driverClass", driverClass);
final String paramsAsJson = new ObjectMapper().writeValueAsString(params);
final RequestBody requestBody = RequestBody.create(paramsAsJson, MediaType.parse("application/json"));
final String requestUrl = "http://localhost:" + this.port + "/sql";
final Request request = new Request.Builder().url(requestUrl).post(requestBody).build();
final Response rawResponse = SQLTests.client.newCall(request).execute();
final ObjectNode result = new ObjectMapper().readValue(rawResponse.body().bytes(), ObjectNode.class);
Assert.assertEquals(result.get("incoming").get("query").asText(), stmt);
Assert.assertTrue(result.get("results").get(0).get("difference").asInt() == 0);
}
}
package us.d8u.balance;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import org.joda.time.DateTime;
import org.joda.time.format.DateTimeFormatter;
import org.joda.time.format.ISODateTimeFormat;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
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.test.context.junit4.SpringRunner;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.common.collect.Sets;
import okhttp3.HttpUrl;
import okhttp3.OkHttpClient;
import okhttp3.Request;
@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT)
public class SSLCheckTests {
private static final OkHttpClient client = new OkHttpClient();
@LocalServerPort
private int port;
@Test
public void sslCheckValidUrl() throws Exception {
final TypeReference<List<Map<String, String>>> tf = new TypeReference<>() {
};
final Request request = new Request.Builder()
.url(HttpUrl.parse("http://localhost:" + this.port + "/sslCheck/hasan.d8u.us/")).build();
final List<Map<String, String>> response = new ObjectMapper()
.readValue(SSLCheckTests.client.newCall(request).execute().body().string(), tf);
final DateTimeFormatter dateFormatter = ISODateTimeFormat.dateTimeNoMillis();
final HashSet<String> expectedSet = Sets.newHashSet("serialNumber", "time", "expirationTime", "validTime",
"publicKey", "signatureAlgorithm", "issuer", "type");
for (final Map<String, String> aCert : response) {
final DateTime expiration = dateFormatter.parseDateTime(aCert.get("expirationTime"));
final DateTime start = dateFormatter.parseDateTime(aCert.get("validTime"));
Assert.assertTrue("Certificate expiration, " + aCert.get("expirationTime") + " is before start, "
+ aCert.get("validTime") + "?", start.isBefore(expiration));
Assert.assertTrue(aCert.keySet() + " is not " + expectedSet, expectedSet.equals(aCert.keySet()));
}
}
}
package us.d8u.balance;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Map;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
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.test.context.junit4.SpringRunner;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
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 StatsTests {
private static final OkHttpClient client = new OkHttpClient();
@LocalServerPort
private int port;
String SAMPLE_CSV = "9,8,7,6";
@Test
public void canAddNewDataToBeFittedWithCustomSeparator() throws Exception {
final Map<String, String> postBody = Maps.newHashMap();
postBody.put("email", "GHMjD0Lp5DY@mailinator.com");
postBody.put("data", this.SAMPLE_CSV.replace(" ", "").replace(",", ";"));
postBody.put("separator", ";");
final okhttp3.RequestBody body = okhttp3.RequestBody.create(new ObjectMapper().writeValueAsBytes(postBody),
MediaType.parse("application/json"));
final HttpUrl fitEndpoint = HttpUrl.parse("http://localhost:" + this.port + "/fit");
final Request request = new Request.Builder().url(fitEndpoint).post(body).build();
final Response response = StatsTests.client.newCall(request).execute();
final 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 canAddNewDataToBeFittedWithDefaultSeparator() throws Exception {
final Map<String, String> postBody = Maps.newHashMap();
postBody.put("email", "GHMjD0Lp5DY@mailinator.com");
postBody.put("data", this.SAMPLE_CSV.replace(" ", ""));
final okhttp3.RequestBody body = okhttp3.RequestBody.create(new ObjectMapper().writeValueAsBytes(postBody),
MediaType.parse("application/json"));
final HttpUrl fitEndpoint = HttpUrl.parse("http://localhost:" + this.port + "/fit");
final Request request = new Request.Builder().url(fitEndpoint).post(body).build();
final Response response = StatsTests.client.newCall(request).execute();
final 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 statAllowsNegativeAndFractionalValues() throws Exception {
final MediaType mediaType = MediaType.parse("text/csv");
final RequestBody body = RequestBody.create("-6,7,8,9,0.1", mediaType);
final Request request = new Request.Builder().url("http://localhost:" + this.port + "/stat/mean")
.method("POST", body).addHeader("Content-Type", " text/csv").build();
final Response response = StatsTests.client.newCall(request).execute();
Assert.assertEquals(true, response.isSuccessful());
}
@Test
public void statDefaultsToCommaAsDelimiter() throws Exception {
final MediaType mediaType = MediaType.parse("application/csv");
final RequestBody body = RequestBody.create("9;8;7", mediaType);
final Request request = new Request.Builder().url("http://localhost:" + this.port + "/stat/mean")
.method("POST", body).addHeader("Content-Type", "application/csv").build();
final Response response = StatsTests.client.newCall(request).execute();
final 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 statHandlesEmbeddedSpaces() throws Exception {
final String requestBody = "1, 2, 3";
final RequestBody body = RequestBody.create(requestBody, MediaType.parse("application/csv"));
final Request request = new Request.Builder().url(
new HttpUrl.Builder().host("localhost").scheme("http").port(this.port).addPathSegment("stat").build())
.post(body).build();
final Response response = StatsTests.client.newCall(request).execute();
Assert.assertTrue(response.isSuccessful());
}
@Test
public void statHandlesTrailingCommas() throws Exception {
final String requestBody = "1,2,3,";
final RequestBody body = RequestBody.create(requestBody, MediaType.parse("application/csv"));
final Request request = new Request.Builder().url(
new HttpUrl.Builder().host("localhost").scheme("http").port(this.port).addPathSegment("stat").build())
.post(body).build();
final Response response = StatsTests.client.newCall(request).execute();
Assert.assertTrue(response.isSuccessful());
}
@Test
public void statsLinearRegression() throws Exception {
final MediaType mediaType = MediaType.parse("text/csv");
final 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);
final Request request = new Request.Builder().url("http://localhost:" + this.port + "/stats/lm")
.method("POST", body).addHeader("Content-Type", "text/csv").build();
final Response response = StatsTests.client.newCall(request).execute();
final JsonNode responseMap = new ObjectMapper().readValue(response.body().string(), JsonNode.class);
final ArrayList<String> keys = Lists.newArrayList(responseMap.fieldNames());
Collections.sort(keys);
Assert.assertTrue(keys.equals(
Lists.newArrayList("intercept", "interceptError", "rSquared", "slope", "slopeErr", "stdErr", "time")));
Assert.assertTrue("20.673".equals(responseMap.get("intercept").asText()));
Assert.assertTrue("0.22".equals(responseMap.get("slopeErr").asText()));
Assert.assertTrue("0.017".equals(responseMap.get("rSquared").asText()));
Assert.assertTrue(
"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"
.equals(responseMap.get("source").asText()));
Assert.assertTrue("1.679".equals(responseMap.get("interceptErr").asText()));
Assert.assertTrue("0.1".equals(responseMap.get("slope").asText()));
}
@Test
public void statsLowerQuartile() throws Exception {
final MediaType mediaType = MediaType.parse("text/csv");
final 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);
final Request request = new Request.Builder().url("http://localhost:" + this.port + "/stats/lowerQuartile")
.method("POST", body).addHeader("Content-Type", "text/csv").build();
final Response response = StatsTests.client.newCall(request).execute();
final JsonNode responseMap = new ObjectMapper().readValue(response.body().string(), JsonNode.class);
Assert.assertTrue("18.79".equals(responseMap.get("lowerQuartile").asText()));
}
@Test
public void statsMaxWorks() throws Exception {
final MediaType mediaType = MediaType.parse("text/csv");
final 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);
final Request request = new Request.Builder().url("http://localhost:" + this.port + "/stats/max")
.method("POST", body).addHeader("Content-Type", "text/csv").build();
final Response response = StatsTests.client.newCall(request).execute();
final JsonNode responseMap = new ObjectMapper().readValue(response.body().string(), JsonNode.class);
Assert.assertTrue("27.27".equals(responseMap.get("maximum").asText()));
}
@Test
public void statsMeanModeWorks() throws Exception {
final MediaType mediaType = MediaType.parse("text/csv");
final RequestBody body = RequestBody.create("9,8,7,6,8", mediaType);
final Request request = new Request.Builder().url("http://localhost:" + this.port + "/stat/mean")
.method("POST", body).addHeader("Content-Type", "text/csv").build();
final Response response = StatsTests.client.newCall(request).execute();
final Map<String, String> responseObj = new ObjectMapper().readValue(response.body().bytes(),
new TypeReference<Map<String, String>>() {
});
Assert.assertTrue("7.6".equals(responseObj.get("arithmeticMean")));
Assert.assertTrue("7.528948990654704".equals(responseObj.get("geometricMean")));
Assert.assertTrue("23.68814".equals(responseObj.get("harmonicMean")));
Assert.assertTrue("8".equals(responseObj.get("mode")));
}
@Test
public void statsMinWorks() throws Exception {
final MediaType mediaType = MediaType.parse("text/csv");
final 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);
final Request request = new Request.Builder().url("http://localhost:" + this.port + "/stats/min")
.method("POST", body).addHeader("Content-Type", "text/csv").build();
final Response response = StatsTests.client.newCall(request).execute();
final JsonNode responseMap = new ObjectMapper().readValue(response.body().string(), JsonNode.class);
Assert.assertTrue("15.71".equals(responseMap.get("minimum").asText()));
}
@Test
public void statsNormalizedWorks() throws Exception {
final MediaType mediaType = MediaType.parse("text/csv");
final 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);
final Request request = new Request.Builder().url("http://localhost:" + this.port + "/stat/normalized")
.method("POST", body).addHeader("Content-Type", "text/csv").build();
final Response response = StatsTests.client.newCall(request).execute();
final JsonNode responseMap = new ObjectMapper().readValue(response.body().string(), JsonNode.class);
Assert.assertTrue(responseMap.has("normalized"));
Assert.assertTrue(
"-0.695, -0.552, -1.069, -1.119, 1.193, 1.854, 1.221, -0.085, 0.102, -0.125, 0.402, -1.749, 0.224, 0.398"
.equals(responseMap.get("normalized").asText()));
}
@Test
public void statsReturnsKurtosisAndSkew() throws Exception {
final MediaType mediaType = MediaType.parse("text/csv");
final 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);
final Request request = new Request.Builder().url("http://localhost:" + this.port + "/stat/skew")
.method("POST", body).addHeader("Content-Type", "text/csv").build();
final Response response = StatsTests.client.newCall(request).execute();
final JsonNode responseMap = new ObjectMapper().readValue(response.body().string(), JsonNode.class);
Assert.assertTrue(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 statsSdAndVarianceWork() throws Exception {
final MediaType mediaType = MediaType.parse("text/csv");
final RequestBody body = RequestBody.create("9,8,7,6", mediaType);
final Request request = new Request.Builder().url("http://localhost:" + this.port + "/stat/variance")
.method("POST", body).addHeader("Content-Type", "text/csv").build();
final Response response = StatsTests.client.newCall(request).execute();
final Map<String, String> responseObj = new ObjectMapper().readValue(response.body().bytes(),
new TypeReference<Map<String, String>>() {
});
Assert.assertTrue("1.18".equals(responseObj.get("sdWithoutBias")));
Assert.assertTrue("1.25".equals(responseObj.get("varianceWithOutBias")));
Assert.assertTrue("1.667".equals(responseObj.get("varianceWithBias")));
Assert.assertTrue("1.291".equals(responseObj.get("sdWithBias")));
}
@Test
public void statsSumAndProduct() throws Exception {
final MediaType mediaType = MediaType.parse("text/csv");
final RequestBody body = RequestBody.create("9,8,7,6", mediaType);
final Request request = new Request.Builder().url("http://localhost:" + this.port + "/stat/sum")
.method("POST", body).addHeader("Content-Type", "text/csv").build();
final Response response = StatsTests.client.newCall(request).execute();
final Map<String, String> responseObj = new ObjectMapper().readValue(response.body().bytes(),
new TypeReference<Map<String, String>>() {
});
Assert.assertTrue("30".equals(responseObj.get("sum")));
Assert.assertTrue("3024".equals(responseObj.get("product")));
}
@Test
public void statsUpperQuartile() throws Exception {
final MediaType mediaType = MediaType.parse("text/csv");
final 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);
final Request request = new Request.Builder().url("http://localhost:" + this.port + "/stats/upperQuartile")
.method("POST", body).addHeader("Content-Type", "text/csv").build();
final Response response = StatsTests.client.newCall(request).execute();
final JsonNode responseMap = new ObjectMapper().readValue(response.body().string(), JsonNode.class);
Assert.assertTrue("23.245".equals(responseMap.get("upperQuartile").asText()));
}
}
package us.d8u.balance;
import java.util.Map;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
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 com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ObjectNode;
import com.google.common.collect.Maps;
import com.google.common.collect.Sets;
import okhttp3.HttpUrl;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT)
public class StatusTests {
private static OkHttpClient client = new OkHttpClient();
@LocalServerPort
private int port;
@Test
public void missingStatusYields400() throws Exception {
final Map<String, String> expected = Maps.newHashMap();
expected.put("status", "400");
expected.put("error", "need something to update status to");
final HttpUrl url = HttpUrl.parse("http://localhost:" + this.port + "/status");
final Map<String, String> response = new ObjectMapper().readValue(
StatusTests.client.newCall(new Request.Builder().url(url).build()).execute().body().string(),
new TypeReference<Map<String, String>>() {
});
Assert.assertTrue(Sets.newHashSet("error", "status").equals(response.keySet()));
Assert.assertTrue("need something to update status to".equals(response.get("error")));
Assert.assertTrue(response.get("status").equals(Integer.toString(HttpStatus.BAD_REQUEST.value())));
}
@Test
public void servicesAreCaseInsensitive() throws Exception {
final Map<String, String> expectedSrc = Maps.newHashMap();
expectedSrc.put("telegram.status", "201 CREATED");
final String expected = Controller.mapper.writeValueAsString(expectedSrc);
final ObjectNode bodySrc = Controller.mapper.createObjectNode();
bodySrc.put("services", "Telegram");
bodySrc.put("status", "test");
final RequestBody body = RequestBody.create(Controller.mapper.writeValueAsString(bodySrc),
MediaType.parse("application/json"));
final HttpUrl url = HttpUrl.parse("http://localhost/status").newBuilder().port(this.port).build();
final String actual = StatusTests.client.newCall(new Request.Builder().url(url).post(body).build()).execute()
.body().string();
Assert.assertTrue("Response incorrect", actual.equals(expected));
}
}
package us.d8u.balance;
import java.util.Map.Entry;
import java.util.Set;
import org.joda.time.DateTime;
import org.joda.time.format.DateTimeFormatter;
import org.joda.time.format.ISODateTimeFormat;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
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.test.context.junit4.SpringRunner;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.api.client.util.Lists;
import com.google.common.collect.Sets;
import okhttp3.HttpUrl;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT)
public class StockTests {
private static final OkHttpClient client = new OkHttpClient();
@LocalServerPort
private int port;
@Test
public void lookingUpChaosHyenaReturnsArbeitMachtFrei() throws Exception {
final HttpUrl requestUrl = new HttpUrl.Builder().host("localhost").scheme("http").port(this.port)
.addPathSegment("stock").addPathSegment("info").addQueryParameter("sym", "ChaosHyena").build();
final Request request = new Request.Builder().url(requestUrl).get().build();
final Response rawResponse = StockTests.client.newCall(request).execute();
final JsonNode response = new ObjectMapper().readTree(rawResponse.body().string());
Assert.assertEquals("Arbeit macht frei", response.get("error").asText());
}
@Test
public void lookingUpGoogleReturnsCompanyInfo() throws Exception {
final HttpUrl requestUrl = new HttpUrl.Builder().host("localhost").scheme("http").port(this.port)
.addPathSegments("stock/info").addQueryParameter("sym", "GOOG").build();
final Request request = new Request.Builder().url(requestUrl).get().build();
final Response rawResponse = StockTests.client.newCall(request).execute();
final Set<String> expectedKeys = Sets.newHashSet("companyName", "now", "tradeDate", "requestDate",
"requestSym");
final JsonNode response = new ObjectMapper().readTree(rawResponse.body().string());
for (final String e : expectedKeys) {
if (!response.has(e)) {
Assert.fail(e + " not found in " + response.fieldNames());
}
}
Assert.assertEquals("Alphabet Inc. - Class C Capital Stock", response.get("companyName"));
Assert.assertTrue(response.get("now").asText().matches("^[0-9.]+$"));
Assert.assertTrue(response.get("volume").asText().matches("^[0-9]+$"));
final DateTime dt = new DateTime(response.get("tradeDate").asLong());
Assert.assertNotNull(dt);
Assert.assertTrue(new DateTime(response.get("requestDate").asLong()) != null);
Assert.assertEquals("GOOG", response.get("requestSym"));
}
@Test
public void lookingUpGooglxReturnsErrorNotFound() throws Exception {
final HttpUrl requestUrl = new HttpUrl.Builder().host("localhost").scheme("http").port(this.port)
.addPathSegments("stock/info").addQueryParameter("sym", "GOOGLx").build();
final Request request = new Request.Builder().url(requestUrl).get().build();
final Response rawResponse = StockTests.client.newCall(request).execute();
final JsonNode response = new ObjectMapper().readTree(rawResponse.body().string());
Assert.assertEquals("symbol not found", response.get("error"));
}
@Test
public void lookingUpWillyOnWheelsIIReturnsRNTError() throws Exception {
final HttpUrl requestUrl = new HttpUrl.Builder().host("localhost").scheme("http").port(this.port)
.addPathSegment("stock").addPathSegment("info").addQueryParameter("sym", "WillyOnWheelsII").build();
final Request request = new Request.Builder().url(requestUrl).get().build();
final Response rawResponse = StockTests.client.newCall(request).execute();
final JsonNode response = new ObjectMapper().readTree(rawResponse.body().string());
Assert.assertEquals("RNT is fighting for the future of South Australia!", response.get("error"));
}
@Test
public void resultsAreOrdered() throws Exception {
final HttpUrl url = HttpUrl.parse("http://localhost/stock?sym=SCHB").newBuilder().port(this.port).build();
final JsonNode response = new ObjectMapper().readTree(
StockTests.client.newCall(new Request.Builder().url(url).build()).execute().body().byteStream());
final DateTimeFormatter fmt = ISODateTimeFormat.date();
for (final Entry<String, JsonNode> responseFields : Lists.newArrayList(response.fields())) {
final String key = responseFields.getKey();
Assert.assertTrue(key + " invalid!",
"request".equals(key) || key.startsWith("Volume.") || key.startsWith("Close."));
if (key.contains(".")) {
final String dateString = key.substring(key.indexOf(".") + 1);
try {
fmt.parseDateTime(dateString);
} catch (final Exception e) {
Assert.fail("not a date " + dateString);
}
final JsonNode stanza = responseFields.getValue();
Assert.assertTrue("Not coercible to a number " + stanza.asText(), stanza.asDouble() > 0.0d);
}
}
}
@Test
public void symbolRequired() throws Exception {
final HttpUrl url = HttpUrl.parse("http://localhost/stock").newBuilder().port(this.port).build();
final JsonNode response = new ObjectMapper().readTree(
StockTests.client.newCall(new Request.Builder().url(url).build()).execute().body().byteStream());
Assert.assertTrue("Expected message incorrect for missing symbol",
"sym[bol] required!".equals(response.get("error").asText()));
}
}
package us.d8u.balance;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.Map;
import java.util.Set;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
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.test.context.junit4.SpringRunner;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.common.collect.Sets;
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 SummaryTests {
private static final OkHttpClient client = new OkHttpClient();
@LocalServerPort
private int port;
@Test
public void cacheWorks() throws Exception {
final HttpUrl endpoint = new HttpUrl.Builder().scheme("http").host("localhost").port(this.port)
.addPathSegment("summary").addQueryParameter("url", "https://www.bbc.com/news/world-us-canada-52265989")
.build();
Request request = new Request.Builder().url(endpoint).build();
Response response = SummaryTests.client.newCall(request).execute();
JsonNode actual = new ObjectMapper().readTree(response.body().string());
final Long initialTime = actual.get("time").asLong();
request = new Request.Builder().url(endpoint).build();
response = SummaryTests.client.newCall(request).execute();
actual = new ObjectMapper().readTree(response.body().string());
Assert.assertTrue(actual.get("time").asLong() < initialTime);
}
@Test
public void getSummary() throws Exception {
final Set<String> expected = Sets.newHashSet("summary", "summaryLength", "time", "request");
final HttpUrl url = new HttpUrl.Builder().scheme("http").host("localhost").port(this.port)
.addPathSegment("summary").addQueryParameter("url", "https://www.bbc.com/news/world-australia-51513886")
.build();
final Request request = new Request.Builder().url(url).build();
final Response response = SummaryTests.client.newCall(request).execute();
Assert.assertTrue(response.isSuccessful());
final 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(
"Last week, China's ambassador to the UK, Liu Xiaoming, said those opposed to Huawei playing a role in the UK's 5G network were conducting \"a witch-hunt\". According to the Sydney Morning Herald, in the meeting with Mr Raab, Anthony Byrne, the deputy chair of Australia's intelligence committee, said that allowing China to build the UK's 5G telecoms infrastructure was equivalent to letting Russia construct it. The UK has only given Huawei partial access to its 5G network, banning it from supplying kit to \"sensitive parts\", known as the core. In a Twitter post at the time, he said the meeting had involved a \"full and frank discussion\" over 5G and strategic challenges. Australian Treasurer Josh Frydenberg however sought to scotch suggestions of a rift, saying \"our relationship with the United Kingdom couldn't be stronger\". Last week, UK Foreign Secretary Dominic Raab visited Australia, where he met members of the parliament's intelligence committee. Details of the meeting were later leaked to the Sydney Morning Herald, which said an MP had rebuked Mr Raab in the meeting over Britain's Huawei decision, saying Australia was very disappointed. According to Australian media that report prompted a formal complaint from Vicki Treadell, the UK's High Commissioner to Australia, to the heads of two Australian parliamentary committees. Australia and the UK are both part of the Five Eyes intelligence alliance, which also includes the US, New Zealand and Canada. Great to meet with UK Foreign Secretary Dominic Raab, accompanied by UK High Commisioner Mrs Vicki Treadell, with colleagues Andrew Hastie MP and Senator David Fawcett this afternoon. In her letter to Australian MPs, Ms Treadell expressed her disapproval of the leak, ABC News reported. Meanwhile, senior US officials stepped up their criticism of Huawei at an international security conference in Munich, Germany on Saturday. That's how we feel about Huawei,\" Mr Byrne was quoted as telling Mr Raab. Washington has argued that Huawei equipment could allow the Chinese state to spy via \"back-doors\". Australia has banned the Chinese telecommunications giant from building its next-generation 5G mobile internet networks but Britain last month decided the company could continue to play a role in its system, despite pressure and warnings from Washington. View original tweet on Twitter The UK High Commission in Australia told the BBC: \"Our position on this is that we won't comment on private briefings or on any information pertaining to be from private briefings.\"",
responseObj.get("summary"));
Assert.assertEquals("1", responseObj.get("summaryLength"));
}
@Test
public void noContentReturns404() throws Exception {
final HttpUrl endpoint = new HttpUrl.Builder().scheme("http").host("localhost").port(this.port)
.addPathSegment("summary").addQueryParameter("url", "https://hasan.d8u.us/me.png").build();
final Request request = new Request.Builder().url(endpoint).build();
final Response response = SummaryTests.client.newCall(request).execute();
final JsonNode actual = new ObjectMapper().readTree(response.body().string());
Assert.assertTrue("404".equals(actual.get("status").asText()));
Assert.assertTrue("No text found".equals(actual.get("error").asText()));
}
@Test
public void postSummary() throws Exception {
final HttpUrl testUrl = new HttpUrl.Builder().scheme("http").host("localhost").port(this.port)
.addPathSegment("summary").addQueryParameter("length", "1").build();
final MediaType mediaType = MediaType.parse("text/plain");
final 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);
final Request request = new Request.Builder().url(testUrl).method("POST", body)
.addHeader("Content-Type", "text/plain").build();
final Response response = SummaryTests.client.newCall(request).execute();
Assert.assertTrue(response.isSuccessful());
final Map<String, String> actual = new ObjectMapper().readValue(response.body().string(),
new TypeReference<Map<String, String>>() {
});
final 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 summaryProcessesUrls() throws Exception {
final HttpUrl endpoint = new HttpUrl.Builder().scheme("http").host("localhost").port(this.port)
.addPathSegment("summary").addQueryParameter("url", "https://www.bbc.com/news/world-us-canada-52265989")
.build();
final Request request = new Request.Builder().url(endpoint).build();
final Response response = SummaryTests.client.newCall(request).execute();
final Map<String, String> actual = new ObjectMapper().readValue(response.body().string(),
new TypeReference<Map<String, String>>() {
});
Assert.assertEquals(Sets.newHashSet("summary", "request", "time"), actual.keySet());
Assert.assertTrue((actual.get("summary") != null) && !actual.get("summary").isBlank()
&& !actual.get("summary").isEmpty());
Assert.assertEquals("https://www.bbc.com/news/world-us-canada-52265989", actual.get("request"));
Assert.assertTrue(null != Double.valueOf(actual.get("time")));
Assert.assertTrue(actual.get("time").strip().matches("^[0-9]+$"));
}
@Test
public void takesBody() throws Exception {
final String body = Files.readString(Paths.get("/Users", "user", "Developer", "hd1-units", "src", "test",
"java", "us", "d8u", "balance", "SummaryTests.java"));
final RequestBody requestBody = RequestBody.create(body.getBytes(), MediaType.parse("text/plain"));
final HttpUrl endpoint = new HttpUrl.Builder().scheme("http").host("localhost").port(this.port)
.addPathSegment("summary").build();
final Request request = new Request.Builder().url(endpoint).post(requestBody).build();
final Response response = SummaryTests.client.newCall(request).execute();
Assert.assertTrue(response.code() == 200);
}
}
package us.d8u.balance;
import org.joda.time.format.DateTimeFormat;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
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.test.context.junit4.SpringRunner;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import okhttp3.HttpUrl;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT)
public class SunTests {
private static final OkHttpClient client = new OkHttpClient();
@LocalServerPort
private int port;
@Test
public void sunriseAndSunsetAreEquivalent() throws Exception {
HttpUrl url = HttpUrl.parse("http://localhost:" + this.port + "/sunrise/937.8752952/-12.4576917/");
Response rawResponse = SunTests.client.newCall(new Request.Builder().url(url).build()).execute();
final JsonNode sunriseJson = new ObjectMapper().readTree(rawResponse.body().string());
url = HttpUrl.parse("http://localhost:" + this.port + "/sunset/937.8752952/-12.4576917/");
rawResponse = SunTests.client.newCall(new Request.Builder().url(url).build()).execute();
final JsonNode json = new ObjectMapper().readTree(rawResponse.body().string());
Assert.assertTrue("Sunrise and sunset are not the same!", sunriseJson.equals(json));
}
@Test
public void sunriseWithoutLocationAndHeaderReturnsError() throws Exception {
final HttpUrl url = HttpUrl.parse("http://localhost:" + this.port + "/sunset/0/0/");
final Response rawResponse = SunTests.client.newCall(new Request.Builder().url(url).build()).execute();
final JsonNode json = new ObjectMapper().readTree(rawResponse.body().string());
Assert.assertEquals(json.get("error").asText(), "location not found");
}
@Test
public void sunsetDefaultsToToday() throws Exception {
final HttpUrl url = HttpUrl.parse("http://localhost:" + this.port + "/sunset/37.8752952/-122.4576917/");
final Response rawResponse = SunTests.client.newCall(new Request.Builder().url(url).build()).execute();
final JsonNode json = new ObjectMapper().readTree(rawResponse.body().string());
final String time = json.get("sunset").asText();
try {
DateTimeFormat.forPattern("HH:mm z").parseDateTime(time);
Assert.assertTrue(true);
} catch (final Exception e) {
Assert.fail(time + " is not in the correct format for a sunset");
}
try {
DateTimeFormat.forPattern("HH:mm z").parseDateTime(json.get("sunrise").asText());
Assert.assertTrue(true);
} catch (final Exception e) {
Assert.fail(time + " is not in the correct format for a sunrise");
}
}
@Test
public void sunsetRangeChecksLatitude() throws Exception {
final HttpUrl url = HttpUrl.parse("http://localhost:" + this.port + "/sunset/937.8752952/-12.4576917/");
final Response rawResponse = SunTests.client.newCall(new Request.Builder().url(url).build()).execute();
final JsonNode json = new ObjectMapper().readTree(rawResponse.body().string());
Assert.assertEquals(json.get("error").asText(), "out of range");
}
@Test
public void sunsetRangeChecksLongitude() throws Exception {
final HttpUrl url = HttpUrl.parse("http://localhost:" + this.port + "/sunset/37.8752952/-192.4576917/");
final Response rawResponse = SunTests.client.newCall(new Request.Builder().url(url).build()).execute();
final JsonNode json = new ObjectMapper().readTree(rawResponse.body().string());
Assert.assertEquals(json.get("error").asText(), "out of range");
}
@Test
public void sunsetResolvesIp() throws Exception {
final HttpUrl url = HttpUrl.parse("http://localhost:" + this.port + "/sunset/0/0/");
final Response rawResponse = SunTests.client
.newCall(new Request.Builder().url(url).addHeader("x-forwarded-for", "172.91.170.129").build())
.execute();
final JsonNode json = new ObjectMapper().readTree(rawResponse.body().string());
Assert.assertTrue(json.has("sunrise") && json.has("sunset") && json.has("latitude") && json.has("longitude"));
}
}
package us.d8u.balance;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.context.SpringBootTest.WebEnvironment;
import org.springframework.boot.test.web.server.LocalServerPort;
import org.springframework.test.context.junit4.SpringRunner;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import okhttp3.HttpUrl;
import okhttp3.OkHttpClient;
import okhttp3.Request;
@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT)
public class ThreadTests {
static OkHttpClient client = new OkHttpClient();
static ObjectMapper mapper = new ObjectMapper();
@LocalServerPort
private Integer port;
@Test
public void notRunningThreadMessage() throws Exception {
HttpUrl UNDER_TEST = HttpUrl.parse("http://localhost/thread").newBuilder().port(port)
.addQueryParameter("id", "-" + (Long.MAX_VALUE + 1)).build();
JsonNode response = mapper
.readTree(client.newCall(new Request.Builder().url(UNDER_TEST).build()).execute().body().byteStream());
Assert.assertTrue(response.get("isLiving").asBoolean() == false);
}
@Test
public void runningTest() throws Exception {
Thread t = new Thread() {
public void run() {
while (true) {
if (System.getProperty("breakTest") != null) {
break;
}
continue;
}
}
};
t.start();
HttpUrl UNDER_TEST = HttpUrl.parse("http://localhost/thread").newBuilder().port(port)
.addQueryParameter("id", Long.toString(t.getId())).build();
JsonNode response = mapper
.readTree(client.newCall(new Request.Builder().url(UNDER_TEST).build()).execute().body().byteStream());
Assert.assertTrue(response.get("isLiving").asBoolean());
System.setProperty("breakTest", "1");
}
}
package us.d8u.balance;
import java.util.ArrayList;
import java.util.Map;
import org.apache.commons.lang3.math.NumberUtils;
import org.joda.time.DateTime;
import org.joda.time.format.ISODateTimeFormat;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
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.test.context.junit4.SpringRunner;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.common.collect.Lists;
import com.google.common.collect.Sets;
import okhttp3.HttpUrl;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT)
public class TimeTests {
@LocalServerPort
private int port;
@Test
public void timeDoesntErrorIfOffsetsHaveLeadingSpaces() throws Exception {
final HttpUrl requestUrl = new HttpUrl.Builder().host("localhost").scheme("http").port(this.port)
.addPathSegment("time").addQueryParameter("fz", "-8").addQueryParameter("time", "202003312317")
.addQueryParameter("tz", "+2").build();
final Request request = new Request.Builder().url(requestUrl).get().build();
final Response rawResponse = new OkHttpClient().newCall(request).execute();
Assert.assertTrue("arbitrary times fail with positive timezones", rawResponse.isSuccessful());
}
@Test
public void timeInvalidZoneReturnsError() throws Exception {
final HttpUrl requestUrl = new HttpUrl.Builder().host("localhost").scheme("http").port(this.port)
.addQueryParameter("z", "local").addPathSegment("time").build();
final Request request = new Request.Builder().url(requestUrl).get().build();
final Response rawResponse = new OkHttpClient().newCall(request).execute();
Assert.assertTrue(rawResponse.isSuccessful());
final JsonNode response = new ObjectMapper().readValue(rawResponse.body().charStream(), JsonNode.class);
Assert.assertEquals("invalid timezone or offset -- local", response.get("error").asText());
}
@Test
public void timeReturnsProperly() throws Exception {
final HttpUrl endpoint = HttpUrl.parse("http://localhost:" + this.port + "/time");
final Request request = new Request.Builder().url(endpoint).build();
final Response response = new OkHttpClient().newCall(request).execute();
final Map<String, String> result = new ObjectMapper().readValue(response.body().bytes(),
new TypeReference<Map<String, String>>() {
});
Assert.assertEquals("Unexpected or missing keys",
Sets.newHashSet("zones", "now", "buddhist", "coptic", "ethiopic", "islamic", "epoch"), result.keySet());
Assert.assertNotNull(ISODateTimeFormat.dateTimeNoMillis().parseDateTime(result.get("now")));
Assert.assertNotNull(ISODateTimeFormat.dateTimeNoMillis().parseDateTime(result.get("buddhist")));
Assert.assertNotNull(ISODateTimeFormat.dateTimeNoMillis().parseDateTime(result.get("coptic")));
Assert.assertNotNull(ISODateTimeFormat.dateTimeNoMillis().parseDateTime(result.get("ethiopic")));
Assert.assertNotNull(ISODateTimeFormat.dateTimeNoMillis().parseDateTime(result.get("islamic")));
Assert.assertTrue(NumberUtils.isDigits(result.get("epoch")));
}
@Test
public void timeSupportsArbitraryTimes() throws Exception {
final HttpUrl requestUrl = new HttpUrl.Builder().host("localhost").scheme("http").port(this.port)
.addPathSegment("time").addQueryParameter("fz", "-8").addQueryParameter("time", "20200331T2317")
.addQueryParameter("tz", "0").build();
final Request request = new Request.Builder().url(requestUrl).get().build();
final Response rawResponse = new OkHttpClient().newCall(request).execute();
final String string = rawResponse.body().string();
final JsonNode response = new ObjectMapper().readValue(string, JsonNode.class);
final 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 timeSupportsMultipleTimezones() throws Exception {
final HttpUrl requestUrl = new HttpUrl.Builder().host("localhost").scheme("http").port(this.port)
.addPathSegment("time").addQueryParameter("z", "3").build();
final Request request = new Request.Builder().url(requestUrl).get().build();
final Response rawResponse = new OkHttpClient().newCall(request).execute();
final String string = rawResponse.body().string();
final JsonNode response = new ObjectMapper().readValue(string, JsonNode.class);
final String time = response.get("now").asText();
Assert.assertTrue(time.endsWith("+03:00"));
final java.util.Iterator<String> fields = response.fieldNames();
final ArrayList<String> fieldList = Lists.newArrayList(fields);
Assert.assertEquals("now", fieldList.get(0));
try {
fieldList.get(1);
Assert.fail("fieldList has a second element.");
} catch (final IndexOutOfBoundsException e) {
}
}
@Test
public void timeTakesZone() throws Exception {
final HttpUrl requestUrl = new HttpUrl.Builder().host("localhost").scheme("http").port(this.port)
.addPathSegment("time").addQueryParameter("z", "UTC").build();
final Request request = new Request.Builder().url(requestUrl).get().build();
final Response rawResponse = new OkHttpClient().newCall(request).execute();
final 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 {
final HttpUrl requestUrl = new HttpUrl.Builder().host("localhost").scheme("http").port(this.port)
.addPathSegment("time").build();
final Request request = new Request.Builder().url(requestUrl).get().build();
final Response rawResponse = new OkHttpClient().newCall(request).execute();
final JsonNode response = new ObjectMapper().readValue(rawResponse.body().charStream(), JsonNode.class);
Assert.assertTrue(response.get("zones").isArray());
}
}
package us.d8u.balance;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
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.test.context.junit4.SpringRunner;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import okhttp3.HttpUrl;
import okhttp3.OkHttpClient;
import okhttp3.Request;
@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT)
public class TitleTests {
private static final OkHttpClient client = new OkHttpClient();
private static final ObjectMapper mapper = new ObjectMapper();
@LocalServerPort
private Integer port;
@Test
public void formatsProperly() throws Exception {
final HttpUrl url = HttpUrl.parse("http://localhost/title").newBuilder().port(this.port)
.addQueryParameter("url", "https://whereiszaf.herokuapp.com").build();
final Request request = new Request.Builder().url(url).build();
final JsonNode response = TitleTests.mapper
.readTree(TitleTests.client.newCall(request).execute().body().string());
Assert.assertTrue("Where was Zaf".equals(response.get("title").asText()));
}
}
package us.d8u.balance;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.context.SpringBootTest.WebEnvironment;
import org.springframework.boot.test.web.server.LocalServerPort;
import org.springframework.test.context.junit4.SpringRunner;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import okhttp3.HttpUrl;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT)
public class TokenTests {
private static final OkHttpClient client = new OkHttpClient();
private static final ObjectMapper mapper = new ObjectMapper();
@LocalServerPort
int port;
@Test
public void getTokenWithoutValue() throws Exception {
HttpUrl url = HttpUrl.parse("http://localhost/token").newBuilder().port(port)
.addQueryParameter("type", "bearer").build();
Response rawResponse = client.newCall(new Request.Builder().url(url).build()).execute();
JsonNode response = mapper.readTree(rawResponse.body().charStream());
Assert.assertTrue("Token not found in body", response.has("token"));
Assert.assertTrue("Token length not 40", response.get("token").asText().length() == 40);
Assert.assertTrue("bearer token misformed", response.get("bearer").asText().startsWith("Bearer ")
&& !response.get("bearer").asText().replace("Bearer ", "").isBlank());
}
@Test
public void getTokenWithValue() throws Exception {
HttpUrl url = HttpUrl.parse("http://localhost/token").newBuilder().port(port)
.addQueryParameter("type", "bearer").addQueryParameter("value", "foo").build();
Response rawResponse = client.newCall(new Request.Builder().url(url).build()).execute();
JsonNode response = mapper.readTree(rawResponse.body().charStream());
Assert.assertTrue("Token not found in body", response.has("token"));
Assert.assertTrue("Token length not 40", response.get("token").asText().length() == 40);
Assert.assertTrue("bearer token misformed",
response.get("bearer").asText().startsWith("Bearer ")
&& !response.get("bearer").asText().replace("Bearer ", "").isBlank()
&& response.get("bearer").asText().contentEquals("Wm05dg=="));
}
}
package us.d8u.balance;
import java.io.ByteArrayInputStream;
import java.text.NumberFormat;
import java.text.ParseException;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.apache.commons.lang3.math.NumberUtils;
import org.joda.time.DateTime;
import org.joda.time.format.ISODateTimeFormat;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
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 com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.common.base.Splitter;
import com.google.common.collect.Iterables;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.google.common.collect.Sets;
import com.rometools.rome.feed.synd.SyndEntry;
import com.rometools.rome.feed.synd.SyndFeed;
import com.rometools.rome.io.SyndFeedInput;
import com.rometools.rome.io.XmlReader;
import okhttp3.HttpUrl;
import okhttp3.Interceptor;
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 TwitterTests {
private static OkHttpClient client = new OkHttpClient();
@LocalServerPort
private int port;
@Test
public void authorParameterWritesCookie() throws Exception {
final HttpUrl requestUrl = new HttpUrl.Builder().host("localhost").scheme("http").port(this.port)
.addPathSegment("twitter").addQueryParameter("author", "hasandiwan2; leanliam").build();
final Request request = new Request.Builder().url(requestUrl).build();
final Map<String, Boolean> seenMap = Maps.newHashMap();
final long start = System.currentTimeMillis();
final Interceptor interceptor = chain -> {
final Response originalResponse = chain.proceed(chain.request());
seenMap.put("intercept", true);
if (!originalResponse.headers("Set-Cookie").isEmpty()) {
final Iterable<String> cookieSplit = Splitter.on('=').split(originalResponse.header("Set-Cookie"));
final String value = Lists.newArrayList(cookieSplit).get(1);
try {
Assert.assertTrue(NumberFormat.getNumberInstance().parse(value).longValue() >= start);
} catch (final ParseException e) {
Assert.fail(value + "is not greater than or equal to start time " + start);
}
}
return originalResponse;
};
TwitterTests.client = TwitterTests.client.newBuilder().addInterceptor(interceptor).build();
TwitterTests.client.newCall(request).execute();
Assert.assertTrue(seenMap.get("intercept") == Boolean.TRUE);
}
@Test
public void authorTweetidOrHashtagRequired() throws Exception {
final HttpUrl requestUrl = new HttpUrl.Builder().host("localhost").scheme("http").port(this.port)
.addPathSegment("twitter").build();
final Request request = new Request.Builder().url(requestUrl).build();
final Map<String, String> seenMap = new ObjectMapper().readValue(
TwitterTests.client.newCall(request).execute().body().bytes(),
new TypeReference<Map<String, String>>() {
});
Assert.assertTrue(seenMap.keySet().equals(Sets.newHashSet("error", "status")));
Assert.assertEquals("hashtag, stock, tweet, or author needed", seenMap.get("error"));
Assert.assertTrue(seenMap.get("status").equals(Integer.toString(HttpStatus.BAD_REQUEST.value())));
}
@Test
public void canNotUpdateStatusWithoutKey() throws Exception {
final HttpUrl requestUrl = new HttpUrl.Builder().host("localhost").scheme("http").port(this.port)
.addPathSegment("status").build();
final Map<String, String> body = Maps.newHashMap();
body.put("services", "twitter");
body.put("twitter.oauth.secret", "JKsdJbEdRpJwkLc9vUEFp3njO");
body.put("twitter.oauth.key", "6148562-1reohOTvMSc90N2eiulfqFLMPIYsKHjRCC1qqbB28h");
body.put("twitter.secret", "3l9QQNvRo6CTsu2KbvvYuqFf2O5xKA9Ep38oZ8mf81oR5hWcSy");
body.put("status", "hello world, this is a test");
final RequestBody requestBody = RequestBody.create(new ObjectMapper().writeValueAsBytes(body),
MediaType.parse("application/json"));
final Request request = new Request.Builder().url(requestUrl).post(requestBody).build();
final Response rawResponse = TwitterTests.client.newCall(request).execute();
final JsonNode response = new ObjectMapper().readTree(rawResponse.body().bytes());
Assert.assertTrue(response.get("status").asInt() == 400);
Assert.assertTrue("missing key twitter.key".equals(response.get("error").asText()));
}
@Test
public void canNotUpdateStatusWithoutOauthKey() throws Exception {
final HttpUrl requestUrl = new HttpUrl.Builder().host("localhost").scheme("http").port(this.port)
.addPathSegment("status").build();
final Map<String, String> body = Maps.newHashMap();
body.put("services", "twitter");
body.put("twitter.key", "JKsdJbEdRpJwkLc9vUEFp3njO");
body.put("twitter.secret", "3l9QQNvRo6CTsu2KbvvYuqFf2O5xKA9Ep38oZ8mf81oR5hWcSy");
body.put("twitter.oauth.secret", "6148562-1reohOTvMSc90N2eiulfqFLMPIYsKHjRCC1qqbB28h");
body.put("status", "hello world, this is a test");
final RequestBody requestBody = RequestBody.create(new ObjectMapper().writeValueAsBytes(body),
MediaType.parse("application/json"));
final Request request = new Request.Builder().url(requestUrl).post(requestBody).build();
final Response rawResponse = TwitterTests.client.newCall(request).execute();
final JsonNode response = new ObjectMapper().readTree(rawResponse.body().bytes());
Assert.assertTrue(response.get("status").asInt() == 400);
Assert.assertTrue("missing key twitter.oauth.key".equals(response.get("error").asText()));
}
@Test
public void canNotUpdateStatusWithoutOauthSecret() throws Exception {
final HttpUrl requestUrl = new HttpUrl.Builder().host("localhost").scheme("http").port(this.port)
.addPathSegment("status").build();
final Map<String, String> errorMap = Maps.newHashMap();
errorMap.put("error", "try again, if you still get this error, email me -- many thanks!");
final Map<String, String> body = Maps.newHashMap();
body.put("services", "twitter");
body.put("twitter.key", "JKsdJbEdRpJwkLc9vUEFp3njO");
body.put("twitter.secret", "3l9QQNvRo6CTsu2KbvvYuqFf2O5xKA9Ep38oZ8mf81oR5hWcSy");
body.put("twitter.oauth.key", "6148562-1reohOTvMSc90N2eiulfqFLMPIYsKHjRCC1qqbB28h");
body.put("status", "hello world, this is a test");
final RequestBody requestBody = RequestBody.create(new ObjectMapper().writeValueAsBytes(body),
MediaType.parse("application/json"));
final Request request = new Request.Builder().url(requestUrl).post(requestBody).build();
Map<String, String> response = null;
do {
final Response rawResponse = TwitterTests.client.newCall(request).execute();
response = new ObjectMapper().readValue(rawResponse.body().bytes(),
new TypeReference<Map<String, String>>() {
});
} while (errorMap.equals(response));
Assert.assertTrue("400".equals(response.get("status")));
Assert.assertTrue("missing key twitter.oauth.secret".equals(response.get("error")));
}
@Test
public void canNotUpdateStatusWithoutSecret() throws Exception {
final HttpUrl requestUrl = new HttpUrl.Builder().host("localhost").scheme("http").port(this.port)
.addPathSegment("status").build();
final Map<String, String> body = Maps.newHashMap();
body.put("services", "twitter");
body.put("twitter.key", "JKsdJbEdRpJwkLc9vUEFp3njO");
body.put("twitter.oauth.secret", "3l9QQNvRo6CTsu2KbvvYuqFf2O5xKA9Ep38oZ8mf81oR5hWcSy");
body.put("twitter.oauth", "6148562-1reohOTvMSc90N2eiulfqFLMPIYsKHjRCC1qqbB28h");
body.put("status", "hello world, this is a test");
final RequestBody requestBody = RequestBody.create(new ObjectMapper().writeValueAsString(body),
MediaType.parse("application/json"));
final Request request = new Request.Builder().url(requestUrl).post(requestBody).build();
final Response rawResponse = TwitterTests.client.newCall(request).execute();
final JsonNode response = new ObjectMapper().readTree(rawResponse.body().bytes());
Assert.assertTrue(response.get("status").asInt() == 400);
Assert.assertTrue("missing key twitter.secret".equals(response.get("error").asText()));
}
@Test
public void countGetsCorrectNumberOfEntries() throws Exception {
final String hashtag = "nufc";
final HttpUrl requestUrl = new HttpUrl.Builder().host("localhost").scheme("http").port(this.port)
.addPathSegment("twitter").addQueryParameter("hashtag", hashtag).addQueryParameter("count", "1")
.build();
final Request request = new Request.Builder().url(requestUrl).build();
final Response rawResponse = TwitterTests.client.newCall(request).execute();
final String response = rawResponse.body().string();
final SyndFeed feed = new SyndFeedInput().build(new XmlReader(new ByteArrayInputStream(response.getBytes())));
Assert.assertTrue(feed.getEntries().size() == 1);
}
@Test
public void emptyParametersRedirectsToMyTwitterFeed() throws Exception {
HttpUrl url = HttpUrl.parse("http://localhost/twitter").newBuilder().port(port).build();
final Request request = new Request.Builder().url(url).build();
final Response rawResponse = TwitterTests.client.newBuilder().followRedirects(false).build().newCall(request)
.execute();
Assert.assertTrue("Location incorrect",
rawResponse.header("location").equals("https://twitter.com/HasanDiwan2"));
}
@Test
public void excludeRetweetsParameterWorks() throws Exception {
final String hashtag = "nufc";
final HttpUrl requestUrl = new HttpUrl.Builder().host("localhost").scheme("http").port(this.port)
.addPathSegment("twitter").addQueryParameter("hashtag", hashtag)
.addQueryParameter("excludeRetweet", "1").build();
final Request request = new Request.Builder().url(requestUrl).build();
final Response rawResponse = TwitterTests.client.newCall(request).execute();
final String response = rawResponse.body().string();
final SyndFeed feed = new SyndFeedInput().build(new XmlReader(new ByteArrayInputStream(response.getBytes())));
for (final SyndEntry anEntry : feed.getEntries().subList(0, feed.getEntries().size() - 1)) {
Assert.assertTrue("Retweet found " + anEntry.getTitle() + "; should have been excluded",
!anEntry.getTitle().startsWith("RT"));
}
}
@Test
public void tweetCanBeCorrected() throws Exception {
if (!System.getenv().containsKey("oauthToken") || !System.getenv().containsKey("oauthSecret")) {
Assert.fail("missing oauthToken and oauthSecret");
}
final HttpUrl requestUrl = new HttpUrl.Builder().host("localhost").scheme("http").port(this.port)
.addPathSegment("twitter").addPathSegment("correction").build();
final String expected = "re: https://twitter.com/HasanDiwan2/status/1250650485205241857 \"if yer wondering why death rates are so low in Germany and so high in America, it’s coz her leader used to be a quantum chemist and yours used to be a reality television host.\"";
final Map<String, String> body = Maps.newHashMap();
body.put("old", "1250650485205241857");
body.put("new",
"if yer wondering why death rates are so low in Germany and so high in America, it’s coz her leader used to be a quantum chemist and yours used to be a reality television host.");
body.put("oauth.key", System.getenv("oauthToken"));
body.put("oauth.secret", System.getenv("oauthSecret"));
final RequestBody postBody = RequestBody.create(new ObjectMapper().writeValueAsBytes(body),
MediaType.parse("application/json"));
final Request request = new Request.Builder().post(postBody).url(requestUrl).build();
final Response rawResponse = TwitterTests.client.newCall(request).execute();
final JsonNode response = new ObjectMapper().readTree(rawResponse.body().bytes());
Assert.assertTrue(expected.equals(response.get("newText").asText()));
Assert.assertTrue(response.get("link").asText().startsWith("https://twitter.com/HasanDiwan2/status/"));
final List<String> path = HttpUrl.parse(response.get("link").asText()).pathSegments();
final String lastComponent = path.get(path.size());
Assert.assertTrue(NumberUtils.isDigits(lastComponent));
}
@Test
public void tweetIdOfNegativeOneReturnsMessageToThatExtent() throws Exception {
final HttpUrl endpoint = HttpUrl.parse("http://localhost:" + this.port + "/twitter?tweet=-1");
final Response response = TwitterTests.client.newCall(new Request.Builder().url(endpoint).build()).execute();
final Map<String, String> returns = new ObjectMapper().readValue(response.body().byteStream(),
new TypeReference<Map<String, String>>() {
});
Assert.assertEquals("tweet must be greater than 1", returns.get("error"));
Assert.assertEquals("422", returns.get("status"));
}
@Test
public void twitterContainsNoSpecialStringsAsNouns() throws Exception {
final HttpUrl requestUrl = HttpUrl
.parse("http://localhost:" + this.port + "/twitter/?tweet=1403780926425862144");
final Request request = new Request.Builder().url(requestUrl).build();
final Response rawResponse = TwitterTests.client.newCall(request).execute();
final Map<String, String> response = new ObjectMapper().readValue(rawResponse.body().string(),
new TypeReference<Map<String, String>>() {
});
final Set<String> badWords = Sets.newHashSet();
badWords.addAll(Splitter.on(";").splitToList("SteveBurnett_; AyoCaesar; hirstysboots"));
final Set<String> nouns = Sets
.newHashSet(Iterables.toArray(Splitter.on(";").split(response.get("nouns")), String.class));
Assert.assertTrue(Sets.intersection(badWords, nouns).isEmpty());
}
@Test
public void twitterGeneratesFeedsFromHashtagWithDefaultLength() throws Exception {
final String hashtag = "#auspol";
final HttpUrl requestUrl = new HttpUrl.Builder().host("localhost").scheme("http").port(this.port)
.addPathSegment("twitter").addQueryParameter("hashtag", hashtag).build();
final Request request = new Request.Builder().url(requestUrl).build();
final Response rawResponse = TwitterTests.client.newCall(request).execute();
final String response = rawResponse.body().string();
final SyndFeed feed = new SyndFeedInput().build(new XmlReader(new ByteArrayInputStream(response.getBytes())));
Assert.assertTrue(("Twitter feed for " + hashtag).equals(feed.getTitle()));
for (final SyndEntry anEntry : feed.getEntries().subList(0, feed.getEntries().size() - 1)) {
final DateTime ourDate = new DateTime(anEntry.getPublishedDate().getTime());
final DateTime nextDate = new DateTime(
feed.getEntries().get(feed.getEntries().indexOf(anEntry) + 1).getPublishedDate().getTime());
Assert.assertTrue(ourDate + " => " + nextDate, ourDate.isAfter(nextDate) || ourDate.isEqual(nextDate));
Assert.assertTrue(anEntry.getLink() + " is not valid, should begin with ",
anEntry.getLink().startsWith("https://units.d8u.us/twitter?tweet="));
}
}
@Test
public void twitterGeneratesRssFeedMaxLength100IfQueryParameterAuthor() throws Exception {
final HttpUrl requestUrl = new HttpUrl.Builder().host("localhost").scheme("http").port(this.port)
.addPathSegment("twitter").addQueryParameter("author", "hasandiwan2").build();
final Request request = new Request.Builder().url(requestUrl).build();
final Response rawResponse = TwitterTests.client.newCall(request).execute();
final SyndFeed feed = new SyndFeedInput()
.build(new XmlReader(new ByteArrayInputStream(rawResponse.body().bytes())));
Assert.assertTrue("Twitter feed for hasandiwan2".equals(feed.getTitle()));
Assert.assertTrue(feed.getEntries().size() < 101);
for (final SyndEntry e : feed.getEntries().subList(0, feed.getEntries().size() - 2)) {
Assert.assertTrue(ISODateTimeFormat.dateTime().print(e.getPublishedDate().getTime()) + " is not a date!",
e.getPublishedDate()
.after(feed.getEntries().get(feed.getEntries().indexOf(e) + 1).getPublishedDate()));
Assert.assertTrue("Invalid twitter url -- " + e.getLink() + "!",
e.getLink().startsWith("https://units.d8u.us/twitter?tweet="));
}
}
@Test
public void twitterGivesErrorIfTweetNotFound() throws Exception {
final HttpUrl requestUrl = new HttpUrl.Builder().host("localhost").scheme("http").port(this.port)
.addPathSegment("twitter").addQueryParameter("tweet", "1").build();
final Request request = new Request.Builder().url(requestUrl).build();
final Response rawResponse = TwitterTests.client.newCall(request).execute();
final Map<String, String> response = new ObjectMapper().readValue(rawResponse.body().string(),
new TypeReference<Map<String, String>>() {
});
Assert.assertEquals(200, rawResponse.code());
Assert.assertEquals("tweet 1 not found", response.get("error"));
Assert.assertEquals("404", response.get("status"));
}
@Test
public void twitterIsCaching() throws Exception {
final HttpUrl requestUrl = new HttpUrl.Builder().host("localhost").scheme("http").port(this.port)
.addPathSegment("twitter").addQueryParameter("tweet", "1250650485205241857").build();
final Request request = new Request.Builder().url(requestUrl).build();
Response rawResponse = TwitterTests.client.newCall(request).execute();
final String response = rawResponse.body().string();
final Map<String, String> json = new ObjectMapper().readValue(response,
new TypeReference<Map<String, String>>() {
});
Assert.assertTrue("Key \"cached?\" found -- shouldn't be happening", !json.containsKey("cached?"));
rawResponse = TwitterTests.client.newCall(request).execute();
final JsonNode jsonNode = new ObjectMapper().readTree(rawResponse.body().bytes());
Assert.assertTrue("Not cached", jsonNode.has("cached?") && "true".equals(jsonNode.get("cached?").asText()));
Assert.assertTrue("cache is not effective, time not saved", jsonNode.get("time").asDouble() < NumberFormat
.getNumberInstance().parse(json.get("time")).doubleValue());
}
@Test
public void twitterResolvesUrlsToLongform() throws Exception {
final HttpUrl url = HttpUrl.parse(
"http://localhost:58081/twitter/?tweet=https://twitter.com/HasanDiwan2/status/1300146349371875334");
final Request request = new Request.Builder()
.addHeader("authorization", "aHdXSTQzVFBTakpFQzY4ZjoyejQwZlAzdU9uMkJSMGZYSTA1dkhjaVM=")
.patch(RequestBody.create("{}", MediaType.parse("text/json"))).url(url).build();
final Response rawResponse = new OkHttpClient.Builder().build().newCall(request).execute();
final Map<String, String> response = new ObjectMapper().readValue(rawResponse.body().string(),
new TypeReference<Map<String, String>>() {
});
for (final String urlFound : Splitter.on(";").split(response.get("urls"))) {
final HttpUrl parsed = HttpUrl.parse(urlFound);
Assert.assertTrue(!parsed.host().contains("t.co"));
}
}
@Test
public void twitterTakesTweet() throws Exception {
final HttpUrl requestUrl = new HttpUrl.Builder().host("localhost").scheme("http").port(this.port)
.addPathSegment("twitter").addQueryParameter("tweet", "1250650485205241857").build();
final Request request = new Request.Builder().url(requestUrl).build();
final Response rawResponse = TwitterTests.client.newCall(request).execute();
final Map<String, String> response = new ObjectMapper().readValue(rawResponse.body().string(),
new TypeReference<Map<String, String>>() {
});
Assert.assertEquals("hasandiwan2", response.get("author"));
Assert.assertEquals("false", response.get("verifiedAuthor"));
Assert.assertEquals("", response.get("people"));
Assert.assertEquals("Germany; America", response.get("places"));
final Set<String> expectedNouns = Sets.newHashSet(Splitter.on("; ")
.split("you; death; rates; it; their; leader; quantum; chemist; yours; reality; television; host"));
final Set<String> actualNouns = Sets.newHashSet(Splitter.on(", ").split(response.get("noun")));
Assert.assertTrue(expectedNouns.equals(actualNouns));
final Set<String> expectedVerbs = Sets.newHashSet(Splitter.on("; ").split("wondering; used; be"));
final Set<String> actualVerbs = Sets.newHashSet(Splitter.on(", ").split(response.get("verb")));
Assert.assertEquals(expectedVerbs, actualVerbs);
Assert.assertEquals("", response.get("dates"));
Assert.assertEquals("", response.get("company"));
Assert.assertEquals("", response.get("hashtag"));
Assert.assertTrue("en".equals(response.get("language")));
Assert.assertEquals("", response.get("stock"));
Assert.assertEquals("", response.get("otherUser"));
Assert.assertEquals("", response.get("url"));
Assert.assertEquals("https://twitter.com/hasandiwan2/1250650485205241857", response.get("permalink"));
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"));
Assert.assertTrue((NumberFormat.getIntegerInstance().parse(response.get("retweetCount")).intValue() > -1)
&& (NumberFormat.getIntegerInstance().parse(response.get("favouriteCount")).intValue() > -1));
}
}
package us.d8u.balance;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
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.test.context.junit4.SpringRunner;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ArrayNode;
import com.fasterxml.jackson.databind.node.ObjectNode;
import okhttp3.HttpUrl;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT)
public class TwoFrontTess {
private static final OkHttpClient client = new OkHttpClient();
private final ObjectNode data = this.mapper.createObjectNode();
private final ObjectMapper mapper = new ObjectMapper();
@LocalServerPort
private Integer port;
@Test
public void nonexistinngPatientReturnsNotFoundMessage() throws Exception {
final HttpUrl url = HttpUrl.parse("http://localhost/twofront/patients/1").newBuilder().port(this.port).build();
final Request request = new Request.Builder().url(url).build();
final Response response = TwoFrontTess.client.newCall(request).execute();
final String size = response.header("x-length");
Assert.assertTrue(size.equals("-1"));
final JsonNode node = this.mapper.readTree(response.body().byteStream());
Assert.assertTrue(node.get("status").asText().equals("404"));
}
@Test
public void patientsListReturnsEverything() throws Exception {
final Integer EXPECTED_LENGTH = this.data.size();
final HttpUrl url = HttpUrl.parse("http://localhost/twofront/patients/list").newBuilder().port(this.port)
.build();
final Request request = new Request.Builder().url(url).build();
final Response response = TwoFrontTess.client.newCall(request).execute();
final String size = response.header("x-length");
Assert.assertTrue(Integer.valueOf(size).equals(EXPECTED_LENGTH));
final JsonNode node = this.mapper.readTree(response.body().byteStream());
Assert.assertTrue(node.equals(this.data));
}
@Test
public void patientWithNumberReturnsThatPatient() throws Exception {
final HttpUrl url = HttpUrl.parse("http://localhost/twofront/patients/1").newBuilder().port(this.port).build();
final Request request = new Request.Builder().url(url).build();
final Response response = TwoFrontTess.client.newCall(request).execute();
final JsonNode node = this.mapper.readTree(response.body().byteStream());
Assert.assertTrue(node.equals(this.data.get(1)));
}
@Test
public void searchYieldsNoResults() throws Exception {
final HttpUrl url = HttpUrl.parse("http://localhost/twofront/patients/find?address=Luton").newBuilder()
.port(this.port).build();
final Request request = new Request.Builder().url(url).build();
final Response response = TwoFrontTess.client.newCall(request).execute();
final String count = response.header("x-length");
Assert.assertTrue(Integer.valueOf(count).equals(0));
}
@Test
public void searchYieldsResults() throws Exception {
final HttpUrl url = HttpUrl.parse("http://localhost/twofront/patients/find?address=London").newBuilder()
.port(this.port).build();
final Request request = new Request.Builder().url(url).build();
final Response response = TwoFrontTess.client.newCall(request).execute();
final String count = response.header("x-length");
Assert.assertTrue(Integer.valueOf(count).equals(2));
final JsonNode node = this.mapper.readTree(response.body().byteStream());
Assert.assertTrue(node.get(1).asInt() == 1);
Assert.assertTrue(node.get(2).asInt() == 2);
}
@Before
public void seed() {
final ArrayNode patients = this.mapper.createArrayNode();
final ObjectNode seed1 = this.mapper.createObjectNode();
seed1.put("name", "Hasan Diwan");
seed1.put("ssn", "507-39-4628");
seed1.put("address", "10 Downing Street, London W1A, England");
seed1.put("phoneNumber", "+4479075551212");
seed1.put("id", "1");
patients.add(seed1);
final ObjectNode seed2 = this.mapper.createObjectNode();
seed2.put("name", "Sarah Griffis");
seed2.put("ssn", "491-17-1456");
seed2.put("address", "11 Downing Street, London W1A, England");
seed2.put("id", "2");
patients.add(seed2); // only for one test
this.data.set("patients", patients);
}
}
package us.d8u.balance;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
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.test.context.junit4.SpringRunner;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ArrayNode;
import com.fasterxml.jackson.databind.node.ObjectNode;
import okhttp3.HttpUrl;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT)
public class TwoFrontTests {
private static final OkHttpClient client = new OkHttpClient();
private final ObjectNode data = this.mapper.createObjectNode();
private final ObjectMapper mapper = new ObjectMapper();
@LocalServerPort
private Integer port;
@Test
public void nonexistinngPatientReturnsNotFoundMessage() throws Exception {
final HttpUrl url = HttpUrl.parse("http://localhost/twofront/patients/1").newBuilder().port(this.port).build();
final Request request = new Request.Builder().url(url).build();
final Response response = TwoFrontTests.client.newCall(request).execute();
final String size = response.header("x-length");
Assert.assertTrue(size.equals("-1"));
final JsonNode node = this.mapper.readTree(response.body().byteStream());
Assert.assertTrue(node.get("status").asText().equals("404"));
}
@Test
public void patientsListReturnsEverything() throws Exception {
final Integer EXPECTED_LENGTH = this.data.size();
final HttpUrl url = HttpUrl.parse("http://localhost/twofront/patients/list").newBuilder().port(this.port)
.build();
final Request request = new Request.Builder().url(url).build();
final Response response = TwoFrontTests.client.newCall(request).execute();
final String size = response.header("x-length");
Assert.assertTrue(Integer.valueOf(size).equals(EXPECTED_LENGTH));
final JsonNode node = this.mapper.readTree(response.body().byteStream()).get("patients");
Assert.assertTrue(node.equals(this.data));
}
@Test
public void patientWithNumberReturnsThatPatient() throws Exception {
final HttpUrl url = HttpUrl.parse("http://localhost/twofront/patients/1").newBuilder().port(this.port).build();
final Request request = new Request.Builder().url(url).build();
final Response response = TwoFrontTests.client.newCall(request).execute();
final JsonNode node = this.mapper.readTree(response.body().byteStream());
Assert.assertTrue(node.equals(this.data.get(1)));
}
@Test
public void searchYieldsNoResults() throws Exception {
final HttpUrl url = HttpUrl.parse("http://localhost/twofront/patients/find?address=Luton").newBuilder()
.port(this.port).build();
final Request request = new Request.Builder().url(url).build();
final Response response = TwoFrontTests.client.newCall(request).execute();
final String count = response.header("x-length");
Assert.assertTrue(Integer.valueOf(count).equals(0));
}
@Test
public void searchYieldsResults() throws Exception {
final HttpUrl url = HttpUrl.parse("http://localhost/twofront/patients/find?address=London").newBuilder()
.port(this.port).build();
final Request request = new Request.Builder().url(url).build();
final Response response = TwoFrontTests.client.newCall(request).execute();
final String count = response.header("x-length");
Assert.assertTrue(Integer.valueOf(count).equals(2));
final JsonNode node = this.mapper.readTree(response.body().byteStream()).get("patients");
Assert.assertTrue(node.get(1).asInt() == 1);
Assert.assertTrue(node.get(2).asInt() == 2);
}
@Before
public void seed() {
final ArrayNode patients = this.mapper.createArrayNode();
final ObjectNode seed1 = this.mapper.createObjectNode();
seed1.put("name", "Hasan Diwan");
seed1.put("ssn", "507-39-4628");
seed1.put("address", "10 Downing Street, London W1A, England");
seed1.put("phoneNumber", "+4479075551212");
seed1.put("id", "1");
patients.add(seed1);
final ObjectNode seed2 = this.mapper.createObjectNode();
seed2.put("name", "Sarah Griffis");
seed2.put("ssn", "491-17-1456");
seed2.put("address", "11 Downing Street, London W1A, England");
seed2.put("phoneNumber", "+448717223344");
seed2.put("id", "2");
patients.add(seed2); // only for one test
this.data.set("patients", patients);
}
}
package us.d8u.balance;
import java.util.Map;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
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.test.context.junit4.SpringRunner;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.common.collect.Maps;
import com.google.common.collect.Sets;
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 UnderscoresToCamelcaseTests {
private static final OkHttpClient client = new OkHttpClient();
private static final ObjectMapper mapper = new ObjectMapper();
@LocalServerPort
private int port;
@Test
public void routesAreTranslatedCorrectly() throws Exception {
final HttpUrl endpoint = HttpUrl.parse("http://localhost:" + this.port + "/underscores2dashes");
final Map<String, String> body = Maps.newHashMap();
body.put("inComing", "resources \"something_with_multiple_words\"");
final Request endpointRequest = new Request.Builder().post(
RequestBody.create(new ObjectMapper().writeValueAsString(body), MediaType.parse("application/json")))
.url(endpoint).build();
final Response endpointResponse = UnderscoresToCamelcaseTests.client.newCall(endpointRequest).execute();
final Map<String, String> response = mapper.readValue(endpointResponse.body().bytes(),
new TypeReference<Map<String, String>>() {
});
Assert.assertEquals("Unexpected or missing keys", Sets.newHashSet("result"), response.keySet());
Assert.assertEquals("resources \"something-with-multiple-words\"", response.get("translated"));
}
}
package us.d8u.balance;
import java.lang.annotation.Annotation;
import java.lang.reflect.Method;
import java.util.List;
import java.util.Map;
import org.assertj.core.util.Lists;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.context.SpringBootTest.WebEnvironment;
import org.springframework.boot.web.server.LocalServerPort;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.web.bind.annotation.RequestMapping;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import okhttp3.HttpUrl;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT)
public class UnitTests {
private static final OkHttpClient client = new OkHttpClient();
@Autowired
private EndpointRepository endpointRepository;
@LocalServerPort
private int port;
@Test
public void allRoutesAccountedFor() throws Exception {
final List<String> necessary = Lists.newArrayList();
final Class<?> clazz = Class.forName("us.d8u.balance.Controller");
for (final Method method : clazz.getMethods()) {
for (final Annotation annotation : method.getDeclaredAnnotations()) {
if ("RequestMapping".equals(annotation.annotationType().getTypeName())) {
final RequestMapping requestAnnotation = (RequestMapping) annotation;
final String value = requestAnnotation.value()[0];
necessary.add(0, value);
}
}
}
final List<String> endpoints = Lists.newArrayList(this.endpointRepository.findEndpoints());
for (final String endpoint : necessary) {
Assert.assertTrue("this.endpointRepository.save(new EndpointBean(\"" + endpoint
+ "\", BigDecimal.ZERO)); \nis missing!", endpoints.contains(endpoint));
}
for (final String endpoint : endpoints) {
Assert.assertTrue("remove " + endpoint, endpoints.contains(endpoint));
}
}
@Test
public void canViewTestCode() throws Exception {
final HttpUrl endpoint = new HttpUrl.Builder().scheme("http").host("localhost").port(this.port)
.addPathSegment("tests").build();
final Request request = new Request.Builder().url(endpoint).build();
final Response response = UnitTests.client.newCall(request).execute();
Assert.assertTrue(response.isSuccessful());
}
@Test
public void unitsCache() throws Exception {
final HttpUrl testUrl = HttpUrl.parse("http://localhost:" + this.port + "/units/64/inches/centimeter/");
final Request request = new Request.Builder().url(testUrl).build();
final Response response = UnitTests.client.newCall(request).execute();
final Map<String, String> actual = new ObjectMapper().readValue(response.body().string(),
new TypeReference<Map<String, String>>() {
});
final Request request2 = new Request.Builder().url(testUrl).build();
final Response response2 = UnitTests.client.newCall(request2).execute();
final Map<String, String> actual2 = new ObjectMapper().readValue(response2.body().string(),
new TypeReference<Map<String, String>>() {
});
Assert.assertTrue("cache is ineffective!",
Long.valueOf(actual2.get("time")) < Long.valueOf(actual.get("time")));
}
@Test
public void unitsCentigradeToFahrenheitWorks() throws Exception {
final HttpUrl testUrl = HttpUrl.parse("http://localhost:" + this.port + "/units/0/degC/degF");
final Request request = new Request.Builder().url(testUrl).build();
final Response response = UnitTests.client.newCall(request).execute();
final Map<String, String> actual = new ObjectMapper().readValue(response.body().string(),
new TypeReference<Map<String, String>>() {
});
final String result = actual.get("resultAmount");
Assert.assertTrue("0 Celcius isn't 32 Fahrenheit, rather it is " + result, result == "0");
}
@Test
public void unitsFahrenheitToCentigradeWorks() throws Exception {
final HttpUrl testUrl = HttpUrl.parse("http://localhost:" + this.port + "/units/32/degF/degC");
final Request request = new Request.Builder().url(testUrl).build();
final Response response = UnitTests.client.newCall(request).execute();
final Map<String, String> actual = new ObjectMapper().readValue(response.body().string(),
new TypeReference<Map<String, String>>() {
});
final String result = actual.get("resultAmount");
Assert.assertTrue("32 Fahrenheight isn't 0 C, rather it is " + result, result == "0");
}
@Test
public void unitsNonValidUnitGivesIncompatibleUnit() throws Exception {
final HttpUrl testUrl = HttpUrl.parse("http://localhost:" + this.port + "/units/1/metrs/feet");
final Request request = new Request.Builder().url(testUrl).build();
final Response response = UnitTests.client.newCall(request).execute();
final Map<String, String> actual = new ObjectMapper().readValue(response.body().string(),
new TypeReference<Map<String, String>>() {
});
Assert.assertEquals("Error: metrs and feet are incompatible", actual.get("resultAmount"));
}
@Test
public void unitsResultDoesNotEndInZeroAsLeastSignificantFractionalComponent() throws Exception {
final HttpUrl testUrl = HttpUrl.parse("http://localhost:" + this.port + "/units/1/meters/feet");
final Request request = new Request.Builder().url(testUrl).build();
final Response response = UnitTests.client.newCall(request).execute();
final Map<String, String> actual = new ObjectMapper().readValue(response.body().string(),
new TypeReference<Map<String, String>>() {
});
final String result = actual.get("resultAmount");
Assert.assertEquals(Double.parseDouble(result), 1.0936133, 6);
}
@Test
public void unitsWorksWithAmounts() throws Exception {
final HttpUrl testUrl = HttpUrl.parse("http://localhost:" + this.port + "/units/64/inches/centimeter/");
final Request request = new Request.Builder().url(testUrl).build();
final Response response = UnitTests.client.newCall(request).execute();
final Map<String, String> actual = new ObjectMapper().readValue(response.body().string(),
new TypeReference<Map<String, String>>() {
});
Assert.assertEquals("inches", actual.get("from"));
Assert.assertEquals("centimeter", actual.get("to"));
Assert.assertEquals("162.56", actual.get("resultAmount"));
}
}
package us.d8u.balance;
import java.util.Map;
import org.apache.commons.validator.routines.InetAddressValidator;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
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.test.context.junit4.SpringRunner;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.common.collect.Sets;
import okhttp3.HttpUrl;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT)
public class UpdateConfigTests {
private static final OkHttpClient client = new OkHttpClient();
@LocalServerPort
private int port;
@Test
public void returnsAllConfigKeysWithoutParams() throws Exception {
final Response rawResponse = UpdateConfigTests.client
.newCall(new Request.Builder().url("http://localhost:" + this.port + "/config").build()).execute();
final Map<String, String> actual = new ObjectMapper().readValue(rawResponse.body().bytes(),
new TypeReference<Map<String, String>>() {
});
Assert.assertTrue(actual.keySet().equals(Sets.newHashSet("tor.host", "home.ip", "whereishasan.jdbc")));
}
@Test
public void returnsOnlyHomeIpKeyIfHomeIpChanged() throws Exception {
final Response rawResponse = UpdateConfigTests.client
.newCall(new Request.Builder().url("http://localhost:" + this.port + "/config?home=8.8.8.8").build())
.execute();
final Map<String, String> actual = new ObjectMapper().readValue(rawResponse.body().bytes(),
new TypeReference<Map<String, String>>() {
});
Assert.assertTrue(actual.keySet().equals(Sets.newHashSet("home.ip")));
Assert.assertTrue(InetAddressValidator.getInstance().isValidInet4Address(actual.get("home.ip"))
&& "8.8.8.8".equals(actual.get("home.ip")));
}
@Test
public void returnsOnlyTorKeyIfTorChanged() throws Exception {
final Response rawResponse = UpdateConfigTests.client
.newCall(new Request.Builder().url("http://localhost:" + this.port + "/config?tor=.onion").build())
.execute();
final Map<String, String> actual = new ObjectMapper().readValue(rawResponse.body().bytes(),
new TypeReference<Map<String, String>>() {
});
Assert.assertTrue(actual.keySet().equals(Sets.newHashSet("tor.host")));
Assert.assertTrue(".onion".equals(actual.get("tor.host")));
}
@Test
public void returnsOnlyWhereIsHasanJdbcIfWhereIsHasanJdbcChanged() throws Exception {
final HttpUrl url = HttpUrl.parse("http://localhost:" + this.port + "/config").newBuilder().addQueryParameter(
"whereishasan.jdbc",
"jdbc:postgresql://ec2-54-243-55-1.compute-1.amazonaws.com/dd90cuhur62sq7?user=iqiilqlvznntyu&password=a769c478d6c6eb0a51d906db06abe07c3194d64f35f7e51225ce823b9a1950f5&sslmode=require")
.build();
final Response rawResponse = UpdateConfigTests.client.newCall(new Request.Builder().url(url).build()).execute();
final Map<String, String> actual = new ObjectMapper().readValue(rawResponse.body().bytes(),
new TypeReference<Map<String, String>>() {
});
Assert.assertTrue(actual.keySet().equals(Sets.newHashSet("whereishasan.jdbc")));
}
}
package us.d8u.balance;
import java.lang.reflect.Method;
import java.util.List;
import java.util.UUID;
import org.junit.Assert;
import org.junit.BeforeClass;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.context.SpringBootTest.WebEnvironment;
import org.springframework.boot.test.web.server.LocalServerPort;
import org.springframework.http.HttpStatus;
import org.springframework.test.context.junit4.SpringRunner;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.common.collect.Lists;
import com.google.common.collect.Sets;
import jakarta.mail.internet.AddressException;
import jakarta.mail.internet.InternetAddress;
import okhttp3.HttpUrl;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT)
public class UploadTests {
private static final OkHttpClient client = new OkHttpClient();
private static final ObjectMapper mapper = new ObjectMapper();
@LocalServerPort
private int port;
List<UUID> streamOfUUIDs = Lists.newArrayList();
@BeforeClass
public void globalSetup() {
int randomSize = 0;
for (Method runnable : this.getClass().getMethods()) {
if (runnable.isAnnotationPresent(Test.class)) {
randomSize++;
}
}
for (int iterCounter = 0; iterCounter < randomSize; iterCounter++) {
UUID random = UUID.randomUUID();
streamOfUUIDs.add(random);
}
}
@Test
public void cantBeUploadededToTwice() throws Exception {
UUID anEntry = streamOfUUIDs.get(1);
HttpUrl underTest = HttpUrl.parse("http://localhost/upload/").newBuilder().port(port)
.addPathSegment(anEntry.toString()).build();
RequestBody fileBody = RequestBody.create(".zshrc", MediaType.parse("text/plain"));
RequestBody formBody = new MultipartBody.Builder().setType(MultipartBody.FORM)
.addFormDataPart("file", "/Users/user/.zshrc", fileBody).build();
Request request = new Request.Builder().url(underTest).post(formBody).build();
Response rawResponse = client.newCall(request).execute();
Assert.assertTrue(rawResponse.code() == HttpStatus.CREATED.value());
JsonNode response = mapper.readTree(rawResponse.body().byteStream());
Assert.assertTrue(Sets.newHashSet("url", "email").iterator().equals(response.fieldNames()));
try {
Assert.assertTrue(InternetAddress.parse(response.get("email").asText())[0] != null);
} catch (AddressException e) {
Assert.fail("email not valid");
}
Assert.assertTrue("Invalid bucket url", HttpUrl.parse(response.get("url").asText()) != null);
}
}
package us.d8u.balance;
import java.util.Map;
import org.joda.time.DateTime;
import org.joda.time.format.DateTimeFormatter;
import org.joda.time.format.ISODateTimeFormat;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
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.test.context.junit4.SpringRunner;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import okhttp3.HttpUrl;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT)
public class UrlCheckinTests {
@LocalServerPort
private Integer port;
@Test(expected = UnsupportedOperationException.class)
public void urlCheckinThrowsErrorForInvalidUrls() throws Exception {
new OkHttpClient().newCall(new okhttp3.Request.Builder()
.url("http://localhost:" + this.port + "/urlCheckin?url=http://localhost").build()).execute();
}
@Test
public void urlCheckinUpdatesTimeWithoutUpdateTimeParameter() throws Exception {
final DateTimeFormatter checkTimeFormatter = ISODateTimeFormat.dateTimeNoMillis();
final HttpUrl checkUrl = HttpUrl.parse("https://whereishasan.herokuapp.com/api");
final Request checkRequest = new Request.Builder().url(checkUrl).build();
final Response rawCheckResponse = new OkHttpClient().newCall(checkRequest).execute();
final Map<String, String> checkResponse = new ObjectMapper()
.readValue(rawCheckResponse.body().bytes(), new TypeReference<Map<String, Map<String, String>>>() {
}).get("data");
final String storedTimeValue = checkResponse.get("timestamp");
final DateTime originalTime = checkTimeFormatter.parseDateTime(storedTimeValue);
final HttpUrl requestUrl = new HttpUrl.Builder().scheme("http").host("localhost").port(this.port)
.addEncodedPathSegments("/urlCheckin")
.addQueryParameter("url",
"https://www.google.be/maps/place/37+Lagoon+Vista+Rd,+Belvedere+Tiburon,+CA+94920/@37.8752952,-122.4576917,17z/data=!3m1!4b1!4m5!3m4!1s0x8085848780bcab29:0xe502cdea4a56947f!8m2!3d37.875291!4d-122.455503")
.build();
final Request request = new Request.Builder().url(requestUrl).build();
final Response response = new OkHttpClient().newCall(request).execute();
if ("true".equals(response.body().string())) {
Assert.assertTrue(originalTime.isAfter(DateTime.now().minusDays(1)));
}
}
@Test
public void urlCheckinWillNotUpdateTimeWithUpdateTimeParameter() throws Exception {
final HttpUrl checkUrl = HttpUrl.parse("https://whereishasan.herokuapp.com/api");
final Request checkRequest = new Request.Builder().url(checkUrl).build();
final Response rawCheckResponse = new OkHttpClient().newCall(checkRequest).execute();
final Map<String, String> checkResponse = new ObjectMapper()
.readValue(rawCheckResponse.body().bytes(), new TypeReference<Map<String, Map<String, String>>>() {
}).get("data");
final String storedTimeValue = checkResponse.get("timestamp");
final HttpUrl requestUrl = new HttpUrl.Builder().scheme("http").host("localhost").port(this.port)
.addEncodedPathSegments("/urlCheckin")
.addQueryParameter("url",
"https://www.google.be/maps/place/37+Lagoon+Vista+Rd,+Belvedere+Tiburon,+CA+94920/@37.8752952,-122.4576917,17z/data=!3m1!4b1!4m5!3m4!1s0x8085848780bcab29:0xe502cdea4a56947f!8m2!3d37.875291!4d-122.455503")
.addQueryParameter("time", "false").build();
final Request request = new Request.Builder().url(requestUrl).build();
Assert.assertTrue("upstream down?",
"true".equals(new OkHttpClient().newCall(request).execute().body().string()));
final Response rawResetResponse = new OkHttpClient().newCall(checkRequest).execute();
final String rawResponse = rawResetResponse.body().string();
final JsonNode response = new ObjectMapper().readValue(rawResponse, JsonNode.class).get("data");
Assert.assertTrue(storedTimeValue + " is not equal to " + response.get("timestamp").asText(),
storedTimeValue.equals(response.get("timestamp").asText()));
}
}
package us.d8u.balance;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
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.test.context.junit4.SpringRunner;
import okhttp3.HttpUrl;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT)
public class UrlTests {
private final OkHttpClient client = new OkHttpClient.Builder().build();
@LocalServerPort
private int port;
@Test
public void goodOutput() throws Exception {
final String expected = "<figure><img src=\"https://cdn.theathletic.com/app/uploads/2022/03/27195215/USATSI_16621810-scaled.jpg\"></img></figure>\n"
+ "<p>&ldquo;I&rsquo;m not sure if you&rsquo;ve heard,&rdquo; a minor-league instructor said to me the other day, &ldquo;but they&rsquo;re moving second base.&rdquo;</p>\n"
+ "<p>Wait. What? They&rsquo;re moving second base? Where would it be moving, exactly? Into a VIP suite? Into a cool little beach house?</p>\n"
+ "<p>No, no, no. It isn&rsquo;t that big a move, it turns out. But sources tell The Athletic that in the second half of this season, baseball will be moving second base inward &mdash; so it will be closer to first base and third base, by about 13.5 inches.</p>\n"
+ "<p>Not in the big leagues, at least not yet. But this will happen in most ballparks at every level of the minor leagues, as part of sweeping minor-league rule-change experiments that will include pitch clocks, <a href=\"https://theathletic.com/3138898/2022/02/21/what-would-happen-if-baseball-killed-the-shift/\">shift limits</a> and robot umps &mdash; all of which could be coming to a big-league ballpark near you one of these years. Or not.</p>\n"
+ "<p>But how did the location of second base get mixed up in all this? Well, there isn&rsquo;t one quick explanation. It isn&rsquo;t to mess with <a href=\"https://theathletic.com/player/mlb/astros/jose-altuve-XBsBnmYpBnTfLi4H/\">Jose Altuve</a> or <a href=\"https://theathletic.com/player/mlb/braves/ozzie-albies/\">Ozzie Albies</a>. It&rsquo;s not some mysterious curse that traces back to the ghost of Rogers Hornsby or something. So let&rsquo;s lay it out this way:</p>\n"
+ "<p>The reason &mdash; traces back more than a century to the weirdness of where second base was originally located on the diamond. Spoiler alert: There has never been a distance of 90 feet between first base and second base, or between second and third, for that matter. That&rsquo;s part of this. I&rsquo;ll explain. But first &hellip;</p>\n"
+ "<p>The goal &mdash; is to create a shorter distance between the bases.</p>";
final HttpUrl url = HttpUrl.parse("http://localhost/url").newBuilder().port(this.port).addEncodedQueryParameter(
"url",
"https://theathletic.com/3212654/2022/03/28/why-baseball-is-moving-second-base-and-what-this-experiment-could-mean-for-the-game/")
.build();
final Response response = this.client.newCall(new Request.Builder().url(url).build()).execute();
Assert.assertTrue("Output doesn't match expected", expected.equals(response.body().string()));
}
}
package us.d8u.balance;
import java.util.Map;
import org.apache.commons.validator.routines.EmailValidator;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
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 com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.common.collect.Sets;
import okhttp3.HttpUrl;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT)
public class UserBeanTests {
private static final OkHttpClient client = new OkHttpClient.Builder().build();
@LocalServerPort
Integer port;
@Test
public void patchWithInvalidUserIdGivesError() throws Exception {
final HttpUrl testUrl = HttpUrl.parse("http://localhost:" + this.port + "/user").newBuilder()
.addQueryParameter("userId", Long.toString(Long.MAX_VALUE + 1)).build();
final Request request = new Request.Builder().url(testUrl).build();
final Response response = UserBeanTests.client.newCall(request).execute();
final Map<String, String> actual = new ObjectMapper().readValue(response.body().string(),
new TypeReference<Map<String, String>>() {
});
Assert.assertTrue(Sets.newHashSet("status", "error").equals(actual.keySet()));
Assert.assertTrue(actual.get("status").equals(Integer.toString(HttpStatus.NOT_FOUND.value())));
Assert.assertTrue(("user not found " + Long.toString(Long.MAX_VALUE + 1)).equals(actual.get("error")));
}
@Test
public void patchWithNonIntegerNumberGivesError() throws Exception {
final HttpUrl testUrl = HttpUrl.parse("http://localhost:" + this.port + "/user").newBuilder()
.addQueryParameter("userId", "a").build();
final Request request = new Request.Builder().url(testUrl).build();
final Response response = UserBeanTests.client.newCall(request).execute();
final Map<String, String> actual = new ObjectMapper().readValue(response.body().string(),
new TypeReference<Map<String, String>>() {
});
Assert.assertTrue(Sets.newHashSet("status", "error").equals(actual.keySet()));
Assert.assertTrue(actual.get("status").equals(Integer.toString(HttpStatus.INTERNAL_SERVER_ERROR.value())));
Assert.assertTrue("number parameter must be numeric, not a".equals(actual.get("error")));
}
@Test
public void patchWithoutUserIdGivesError() throws Exception {
final HttpUrl testUrl = HttpUrl.parse("http://localhost:" + this.port + "/user");
final Request request = new Request.Builder().url(testUrl).build();
final Response response = UserBeanTests.client.newCall(request).execute();
final Map<String, String> actual = new ObjectMapper().readValue(response.body().string(),
new TypeReference<Map<String, String>>() {
});
Assert.assertTrue(Sets.newHashSet("status", "error").equals(actual.keySet()));
Assert.assertTrue(actual.get("status").equals(Integer.toString(HttpStatus.BAD_REQUEST.value())));
Assert.assertTrue("missing userId".equals(actual.get("error")));
}
@Test
public void usersReturnsIdsAndNames() throws Exception {
final HttpUrl testUrl = HttpUrl.parse("http://localhost:" + this.port + "/users/");
final Request request = new Request.Builder().url(testUrl).build();
final Response response = UserBeanTests.client.newCall(request).execute();
final Map<String, String> actual = new ObjectMapper().readValue(response.body().string(),
new TypeReference<Map<String, String>>() {
});
for (final String key : actual.keySet()) {
try {
Long.valueOf(key);
} catch (final NumberFormatException e) {
Assert.fail(key + " is not a number!");
}
Assert.assertTrue(EmailValidator.getInstance().isValid(actual.get(key)));
}
}
@Test
public void validUserEdit() throws Exception {
final HttpUrl testUrl = HttpUrl.parse("http://localhost:" + this.port + "/user").newBuilder()
.addQueryParameter("userId", "2").addQueryParameter("number", "000").build();
Request request = new Request.Builder().url(testUrl).build();
final Response response = UserBeanTests.client.newCall(request).execute();
final Map<String, String> actual = new ObjectMapper().readValue(response.body().string(),
new TypeReference<Map<String, String>>() {
});
Assert.assertTrue(Sets.newHashSet("userId", "name", "number").equals(actual.keySet()));
final HttpUrl resetUrl = HttpUrl.parse("http://localhost:" + this.port + "/user").newBuilder()
.addQueryParameter("userId", "2").addQueryParameter("number", "14156907930").build();
request = new Request.Builder().url(resetUrl).build();
UserBeanTests.client.newCall(request).execute();
}
}
package us.d8u.balance;
import java.util.Map;
import org.apache.commons.validator.routines.EmailValidator;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
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 com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.common.collect.Sets;
import okhttp3.HttpUrl;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT)
public class UserTests {
private static final OkHttpClient client = new OkHttpClient.Builder().build();
@LocalServerPort
Integer port;
@Test
public void usersReturnsIdsAndNames() throws Exception {
final HttpUrl testUrl = HttpUrl.parse("http://localhost:" + port + "/users/");
final Request request = new Request.Builder().url(testUrl).build();
final Response response = client.newCall(request).execute();
final Map<String, String> actual = new ObjectMapper().readValue(response.body().string(),
new TypeReference<Map<String, String>>() {
});
for (final String key : actual.keySet()) {
try {
Long.valueOf(key);
} catch (final NumberFormatException e) {
Assert.fail(key + " is not a number!");
}
Assert.assertTrue(EmailValidator.getInstance().isValid(actual.get(key)));
}
}
@Test
public void patchWithoutUserIdGivesError() throws Exception {
final HttpUrl testUrl = HttpUrl.parse("http://localhost:" + port + "/user");
final Request request = new Request.Builder().url(testUrl).build();
final Response response = client.newCall(request).execute();
final Map<String, String> actual = new ObjectMapper().readValue(response.body().string(),
new TypeReference<Map<String, String>>() {
});
Assert.assertTrue(Sets.newHashSet("status", "error").equals(actual.keySet()));
Assert.assertTrue(actual.get("status").equals(Integer.toString(HttpStatus.BAD_REQUEST.value())));
Assert.assertTrue(actual.get("error").equals("missing userId"));
}
@Test
public void patchWithInvalidUserIdGivesError() throws Exception {
final HttpUrl testUrl = HttpUrl.parse("http://localhost:" + port + "/user").newBuilder()
.addQueryParameter("userId", Long.toString(Long.MAX_VALUE + 1)).build();
final Request request = new Request.Builder().url(testUrl).build();
final Response response = client.newCall(request).execute();
final Map<String, String> actual = new ObjectMapper().readValue(response.body().string(),
new TypeReference<Map<String, String>>() {
});
Assert.assertTrue(Sets.newHashSet("status", "error").equals(actual.keySet()));
Assert.assertTrue(actual.get("status").equals(Integer.toString(HttpStatus.NOT_FOUND.value())));
Assert.assertTrue(actual.get("error").equals("user not found " + Long.toString(Long.MAX_VALUE + 1)));
}
@Test
public void patchWithNonIntegerNumberGivesError() throws Exception {
final HttpUrl testUrl = HttpUrl.parse("http://localhost:" + port + "/user").newBuilder()
.addQueryParameter("userId", "a").build();
final Request request = new Request.Builder().url(testUrl).build();
final Response response = client.newCall(request).execute();
final Map<String, String> actual = new ObjectMapper().readValue(response.body().string(),
new TypeReference<Map<String, String>>() {
});
Assert.assertTrue(Sets.newHashSet("status", "error").equals(actual.keySet()));
Assert.assertTrue(actual.get("status").equals(Integer.toString(HttpStatus.INTERNAL_SERVER_ERROR.value())));
Assert.assertTrue(actual.get("error").equals("number parameter must be numeric, not a"));
}
@Test
public void validUserEdit() throws Exception {
final HttpUrl testUrl = HttpUrl.parse("http://localhost:" + port + "/user").newBuilder()
.addQueryParameter("userId", "2").addQueryParameter("number", "000").build();
Request request = new Request.Builder().url(testUrl).build();
final Response response = client.newCall(request).execute();
final Map<String, String> actual = new ObjectMapper().readValue(response.body().string(),
new TypeReference<Map<String, String>>() {
});
Assert.assertTrue(Sets.newHashSet("userId", "name", "number").equals(actual.keySet()));
final HttpUrl resetUrl = HttpUrl.parse("http://localhost:" + port + "/user").newBuilder()
.addQueryParameter("userId", "2").addQueryParameter("number", "14156907930").build();
request = new Request.Builder().url(resetUrl).build();
client.newCall(request).execute();
}
}
package us.d8u.balance;
import java.util.Set;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
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.test.context.junit4.SpringRunner;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.common.collect.ImmutableSet;
import okhttp3.HttpUrl;
import okhttp3.OkHttpClient;
import okhttp3.Request;
@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT)
public class UuidTests {
private static final OkHttpClient client = new OkHttpClient();
@LocalServerPort
private int port;
@Test
public void properKeys() throws Exception {
final HttpUrl url = HttpUrl.parse("http://localhost/uuid").newBuilder().port(this.port).build();
final JsonNode keys = new ObjectMapper().readValue(
UuidTests.client.newCall(new Request.Builder().url(url).build()).execute().body().charStream(),
JsonNode.class);
final Set<String> expected = ImmutableSet.of("mostSignificant", "time", "leastSignificant", "total");
Assert.assertEquals(expected, keys.fieldNames());
Assert.assertTrue(keys.get("time").asText().matches("^[0-9.]+$"));
}
}
package us.d8u.balance;
import java.util.Map;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
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 com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.common.collect.Maps;
import okhttp3.HttpUrl;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT)
public class ValidateTests {
private static final OkHttpClient client = new OkHttpClient();
@SuppressWarnings("unused")
private static Logger LOG = LoggerFactory.getLogger("us.d8u.balance.ValidateTests");
@LocalServerPort
private int port;
@Test
public void xmlErrorForEmptyXmlUrl() throws Exception {
final Map<String, String> expected = Maps.newHashMap();
expected.put("error", "xmlUrl pointing to remote XML document required");
expected.put("status", Integer.toString(HttpStatus.EXPECTATION_FAILED.value()));
expected.put("valid", "false");
final HttpUrl requestUrl = HttpUrl.parse("http://localhost:" + this.port + "/validate");
final Request request = new Request.Builder().url(requestUrl).build();
final Response rawResponse = ValidateTests.client.newCall(request).execute();
Assert.assertTrue(rawResponse.isSuccessful());
final String string = rawResponse.body().string();
final Map<String, String> actual = new ObjectMapper().readValue(string,
new TypeReference<Map<String, String>>() {
});
Assert.assertEquals(expected, actual);
}
@Test
public void xmlValid() throws Exception {
final Map<String, String> expected = Maps.newHashMap();
expected.put("valid", "true");
expected.put("xmlUrl", "https://hd1-devel.blogspot.com/atom.xml");
final HttpUrl requestUrl = new HttpUrl.Builder().scheme("http").host("localhost").port(this.port)
.addPathSegment("validate").addQueryParameter("xmlUrl", expected.get("xmlUrl")).build();
final Request request = new Request.Builder().url(requestUrl).build();
final Response response = ValidateTests.client.newCall(request).execute();
Assert.assertTrue(response.isSuccessful());
final Map<String, String> actual = new ObjectMapper().readValue(response.body().string(),
new TypeReference<Map<String, String>>() {
});
Assert.assertEquals(expected, actual);
}
}
package us.d8u.balance;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
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.test.context.junit4.SpringRunner;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.common.collect.Sets;
import okhttp3.HttpUrl;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT)
public class VerbTests {
private static final OkHttpClient client = new OkHttpClient();
@LocalServerPort
private int port;
ObjectMapper mapper = new ObjectMapper();
@Test
public void expectedForInvalidEndpoint() throws Exception {
final HttpUrl url = HttpUrl.parse("http://localhost/nlp/verb").newBuilder().port(this.port)
.addQueryParameter("word", "see").addEncodedQueryParameter("invalidTest", "true").build();
final Request request = new Request.Builder().url(url).build();
final Response response = VerbTests.client.newCall(request).execute();
Assert.assertEquals(200, response.code());
final JsonNode rootNode = this.mapper.readTree(response.body().charStream());
Assert.assertTrue(Sets.newHashSet("error", "status").equals(Sets.newHashSet(rootNode.fieldNames())));
Assert.assertTrue(rootNode.get("status").asInt() == 502);
Assert.assertTrue("helper error".equals(rootNode.get("error").asText()));
}
@Test
public void expectedForValidEndpoint() throws Exception {
final HttpUrl url = HttpUrl.parse("http://localhost/nlp/verb").newBuilder().port(this.port)
.addQueryParameter("word", "see").build();
final Request request = new Request.Builder().url(url).build();
final Response response = VerbTests.client.newCall(request).execute();
Assert.assertEquals(200, response.code());
final JsonNode rootNode = this.mapper.readTree(response.body().charStream());
Assert.assertTrue(Sets.newHashSet("past", "firstPerson", "secondPerson", "thirdPerson")
.equals(Sets.newHashSet(rootNode.fieldNames())));
Assert.assertTrue("saw".equals(rootNode.get("past").asText()));
Assert.assertTrue("see".equals(rootNode.get("firstPerson").asText())
&& "see".equals(rootNode.get("secondPerson").asText())
&& "sees".equals(rootNode.get("thirdPerson").asText()));
}
}
package us.d8u.balance;
import java.time.ZoneOffset;
import org.joda.time.DateTime;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.context.SpringBootTest.WebEnvironment;
import org.springframework.boot.web.server.LocalServerPort;
import org.springframework.data.domain.Sort;
import org.springframework.test.context.junit4.SpringRunner;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ObjectNode;
import com.google.common.collect.Sets;
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 VerifyTests {
private static final OkHttpClient client = new OkHttpClient();
private static final ObjectMapper mapper = new ObjectMapper();
@LocalServerPort
private int port;
@Autowired
AuthRepository authRepository;
@Test
public void invalidHeader() throws Exception {
final HttpUrl endpoint = HttpUrl.parse("http://localhost/verify").newBuilder().port(this.port).build();
final String authHeader = "foo";
final Request request = new Request.Builder().addHeader("authorization", authHeader).url(endpoint).build();
final Response response = VerifyTests.client.newCall(request).execute();
final JsonNode result = VerifyTests.mapper.readTree(response.body().byteStream());
Assert.assertTrue("Missing or extra keys!",
Sets.newHashSet("valid?", "authHeader").equals(Sets.newHashSet(result.fieldNames())));
Assert.assertTrue("authHeader wrong", result.get("authHeader").asText().contentEquals(authHeader));
Assert.assertTrue("valid? not boolean", Boolean.parseBoolean(result.get("valid?").asText()));
Assert.assertTrue("not invalid", !result.get("valid").asBoolean());
}
@Test
public void valid() throws Exception {
final long oldCount = this.authRepository.count();
HttpUrl endpoint = HttpUrl.parse("http://localhost/auth/key").newBuilder().port(this.port).build();
final ObjectNode jsonBody = VerifyTests.mapper.createObjectNode();
jsonBody.put("endpoint", "/");
final String json = VerifyTests.mapper.writeValueAsString(jsonBody);
final RequestBody body = RequestBody.create(json, MediaType.parse("application/json"));
final Request postRequest = new Request.Builder().url(endpoint).post(body).build();
final JsonNode newKey = VerifyTests.mapper
.readTree(VerifyTests.client.newCall(postRequest).execute().body().byteStream());
final String validHeader = newKey.get("authorizationHeader").asText();
endpoint = endpoint.newBuilder().encodedPath("/verify").build();
final Request validityRequest = new Request.Builder().url(endpoint).addHeader("authorization", validHeader)
.build();
final JsonNode validResponse = VerifyTests.mapper
.readTree(VerifyTests.client.newCall(validityRequest).execute().body().byteStream());
Assert.assertTrue("header not valid, huh?", validResponse.get("valid?").asBoolean());
Assert.assertTrue("Not stored", (this.authRepository.count() - oldCount) == 1);
final AuthBean newest = this.authRepository.findAll(Sort.by("createdAt").descending()).get(1);
Assert.assertTrue("not updated creationTime on access", DateTime.now().plusMinutes(10)
.equals(new DateTime(newest.getCreatedAt().toEpochSecond(ZoneOffset.UTC))));
}
}
package us.d8u.balance;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.context.SpringBootTest.WebEnvironment;
import org.springframework.boot.test.web.server.LocalServerPort;
import org.springframework.test.context.junit4.SpringRunner;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.common.collect.Sets;
import okhttp3.HttpUrl;
import okhttp3.OkHttpClient;
import okhttp3.Request;
@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT)
public class VersionTests {
private static final OkHttpClient client = new OkHttpClient();
private static final ObjectMapper mapper = new ObjectMapper();
@LocalServerPort
int port;
@Test
public void properlyFormattedResponse() throws Exception {
HttpUrl underTest = HttpUrl.parse("http://localhost/version").newBuilder().port(port).build();
JsonNode response = mapper
.readTree(client.newCall(new Request.Builder().url(underTest).build()).execute().body().bytes());
Assert.assertTrue("Wrong field names", response.fieldNames().equals(Sets
.newHashSet("version", "time", "deployUpdateTime", "revision", "message", "diff", "branch", "runtime")
.iterator()));
Assert.assertTrue(response.get("runtime").asLong() > 0L);
}
@Test
public void versionWithHttpsUrl() throws Exception {
HttpUrl underTest = HttpUrl.parse("http://localhost/version").newBuilder().port(port)
.addEncodedQueryParameter("url", "https://github.com/hasandiwan/hasandiwan.github.io.git").build();
JsonNode response = mapper
.readTree(client.newCall(new Request.Builder().url(underTest).build()).execute().body().bytes());
Assert.assertTrue("Wrong field names", response.fieldNames().equals(
Sets.newHashSet("version", "deployUpdateTime", "revision", "message", "branch", "time", "url", "diff")
.iterator()));
}
@Test
public void versionWithSshUrl() throws Exception {
HttpUrl underTest = HttpUrl.parse("http://localhost/version").newBuilder().port(port)
.addEncodedQueryParameter("url", "git@github.com:hasandiwan/hasandiwan.github.io.git").build();
JsonNode response = mapper
.readTree(client.newCall(new Request.Builder().url(underTest).build()).execute().body().bytes());
Assert.assertTrue("Wrong field names", response.fieldNames().equals(
Sets.newHashSet("version", "deployUpdateTime", "revision", "message", "branch", "time", "url", "diff")
.iterator()));
}
}
package us.d8u.balance;
import java.util.HashSet;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
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 com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.common.collect.Sets;
import okhttp3.HttpUrl;
import okhttp3.OkHttpClient;
import okhttp3.Request;
@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT)
public class VinTests {
private static final OkHttpClient client = new OkHttpClient();
private static final Logger LOG = LogManager.getLogger(VinTests.class);
private static final ObjectMapper mapper = new ObjectMapper();
@LocalServerPort
private int port;
@Test
public void fullySpecifiedVinReturnsStanzaLikeThis() throws Exception {
final String VIN = "ZPBUA1ZL9KLA00848";
final JsonNode response = VinTests.mapper.readTree(VinTests.client.newCall(new Request.Builder()
.url(HttpUrl.parse("http://localhost:" + this.port + "/vin").newBuilder().addPathSegment(VIN).build())
.build()).execute().body().charStream());
final HashSet<String> keys = Sets.newHashSet(response.fieldNames());
Assert.assertTrue("Unexpected keys", keys.equals(Sets.newHashSet("vin", "model", "year", "cylinders",
"fuelType", "motorwayMpg", "urbanMpg", "doors", "transmission", "msrp", "time", "type")));
Assert.assertTrue("vin is incorrect", VIN.equals(response.get("vin").asText()));
Assert.assertTrue("model is incorrect", "Lamborghini Urus".equals(response.get("model").asText()));
Assert.assertTrue("type is incorrect", "SUV".equals(response.get("type").asText()));
Assert.assertTrue("year is incorrect", response.get("year").asInt() == 2019);
Assert.assertTrue("cylinders is incorrect", response.get("cylinders").asInt() == 8);
Assert.assertTrue("urbanMpg is incorrect", response.get("urbanMpg").asInt() == 12);
Assert.assertTrue("doors is incorrect", response.get("doors").asInt() == 4);
Assert.assertTrue("transmission is incorrect", "automatic".equals(response.get("transmission").asText()));
Assert.assertTrue("motorwayMpg is incorrect", response.get("motorwayMpg").asInt() == 17);
Assert.assertTrue("msrp is incorrect", response.get("msrp").asInt() == 200000);
Assert.assertTrue("fuelType is incorrect", "premium unleaded".equals(response.get("fuelType").asText()));
}
@Test
public void invalidVinReturnsError() throws Exception {
final String VIN = "0xdeadbeef";
final JsonNode response = VinTests.mapper.readTree(VinTests.client.newCall(new Request.Builder()
.url(HttpUrl.parse("http://localhost:" + this.port + "/vin").newBuilder().addPathSegment(VIN).build())
.build()).execute().body().charStream());
final HashSet<String> keys = Sets.newHashSet(response.fieldNames());
VinTests.LOG.info(VinTests.mapper.writeValueAsString(keys) + " are our keys.");
Assert.assertTrue(keys.equals(Sets.newHashSet("vin", "status", "error")));
Assert.assertTrue("vin is incorrect", VIN.equals(response.get("vin").asText()));
Assert.assertTrue("status is not 404", response.get("status").asInt() == HttpStatus.NOT_FOUND.value());
Assert.assertTrue("error is incorrect", "VIN not found".equals(response.get("error").asText()));
}
}
package us.d8u.balance;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
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 com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import okhttp3.HttpUrl;
import okhttp3.OkHttpClient;
import okhttp3.Request;
@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT)
public class VisioTests {
private static final OkHttpClient client = new OkHttpClient();
private static final ObjectMapper mapper = new ObjectMapper();
@LocalServerPort
private int port;
@Test
public void visioUnsupported() throws Exception {
final JsonNode response = VisioTests.mapper.readTree(VisioTests.client
.newCall(new Request.Builder().url(HttpUrl.parse("http://localhost/word").newBuilder()
.addQueryParameter("url", "https://hasan.d8u.us/foo.vsd").build()).build())
.execute().body().byteStream());
Assert.assertTrue(response.get("status").asInt() == HttpStatus.UNSUPPORTED_MEDIA_TYPE.value());
Assert.assertTrue("Visio unsupported".equals(response.get("error").asText()));
}
}
package us.d8u.balance;
import java.io.FileReader;
import java.text.ParseException;
import java.util.HashSet;
import java.util.Map;
import java.util.Properties;
import java.util.Set;
import org.joda.time.DateTime;
import org.joda.time.format.ISODateTimeFormat;
import org.junit.Assert;
import org.junit.BeforeClass;
import org.junit.Test;
import org.junit.runner.RunWith;
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 com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.common.collect.Maps;
import com.google.common.collect.Sets;
import com.ibm.icu.text.NumberFormat;
import okhttp3.HttpUrl;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT)
public class WeatherTests {
private static Properties applicationProperties = System.getProperties();
private static final OkHttpClient client = new OkHttpClient();
private static final ObjectMapper mapper = new ObjectMapper();
@BeforeClass
public static void init() {
try {
WeatherTests.applicationProperties.load(new FileReader("src/main/resources/application.properties"));
} catch (final Exception e) {
Assert.fail("can't get the properties loaded");
}
}
@LocalServerPort
private int port;
@Test
public void error() throws Exception {
final HttpUrl endpoint = HttpUrl.parse("http://localhost/weather").newBuilder()
.addQueryParameter("zip", "foobarbaz").port(this.port).build();
final JsonNode response = WeatherTests.mapper.readTree(
WeatherTests.client.newCall(new Request.Builder().url(endpoint).build()).execute().body().byteStream());
Assert.assertTrue("foobarbaz not found".equals(response.get("error").asText()));
Assert.assertTrue(response.get("status").asInt() == HttpStatus.NOT_FOUND.value());
}
@Test
public void keysAreCorrectForValidRequest() throws Exception {
final DateTime start = DateTime.now();
final HttpUrl.Builder endpoint = HttpUrl.parse("http://localhost/weather").newBuilder().port(this.port);
final Map<String, String> params = Maps.newHashMap();
params.put("zip", "94920");
for (final String k : params.keySet()) {
endpoint.addQueryParameter(k, params.get(k));
}
final JsonNode response = WeatherTests.mapper.readTree(WeatherTests.client
.newCall(new Request.Builder().url(endpoint.build()).build()).execute().body().byteStream());
Assert.assertTrue(Sets.newHashSet("tempF", "tempC", "humidity", "request", "timestamp")
.equals(Sets.newHashSet(response.fieldNames())));
Assert.assertTrue("timetsamp format invalid",
ISODateTimeFormat.dateTimeNoMillis().parseDateTime(response.get("timestamp").asText()).isAfter(start));
Assert.assertTrue("request doesn't match location", response.get("request").asText().equals(params.get("zip")));
Assert.assertTrue("tempF is not a number",
NumberFormat.getInstance().parse(response.get("tempF").asText()) != null);
Assert.assertTrue("tempC is not a number", response.get("tempC").asText().matches("^[0-9.]+$"));
Assert.assertTrue("humidity is not a percentage",
NumberFormat.getPercentInstance().parse(response.get("humidity").asText()) != null);
Assert.assertTrue("humidity is greater than 100%",
NumberFormat.getPercentInstance().parse(response.get("humidity").asText()).doubleValue() < 100.0d);
}
@Test
public void weatherTakesCityStateCountry() throws Exception {
final HttpUrl requestUrl = new HttpUrl.Builder().host("localhost").scheme("http").port(this.port)
.addPathSegment("weather").addQueryParameter("zip", "Oakland, California, USA").build();
final Request request = new Request.Builder().url(requestUrl).get().build();
final Response responseObj = WeatherTests.client.newCall(request).execute();
Assert.assertEquals(200, responseObj.code());
final 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");
final 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 weatherTakesZipcode() throws Exception {
final HttpUrl requestUrl = new HttpUrl.Builder().host("localhost").scheme("http").port(this.port)
.addPathSegment("weather").addQueryParameter("zip", "94920").build();
final Request request = new Request.Builder().url(requestUrl).get().build();
final Response responseObj = WeatherTests.client.newCall(request).execute();
Assert.assertEquals(200, responseObj.code());
final 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");
final 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"));
final NumberFormat nf = NumberFormat.getNumberInstance();
for (final String key : expectedKeys) {
try {
nf.parse(response.get(key));
} catch (final ParseException e) {
if ("barometricPressure".equals(key) && !"-Infinity".equals(response.get("barometricPressure"))) {
Assert.fail("<" + key + ", " + response.get(key) + " -- " + e.getMessage());
}
}
}
}
@Test
public void weatherWorksOutsideUs() throws Exception {
final HttpUrl requestUrl = new HttpUrl.Builder().host("localhost").scheme("http").port(this.port)
.addPathSegment("weather").addQueryParameter("zip", "Singapore, Singapore").build();
final Request request = new Request.Builder().url(requestUrl).get().build();
final Response responseObj = WeatherTests.client.newCall(request).execute();
Assert.assertEquals(200, responseObj.code());
}
}
package us.d8u.balance;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
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 okhttp3.HttpUrl;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT)
public class WhereAmITests {
private static OkHttpClient client;
@LocalServerPort
private int port;
@Test
public void locIsAnAlias() throws Exception {
final HttpUrl url = HttpUrl.parse("http://localhost:" + this.port + "/whereami");
final HttpUrl url2 = HttpUrl.parse("http://localhost:" + this.port + "/loc");
final Response response = WhereAmITests.client.newCall(new Request.Builder().url(url).build()).execute();
final Response response2 = WhereAmITests.client.newCall(new Request.Builder().url(url2).build()).execute();
final byte[] body = response.body().bytes();
final byte[] body2 = response2.body().bytes();
Assert.assertTrue((null != body) && body.equals(body2));
}
@Test
public void redirectsToCorrectPage() throws Exception {
final HttpUrl url = HttpUrl.parse("http://localhost:" + this.port + "/whereami");
final Response response = WhereAmITests.client.newCall(new Request.Builder().url(url).build()).execute();
Assert.assertTrue(HttpStatus.PERMANENT_REDIRECT.value() == response.code());
Assert.assertTrue("https://whereishasan.herokuapp.com".equals(response.header("Location")));
}
}
package us.d8u.balance;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
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 com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import okhttp3.HttpUrl;
import okhttp3.OkHttpClient;
import okhttp3.Request;
@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT)
public class WordTests {
private static final OkHttpClient client = new OkHttpClient();
private static final ObjectMapper mapper = new ObjectMapper();
@LocalServerPort
private int port;
@Test
public void blankDocument() throws Exception {
final JsonNode response = WordTests.mapper
.readTree(WordTests.client.newCall(new Request.Builder()
.url(HttpUrl.parse("http://localhost/word").newBuilder()
.addQueryParameter("url", "https://hasan.d8u.us/foo.doc").port(this.port).build())
.build()).execute().body().byteStream());
Assert.assertTrue(response.get("status").asInt() == HttpStatus.NOT_FOUND.value());
Assert.assertTrue("Couldn't retrieve".equals(response.get("error").asText()));
}
@Test
public void invalidScheme() throws Exception {
final JsonNode response = WordTests.mapper.readTree(WordTests.client
.newCall(new Request.Builder().url(HttpUrl.parse("http://localhost/word").newBuilder()
.addQueryParameter("url", "file:////foo.doc").port(this.port).build()).build())
.execute().body().byteStream());
Assert.assertTrue(response.get("status").asInt() == HttpStatus.BAD_REQUEST.value());
Assert.assertTrue("Unsupported schema".equals(response.get("error").asText()));
}
@Test
public void missingUrl() throws Exception {
final JsonNode response = WordTests.mapper.readTree(WordTests.client
.newCall(new Request.Builder()
.url(HttpUrl.parse("http://localhost/word").newBuilder().port(this.port).build()).build())
.execute().body().byteStream());
Assert.assertTrue(response.get("status").asInt() == HttpStatus.BAD_REQUEST.value());
Assert.assertTrue("Missing URL".equals(response.get("error").asText()));
}
@Test
public void responseCorrect() throws Exception {
final String URL = "https://github.com/apache/poi/raw/trunk/test-data/document/47304.doc";
final JsonNode response = WordTests.mapper
.readTree(WordTests.client
.newCall(new Request.Builder().url(HttpUrl.parse("http://localhost/word").newBuilder()
.port(this.port).addEncodedQueryParameter("url", URL).build()).build())
.execute().body().byteStream());
Assert.assertTrue("Just a \"test\"".equals(response.get("text").asText()));
Assert.assertTrue(response.get("wordCount").asInt() == 3);
Assert.assertTrue(response.get("pageCount").asInt() == 1);
Assert.assertTrue(response.get("phraseCount").asInt() == 1);
}
}
package us.d8u.balance;
import java.util.Map;
import java.util.Set;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
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.test.context.junit4.SpringRunner;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.common.collect.Sets;
import okhttp3.HttpUrl;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT)
public class XmlTests {
private static final OkHttpClient client = new OkHttpClient();
@LocalServerPort
private int port;
@Test
public void xmlTakesAtomAndReturnsJsonProperly() throws Exception {
final HttpUrl requestUrl = new HttpUrl.Builder().host("localhost").scheme("http").port(this.port)
.addPathSegment("xml").addQueryParameter("xml", "https://news.google.com/news/atom").build();
final Request request = new Request.Builder().url(requestUrl).get().build();
final Response rawResponse = XmlTests.client.newCall(request).execute();
final String string = rawResponse.body().string();
final Map<String, String> response = new ObjectMapper().readValue(string,
new TypeReference<Map<String, String>>() {
});
final 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 (final String required : expectedKeys) {
Assert.assertTrue("Missing key: " + required, response.containsKey(required));
}
}
}
package us.d8u.balance;
import java.util.Map;
import java.util.Set;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
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.test.context.junit4.SpringRunner;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.common.collect.Maps;
import com.google.common.collect.Sets;
import okhttp3.HttpUrl;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT)
public class XQueryTests {
private static final OkHttpClient client = new OkHttpClient();
@LocalServerPort
private int port;
@Test
public void xquery() throws Exception {
final Map<String, String> xqBody = Maps.newHashMap();
final var xmlSource = "<?xml version='1.0' encoding='UTF-8'?><bookstore><book category='COOKING'> <title lang='en'>Everyday Italian</title><author>Giada De Laurentiis</author> <year>2005</year> <price>30.00</price></book><book category='CHILDREN'> <title lang='en'>Harry Potter</title> <author>J K. Rowling</author> <year>2005</year> <price>29.99</price></book><book category='WEB'> <title lang='en'>XQuery Kick Start</title> <author>James McGovern</author> <author>Per Bothner</author> <author>Kurt Cagle</author> <author>James Linn</author> <author>Vaidyanathan Nagarajan</author> <year>2003</year> <price>49.99</price></book><book category='WEB'> <title lang='en'>Learning XML</title> <author>Erik T. Ray</author> <year>2003</year> <price>39.95</price></book></bookstore>";
final var path = "/bookstore/book[3]/title";
xqBody.put("in", xmlSource);
xqBody.put("query", path);
final var xqUrl = HttpUrl.parse("http://localhost:" + this.port + "/xquery");
final var xqReq = new Request.Builder().url(xqUrl)
.post(RequestBody.create(new ObjectMapper().writeValueAsString(xqBody), MediaType.parse("text/json")))
.build();
final var xqResp = XQueryTests.client.newCall(xqReq).execute();
final Map<String, String> xqResponse = new ObjectMapper().readValue(xqResp.body().string(),
new TypeReference<Map<String, String>>() {
});
final Set<String> expectedKeys = Sets.newHashSet("results", "in", "query");
Assert.assertTrue(expectedKeys.equals(xqResponse.keySet()));
final Map<String, String> original = Maps.newHashMap(xqResponse);
final var result = original.remove("results");
Assert.assertTrue(original.equals(xqBody));
Assert.assertTrue("XQuery Kick Start".equals(result));
}
}
package us.d8u.balance;
import java.util.Map;
import java.util.Set;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
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.test.context.junit4.SpringRunner;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.common.collect.Sets;
import okhttp3.HttpUrl;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT)
public class ZipTests {
private static final OkHttpClient client = new OkHttpClient();
@LocalServerPort
private int port;
@Test
public void zipReturnsCitiesStateCountyTimezoneAreacodesCountryLatitudeLongitude() throws Exception {
final Set<String> expected = Sets.newHashSet("cities", "state", "county", "timezone", "itu", "country",
"latitude", "longitude", "valid?", "request");
final Request request = new Request.Builder().url("http://localhost:" + this.port + "/zip?code=90211").build();
final Response rawResponse = ZipTests.client.newCall(request).execute();
final ObjectMapper mapper = new ObjectMapper();
final Map<String, String> response = mapper.readValue(rawResponse.body().bytes(),
new TypeReference<Map<String, String>>() {
});
Assert.assertEquals(expected, response.keySet());
Assert.assertEquals("90211", response.get("request"));
Assert.assertEquals("California", response.get("state"));
Assert.assertEquals("Los Angeles", response.get("county"));
Assert.assertEquals("34.0652", response.get("latitude"));
Assert.assertEquals("-118.383", response.get("longitude"));
Assert.assertEquals("United States", response.get("country"));
}
@Test
public void zipTooLongReturnsError() throws Exception {
final Request request = new Request.Builder()
.url(HttpUrl.parse("http://0:58081/zip/?code=902111").newBuilder().port(this.port).build()).build();
final Response rawResponse = ZipTests.client.newCall(request).execute();
final ObjectMapper mapper = new ObjectMapper();
final Map<String, String> response = mapper.readValue(rawResponse.body().bytes(),
new TypeReference<Map<String, String>>() {
});
Assert.assertTrue("417".equals(response.get("status")));
Assert.assertTrue("902111 is too long!".equals(response.get("error")));
}
@Test
public void zipTooShortReturnsError() throws Exception {
final Request request = new Request.Builder()
.url(HttpUrl.parse("http://0:58081/zip/?code=911").newBuilder().port(this.port).build()).build();
final Response rawResponse = ZipTests.client.newCall(request).execute();
final ObjectMapper mapper = new ObjectMapper();
final Map<String, String> response = mapper.readValue(rawResponse.body().bytes(),
new TypeReference<Map<String, String>>() {
});
Assert.assertTrue("417".equals(response.get("status")));
Assert.assertTrue("911 is too short!".equals(response.get("error")));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment