diff --git a/UserFront/src/test/java/com/userFront/AdminRestSmokeTest.java b/UserFront/src/test/java/com/userFront/AdminRestSmokeTest.java new file mode 100644 index 00000000..678a72ff --- /dev/null +++ b/UserFront/src/test/java/com/userFront/AdminRestSmokeTest.java @@ -0,0 +1,305 @@ +package com.userFront; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertTrue; +import static org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestPostProcessors.user; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; + +import java.math.BigDecimal; +import java.time.Instant; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Comparator; +import java.util.Date; +import java.util.List; + +import org.junit.Before; +import org.junit.Test; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.http.MediaType; +import org.springframework.test.web.servlet.request.MockHttpServletRequestBuilder; +import org.springframework.test.web.servlet.request.RequestPostProcessor; + +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.node.ArrayNode; +import com.fasterxml.jackson.databind.node.JsonNodeFactory; +import com.userFront.dao.AppointmentDao; +import com.userFront.dao.PrimaryAccountDao; +import com.userFront.dao.PrimaryTransactionDao; +import com.userFront.dao.RecipientDao; +import com.userFront.dao.RoleDao; +import com.userFront.dao.SavingsAccountDao; +import com.userFront.dao.SavingsTransactionDao; +import com.userFront.dao.UserDao; +import com.userFront.domain.Appointment; +import com.userFront.domain.PrimaryAccount; +import com.userFront.domain.PrimaryTransaction; +import com.userFront.domain.Recipient; +import com.userFront.domain.SavingsAccount; +import com.userFront.domain.SavingsTransaction; +import com.userFront.domain.User; +import com.userFront.domain.security.Role; +import com.userFront.domain.security.UserRole; +import com.userFront.golden.GoldenFixtures; +import com.userFront.golden.JsonParseEquivalence; + +/** + * Regression contract for the admin REST API consumed by the AdminPortal, captured on Boot 1.5.4. + * + *

Responses are compared with {@link JsonParseEquivalence} against the committed + * {@code golden/boot15/*.json} fixtures; regenerate them with {@code -Dgolden.update=true}. The + * fixtures hold the response bodies as served, restricted to the {@value #PREFIX}* rows this class + * seeds (other smoke tests share the JVM, context and database), with transaction and appointment + * rows sorted by date (the queries have no ORDER BY), and pretty-printed. Generated ids + * are compared for presence and type only; everything else, including account numbers, balances, + * dates and the exposed password hash, is seeded with fixed values. + * + *

Rows are written directly through the DAOs with fixed account numbers rather than through + * signup, whose static account-number counter restarts per JVM (COG-1179). + */ +public class AdminRestSmokeTest extends AbstractIntegrationTest { + + private static final String PREFIX = "adminsmoke-"; + + private static final String ALICE = PREFIX + "alice"; + + private static final String BOB = PREFIX + "bob"; + + /** Only used by the enable/disable test, so its {@code enabled} flag never leaks into a fixture. */ + private static final String TOGGLE = PREFIX + "toggle"; + + private static final String PASSWORD_HASH = "adminsmoke-fixed-password-hash"; + + /** + * {@code User.recipientList} has no {@code @JsonIgnore}, so {@code /api/user/all} (and the + * nested {@code user} of {@code /api/appointment/all}) currently serialises every user's + * recipients. COG-1150 adds the annotation: flip this to {@code false} and regenerate + * {@code user-all.json} and {@code appointment-all.json} in that PR. + */ + private static final boolean RECIPIENT_LIST_IN_USER_ALL = true; + + private static final JsonParseEquivalence EQUIVALENCE = JsonParseEquivalence.create() + .ignoringValuesOf("id", "userId"); + + private static final RequestPostProcessor ADMIN = user(PREFIX + "admin").roles("ADMIN"); + + private static final RequestPostProcessor CUSTOMER = user(ALICE).roles("USER"); + + @Autowired + private UserDao userDao; + + @Autowired + private RoleDao roleDao; + + @Autowired + private PrimaryAccountDao primaryAccountDao; + + @Autowired + private SavingsAccountDao savingsAccountDao; + + @Autowired + private PrimaryTransactionDao primaryTransactionDao; + + @Autowired + private SavingsTransactionDao savingsTransactionDao; + + @Autowired + private RecipientDao recipientDao; + + @Autowired + private AppointmentDao appointmentDao; + + /** + * The enable/disable request. Both endpoints are plain {@code @RequestMapping}s reached with GET + * today; COG-1154 moves them to POST, which only needs this method to change. + */ + private static MockHttpServletRequestBuilder toggleUser(String username, String action) { + return get("/api/user/{username}/{action}", username, action); + } + + @Before + public void seed() { + if (userDao.findByUsername(ALICE) != null) { + return; + } + Role role = new Role(); + role.setRoleId(1); + role.setName("ROLE_USER"); + role = roleDao.save(role); + + User alice = saveUser(ALICE, "Alice", "Admin-Smoke", "5550001001", 91145001, "1500.00", 91145002, "250.75", + role); + User bob = saveUser(BOB, "Bob", "Admin-Smoke", "5550001002", 91145003, "0.00", 91145004, "0.00", role); + saveUser(TOGGLE, "Toggle", "Admin-Smoke", "5550001003", 91145005, "0.00", 91145006, "0.00", role); + + Recipient recipient = new Recipient(); + recipient.setName(PREFIX + "landlord"); + recipient.setEmail("adminsmoke-landlord@example.com"); + recipient.setPhone("5550002001"); + recipient.setAccountNumber("99887766"); + recipient.setDescription("Rent"); + recipient.setUser(alice); + recipientDao.save(recipient); + + primaryTransactionDao.save(new PrimaryTransaction(at("2017-06-15T10:15:30Z"), "Deposit to Primary Account", + "Account", "Finished", 2000.0, new BigDecimal("2000.00"), alice.getPrimaryAccount())); + primaryTransactionDao.save(new PrimaryTransaction(at("2017-06-16T09:00:00Z"), + "Transfer to recipient " + recipient.getName(), "Transfer", "Finished", 500.0, + new BigDecimal("1500.00"), alice.getPrimaryAccount())); + savingsTransactionDao.save(new SavingsTransaction(at("2017-06-17T14:30:00Z"), "Deposit to savings Account", + "Account", "Finished", 250.75, new BigDecimal("250.75"), alice.getSavingsAccount())); + + saveAppointment(alice, "2017-07-01T15:00:00Z", "Chicago branch", "Mortgage consultation", false); + saveAppointment(bob, "2017-07-02T16:30:00Z", "New York branch", "Open a savings account", true); + } + + @Test + public void userAllMatchesBoot15Fixture() throws Exception { + JsonNode users = getJsonAsAdmin("/api/user/all"); + assertTrue(users.isArray()); + + GoldenFixtures.assertMatches(GoldenFixtures.BOOT15, "user-all", onlyUsers(users, ALICE, BOB), EQUIVALENCE); + } + + @Test + public void userAllSerialisesRecipientList() throws Exception { + JsonNode alice = onlyUsers(getJsonAsAdmin("/api/user/all"), ALICE).get(0); + + assertEquals(RECIPIENT_LIST_IN_USER_ALL, alice.has("recipientList")); + if (RECIPIENT_LIST_IN_USER_ALL) { + assertEquals(1, alice.get("recipientList").size()); + assertEquals(PREFIX + "landlord", alice.get("recipientList").get(0).get("name").asText()); + } + } + + @Test + public void primaryTransactionsMatchBoot15Fixture() throws Exception { + JsonNode transactions = getJsonAsAdmin("/api/user/primary/transaction?username=" + ALICE); + + GoldenFixtures.assertMatches(GoldenFixtures.BOOT15, "user-primary-transaction", sortedByDate(transactions), + EQUIVALENCE); + } + + @Test + public void savingsTransactionsMatchBoot15Fixture() throws Exception { + JsonNode transactions = getJsonAsAdmin("/api/user/savings/transaction?username=" + ALICE); + + GoldenFixtures.assertMatches(GoldenFixtures.BOOT15, "user-savings-transaction", sortedByDate(transactions), + EQUIVALENCE); + } + + @Test + public void appointmentAllMatchesBoot15Fixture() throws Exception { + JsonNode appointments = getJsonAsAdmin("/api/appointment/all"); + assertTrue(appointments.isArray()); + + List seeded = new ArrayList<>(); + for (JsonNode appointment : appointments) { + if (appointment.path("user").path("username").asText().startsWith(PREFIX)) { + seeded.add(appointment); + } + } + GoldenFixtures.assertMatches(GoldenFixtures.BOOT15, "appointment-all", sortedByDate(seeded), EQUIVALENCE); + } + + @Test + public void disableAndEnableFlipTheEnabledFlag() throws Exception { + mockMvc.perform(toggleUser(TOGGLE, "disable").with(ADMIN)) + .andExpect(status().isOk()) + .andExpect(content().string("")); + assertFalse(userDao.findByUsername(TOGGLE).isEnabled()); + + mockMvc.perform(toggleUser(TOGGLE, "enable").with(ADMIN)) + .andExpect(status().isOk()) + .andExpect(content().string("")); + assertTrue(userDao.findByUsername(TOGGLE).isEnabled()); + } + + @Test + public void customerRoleIsForbiddenFromAdminEndpoints() throws Exception { + List adminRequests = Arrays.asList( + get("/api/user/all"), + get("/api/user/primary/transaction").param("username", ALICE), + get("/api/user/savings/transaction").param("username", ALICE), + get("/api/appointment/all"), + toggleUser(TOGGLE, "disable"), + toggleUser(TOGGLE, "enable")); + + for (MockHttpServletRequestBuilder request : adminRequests) { + mockMvc.perform(request.with(CUSTOMER)).andExpect(status().isForbidden()); + } + assertTrue(userDao.findByUsername(TOGGLE).isEnabled()); + } + + /** Reads and parses the whole body, so a lazy-loading failure anywhere in it fails the test. */ + private JsonNode getJsonAsAdmin(String url) throws Exception { + String body = mockMvc.perform(get(url).with(ADMIN)) + .andExpect(status().isOk()) + .andExpect(content().contentTypeCompatibleWith(MediaType.APPLICATION_JSON)) + .andReturn().getResponse().getContentAsString(); + return JsonParseEquivalence.parse(body); + } + + /** The endpoints query without ORDER BY, so rows are compared in date order rather than as returned. */ + private static ArrayNode sortedByDate(Iterable rows) { + List sorted = new ArrayList<>(); + rows.forEach(sorted::add); + sorted.sort(Comparator.comparing(row -> JsonParseEquivalence.parseInstant(row.get("date")))); + return JsonNodeFactory.instance.arrayNode().addAll(sorted); + } + + private static ArrayNode onlyUsers(JsonNode users, String... usernames) { + ArrayNode selected = JsonNodeFactory.instance.arrayNode(); + for (String username : usernames) { + JsonNode match = null; + for (JsonNode user : users) { + if (username.equals(user.path("username").asText())) { + match = user; + } + } + assertNotNull("No " + username + " in " + users, match); + selected.add(match); + } + return selected; + } + + private User saveUser(String username, String firstName, String lastName, String phone, int primaryNumber, + String primaryBalance, int savingsNumber, String savingsBalance, Role role) { + PrimaryAccount primary = new PrimaryAccount(); + primary.setAccountNumber(primaryNumber); + primary.setAccountBalance(new BigDecimal(primaryBalance)); + SavingsAccount savings = new SavingsAccount(); + savings.setAccountNumber(savingsNumber); + savings.setAccountBalance(new BigDecimal(savingsBalance)); + + User user = new User(); + user.setUsername(username); + user.setPassword(PASSWORD_HASH); + user.setFirstName(firstName); + user.setLastName(lastName); + user.setEmail(username + "@example.com"); + user.setPhone(phone); + user.setPrimaryAccount(primaryAccountDao.save(primary)); + user.setSavingsAccount(savingsAccountDao.save(savings)); + user.getUserRoles().add(new UserRole(user, role)); + return userDao.save(user); + } + + private void saveAppointment(User user, String date, String location, String description, boolean confirmed) { + Appointment appointment = new Appointment(); + appointment.setUser(user); + appointment.setDate(at(date)); + appointment.setLocation(location); + appointment.setDescription(description); + appointment.setConfirmed(confirmed); + appointmentDao.save(appointment); + } + + private static Date at(String isoInstant) { + return Date.from(Instant.parse(isoInstant)); + } +} diff --git a/UserFront/src/test/java/com/userFront/golden/GoldenFixtures.java b/UserFront/src/test/java/com/userFront/golden/GoldenFixtures.java new file mode 100644 index 00000000..ba1d98fa --- /dev/null +++ b/UserFront/src/test/java/com/userFront/golden/GoldenFixtures.java @@ -0,0 +1,67 @@ +package com.userFront.golden; + +import static org.junit.Assert.assertNotNull; + +import java.io.IOException; +import java.io.InputStream; +import java.io.UncheckedIOException; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.Paths; +import java.util.Scanner; + +import com.fasterxml.jackson.databind.JsonNode; + +/** + * Golden JSON fixtures under {@code src/test/resources/golden//.json}. + * + *

{@link #assertMatches} compares a response against the committed fixture with a + * {@link JsonParseEquivalence}. Run the tests with {@code -D}{@value #UPDATE_PROPERTY}{@code =true} + * to (re)write the fixtures from the current responses instead, then commit them. + */ +public final class GoldenFixtures { + + /** Responses captured on Spring Boot 1.5.4 (Jackson 2.8, dates as epoch milliseconds). */ + public static final String BOOT15 = "boot15"; + + public static final String UPDATE_PROPERTY = "golden.update"; + + private static final Path SOURCE_ROOT = Paths.get("src", "test", "resources", "golden"); + + private GoldenFixtures() { + } + + public static void assertMatches(String set, String name, JsonNode actual, JsonParseEquivalence equivalence) { + if (Boolean.getBoolean(UPDATE_PROPERTY)) { + write(set, name, actual); + return; + } + equivalence.assertEquivalent(read(set, name), actual); + } + + public static JsonNode read(String set, String name) { + String resource = "/golden/" + set + "/" + name + ".json"; + try (InputStream in = GoldenFixtures.class.getResourceAsStream(resource)) { + assertNotNull("Missing golden fixture " + resource + "; generate it with -D" + UPDATE_PROPERTY + "=true", + in); + try (Scanner scanner = new Scanner(in, StandardCharsets.UTF_8.name()).useDelimiter("\\A")) { + return JsonParseEquivalence.parse(scanner.hasNext() ? scanner.next() : ""); + } + } + catch (IOException e) { + throw new UncheckedIOException(e); + } + } + + private static void write(String set, String name, JsonNode actual) { + Path file = SOURCE_ROOT.resolve(set).resolve(name + ".json"); + try { + Files.createDirectories(file.getParent()); + Files.write(file, JsonParseEquivalence.write(actual).getBytes(StandardCharsets.UTF_8)); + } + catch (IOException e) { + throw new UncheckedIOException(e); + } + } +} diff --git a/UserFront/src/test/java/com/userFront/golden/JsonParseEquivalence.java b/UserFront/src/test/java/com/userFront/golden/JsonParseEquivalence.java new file mode 100644 index 00000000..feff2d3a --- /dev/null +++ b/UserFront/src/test/java/com/userFront/golden/JsonParseEquivalence.java @@ -0,0 +1,219 @@ +package com.userFront.golden; + +import static org.junit.Assert.fail; + +import java.io.IOException; +import java.io.UncheckedIOException; +import java.math.BigDecimal; +import java.time.Instant; +import java.time.OffsetDateTime; +import java.time.format.DateTimeFormatter; +import java.time.format.DateTimeFormatterBuilder; +import java.time.format.DateTimeParseException; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collections; +import java.util.Iterator; +import java.util.LinkedHashSet; +import java.util.List; +import java.util.Set; +import java.util.TreeSet; + +import com.fasterxml.jackson.databind.DeserializationFeature; +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.SerializationFeature; +import com.fasterxml.jackson.databind.node.JsonNodeFactory; + +/** + * Asserts that two JSON documents are parse-equivalent: same structure, same field names, + * same values after parsing, rather than the same string. + * + *

+ * + *

Public API for the migration waves: later waves assert live responses against the + * {@code golden/boot15} fixtures with this class (see {@link GoldenFixtures}). + */ +public final class JsonParseEquivalence { + + public static final String DEFAULT_DATE_FIELD = "date"; + + private static final ObjectMapper MAPPER = new ObjectMapper() + .enable(DeserializationFeature.USE_BIG_DECIMAL_FOR_FLOATS) + .enable(SerializationFeature.INDENT_OUTPUT) + .setNodeFactory(JsonNodeFactory.withExactBigDecimals(true)); + + private static final DateTimeFormatter ISO_WITH_OFFSET = new DateTimeFormatterBuilder() + .append(DateTimeFormatter.ISO_LOCAL_DATE_TIME) + .optionalStart().appendOffset("+HH:MM", "Z").optionalEnd() + .optionalStart().appendOffset("+HHMM", "Z").optionalEnd() + .optionalStart().appendOffset("+HH", "Z").optionalEnd() + .toFormatter(); + + private final Set dateFields; + + private final Set presenceOnlyFields; + + private JsonParseEquivalence(Set dateFields, Set presenceOnlyFields) { + this.dateFields = Collections.unmodifiableSet(dateFields); + this.presenceOnlyFields = Collections.unmodifiableSet(presenceOnlyFields); + } + + /** Treats {@value #DEFAULT_DATE_FIELD} as a date field and compares every other value. */ + public static JsonParseEquivalence create() { + return new JsonParseEquivalence(new LinkedHashSet<>(Collections.singleton(DEFAULT_DATE_FIELD)), + new LinkedHashSet<>()); + } + + /** Adds field names whose values are compared as instants. */ + public JsonParseEquivalence withDateFields(String... fieldNames) { + Set dates = new LinkedHashSet<>(dateFields); + dates.addAll(Arrays.asList(fieldNames)); + return new JsonParseEquivalence(dates, presenceOnlyFields); + } + + /** Adds field names that must be present with the same JSON type, but whose values are not compared. */ + public JsonParseEquivalence ignoringValuesOf(String... fieldNames) { + Set ignored = new LinkedHashSet<>(presenceOnlyFields); + ignored.addAll(Arrays.asList(fieldNames)); + return new JsonParseEquivalence(dateFields, ignored); + } + + public void assertEquivalent(String expectedJson, String actualJson) { + assertEquivalent(parse(expectedJson), parse(actualJson)); + } + + public void assertEquivalent(JsonNode expected, JsonNode actual) { + List differences = differences(expected, actual); + if (!differences.isEmpty()) { + fail("JSON documents are not parse-equivalent:\n " + String.join("\n ", differences)); + } + } + + /** Every difference between the two documents, as {@code $.path: description}; empty when equivalent. */ + public List differences(JsonNode expected, JsonNode actual) { + List differences = new ArrayList<>(); + compare("$", null, expected, actual, differences); + return differences; + } + + /** Parses JSON keeping decimals exact, so {@code 1000.00} round-trips unchanged. */ + public static JsonNode parse(String json) { + try { + return MAPPER.readTree(json); + } + catch (IOException e) { + throw new UncheckedIOException("Not valid JSON: " + json, e); + } + } + + /** Pretty-prints a node with the same exact-decimal settings used by {@link #parse}. */ + public static String write(JsonNode node) { + try { + return MAPPER.writeValueAsString(node) + "\n"; + } + catch (IOException e) { + throw new UncheckedIOException(e); + } + } + + /** + * Reads a serialised {@code java.util.Date}: a number is epoch milliseconds, a string must be + * ISO-8601 with an offset ({@code Z}, {@code +00}, {@code +0000} or {@code +00:00}). + */ + public static Instant parseInstant(JsonNode node) { + if (node.isIntegralNumber()) { + return Instant.ofEpochMilli(node.longValue()); + } + if (node.isTextual()) { + return OffsetDateTime.parse(node.textValue(), ISO_WITH_OFFSET).toInstant(); + } + throw new IllegalArgumentException("Not a date value: " + node); + } + + private void compare(String path, String fieldName, JsonNode expected, JsonNode actual, List out) { + if (fieldName != null && presenceOnlyFields.contains(fieldName)) { + if (expected.getNodeType() != actual.getNodeType()) { + out.add(path + ": expected a " + expected.getNodeType() + " but was " + actual); + } + return; + } + if (fieldName != null && dateFields.contains(fieldName) && !expected.isNull() && !actual.isNull()) { + compareInstants(path, expected, actual, out); + return; + } + if (expected.isObject() && actual.isObject()) { + compareObjects(path, expected, actual, out); + } + else if (expected.isArray() && actual.isArray()) { + if (expected.size() != actual.size()) { + out.add(path + ": expected " + expected.size() + " elements but was " + actual.size()); + return; + } + for (int i = 0; i < expected.size(); i++) { + compare(path + "[" + i + "]", null, expected.get(i), actual.get(i), out); + } + } + else if (expected.isNumber() && actual.isNumber()) { + if (expected.decimalValue().compareTo(actual.decimalValue()) != 0) { + out.add(path + ": expected " + expected + " but was " + actual); + } + } + else if (!expected.equals(actual)) { + out.add(path + ": expected " + expected + " but was " + actual); + } + } + + private void compareObjects(String path, JsonNode expected, JsonNode actual, List out) { + Set expectedNames = fieldNames(expected); + Set actualNames = fieldNames(actual); + for (String name : expectedNames) { + if (!actualNames.contains(name)) { + out.add(path + "." + name + ": missing"); + } + else { + compare(path + "." + name, name, expected.get(name), actual.get(name), out); + } + } + for (String name : actualNames) { + if (!expectedNames.contains(name)) { + out.add(path + "." + name + ": unexpected field with value " + actual.get(name)); + } + } + } + + private static void compareInstants(String path, JsonNode expected, JsonNode actual, List out) { + Instant expectedInstant; + Instant actualInstant; + try { + expectedInstant = parseInstant(expected); + actualInstant = parseInstant(actual); + } + catch (IllegalArgumentException | DateTimeParseException e) { + out.add(path + ": expected date " + expected + " but was " + actual + " (" + e.getMessage() + ")"); + return; + } + if (!expectedInstant.equals(actualInstant)) { + out.add(path + ": expected instant " + expectedInstant + " (" + expected + ") but was " + actualInstant + + " (" + actual + ")"); + } + } + + private static Set fieldNames(JsonNode node) { + Set names = new TreeSet<>(); + for (Iterator it = node.fieldNames(); it.hasNext();) { + names.add(it.next()); + } + return names; + } +} diff --git a/UserFront/src/test/java/com/userFront/golden/JsonParseEquivalenceTest.java b/UserFront/src/test/java/com/userFront/golden/JsonParseEquivalenceTest.java new file mode 100644 index 00000000..6b98bfc0 --- /dev/null +++ b/UserFront/src/test/java/com/userFront/golden/JsonParseEquivalenceTest.java @@ -0,0 +1,79 @@ +package com.userFront.golden; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; + +import java.util.List; + +import org.junit.Test; + +public class JsonParseEquivalenceTest { + + private static final String EPOCH = "{\"date\":1497521730000}"; + + private final JsonParseEquivalence equivalence = JsonParseEquivalence.create(); + + @Test + public void epochMillisAndIsoOffsetsDenotingTheSameInstantAreEquivalent() { + equivalence.assertEquivalent(EPOCH, "{\"date\":\"2017-06-15T10:15:30.000+0000\"}"); + equivalence.assertEquivalent(EPOCH, "{\"date\":\"2017-06-15T10:15:30.000+00:00\"}"); + equivalence.assertEquivalent(EPOCH, "{\"date\":\"2017-06-15T10:15:30Z\"}"); + equivalence.assertEquivalent(EPOCH, "{\"date\":\"2017-06-15T12:15:30+02:00\"}"); + equivalence.assertEquivalent("{\"date\":\"2017-06-15T10:15:30.000+0000\"}", + "{\"date\":\"2017-06-15T10:15:30.000+00:00\"}"); + } + + @Test + public void differentInstantsAreReported() { + assertEquals(1, diff(EPOCH, "{\"date\":\"2017-06-15T10:15:31Z\"}").size()); + assertEquals(1, diff(EPOCH, "{\"date\":1497521730001}").size()); + } + + @Test + public void unparseableOrOffsetlessDatesAreReported() { + assertEquals(1, diff(EPOCH, "{\"date\":\"2017-06-15T10:15:30\"}").size()); + assertEquals(1, diff(EPOCH, "{\"date\":\"not a date\"}").size()); + } + + @Test + public void datesAreOnlyLenientInDateFields() { + assertEquals(1, diff("{\"created\":1497521730000}", "{\"created\":\"2017-06-15T10:15:30Z\"}").size()); + JsonParseEquivalence.create().withDateFields("created") + .assertEquivalent("{\"created\":1497521730000}", "{\"created\":\"2017-06-15T10:15:30Z\"}"); + } + + @Test + public void numbersCompareByValue() { + equivalence.assertEquivalent("{\"balance\":1000.00}", "{\"balance\":1000}"); + assertEquals(1, diff("{\"balance\":1000.00}", "{\"balance\":1000.01}").size()); + assertEquals(1, diff("{\"balance\":1000}", "{\"balance\":\"1000\"}").size()); + } + + @Test + public void missingAndUnexpectedFieldsAreReported() { + List differences = diff("{\"a\":1,\"recipientList\":[]}", "{\"a\":1,\"b\":2}"); + assertEquals(2, differences.size()); + assertTrue(differences.get(0), differences.get(0).startsWith("$.recipientList: missing")); + assertTrue(differences.get(1), differences.get(1).startsWith("$.b: unexpected")); + } + + @Test + public void arraysCompareByLengthAndOrder() { + assertEquals(1, diff("[1,2]", "[1,2,3]").size()); + assertEquals(2, diff("[1,2]", "[2,1]").size()); + } + + @Test + public void presenceOnlyFieldsIgnoreValuesButNotTypeOrPresence() { + JsonParseEquivalence ids = JsonParseEquivalence.create().ignoringValuesOf("id"); + ids.assertEquivalent("{\"id\":1,\"nested\":{\"id\":7}}", "{\"id\":42,\"nested\":{\"id\":99}}"); + assertEquals(1, ids.differences(JsonParseEquivalence.parse("{\"id\":1}"), + JsonParseEquivalence.parse("{\"id\":\"1\"}")).size()); + assertEquals(1, ids.differences(JsonParseEquivalence.parse("{\"id\":1}"), + JsonParseEquivalence.parse("{}")).size()); + } + + private List diff(String expected, String actual) { + return equivalence.differences(JsonParseEquivalence.parse(expected), JsonParseEquivalence.parse(actual)); + } +} diff --git a/UserFront/src/test/resources/golden/boot15/appointment-all.json b/UserFront/src/test/resources/golden/boot15/appointment-all.json new file mode 100644 index 00000000..4d18287e --- /dev/null +++ b/UserFront/src/test/resources/golden/boot15/appointment-all.json @@ -0,0 +1,74 @@ +[ { + "id" : 1, + "date" : 1498921200000, + "location" : "Chicago branch", + "description" : "Mortgage consultation", + "confirmed" : false, + "user" : { + "userId" : 1, + "username" : "adminsmoke-alice", + "password" : "adminsmoke-fixed-password-hash", + "firstName" : "Alice", + "lastName" : "Admin-Smoke", + "email" : "adminsmoke-alice@example.com", + "phone" : "5550001001", + "enabled" : true, + "primaryAccount" : { + "id" : 1, + "accountNumber" : 91145001, + "accountBalance" : 1500.00 + }, + "savingsAccount" : { + "id" : 1, + "accountNumber" : 91145002, + "accountBalance" : 250.75 + }, + "recipientList" : [ { + "id" : 1, + "name" : "adminsmoke-landlord", + "email" : "adminsmoke-landlord@example.com", + "phone" : "5550002001", + "accountNumber" : "99887766", + "description" : "Rent" + } ], + "authorities" : [ { + "authority" : "ROLE_USER" + } ], + "accountNonExpired" : true, + "accountNonLocked" : true, + "credentialsNonExpired" : true + } +}, { + "id" : 2, + "date" : 1499013000000, + "location" : "New York branch", + "description" : "Open a savings account", + "confirmed" : true, + "user" : { + "userId" : 2, + "username" : "adminsmoke-bob", + "password" : "adminsmoke-fixed-password-hash", + "firstName" : "Bob", + "lastName" : "Admin-Smoke", + "email" : "adminsmoke-bob@example.com", + "phone" : "5550001002", + "enabled" : true, + "primaryAccount" : { + "id" : 2, + "accountNumber" : 91145003, + "accountBalance" : 0.00 + }, + "savingsAccount" : { + "id" : 2, + "accountNumber" : 91145004, + "accountBalance" : 0.00 + }, + "recipientList" : [ ], + "authorities" : [ { + "authority" : "ROLE_USER" + } ], + "accountNonExpired" : true, + "accountNonLocked" : true, + "credentialsNonExpired" : true + } +} ] diff --git a/UserFront/src/test/resources/golden/boot15/user-all.json b/UserFront/src/test/resources/golden/boot15/user-all.json new file mode 100644 index 00000000..cd2d419b --- /dev/null +++ b/UserFront/src/test/resources/golden/boot15/user-all.json @@ -0,0 +1,60 @@ +[ { + "userId" : 1, + "username" : "adminsmoke-alice", + "password" : "adminsmoke-fixed-password-hash", + "firstName" : "Alice", + "lastName" : "Admin-Smoke", + "email" : "adminsmoke-alice@example.com", + "phone" : "5550001001", + "enabled" : true, + "primaryAccount" : { + "id" : 1, + "accountNumber" : 91145001, + "accountBalance" : 1500.00 + }, + "savingsAccount" : { + "id" : 1, + "accountNumber" : 91145002, + "accountBalance" : 250.75 + }, + "recipientList" : [ { + "id" : 1, + "name" : "adminsmoke-landlord", + "email" : "adminsmoke-landlord@example.com", + "phone" : "5550002001", + "accountNumber" : "99887766", + "description" : "Rent" + } ], + "authorities" : [ { + "authority" : "ROLE_USER" + } ], + "accountNonExpired" : true, + "accountNonLocked" : true, + "credentialsNonExpired" : true +}, { + "userId" : 2, + "username" : "adminsmoke-bob", + "password" : "adminsmoke-fixed-password-hash", + "firstName" : "Bob", + "lastName" : "Admin-Smoke", + "email" : "adminsmoke-bob@example.com", + "phone" : "5550001002", + "enabled" : true, + "primaryAccount" : { + "id" : 2, + "accountNumber" : 91145003, + "accountBalance" : 0.00 + }, + "savingsAccount" : { + "id" : 2, + "accountNumber" : 91145004, + "accountBalance" : 0.00 + }, + "recipientList" : [ ], + "authorities" : [ { + "authority" : "ROLE_USER" + } ], + "accountNonExpired" : true, + "accountNonLocked" : true, + "credentialsNonExpired" : true +} ] diff --git a/UserFront/src/test/resources/golden/boot15/user-primary-transaction.json b/UserFront/src/test/resources/golden/boot15/user-primary-transaction.json new file mode 100644 index 00000000..374118e2 --- /dev/null +++ b/UserFront/src/test/resources/golden/boot15/user-primary-transaction.json @@ -0,0 +1,27 @@ +[ { + "id" : 1, + "date" : 1497521730000, + "description" : "Deposit to Primary Account", + "type" : "Account", + "status" : "Finished", + "amount" : 2000.0, + "availableBalance" : 2000.00, + "primaryAccount" : { + "id" : 1, + "accountNumber" : 91145001, + "accountBalance" : 1500.00 + } +}, { + "id" : 2, + "date" : 1497603600000, + "description" : "Transfer to recipient adminsmoke-landlord", + "type" : "Transfer", + "status" : "Finished", + "amount" : 500.0, + "availableBalance" : 1500.00, + "primaryAccount" : { + "id" : 1, + "accountNumber" : 91145001, + "accountBalance" : 1500.00 + } +} ] diff --git a/UserFront/src/test/resources/golden/boot15/user-savings-transaction.json b/UserFront/src/test/resources/golden/boot15/user-savings-transaction.json new file mode 100644 index 00000000..c85369b2 --- /dev/null +++ b/UserFront/src/test/resources/golden/boot15/user-savings-transaction.json @@ -0,0 +1,14 @@ +[ { + "id" : 1, + "date" : 1497709800000, + "description" : "Deposit to savings Account", + "type" : "Account", + "status" : "Finished", + "amount" : 250.75, + "availableBalance" : 250.75, + "savingsAccount" : { + "id" : 1, + "accountNumber" : 91145002, + "accountBalance" : 250.75 + } +} ]