aboutsummaryrefslogtreecommitdiffstats
path: root/testutil/src/main/java/com/yahoo/test/json/JsonTestHelper.java
blob: 05532d2a5045e18500b6a2c2a5f525959202f856 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.test.json;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.common.base.Joiner;

import java.io.UncheckedIOException;

import static org.junit.Assert.assertEquals;

/**
 * @author Vegard Sjonfjell
 */
public class JsonTestHelper {

    private static final ObjectMapper mapper = new ObjectMapper();

    /**
     * Convenience method to input JSON without escaping double quotes and newlines
     * Each parameter represents a line of JSON encoded data
     * The lines are joined with newline and single quotes are replaced with double quotes
     */
    public static String inputJson(String... lines) {
        return Joiner.on("\n").join(lines).replaceAll("'", "\"");
    }

    /** Structurally compare two JSON encoded strings */
    public static void assertJsonEquals(String inputJson, String expectedJson) {
        try {
            JsonNode expected = mapper.readTree(expectedJson);
            JsonNode actual = mapper.readTree(inputJson);
            assertEquals(expected, actual);
        } catch (JsonProcessingException e) {
            throw new RuntimeException("Exception when comparing json strings." , e);
        }
    }

    /** Structurally compare a {@link JsonNode} and a JSON string. */
    public static void assertJsonEquals(JsonNode left, String rightJson) {
        try {
            String leftJson = mapper.writeValueAsString(left);
            assertJsonEquals(leftJson, rightJson);
        } catch (JsonProcessingException e) {
            throw new UncheckedIOException(e);
        }
    }

    /** Structurally compare two {@link JsonNode}s. */
    public static void assertJsonEquals(JsonNode left, JsonNode right) {
        try {
            String leftJson = mapper.writeValueAsString(left);
            String rightJson = mapper.writeValueAsString(right);
            assertJsonEquals(leftJson, rightJson);
        } catch (JsonProcessingException e) {
            throw new UncheckedIOException(e);
        }
    }
}