diff --git a/README.md b/README.md index 837bf7f..ac13b1b 100644 --- a/README.md +++ b/README.md @@ -1,23 +1,122 @@ -## Sendgrid API - -https://www.twilio.com/docs/sendgrid - -Instantiate - -```java -SendgridApi api = new SendgridApi(apiKey); -``` - -Send Email - -```java -api.sendEmail(from, to, subject, body); -``` - -Send Template Email - -```java -api.sendTemplateEmail(templateId, from, to, templateData); -``` - -**Note**: Template Data is a HashMap that maps to email {{ variable }} +## Sendgrid API + +A small, opinionated Java client for a subset of the +[SendGrid v3 REST API](https://www.twilio.com/docs/sendgrid). It +wraps the official `sendgrid-java` SDK behind an easy-to-use facade +for two common use cases: + +- Sending plain-text and dynamic-template emails +- Pulling email-sending statistics from the `/stats` endpoint + +### Requirements + +- Java 17+ +- Maven 3.9+ + +### Installation + +The library is published as a Maven artifact: + +```xml + + io.ljunggren + sendgrid-api + 0.0.1-SNAPSHOT + +``` + +### Usage + +#### Instantiate + +```java +SendgridApi api = new SendgridApi(apiKey); +``` + +The API key must be non-null and non-blank; otherwise the +constructor throws `IllegalArgumentException`. + +#### Send a plain-text email + +```java +api.sendEmail(from, to, subject, body); +``` + +#### Send a dynamic-template email + +```java +api.sendTemplateEmail(templateId, from, to, templateData); +``` + +`templateData` is a `Map` whose keys map to +`{{ variable }}` placeholders in the SendGrid template. It may be +null or empty. + +#### Fetch usage statistics + +```java +// Today only. +List today = api.getDailyUsage(); + +// Day-by-day stats for the current calendar month so far. +List monthToDate = api.getMonthlyStatistics(); + +// Day-by-day stats for the last N days (inclusive of today). +List lastWeek = api.getStatistics(7); + +// Stats aggregated by week or month. +List byWeek = api.getStatistics(28, Aggregation.WEEK); +List byMonth = api.getStatistics(90, Aggregation.MONTH); +``` + +### Error handling + +All operations throw `SendgridException`, a checked exception, when +the underlying SendGrid call fails. The exception always preserves +the original cause when one exists, so wrapping IO or parse errors +do not lose the stack trace. + +| Failure mode | Behavior | +|------------------------------------|-----------------------------------------------------------| +| Network / IO error | `SendgridException` with the `IOException` as cause | +| Email send returns non-202 | `SendgridException` whose message includes status + body | +| Stats endpoint returns non-2xx | `SendgridException` whose message includes status + body | +| Stats response cannot be parsed | `SendgridException` with the parse error as cause | +| Null/blank required argument | `IllegalArgumentException` | + +### Building + +```bash +mvn clean install +``` + +### Running tests + +```bash +mvn test +``` + +The project ships with a JUnit 5 test suite covering the public +facade, both services, the model classes, and the exception types. +Mockito is used to stub the underlying `SendGrid` client so tests +run fully offline. + +### Project layout + +``` +src/main/java/io/ljunggren/sendgrid/api/ + SendgridApi.java -- public facade + exception/SendgridException -- checked exception + model/ -- Jackson-bound DTOs (Statistics, Stat, Metrics) + service/ -- EmailService, UsageService, BaseService, Aggregation +src/test/java/ -- JUnit 5 + Mockito tests +``` + +### Notes + +- `Statistics.date` is exposed as `java.time.LocalDate`. The + service registers the `JavaTimeModule` so deserialization works + out of the box. +- The package-private constructors on `SendgridApi`, `EmailService`, + and `UsageService` exist purely to enable mocking in tests; the + public API surface still takes only an API key. diff --git a/pom.xml b/pom.xml index d0f1001..ab1dfb7 100644 --- a/pom.xml +++ b/pom.xml @@ -14,6 +14,8 @@ UTF-8 17 + 2.14.0 + 5.14.2 @@ -40,6 +42,16 @@ 0.0.1-SNAPSHOT + com.fasterxml.jackson.core + jackson-annotations + ${jackson.version} + + + com.fasterxml.jackson.datatype + jackson-datatype-jsr310 + ${jackson.version} + + commons-io commons-io 2.20.0 @@ -60,6 +72,33 @@ junit-jupiter-api test + + org.mockito + mockito-core + ${mockito.version} + test + + + org.mockito + mockito-junit-jupiter + ${mockito.version} + test + + + + + org.apache.maven.plugins + maven-compiler-plugin + 3.13.0 + + + org.apache.maven.plugins + maven-surefire-plugin + 3.5.0 + + + + diff --git a/src/main/java/io/ljunggren/sendgrid/api/SendgridApi.java b/src/main/java/io/ljunggren/sendgrid/api/SendgridApi.java index ace25ed..204b8fb 100644 --- a/src/main/java/io/ljunggren/sendgrid/api/SendgridApi.java +++ b/src/main/java/io/ljunggren/sendgrid/api/SendgridApi.java @@ -5,37 +5,110 @@ import io.ljunggren.sendgrid.api.exception.SendgridException; import io.ljunggren.sendgrid.api.model.Statistics; +import io.ljunggren.sendgrid.api.service.Aggregation; import io.ljunggren.sendgrid.api.service.EmailService; import io.ljunggren.sendgrid.api.service.UsageService; +/** + * Public facade for the SendGrid REST API. Wraps the email + * sending and usage statistics services so callers only need a + * single API key and a single object. + * + *

