package net.lshift.diffa.participant.scanning;

import org.joda.time.DateTime;
import org.joda.time.DateTimeZone;
import org.junit.Test;

import java.io.ByteArrayOutputStream;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;

import static org.junit.Assert.assertEquals;

/**
 * Tests for the JSON serialisation support.
 */
public class JSONHelperTest {
  @Test
  public void shouldSerialiseEmptyList() throws Exception {
    String emptyRes = serialiseResult(new ArrayList<ScanResultEntry>());
    assertEquals("[]", emptyRes);
  }

  @Test
  public void shouldSerialiseSingleEntityWithNoAttributes() throws Exception {
    String single = serialiseResult(Arrays.asList(
      ScanResultEntry.forEntity("id1", "v1", new DateTime(2011, 6, 5, 15, 3, 0, 0, DateTimeZone.UTC))));
    assertEquals("[{\"id\":\"id1\",\"version\":\"v1\",\"lastUpdated\":\"2011-06-05T15:03:00.000Z\"}]", single);
  }

  @Test
  public void shouldSerialiseSingleEntityWithAttributes() throws Exception {
    String single = serialiseResult(Arrays.asList(
      ScanResultEntry.forEntity("id1", "v1", new DateTime(2011, 6, 5, 15, 3, 0, 0, DateTimeZone.UTC),
          generateAttributes("a1v1", "a2v2"))));
    assertEquals(
      "[{\"id\":\"id1\",\"attributes\":{\"a1\":\"a1v1\",\"a2\":\"a2v2\"},\"version\":\"v1\",\"lastUpdated\":\"2011-06-05T15:03:00.000Z\"}]",
      single);
  }

  private static String serialiseResult(Iterable<ScanResultEntry> entries) throws Exception {
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    JSONHelper.writeQueryResult(baos, entries);

    return new String(baos.toByteArray(), "UTF-8");
  }

  private static Map<String, String> generateAttributes(String a1, String a2) {
    Map<String, String> result = new HashMap<String, String>();
    result.put("a1", a1);
    result.put("a2", a2);
    return result;
  }
}

@@ -41,16 +41,100 @@
 nning;%0A%0A
+import org.codehaus.jackson.JsonNode;%0Aimport org.codehaus.jackson.map.ObjectMapper;%0A
 import o
@@ -156,16 +156,16 @@
 teTime;%0A
-
 import o
@@ -253,16 +253,44 @@
 Stream;%0A
+import java.io.IOException;%0A
 import j
@@ -655,32 +655,36 @@
 %3E());%0A    assert
+JSON
 Equals(%22%5B%5D%22, emp
@@ -945,24 +945,28 @@
 ;%0A    assert
+JSON
 Equals(%22%5B%7B%5C%22
@@ -1353,24 +1353,28 @@
 ;%0A    assert
+JSON
 Equals(%0A    
@@ -1988,16 +1988,16 @@
 %22, a2);%0A
-
     retu
@@ -2010,11 +2010,305 @@
 ult;%0A  %7D
+%0A%0A  private static void assertJSONEquals(String expected, String actual) throws IOException %7B%0A    ObjectMapper mapper = new ObjectMapper();%0A    JsonNode expectedTree = mapper.readTree(expected);%0A    JsonNode actualTree = mapper.readTree(actual);%0A%0A    assertEquals(expectedTree, actualTree);%0A  %7D
 %0A%7D%0A

Add JSON-aware assertion