package com.atlassian.bitbucket;

import com.google.gson.JsonElement;
import com.google.gson.JsonParser;

import static org.junit.Assert.*;

public class JsonTestUtils {

    public static void assertJsonContains(String json, String key, String value) {
        JsonElement element = find(json, key);
        assertNotNull("element '" + key + "' not found in JSON " + json, element);
        assertTrue(element.isJsonPrimitive());
        assertEquals("value for " + key + " does not match", value, element.getAsString());
    }

    public static void assertJsonNotContains(String json, String key) {
        JsonElement element = find(json, key);
        assertNull("'" + key + "' should not be present in JSON " + json, element);
    }

    private static JsonElement find(String json, String key) {
        JsonElement element = new JsonParser().parse(json);
        for (String part : key.split("\\.")) {
            if (element == null) {
                return null;
            }
            element = element.getAsJsonObject().get(part);
        }
        return element;
    }
}