Example: + *

{@code
+ * SendgridApi api = new SendgridApi(apiKey);
+ * api.sendEmail(from, to, subject, body);
+ * }
+ */ public class SendgridApi { - - private EmailService emailService; - private UsageService usageService; - + + private final EmailService emailService; + private final UsageService usageService; + + /** + * Create a new {@code SendgridApi} using the given API key. + * + * @param apiKey the SendGrid API key + * @throws IllegalArgumentException if {@code apiKey} is null or blank + */ public SendgridApi(String apiKey) { - this.emailService = new EmailService(apiKey); - this.usageService = new UsageService(apiKey); + this(new EmailService(apiKey), new UsageService(apiKey)); } - + + /** + * Package-private constructor primarily used by tests to + * inject mock services. + * + * @param emailService email service + * @param usageService usage service + */ + SendgridApi(EmailService emailService, UsageService usageService) { + if (emailService == null || usageService == null) { + throw new IllegalArgumentException("emailService and usageService must not be null"); + } + this.emailService = emailService; + this.usageService = usageService; + } + + /** + * Send a plain-text email. + * + * @param from sender address + * @param to recipient address + * @param subject email subject + * @param body plain-text body + * @throws SendgridException if the email cannot be sent + */ public void sendEmail(String from, String to, String subject, String body) throws SendgridException { emailService.sendEmail(from, to, subject, body); } - + + /** + * Send a SendGrid template email. + * + * @param templateId SendGrid template id + * @param from sender address + * @param to recipient address + * @param templateData substitution variables + * @throws SendgridException if the email cannot be sent + */ public void sendTemplateEmail(String templateId, String from, String to, Map templateData) throws SendgridException { emailService.sendTemplateEmail(templateId, from, to, templateData); } - + + /** + * @return statistics for today only + * @throws SendgridException on error + */ public List getDailyUsage() throws SendgridException { return usageService.getDailyUsage(); } - + + /** + * @return daily statistics for the current calendar month so far + * @throws SendgridException on error + */ public List getMonthlyStatistics() throws SendgridException { return usageService.getMonthlyStatistics(); } - + + /** + * @param days number of days of history (inclusive of today) + * @return daily statistics for the last {@code days} days + * @throws SendgridException on error + */ public List getStatistics(int days) throws SendgridException { return usageService.getStatistics(days); } + /** + * @param days number of days of history (inclusive of today) + * @param aggregation aggregation granularity + * @return statistics for the last {@code days} days, aggregated as requested + * @throws SendgridException on error + */ + public List getStatistics(int days, Aggregation aggregation) throws SendgridException { + return usageService.getStatistics(days, aggregation); + } + } diff --git a/src/main/java/io/ljunggren/sendgrid/api/exception/SendgridException.java b/src/main/java/io/ljunggren/sendgrid/api/exception/SendgridException.java index bc306d6..d08a50b 100644 --- a/src/main/java/io/ljunggren/sendgrid/api/exception/SendgridException.java +++ b/src/main/java/io/ljunggren/sendgrid/api/exception/SendgridException.java @@ -1,15 +1,41 @@ package io.ljunggren.sendgrid.api.exception; +/** + * Checked exception thrown by the SendGrid API client to wrap + * any error originating from the SendGrid service or the + * underlying HTTP/IO layer. + */ public class SendgridException extends Exception { private static final long serialVersionUID = -2630051469419822905L; - + + /** + * Create a new exception with a descriptive message. + * + * @param message human readable description of the failure + */ public SendgridException(String message) { super(message); } - - public SendgridException(Exception e) { - super(e); + + /** + * Create a new exception that wraps an underlying cause. + * + * @param cause the original exception that triggered this failure + */ + public SendgridException(Throwable cause) { + super(cause); + } + + /** + * Create a new exception with a descriptive message and an + * underlying cause. + * + * @param message human readable description of the failure + * @param cause the original exception that triggered this failure + */ + public SendgridException(String message, Throwable cause) { + super(message, cause); } } diff --git a/src/main/java/io/ljunggren/sendgrid/api/model/Metrics.java b/src/main/java/io/ljunggren/sendgrid/api/model/Metrics.java index 34c72a9..1ad26be 100644 --- a/src/main/java/io/ljunggren/sendgrid/api/model/Metrics.java +++ b/src/main/java/io/ljunggren/sendgrid/api/model/Metrics.java @@ -7,11 +7,15 @@ import lombok.Data; +/** + * Email-sending counters returned by SendGrid for a single + * day or aggregated period. + */ @Data @JsonInclude(Include.NON_NULL) @JsonIgnoreProperties(ignoreUnknown = true) public class Metrics { - + private int blocks; @JsonProperty("bounce_drops") private int bounceDrops; @@ -35,5 +39,5 @@ @JsonProperty("unsubscribe_drops") private int unsubscribeDrops; private int unsubscribes; - + } diff --git a/src/main/java/io/ljunggren/sendgrid/api/model/Stat.java b/src/main/java/io/ljunggren/sendgrid/api/model/Stat.java index 5e267c5..9932b8d 100644 --- a/src/main/java/io/ljunggren/sendgrid/api/model/Stat.java +++ b/src/main/java/io/ljunggren/sendgrid/api/model/Stat.java @@ -6,11 +6,15 @@ import lombok.Data; +/** + * Wrapper around a {@link Metrics} block as returned by the + * SendGrid {@code /stats} endpoint. + */ @Data @JsonInclude(Include.NON_NULL) @JsonIgnoreProperties(ignoreUnknown = true) public class Stat { private Metrics metrics; - + } diff --git a/src/main/java/io/ljunggren/sendgrid/api/model/Statistics.java b/src/main/java/io/ljunggren/sendgrid/api/model/Statistics.java index 1b38a7b..d7f720f 100644 --- a/src/main/java/io/ljunggren/sendgrid/api/model/Statistics.java +++ b/src/main/java/io/ljunggren/sendgrid/api/model/Statistics.java @@ -1,6 +1,6 @@ package io.ljunggren.sendgrid.api.model; -import java.util.Date; +import java.time.LocalDate; import java.util.List; import com.fasterxml.jackson.annotation.JsonFormat; @@ -10,13 +10,17 @@ import lombok.Data; +/** + * One day's worth of SendGrid statistics, deserialized from + * the {@code /stats} endpoint. + */ @Data @JsonInclude(Include.NON_NULL) @JsonIgnoreProperties(ignoreUnknown = true) public class Statistics { - - @JsonFormat(shape=JsonFormat.Shape.STRING, pattern="yyyy-MM-dd") - private Date date; + + @JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "yyyy-MM-dd") + private LocalDate date; private List stats; -} \ No newline at end of file +} diff --git a/src/main/java/io/ljunggren/sendgrid/api/service/Aggregation.java b/src/main/java/io/ljunggren/sendgrid/api/service/Aggregation.java new file mode 100755 index 0000000..9ba74c0 --- /dev/null +++ b/src/main/java/io/ljunggren/sendgrid/api/service/Aggregation.java @@ -0,0 +1,27 @@ +package io.ljunggren.sendgrid.api.service; + +/** + * Aggregation granularity for SendGrid statistics queries. + * + *

Maps to the {@code aggregated_by} query parameter on the + * SendGrid {@code /stats} endpoint.

+ */ +public enum Aggregation { + + DAY("day"), + WEEK("week"), + MONTH("month"); + + private final String value; + + Aggregation(String value) { + this.value = value; + } + + /** + * @return the value expected by the SendGrid REST API + */ + public String getValue() { + return value; + } +} diff --git a/src/main/java/io/ljunggren/sendgrid/api/service/BaseService.java b/src/main/java/io/ljunggren/sendgrid/api/service/BaseService.java index b9522eb..daa1335 100644 --- a/src/main/java/io/ljunggren/sendgrid/api/service/BaseService.java +++ b/src/main/java/io/ljunggren/sendgrid/api/service/BaseService.java @@ -2,12 +2,38 @@ import com.sendgrid.SendGrid; +/** + * Base class shared by SendGrid service classes. It owns the + * underlying {@link SendGrid} client and validates the API key. + */ public class BaseService { - protected SendGrid sendGrid; - - protected BaseService(String apiKey) { - this.sendGrid = new SendGrid(apiKey); - } + protected SendGrid sendGrid; + + /** + * Create a new service backed by a real SendGrid client. + * + * @param apiKey the SendGrid API key. Must be non-null and non-blank. + * @throws IllegalArgumentException if {@code apiKey} is null or blank + */ + protected BaseService(String apiKey) { + if (apiKey == null || apiKey.isBlank()) { + throw new IllegalArgumentException("apiKey must not be null or blank"); + } + this.sendGrid = new SendGrid(apiKey); + } + + /** + * Package-private constructor used by tests to inject a mock + * {@link SendGrid} client without contacting the real service. + * + * @param sendGrid pre-built (potentially mocked) SendGrid client + */ + BaseService(SendGrid sendGrid) { + if (sendGrid == null) { + throw new IllegalArgumentException("sendGrid must not be null"); + } + this.sendGrid = sendGrid; + } } diff --git a/src/main/java/io/ljunggren/sendgrid/api/service/EmailService.java b/src/main/java/io/ljunggren/sendgrid/api/service/EmailService.java index 9a4c466..ed3234e 100644 --- a/src/main/java/io/ljunggren/sendgrid/api/service/EmailService.java +++ b/src/main/java/io/ljunggren/sendgrid/api/service/EmailService.java @@ -1,11 +1,13 @@ package io.ljunggren.sendgrid.api.service; import java.io.IOException; +import java.net.HttpURLConnection; import java.util.Map; import com.sendgrid.Method; import com.sendgrid.Request; import com.sendgrid.Response; +import com.sendgrid.SendGrid; import com.sendgrid.helpers.mail.Mail; import com.sendgrid.helpers.mail.objects.Content; import com.sendgrid.helpers.mail.objects.Email; @@ -13,46 +15,100 @@ import io.ljunggren.sendgrid.api.exception.SendgridException; +/** + * Service that sends emails via the SendGrid v3 mail/send endpoint. + */ public class EmailService extends BaseService { + private static final String MAIL_SEND_ENDPOINT = "mail/send"; + private static final String DEFAULT_CONTENT_TYPE = "text/plain"; + + /** + * Create a new {@code EmailService} backed by a real SendGrid client. + * + * @param apiKey the SendGrid API key + * @throws IllegalArgumentException if {@code apiKey} is null or blank + */ public EmailService(String apiKey) { super(apiKey); } + /** + * Test-only constructor that accepts a pre-built (possibly mocked) client. + * + * @param sendGrid the SendGrid client to use + */ + EmailService(SendGrid sendGrid) { + super(sendGrid); + } + + /** + * Send a simple plain-text email. + * + * @param from sender address (must not be null or blank) + * @param to recipient address (must not be null or blank) + * @param subject email subject + * @param body plain-text body + * @throws SendgridException if the email cannot be sent + */ public void sendEmail(String from, String to, String subject, String body) throws SendgridException { + requireNonBlank(from, "from"); + requireNonBlank(to, "to"); Mail mail = new Mail( - new Email(from), - subject, - new Email(to), - new Content("text/plain", body)); + new Email(from), + subject, + new Email(to), + new Content(DEFAULT_CONTENT_TYPE, body)); sendEmail(mail); } - + + /** + * Send a templated email using SendGrid dynamic templates. + * + * @param templateId SendGrid template id (must not be null or blank) + * @param from sender address (must not be null or blank) + * @param to recipient address (must not be null or blank) + * @param templateData substitution variables; may be null or empty + * @throws SendgridException if the email cannot be sent + */ public void sendTemplateEmail(String templateId, String from, String to, Map templateData) throws SendgridException { + requireNonBlank(templateId, "templateId"); + requireNonBlank(from, "from"); + requireNonBlank(to, "to"); Mail mail = new Mail(); mail.setTemplateId(templateId); mail.setFrom(new Email(from)); Personalization personalization = new Personalization(); personalization.addTo(new Email(to)); - templateData.entrySet().stream().forEach(entry -> personalization.addDynamicTemplateData(entry.getKey(), entry.getValue())); + if (templateData != null) { + templateData.forEach(personalization::addDynamicTemplateData); + } mail.addPersonalization(personalization); sendEmail(mail); } - + private void sendEmail(Mail mail) throws SendgridException { try { Request request = new Request(); request.setMethod(Method.POST); - request.setEndpoint("mail/send"); + request.setEndpoint(MAIL_SEND_ENDPOINT); request.setBody(mail.build()); Response response = sendGrid.api(request); - if (response.getStatusCode() == 202) { + if (response.getStatusCode() == HttpURLConnection.HTTP_ACCEPTED) { return; } - throw new SendgridException("Error sending email: " + response.getBody()); + throw new SendgridException( + "Error sending email. status=" + response.getStatusCode() + + ", body=" + response.getBody()); } catch (IOException e) { - throw new SendgridException(e.getMessage()); + throw new SendgridException("Failed to send email", e); } } - + + private static void requireNonBlank(String value, String name) { + if (value == null || value.isBlank()) { + throw new IllegalArgumentException(name + " must not be null or blank"); + } + } + } diff --git a/src/main/java/io/ljunggren/sendgrid/api/service/UsageService.java b/src/main/java/io/ljunggren/sendgrid/api/service/UsageService.java index 9bd38bd..0ef4d26 100644 --- a/src/main/java/io/ljunggren/sendgrid/api/service/UsageService.java +++ b/src/main/java/io/ljunggren/sendgrid/api/service/UsageService.java @@ -1,63 +1,137 @@ package io.ljunggren.sendgrid.api.service; +import java.io.IOException; +import java.net.HttpURLConnection; import java.time.LocalDate; import java.time.format.DateTimeFormatter; +import java.util.Collections; import java.util.List; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule; import com.sendgrid.Method; import com.sendgrid.Request; import com.sendgrid.Response; +import com.sendgrid.SendGrid; import io.ljunggren.json.utils.JsonUtils; import io.ljunggren.sendgrid.api.exception.SendgridException; import io.ljunggren.sendgrid.api.model.Statistics; +/** + * Service that retrieves email-sending statistics from the + * SendGrid {@code /stats} endpoint. + */ public class UsageService extends BaseService { + private static final String STATS_ENDPOINT = "stats"; + private static final DateTimeFormatter DATE_FORMATTER = DateTimeFormatter.ofPattern("yyyy-MM-dd"); + private static final ObjectMapper OBJECT_MAPPER = new ObjectMapper().registerModule(new JavaTimeModule()); + + /** + * Create a new {@code UsageService} backed by a real SendGrid client. + * + * @param apiKey the SendGrid API key + * @throws IllegalArgumentException if {@code apiKey} is null or blank + */ public UsageService(String apiKey) { super(apiKey); } - public List getDailyUsage() throws SendgridException { - List statisticses = getStatistics(0); - if (statisticses == null) { - throw new SendgridException("Could not fetch SendGrid statistics"); - } - return statisticses; + /** + * Test-only constructor that accepts a pre-built (possibly mocked) client. + * + * @param sendGrid the SendGrid client to use + */ + UsageService(SendGrid sendGrid) { + super(sendGrid); } - + + /** + * Returns statistics for today only. + * + * @return a non-null list of {@link Statistics} (one entry for today) + * @throws SendgridException if the call fails + */ + public List getDailyUsage() throws SendgridException { + return getStatistics(0); + } + + /** + * Returns statistics for the current calendar month so far, + * day-by-day, from the first of the month through today. + * + * @return a non-null list of {@link Statistics} + * @throws SendgridException if the call fails + */ public List getMonthlyStatistics() throws SendgridException { int dayOfMonth = LocalDate.now().getDayOfMonth(); - List statisticses = getStatistics(dayOfMonth - 1); - if (statisticses == null) { - throw new SendgridException("Could not fetch SendGrid statistics"); - } - return statisticses; + return getStatistics(dayOfMonth - 1); } - + + /** + * Returns daily statistics for the last {@code days} days through today. + * + * @param days how many days back from today (inclusive of today) + * @return a non-null list of {@link Statistics} + * @throws SendgridException if the call fails + * @throws IllegalArgumentException if {@code days} is negative + */ public List getStatistics(int days) throws SendgridException { - LocalDate endDate = LocalDate.now(); - LocalDate startDate = endDate.minusDays(days); - DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd"); - return getStatistics("day", - startDate.format(formatter), - endDate.format(formatter) - ); + return getStatistics(days, Aggregation.DAY); } - + + /** + * Returns statistics for the last {@code days} days, aggregated by + * the given granularity. + * + * @param days how many days back from today (inclusive of today) + * @param aggregation aggregation granularity + * @return a non-null list of {@link Statistics} + * @throws SendgridException if the call fails + * @throws IllegalArgumentException if {@code days} is negative or {@code aggregation} is null + */ + public List getStatistics(int days, Aggregation aggregation) throws SendgridException { + if (days < 0) { + throw new IllegalArgumentException("days must not be negative"); + } + if (aggregation == null) { + throw new IllegalArgumentException("aggregation must not be null"); + } + LocalDate endDate = LocalDate.now(); + LocalDate startDate = endDate.minusDays(days); + return getStatistics(aggregation.getValue(), + startDate.format(DATE_FORMATTER), + endDate.format(DATE_FORMATTER)); + } + private List getStatistics(String aggregate, String startDate, String endDate) throws SendgridException { - Request request = new Request(); - request.setMethod(Method.GET); - request.setEndpoint("stats"); - request.addQueryParam("aggregated_by", aggregate); - request.addQueryParam("start_date", startDate); - request.addQueryParam("end_date", endDate); - try { - Response response = sendGrid.api(request); - return JsonUtils.jsonToList(response.getBody(), Statistics.class); - } catch (Exception e) { - throw new SendgridException(e); - } + Request request = new Request(); + request.setMethod(Method.GET); + request.setEndpoint(STATS_ENDPOINT); + request.addQueryParam("aggregated_by", aggregate); + request.addQueryParam("start_date", startDate); + request.addQueryParam("end_date", endDate); + Response response; + try { + response = sendGrid.api(request); + } catch (IOException e) { + throw new SendgridException("Failed to call SendGrid stats endpoint", e); + } + if (response == null) { + throw new SendgridException("SendGrid stats endpoint returned no response"); + } + if (response.getStatusCode() < HttpURLConnection.HTTP_OK + || response.getStatusCode() >= HttpURLConnection.HTTP_MULT_CHOICE) { + throw new SendgridException("SendGrid stats endpoint returned status=" + + response.getStatusCode() + ", body=" + response.getBody()); + } + try { + List statistics = JsonUtils.jsonToList(response.getBody(), Statistics.class, OBJECT_MAPPER); + return statistics == null ? Collections.emptyList() : statistics; + } catch (Exception e) { + throw new SendgridException("Failed to parse SendGrid stats response", e); + } } - + } diff --git a/src/test/java/io/ljunggren/sendgrid/api/SendgridApiTest.java b/src/test/java/io/ljunggren/sendgrid/api/SendgridApiTest.java new file mode 100755 index 0000000..7104048 --- /dev/null +++ b/src/test/java/io/ljunggren/sendgrid/api/SendgridApiTest.java @@ -0,0 +1,105 @@ +package io.ljunggren.sendgrid.api; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertSame; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +import java.util.Collections; +import java.util.List; +import java.util.Map; + +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.mockito.Mock; +import org.mockito.junit.jupiter.MockitoExtension; + +import io.ljunggren.sendgrid.api.exception.SendgridException; +import io.ljunggren.sendgrid.api.model.Statistics; +import io.ljunggren.sendgrid.api.service.Aggregation; +import io.ljunggren.sendgrid.api.service.EmailService; +import io.ljunggren.sendgrid.api.service.UsageService; + +@ExtendWith(MockitoExtension.class) +class SendgridApiTest { + + @Mock + private EmailService emailService; + + @Mock + private UsageService usageService; + + private SendgridApi api; + + @BeforeEach + void setUp() { + api = new SendgridApi(emailService, usageService); + } + + @Test + void publicConstructor_rejectsNullApiKey() { + assertThrows(IllegalArgumentException.class, () -> new SendgridApi(null)); + } + + @Test + void publicConstructor_rejectsBlankApiKey() { + assertThrows(IllegalArgumentException.class, () -> new SendgridApi(" ")); + } + + @Test + void packageConstructor_rejectsNullEmailService() { + assertThrows(IllegalArgumentException.class, () -> new SendgridApi(null, usageService)); + } + + @Test + void packageConstructor_rejectsNullUsageService() { + assertThrows(IllegalArgumentException.class, () -> new SendgridApi(emailService, null)); + } + + @Test + void sendEmail_delegatesToEmailService() throws SendgridException { + api.sendEmail("a@b.com", "c@d.com", "hi", "body"); + verify(emailService, times(1)).sendEmail("a@b.com", "c@d.com", "hi", "body"); + verify(usageService, never()).getDailyUsage(); + } + + @Test + void sendTemplateEmail_delegatesToEmailService() throws SendgridException { + Map data = Map.of("k", "v"); + api.sendTemplateEmail("tpl", "a@b.com", "c@d.com", data); + verify(emailService, times(1)).sendTemplateEmail("tpl", "a@b.com", "c@d.com", data); + } + + @Test + void getDailyUsage_delegatesToUsageService() throws SendgridException { + List expected = Collections.singletonList(new Statistics()); + when(usageService.getDailyUsage()).thenReturn(expected); + assertSame(expected, api.getDailyUsage()); + } + + @Test + void getMonthlyStatistics_delegatesToUsageService() throws SendgridException { + List expected = Collections.singletonList(new Statistics()); + when(usageService.getMonthlyStatistics()).thenReturn(expected); + assertSame(expected, api.getMonthlyStatistics()); + } + + @Test + void getStatisticsWithDays_delegatesToUsageService() throws SendgridException { + List expected = Collections.emptyList(); + when(usageService.getStatistics(7)).thenReturn(expected); + assertEquals(expected, api.getStatistics(7)); + } + + @Test + void getStatisticsWithAggregation_delegatesToUsageService() throws SendgridException { + List expected = Collections.emptyList(); + when(usageService.getStatistics(7, Aggregation.WEEK)).thenReturn(expected); + assertEquals(expected, api.getStatistics(7, Aggregation.WEEK)); + } + +} diff --git a/src/test/java/io/ljunggren/sendgrid/api/exception/SendgridExceptionTest.java b/src/test/java/io/ljunggren/sendgrid/api/exception/SendgridExceptionTest.java new file mode 100755 index 0000000..ba8d311 --- /dev/null +++ b/src/test/java/io/ljunggren/sendgrid/api/exception/SendgridExceptionTest.java @@ -0,0 +1,33 @@ +package io.ljunggren.sendgrid.api.exception; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertSame; + +import org.junit.jupiter.api.Test; + +class SendgridExceptionTest { + + @Test + void messageOnlyConstructor_setsMessage() { + SendgridException ex = new SendgridException("boom"); + assertEquals("boom", ex.getMessage()); + assertNull(ex.getCause()); + } + + @Test + void causeOnlyConstructor_setsCause() { + Throwable cause = new IllegalStateException("inner"); + SendgridException ex = new SendgridException(cause); + assertSame(cause, ex.getCause()); + } + + @Test + void messageAndCauseConstructor_setsBoth() { + Throwable cause = new RuntimeException("rt"); + SendgridException ex = new SendgridException("wrap", cause); + assertEquals("wrap", ex.getMessage()); + assertSame(cause, ex.getCause()); + } + +} diff --git a/src/test/java/io/ljunggren/sendgrid/api/model/MetricsTest.java b/src/test/java/io/ljunggren/sendgrid/api/model/MetricsTest.java new file mode 100755 index 0000000..fd468ea --- /dev/null +++ b/src/test/java/io/ljunggren/sendgrid/api/model/MetricsTest.java @@ -0,0 +1,60 @@ +package io.ljunggren.sendgrid.api.model; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotEquals; + +import org.junit.jupiter.api.Test; + +class MetricsTest { + + @Test + void settersAndGetters_round_trip() { + Metrics m = new Metrics(); + m.setBlocks(1); + m.setBounceDrops(2); + m.setBounces(3); + m.setClicks(4); + m.setDeferred(5); + m.setDelivered(6); + m.setInvalidEmails(7); + m.setOpens(8); + m.setProcessed(9); + m.setRequests(10); + m.setSpamReportDrops(11); + m.setSpamReports(12); + m.setUniqueClicks(13); + m.setUniqueOpens(14); + m.setUnsubscribeDrops(15); + m.setUnsubscribes(16); + + assertEquals(1, m.getBlocks()); + assertEquals(2, m.getBounceDrops()); + assertEquals(3, m.getBounces()); + assertEquals(4, m.getClicks()); + assertEquals(5, m.getDeferred()); + assertEquals(6, m.getDelivered()); + assertEquals(7, m.getInvalidEmails()); + assertEquals(8, m.getOpens()); + assertEquals(9, m.getProcessed()); + assertEquals(10, m.getRequests()); + assertEquals(11, m.getSpamReportDrops()); + assertEquals(12, m.getSpamReports()); + assertEquals(13, m.getUniqueClicks()); + assertEquals(14, m.getUniqueOpens()); + assertEquals(15, m.getUnsubscribeDrops()); + assertEquals(16, m.getUnsubscribes()); + } + + @Test + void equalsAndHashCode_basedOnAllFields() { + Metrics a = new Metrics(); + a.setDelivered(5); + Metrics b = new Metrics(); + b.setDelivered(5); + assertEquals(a, b); + assertEquals(a.hashCode(), b.hashCode()); + b.setDelivered(6); + assertNotEquals(a, b); + } + +} diff --git a/src/test/java/io/ljunggren/sendgrid/api/model/StatTest.java b/src/test/java/io/ljunggren/sendgrid/api/model/StatTest.java new file mode 100755 index 0000000..5ff6fef --- /dev/null +++ b/src/test/java/io/ljunggren/sendgrid/api/model/StatTest.java @@ -0,0 +1,25 @@ +package io.ljunggren.sendgrid.api.model; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNull; + +import org.junit.jupiter.api.Test; + +class StatTest { + + @Test + void defaultMetrics_isNull() { + Stat s = new Stat(); + assertNull(s.getMetrics()); + } + + @Test + void setMetrics_roundTrip() { + Stat s = new Stat(); + Metrics m = new Metrics(); + m.setDelivered(7); + s.setMetrics(m); + assertEquals(7, s.getMetrics().getDelivered()); + } + +} diff --git a/src/test/java/io/ljunggren/sendgrid/api/model/StatisticsTest.java b/src/test/java/io/ljunggren/sendgrid/api/model/StatisticsTest.java index f63d7e6..16737dd 100644 --- a/src/test/java/io/ljunggren/sendgrid/api/model/StatisticsTest.java +++ b/src/test/java/io/ljunggren/sendgrid/api/model/StatisticsTest.java @@ -1,26 +1,41 @@ package io.ljunggren.sendgrid.api.model; -import static org.junit.jupiter.api.Assertions.*; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; import java.io.IOException; +import java.io.InputStream; +import java.nio.charset.StandardCharsets; +import java.time.LocalDate; import java.util.List; import org.apache.commons.io.IOUtils; import org.junit.jupiter.api.Test; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule; + import io.ljunggren.json.utils.JsonUtils; class StatisticsTest { - private String readFromResources(String file) throws IOException { - return IOUtils.toString(this.getClass().getResourceAsStream(file), "UTF-8"); - } + private static final ObjectMapper MAPPER = new ObjectMapper().registerModule(new JavaTimeModule()); + + private String readFromResources(String file) throws IOException { + try (InputStream in = this.getClass().getResourceAsStream(file)) { + assertNotNull(in, "Test resource not found: " + file); + return IOUtils.toString(in, StandardCharsets.UTF_8); + } + } @Test void instantiateTest() throws IOException { String json = readFromResources("/io/ljunggren/sendgrid/api/model/stats.json"); - List statisticses = JsonUtils.jsonToList(json, Statistics.class); - assertEquals(2, statisticses.size()); + List statistics = JsonUtils.jsonToList(json, Statistics.class, MAPPER); + assertEquals(2, statistics.size()); + assertEquals(LocalDate.of(2025, 10, 18), statistics.get(0).getDate()); + assertEquals(LocalDate.of(2025, 10, 19), statistics.get(1).getDate()); + assertEquals(1, statistics.get(1).getStats().get(0).getMetrics().getDelivered()); } } diff --git a/src/test/java/io/ljunggren/sendgrid/api/service/AggregationTest.java b/src/test/java/io/ljunggren/sendgrid/api/service/AggregationTest.java new file mode 100755 index 0000000..77daa63 --- /dev/null +++ b/src/test/java/io/ljunggren/sendgrid/api/service/AggregationTest.java @@ -0,0 +1,26 @@ +package io.ljunggren.sendgrid.api.service; + +import static org.junit.jupiter.api.Assertions.assertEquals; + +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.CsvSource; + +class AggregationTest { + + @ParameterizedTest + @CsvSource({ + "DAY, day", + "WEEK, week", + "MONTH, month" + }) + void getValue_returnsExpectedString(Aggregation aggregation, String expected) { + assertEquals(expected, aggregation.getValue()); + } + + @org.junit.jupiter.api.Test + void valueOf_roundTrip() { + assertEquals(Aggregation.DAY, Aggregation.valueOf("DAY")); + assertEquals(3, Aggregation.values().length); + } + +} diff --git a/src/test/java/io/ljunggren/sendgrid/api/service/BaseServiceTest.java b/src/test/java/io/ljunggren/sendgrid/api/service/BaseServiceTest.java new file mode 100755 index 0000000..99cc9f3 --- /dev/null +++ b/src/test/java/io/ljunggren/sendgrid/api/service/BaseServiceTest.java @@ -0,0 +1,33 @@ +package io.ljunggren.sendgrid.api.service; + +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertThrows; + +import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.NullAndEmptySource; +import org.junit.jupiter.params.provider.ValueSource; + +class BaseServiceTest { + + /** Concrete subclass used purely so we can exercise the protected constructor. */ + private static class TestService extends BaseService { + TestService(String apiKey) { + super(apiKey); + } + } + + @ParameterizedTest + @NullAndEmptySource + @ValueSource(strings = { " ", "\t" }) + void apiKeyConstructor_rejectsNullOrBlank(String apiKey) { + assertThrows(IllegalArgumentException.class, () -> new TestService(apiKey)); + } + + @Test + void apiKeyConstructor_acceptsNonBlank() { + TestService service = new TestService("sg-key"); + assertNotNull(service.sendGrid); + } + +} diff --git a/src/test/java/io/ljunggren/sendgrid/api/service/EmailServiceTest.java b/src/test/java/io/ljunggren/sendgrid/api/service/EmailServiceTest.java new file mode 100755 index 0000000..f9823e7 --- /dev/null +++ b/src/test/java/io/ljunggren/sendgrid/api/service/EmailServiceTest.java @@ -0,0 +1,146 @@ +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.assertNull; +import static org.junit.jupiter.api.Assertions.assertSame; +import static org.junit.jupiter.api.Assertions.assertThrows; +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.util.HashMap; +import java.util.Map; + +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.NullAndEmptySource; +import org.junit.jupiter.params.provider.ValueSource; +import org.mockito.ArgumentCaptor; + +import com.sendgrid.Request; +import com.sendgrid.Response; +import com.sendgrid.SendGrid; + +import io.ljunggren.sendgrid.api.exception.SendgridException; + +class EmailServiceTest { + + private SendGrid sendGrid; + private EmailService service; + + @BeforeEach + void setUp() { + sendGrid = org.mockito.Mockito.mock(SendGrid.class); + service = new EmailService(sendGrid); + } + + @Test + void publicConstructor_rejectsBlankApiKey() { + assertThrows(IllegalArgumentException.class, () -> new EmailService("")); + } + + @Test + void sendEmail_success_returnsNormally() throws Exception { + Response response = new Response(); + response.setStatusCode(202); + when(sendGrid.api(any(Request.class))).thenReturn(response); + + service.sendEmail("from@x.com", "to@y.com", "subject", "body"); + + ArgumentCaptor captor = ArgumentCaptor.forClass(Request.class); + verify(sendGrid, times(1)).api(captor.capture()); + Request sent = captor.getValue(); + assertEquals("mail/send", sent.getEndpoint()); + assertNotNull(sent.getBody()); + } + + @Test + void sendEmail_non202Response_throws() throws Exception { + Response response = new Response(); + response.setStatusCode(400); + response.setBody("invalid request"); + when(sendGrid.api(any(Request.class))).thenReturn(response); + + SendgridException ex = assertThrows(SendgridException.class, + () -> service.sendEmail("from@x.com", "to@y.com", "subj", "body")); + assertNotNull(ex.getMessage()); + // Message should include the status code we got back. + assertEquals(true, ex.getMessage().contains("400")); + } + + @Test + void sendEmail_ioExceptionFromClient_isWrappedWithCause() throws Exception { + IOException ioe = new IOException("network down"); + when(sendGrid.api(any(Request.class))).thenThrow(ioe); + + SendgridException ex = assertThrows(SendgridException.class, + () -> service.sendEmail("from@x.com", "to@y.com", "subj", "body")); + assertSame(ioe, ex.getCause()); + } + + @ParameterizedTest + @NullAndEmptySource + @ValueSource(strings = { " " }) + void sendEmail_rejectsNullOrBlankFrom(String from) { + assertThrows(IllegalArgumentException.class, + () -> service.sendEmail(from, "to@y.com", "s", "b")); + } + + @ParameterizedTest + @NullAndEmptySource + @ValueSource(strings = { " " }) + void sendEmail_rejectsNullOrBlankTo(String to) { + assertThrows(IllegalArgumentException.class, + () -> service.sendEmail("from@x.com", to, "s", "b")); + } + + @Test + void sendTemplateEmail_success() throws Exception { + Response response = new Response(); + response.setStatusCode(202); + when(sendGrid.api(any(Request.class))).thenReturn(response); + + Map data = new HashMap<>(); + data.put("name", "World"); + service.sendTemplateEmail("tpl-1", "from@x.com", "to@y.com", data); + + verify(sendGrid, times(1)).api(any(Request.class)); + } + + @Test + void sendTemplateEmail_nullTemplateData_doesNotThrowNpe() throws Exception { + Response response = new Response(); + response.setStatusCode(202); + when(sendGrid.api(any(Request.class))).thenReturn(response); + + service.sendTemplateEmail("tpl-1", "from@x.com", "to@y.com", null); + + verify(sendGrid, times(1)).api(any(Request.class)); + } + + @ParameterizedTest + @NullAndEmptySource + @ValueSource(strings = { " " }) + void sendTemplateEmail_rejectsNullOrBlankTemplateId(String id) { + assertThrows(IllegalArgumentException.class, + () -> service.sendTemplateEmail(id, "from@x.com", "to@y.com", null)); + } + + @Test + void sendTemplateEmail_non202_throwsAndPreservesContext() throws Exception { + Response response = new Response(); + response.setStatusCode(500); + response.setBody("server error"); + when(sendGrid.api(any(Request.class))).thenReturn(response); + + SendgridException ex = assertThrows(SendgridException.class, + () -> service.sendTemplateEmail("tpl", "f@x.com", "t@y.com", null)); + assertNull(ex.getCause()); + assertEquals(true, ex.getMessage().contains("500")); + } + +} diff --git a/src/test/java/io/ljunggren/sendgrid/api/service/UsageServiceTest.java b/src/test/java/io/ljunggren/sendgrid/api/service/UsageServiceTest.java new file mode 100755 index 0000000..8ff3b44 --- /dev/null +++ b/src/test/java/io/ljunggren/sendgrid/api/service/UsageServiceTest.java @@ -0,0 +1,143 @@ +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 result = service.getDailyUsage(); + assertNotNull(result); + assertEquals(1, result.size()); + assertEquals(LocalDate.of(2025, 10, 19), result.get(0).getDate()); + + ArgumentCaptor 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 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 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()); + } + +}