Newer
Older
sendgrid-api / src / test / java / io / ljunggren / sendgrid / api / service / UsageServiceTest.java
package io.ljunggren.sendgrid.api.service;

import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertSame;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;

import java.io.IOException;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.List;

import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.mockito.ArgumentCaptor;

import com.sendgrid.Request;
import com.sendgrid.Response;
import com.sendgrid.SendGrid;

import io.ljunggren.sendgrid.api.exception.SendgridException;
import io.ljunggren.sendgrid.api.model.Statistics;

class UsageServiceTest {

	private static final String STATS_BODY = "[ {\"date\": \"2025-10-19\", \"stats\": [ {\"metrics\": {\"delivered\": 1}} ] } ]";

	private SendGrid sendGrid;
	private UsageService service;

	@BeforeEach
	void setUp() {
		sendGrid = org.mockito.Mockito.mock(SendGrid.class);
		service = new UsageService(sendGrid);
	}

	@Test
	void publicConstructor_rejectsBlankApiKey() {
		assertThrows(IllegalArgumentException.class, () -> new UsageService(""));
	}

	private Response okResponse() {
		Response r = new Response();
		r.setStatusCode(200);
		r.setBody(STATS_BODY);
		return r;
	}

	@Test
	void getDailyUsage_returnsParsedStatistics() throws Exception {
		when(sendGrid.api(any(Request.class))).thenReturn(okResponse());

		List<Statistics> result = service.getDailyUsage();
		assertNotNull(result);
		assertEquals(1, result.size());
		assertEquals(LocalDate.of(2025, 10, 19), result.get(0).getDate());

		ArgumentCaptor<Request> captor = ArgumentCaptor.forClass(Request.class);
		verify(sendGrid, times(1)).api(captor.capture());
		Request req = captor.getValue();
		assertEquals("stats", req.getEndpoint());
		String today = LocalDate.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd"));
		// daily usage uses today as both start and end (days=0)
		assertEquals(today, req.getQueryParams().get("start_date"));
		assertEquals(today, req.getQueryParams().get("end_date"));
		assertEquals("day", req.getQueryParams().get("aggregated_by"));
	}

	@Test
	void getMonthlyStatistics_usesFirstOfMonthAsStart() throws Exception {
		when(sendGrid.api(any(Request.class))).thenReturn(okResponse());

		service.getMonthlyStatistics();

		ArgumentCaptor<Request> captor = ArgumentCaptor.forClass(Request.class);
		verify(sendGrid, times(1)).api(captor.capture());
		Request req = captor.getValue();
		LocalDate today = LocalDate.now();
		String firstOfMonth = today.withDayOfMonth(1).format(DateTimeFormatter.ofPattern("yyyy-MM-dd"));
		assertEquals(firstOfMonth, req.getQueryParams().get("start_date"));
		assertEquals(today.format(DateTimeFormatter.ofPattern("yyyy-MM-dd")),
				req.getQueryParams().get("end_date"));
	}

	@Test
	void getStatistics_negativeDays_throws() {
		assertThrows(IllegalArgumentException.class, () -> service.getStatistics(-1));
	}

	@Test
	void getStatistics_nullAggregation_throws() {
		assertThrows(IllegalArgumentException.class, () -> service.getStatistics(7, null));
	}

	@Test
	void getStatistics_passesAggregationValueAsQueryParam() throws Exception {
		when(sendGrid.api(any(Request.class))).thenReturn(okResponse());

		service.getStatistics(7, Aggregation.WEEK);

		ArgumentCaptor<Request> captor = ArgumentCaptor.forClass(Request.class);
		verify(sendGrid, times(1)).api(captor.capture());
		assertEquals("week", captor.getValue().getQueryParams().get("aggregated_by"));
	}

	@Test
	void getStatistics_ioExceptionFromClient_isWrapped() throws Exception {
		IOException ioe = new IOException("boom");
		when(sendGrid.api(any(Request.class))).thenThrow(ioe);

		SendgridException ex = assertThrows(SendgridException.class, () -> service.getDailyUsage());
		assertSame(ioe, ex.getCause());
	}

	@Test
	void getStatistics_non2xxResponse_throws() throws Exception {
		Response r = new Response();
		r.setStatusCode(401);
		r.setBody("unauthorized");
		when(sendGrid.api(any(Request.class))).thenReturn(r);

		SendgridException ex = assertThrows(SendgridException.class, () -> service.getDailyUsage());
		assertTrue(ex.getMessage().contains("401"));
		assertTrue(ex.getMessage().contains("unauthorized"));
	}

	@Test
	void getStatistics_invalidJson_throwsWithCause() throws Exception {
		Response r = new Response();
		r.setStatusCode(200);
		r.setBody("not json");
		when(sendGrid.api(any(Request.class))).thenReturn(r);

		SendgridException ex = assertThrows(SendgridException.class, () -> service.getDailyUsage());
		assertNotNull(ex.getCause());
	}

}