Newer
Older
dhl-api / src / test / java / io / ljunggren / dhl / api / service / TrackingServiceTest.java
package io.ljunggren.dhl.api.service;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertThrows;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.nio.charset.StandardCharsets;

import org.apache.http.HttpEntity;
import org.apache.http.StatusLine;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.junit.Test;

import io.ljunggren.dhl.api.model.tracking.response.TrackingResponse;

public class TrackingServiceTest {

    private static final String SUCCESS_JSON = "{\"shipments\":[{\"id\":\"123\"}]}";
    private static final String ERROR_429_JSON = "{\"title\":\"Too Many Requests\",\"status\":429,\"detail\":\"slow down\"}";
    private static final String ERROR_400_JSON = "{\"title\":\"Bad Request\",\"status\":400,\"detail\":\"invalid tracking number\"}";

    private static class NoSleepTrackingService extends TrackingService {
        NoSleepTrackingService(String domain, String apiKey) {
            super(domain, apiKey);
        }

        @Override
        protected void sleep(long millis) throws IOException {
            // no-op so retry tests don't actually wait
        }
    }

    private CloseableHttpResponse mockHttpResponse(int statusCode, String body) throws IOException {
        CloseableHttpResponse httpResponse = mock(CloseableHttpResponse.class);
        StatusLine statusLine = mock(StatusLine.class);
        when(statusLine.getStatusCode()).thenReturn(statusCode);
        when(httpResponse.getStatusLine()).thenReturn(statusLine);
        HttpEntity entity = mock(HttpEntity.class);
        when(entity.getContent()).thenReturn(new ByteArrayInputStream(body.getBytes(StandardCharsets.UTF_8)));
        when(httpResponse.getEntity()).thenReturn(entity);
        return httpResponse;
    }

    @Test
    public void trackReturnsParsedResponseOnSuccess() throws Exception {
        TrackingService service = new NoSleepTrackingService("https://api-test.dhl.com", "key");
        CloseableHttpClient httpClient = mock(CloseableHttpClient.class);
        CloseableHttpResponse httpResponse = mockHttpResponse(200, SUCCESS_JSON);
        when(httpClient.execute(any(HttpGet.class))).thenReturn(httpResponse);

        TrackingResponse trackingResponse = service.track(httpClient, new String[] {"123"}, true);

        assertNotNull(trackingResponse);
        assertNull(trackingResponse.getError());
        assertEquals(1, trackingResponse.getShipments().size());
        assertEquals("123", trackingResponse.getShipments().get(0).getId());
    }

    @Test
    public void trackReturnsErrorResponseForNonRetryableStatus() throws Exception {
        TrackingService service = new NoSleepTrackingService("https://api-test.dhl.com", "key");
        CloseableHttpClient httpClient = mock(CloseableHttpClient.class);
        CloseableHttpResponse httpResponse = mockHttpResponse(400, ERROR_400_JSON);
        when(httpClient.execute(any(HttpGet.class))).thenReturn(httpResponse);

        TrackingResponse trackingResponse = service.track(httpClient, new String[] {"123"}, true);

        assertNotNull(trackingResponse);
        assertNotNull(trackingResponse.getError());
        assertEquals(400, trackingResponse.getError().getStatus());
    }

    @Test
    public void trackRetriesOnceOn429ThenGivesUp() throws Exception {
        TrackingService service = new NoSleepTrackingService("https://api-test.dhl.com", "key");
        CloseableHttpClient httpClient = mock(CloseableHttpClient.class);
        CloseableHttpResponse firstAttempt = mockHttpResponse(429, ERROR_429_JSON);
        CloseableHttpResponse secondAttempt = mockHttpResponse(429, ERROR_429_JSON);
        when(httpClient.execute(any(HttpGet.class))).thenReturn(firstAttempt).thenReturn(secondAttempt);

        TrackingResponse trackingResponse = service.track(httpClient, new String[] {"123"}, true);

        assertNotNull(trackingResponse);
        assertNotNull(trackingResponse.getError());
        assertEquals(429, trackingResponse.getError().getStatus());
        verify(httpClient, times(2)).execute(any(HttpGet.class));
    }

    @Test
    public void trackReturnsUnknownErrorWhenBodyIsNotAJsonError() throws Exception {
        TrackingService service = new NoSleepTrackingService("https://api-test.dhl.com", "key");
        CloseableHttpClient httpClient = mock(CloseableHttpClient.class);
        CloseableHttpResponse httpResponse = mockHttpResponse(503, "<html>Service Unavailable</html>");
        when(httpClient.execute(any(HttpGet.class))).thenReturn(httpResponse);

        TrackingResponse trackingResponse = service.track(httpClient, new String[] {"123"}, true);

        assertNotNull(trackingResponse);
        assertNotNull(trackingResponse.getError());
        assertEquals(503, trackingResponse.getError().getStatus());
    }

    @Test
    public void parseThrowsIOExceptionForInvalidJson() {
        TrackingService service = new TrackingService("https://api-test.dhl.com", "key");
        assertThrows(IOException.class, () -> service.parse("not-json", TrackingResponse.class));
    }

}