package io.ljunggren.fedex.api.authorization;

import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;

import java.io.IOException;

import org.apache.commons.io.IOUtils;
import org.junit.Test;

import io.ljunggren.json.utils.JsonUtils;

public class OauthResponseTest {

    private String readFromResources(String file) throws IOException {
        return IOUtils.toString(this.getClass().getResourceAsStream(file), "UTF-8");
    }

    @Test
    public void deserializeTest() throws IOException {
        String json = readFromResources("/oauthResponse.json");
        AuthToken response = JsonUtils.jsonToObject(json, AuthToken.class);
        assertNotNull(response);
    }
    
    @Test
    public void serializeTest() throws IOException {
        String json = readFromResources("/oauthResponse.json");
        AuthToken response = JsonUtils.jsonToObject(json, AuthToken.class);
        String serializeResponse = JsonUtils.objectToJson(response);
        assertTrue(JsonUtils.areEqual(json, serializeResponse));
    }

    @Test
    public void deserializeWithErrorTest() throws IOException {
        // The error payload doesn't carry access_token/token_type/expires_in/scope, so
        // parsing it as an AuthToken (which is what OauthService does for every response,
        // success or failure) yields an object with every field null.
        String json = readFromResources("/oauthErrorResponse.json");
        AuthToken response = JsonUtils.jsonToObject(json, AuthToken.class);
        assertNotNull(response);
        assertNull(response.getAccessToken());
        assertNull(response.getTokenType());
        assertNull(response.getExpiresIn());
        assertNull(response.getScope());
    }
    
}
