Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -163,7 +163,7 @@ mailtrap tokens reset --id 42 --expires-at never

# Contacts
mailtrap contacts create --email "user@example.com" --first-name "John"
mailtrap contacts update --id <CONTACT_ID> --email "user@example.com" \
mailtrap contacts update --id <CONTACT_ID> \
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
--subscription-topics '[{"subscription_topic_id":7,"domain_id":4321,"status":"unsubscribed"}]'
mailtrap contact-lists list
mailtrap contact-lists list --search news
Expand Down
16 changes: 9 additions & 7 deletions docs/TEST_PLAN.md
Original file line number Diff line number Diff line change
Expand Up @@ -199,14 +199,16 @@ Tests are organized by endpoint group. Each test specifies:
|---|------|---------|----------|
| 10.1 | Create contact | `mailtrap contacts create --email "test@integration.com"` | New contact in output |
| 10.2 | Get contact | `mailtrap contacts get --id <CONTACT_ID>` | Single contact details |
| 10.3 | Update contact | `mailtrap contacts update --id <CONTACT_ID> --email "test@integration.com" --first-name "Test"` | Updated contact |
| 10.3 | Update contact | `mailtrap contacts update --id <CONTACT_ID> --first-name "Test"` | Updated contact; email unchanged |
| 10.4 | List contacts | `mailtrap contacts list` | Table with contacts (may 404 — investigate) |
| 10.5 | Import contacts | `mailtrap contacts import --file contacts.csv` | Import initiated |
| 10.6 | Import status | `mailtrap contacts import-status --id <IMPORT_ID>` | Status details |
| 10.7 | Export contacts | `mailtrap contacts export` | Export initiated |
| 10.8 | Export status | `mailtrap contacts export-status --id <EXPORT_ID>` | Status details |
| 10.9 | Create event | `mailtrap contacts create-event --id <CONTACT_ID> --type "purchase"` | Event created |
| 10.9 | Create event | `mailtrap contacts create-event --id <CONTACT_ID> --name "purchase"` | Event created |
| 10.10 | Delete contact | `mailtrap contacts delete --id <CONTACT_ID>` | Success message |
| 10.11 | Update without flags | `mailtrap contacts update --id <CONTACT_ID>` | Error: `at least one attribute flag is required`; no request sent |
| 10.12 | Invalid email | `mailtrap contacts create --email "not-an-email"` | `Error: API error 422: email is invalid` |

**Cleanup:** Delete created contact.

Expand Down Expand Up @@ -394,14 +396,14 @@ Prerequisite: Send an email with an attachment to the sandbox.
| 23.6 | Get missing ID | `mailtrap subscription-topics get` | Error: `required flag(s) "id" not set` |
| 23.7 | Campaign with topic | `mailtrap email-campaigns create --name "topic-test" --domain-id <DOMAIN_ID> --from-local-part news --subject "Hi" --subscription-topic-id <TOPIC_ID>` | TOPIC ID column shows the topic; `email-campaigns get --id <NEW_ID> -o json` has `subscription_topic_id` |
| 23.8 | Campaign with uncovered topic | `mailtrap email-campaigns update --id <NEW_ID> --subscription-topic-id <OTHER_DOMAIN_TOPIC_ID>` | `API error 422`, campaign unchanged |
| 23.9 | Contact topic preferences | `mailtrap contacts update --id <CONTACT_ID> --email <EMAIL> --subscription-topics '[{"subscription_topic_id":<TOPIC_ID>,"domain_id":<DOMAIN_ID>,"status":"unsubscribed"}]' -o json` | `subscription_topics` lists the topic as `unsubscribed` on that domain and `subscribed` on the other |
| 23.10 | Invalid topic entry | `mailtrap contacts update --id <CONTACT_ID> --email <EMAIL> --subscription-topics '[{"subscription_topic_id":<TOPIC_ID>,"status":"unsubscribed"}]'` | Error: `entry 1: domain_id must be greater than 0`; no request sent |
| 23.9 | Contact topic preferences | `mailtrap contacts update --id <CONTACT_ID> --subscription-topics '[{"subscription_topic_id":<TOPIC_ID>,"domain_id":<DOMAIN_ID>,"status":"unsubscribed"}]' -o json` | `subscription_topics` lists the topic as `unsubscribed` on that domain and `subscribed` on the other |
| 23.10 | Invalid topic entry | `mailtrap contacts update --id <CONTACT_ID> --subscription-topics '[{"subscription_topic_id":<TOPIC_ID>,"status":"unsubscribed"}]'` | Error: `entry 1: domain_id must be greater than 0`; no request sent |
| 23.11 | Import with topics | `mailtrap contacts import --file contacts.json` with a contact carrying `subscription_topics` | Import completes; `contacts get` shows the preference |
| 23.12 | Topic unsubscriptions | `mailtrap suppressions list --include-topic-unsubscriptions` after 23.9 | A `topic unsubscription` row with TOPIC_ID and DOMAIN_NAME; without the flag, or with a token limited to one domain, the row is absent |
| 23.13 | Topics off: list | `mailtrap subscription-topics list` | `API error 403` |
| 23.14 | Topics off: campaign | `mailtrap email-campaigns create ... --subscription-topic-id 1` | Campaign saved; TOPIC ID empty |
| 23.15 | Topics off: contact read | `mailtrap contacts get --id <CONTACT_ID> -o json` | No `subscription_topics` key, no error |
| 23.16 | Topics off: contact write | `mailtrap contacts update --id <CONTACT_ID> --email <EMAIL> --subscription-topics '[{"subscription_topic_id":1,"domain_id":<DOMAIN_ID>,"status":"subscribed"}]'` | `API error 422` naming `subscription_topics` ("are not available for this account") |
| 23.16 | Topics off: contact write | `mailtrap contacts update --id <CONTACT_ID> --subscription-topics '[{"subscription_topic_id":1,"domain_id":<DOMAIN_ID>,"status":"subscribed"}]'` | `API error 422: subscription_topics are not available for this account` |
| 23.17 | Topics off: suppressions | `mailtrap suppressions list --include-topic-unsubscriptions` | No `topic unsubscription` rows |

**Cleanup:** Delete the campaign created in 23.7 and the contacts imported in 23.11.
Expand Down Expand Up @@ -465,7 +467,7 @@ Run tests in dependency order so earlier tests create resources needed by later
| Email Logs | 2 | 4 |
| Contact Lists | 5 | 6 |
| Contact Fields | 5 | 6 |
| Contacts | 10 | 10 |
| Contacts | 10 | 12 |
| Projects | 5 | 6 |
| Sandboxes | 10 | 11 |
| Sandbox Send | 2 | 3 |
Expand All @@ -479,4 +481,4 @@ Run tests in dependency order so earlier tests create resources needed by later
| Configure | 1 | 2 |
| Inbound | 24 | 30 |
| Subscription Topics | 2 | 17 |
| **Total** | **~117** | **~156** |
| **Total** | **~117** | **~158** |
8 changes: 2 additions & 6 deletions internal/client/client.go
Original file line number Diff line number Diff line change
Expand Up @@ -85,11 +85,7 @@ func (c *Client) do(ctx context.Context, base BaseURL, method, path string, quer
}

if resp.StatusCode >= 400 {
apiErr := &APIError{StatusCode: resp.StatusCode}
if json.Unmarshal(respBody, apiErr) != nil {
apiErr.Message = string(respBody)
}
return apiErr
return newAPIError(resp.StatusCode, respBody)
}

if result != nil && len(respBody) > 0 {
Expand Down Expand Up @@ -151,7 +147,7 @@ func (c *Client) GetRaw(ctx context.Context, base BaseURL, path string, query ur
}

if resp.StatusCode >= 400 {
return nil, &APIError{StatusCode: resp.StatusCode, Message: string(data)}
return nil, newAPIError(resp.StatusCode, data)
}

return data, nil
Expand Down
58 changes: 51 additions & 7 deletions internal/client/client_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,6 @@ import (
"net/http"
"net/http/httptest"
"net/url"
"strings"
"testing"
)

Expand Down Expand Up @@ -322,19 +321,64 @@ func TestAPIError_JSONBody(t *testing.T) {
if apiErr.StatusCode != 422 {
t.Errorf("expected status 422, got %d", apiErr.StatusCode)
}
if apiErr.Message != "validation failed" {
t.Errorf("expected message %q, got %q", "validation failed", apiErr.Message)
}
if v, ok := apiErr.Errors["name"]; !ok || v != "is required" {
t.Errorf("expected errors[name]=%q, got %v", "is required", apiErr.Errors)
if apiErr.Message != "validation failed; name is required" {
t.Errorf("expected message %q, got %q", "validation failed; name is required", apiErr.Message)
}
// Check Error() string output
errStr := apiErr.Error()
if !strings.Contains(errStr, "422") || !strings.Contains(errStr, "validation failed") {
if errStr != "API error 422: validation failed; name is required" {
t.Errorf("unexpected Error() output: %s", errStr)
}
}

func TestAPIError_ErrorsFormats(t *testing.T) {
cases := []struct {
name string
status int
body string
want string
}{
{"error", http.StatusNotFound, `{"error":"Not Found"}`, "API error 404: Not Found"},
{"errors string", http.StatusServiceUnavailable,
`{"errors":"The contact was saved, but its subscription topic preferences were not. Send them again in an update of contact abc-123."}`,
"API error 503: The contact was saved, but its subscription topic preferences were not. Send them again in an update of contact abc-123."},
{"errors array", http.StatusBadRequest, `{"success":false,"errors":["'from' is required","'subject' is required"]}`,
"API error 400: 'from' is required; 'subject' is required"},
{"errors object of arrays", http.StatusUnprocessableEntity, `{"errors":{"name":["can't be blank"],"email":["is invalid","is too long"]}}`,
"API error 422: email is invalid; email is too long; name can't be blank"},
{"errors object of strings", http.StatusUnprocessableEntity, `{"errors":{"name":"is required"}}`, "API error 422: name is required"},
{"base errors", http.StatusUnprocessableEntity, `{"errors":{"base":["Contacts limit reached"],"email":["is invalid"]}}`,
"API error 422: Contacts limit reached; email is invalid"},
{"nested errors", http.StatusUnprocessableEntity, `{"errors":{"contacts":[{"email":["is invalid"]}],"limit":5000}}`,
"API error 422: contacts email is invalid; limit 5000"},
{"null errors", http.StatusNotFound, `{"error":"Not Found","errors":null}`, "API error 404: Not Found"},
{"other JSON", http.StatusForbidden, `{"message":"Access to this inbox is forbidden"}`,
`API error 403: {"message":"Access to this inbox is forbidden"}`},
{"plain text", http.StatusBadGateway, "bad gateway", "API error 502: bad gateway"},
{"empty body", http.StatusForbidden, "", "API error 403"},
}

for _, tc := range cases {
_, c, base := setupTestServer(t, func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(tc.status)
io.WriteString(w, tc.body)
})

t.Run(tc.name, func(t *testing.T) {
err := c.Post(context.Background(), base, "/api/items", map[string]string{}, nil)
if err == nil || err.Error() != tc.want {
t.Errorf("expected %q, got %v", tc.want, err)
}
})
t.Run(tc.name+" raw", func(t *testing.T) {
_, err := c.GetRaw(context.Background(), base, "/api/items/1/raw", nil)
if err == nil || err.Error() != tc.want {
t.Errorf("expected %q, got %v", tc.want, err)
}
})
}
}

func TestAPIError_EmptyMessage(t *testing.T) {
apiErr := &APIError{StatusCode: 403}
expected := "API error 403"
Expand Down
77 changes: 74 additions & 3 deletions internal/client/errors.go
Original file line number Diff line number Diff line change
@@ -1,11 +1,38 @@
package client

import "fmt"
import (
"bytes"
"encoding/json"
"fmt"
"maps"
"slices"
"strings"
)

type APIError struct {
StatusCode int
Message string `json:"error"`
Errors map[string]string `json:"errors,omitempty"`
Message string
}

// newAPIError builds the error for a failed response. Its message is the body's
// "error" text followed by its "errors" (see errorMessages), joined with "; ".
// A body that isn't a JSON object of this shape, or carries no message in it,
// becomes the message as is.
func newAPIError(statusCode int, body []byte) *APIError {
var parsed struct {
Error string `json:"error"`
Errors json.RawMessage `json:"errors"`
}
if json.Unmarshal(body, &parsed) == nil {
messages := errorMessages(parsed.Errors)
if parsed.Error != "" {
messages = append([]string{parsed.Error}, messages...)
}
if len(messages) > 0 {
return &APIError{StatusCode: statusCode, Message: strings.Join(messages, "; ")}
}
}
return &APIError{StatusCode: statusCode, Message: string(body)}
}

func (e *APIError) Error() string {
Expand All @@ -14,3 +41,47 @@ func (e *APIError) Error() string {
}
return fmt.Sprintf("API error %d", e.StatusCode)
}

// errorMessages flattens an "errors" value into readable messages: a string as
// is, an array element by element, and an object as "field message" pairs
// sorted by field ("base" errors, which belong to no field, without one).
func errorMessages(raw json.RawMessage) []string {
raw = bytes.TrimSpace(raw)
if len(raw) == 0 || bytes.Equal(raw, []byte("null")) {
return nil
}

var text string
if json.Unmarshal(raw, &text) == nil {
if text == "" {
return nil
}
return []string{text}
}

var list []json.RawMessage
if json.Unmarshal(raw, &list) == nil {
var messages []string
for _, item := range list {
messages = append(messages, errorMessages(item)...)
}
return messages
}

var fields map[string]json.RawMessage
if json.Unmarshal(raw, &fields) == nil {
var messages []string
for _, name := range slices.Sorted(maps.Keys(fields)) {
for _, message := range errorMessages(fields[name]) {
if name != "base" {
message = name + " " + message
}
messages = append(messages, message)
}
}
return messages
}

// A number or a boolean prints as sent.
return []string{string(raw)}
}
15 changes: 13 additions & 2 deletions internal/commands/contacts/contacts_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -291,6 +291,14 @@ func TestContactsUpdateWithListFlags(t *testing.T) {
}
}

func TestContactsUpdateNothingToUpdate(t *testing.T) {
noRequest := func(w http.ResponseWriter, r *http.Request) {
t.Error("unexpected request")
}

expectError(t, noRequest, []string{"update", "--id", "abc-123"}, "at least one attribute flag is required")
}

func TestContactsDelete(t *testing.T) {
f, buf, cleanup := setupTest(func(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodDelete {
Expand Down Expand Up @@ -510,17 +518,20 @@ func TestContactsSendSubscriptionTopics(t *testing.T) {
},
}
withoutTopics := map[string]interface{}{"email": "x@y.com"}
onlyTopics := map[string]interface{}{"subscription_topics": withTopics["subscription_topics"]}
withoutEmail := map[string]interface{}{"fields": map[string]interface{}{"first_name": "Jane"}, "unsubscribed": false}

// A topic-only update: the CLI still requires --email.
for _, tc := range []struct {
name string
args []string
contact map[string]interface{}
}{
{"create", []string{"create", "--email", "x@y.com", "--subscription-topics", topics}, withTopics},
{"update", []string{"update", "--id", "abc-123", "--email", "x@y.com", "--subscription-topics", topics}, withTopics},
{"topic-only update", []string{"update", "--id", "abc-123", "--subscription-topics", topics}, onlyTopics},
{"create without topics", []string{"create", "--email", "x@y.com"}, withoutTopics},
{"update without topics", []string{"update", "--id", "abc-123", "--email", "x@y.com"}, withoutTopics},
{"update without email", []string{"update", "--id", "abc-123", "--first-name", "Jane", "--unsubscribed=false"}, withoutEmail},
} {
t.Run(tc.name, func(t *testing.T) {
f, buf, cleanup := setupTest(func(w http.ResponseWriter, r *http.Request) {
Expand Down Expand Up @@ -595,7 +606,7 @@ func TestContactsInvalidSubscriptionTopics(t *testing.T) {
}
// update shares the parser; one case shows it is wired in.
t.Run("update", func(t *testing.T) {
expectError(t, noRequest, []string{"update", "--id", "abc-123", "--email", "x@y.com", "--subscription-topics", `[{"subscription_topic_id":7}]`},
expectError(t, noRequest, []string{"update", "--id", "abc-123", "--subscription-topics", `[{"subscription_topic_id":7}]`},
"entry 1: domain_id must be greater than 0")
})
}
Expand Down
38 changes: 20 additions & 18 deletions internal/commands/contacts/update.go
Original file line number Diff line number Diff line change
Expand Up @@ -28,12 +28,11 @@ func NewCmdUpdate(f *cmdutil.Factory) *cobra.Command {
if err := cmdutil.RequireFlag("id", contactID); err != nil {
return err
}
if err := cmdutil.RequireFlag("email", email); err != nil {
return err
}

contactData := map[string]interface{}{
"email": email,
// The API finds the contact by its ID, so the email is sent only to change it.
contactData := map[string]interface{}{}
if cmd.Flags().Changed("email") {
contactData["email"] = email
}
if cmd.Flags().Changed("subscription-topics") {
parsed, err := parseSubscriptionTopics(subscriptionTopics)
Expand All @@ -43,18 +42,6 @@ func NewCmdUpdate(f *cmdutil.Factory) *cobra.Command {
contactData["subscription_topics"] = parsed
}

c, err := f.NewClient()
if err != nil {
return err
}

_, err = config.RequireAccountID()
if err != nil {
return err
}

path := cmdutil.AccountPath("contacts", fmt.Sprintf("%s", contactID))

fields := map[string]interface{}{}
if firstName != "" {
fields["first_name"] = firstName
Expand All @@ -75,6 +62,21 @@ func NewCmdUpdate(f *cmdutil.Factory) *cobra.Command {
if cmd.Flags().Changed("unsubscribed") {
contactData["unsubscribed"] = unsubscribed
}
if len(contactData) == 0 {
return fmt.Errorf("at least one attribute flag is required")
}

c, err := f.NewClient()
if err != nil {
return err
}

_, err = config.RequireAccountID()
if err != nil {
return err
}

path := cmdutil.AccountPath("contacts", contactID)

body := map[string]interface{}{
"contact": contactData,
Expand All @@ -91,7 +93,7 @@ func NewCmdUpdate(f *cmdutil.Factory) *cobra.Command {
}

cmd.Flags().StringVar(&contactID, "id", "", "Contact ID (required)")
cmd.Flags().StringVar(&email, "email", "", "Contact email (required)")
cmd.Flags().StringVar(&email, "email", "", "Contact email")
cmd.Flags().StringVar(&firstName, "first-name", "", "Contact first name")
cmd.Flags().StringVar(&lastName, "last-name", "", "Contact last name")
cmd.Flags().IntSliceVar(&listIDsIncluded, "list-ids-included", nil, "List IDs to subscribe to")
Expand Down
4 changes: 2 additions & 2 deletions skill-evals/mailtrap-cli/evals.json
Original file line number Diff line number Diff line change
Expand Up @@ -103,8 +103,8 @@
"prompt": "Import contacts from my contacts.json file into list 5",
"expected": {
"command": "contacts import",
"flags": ["--file", "--list-id"],
"must_not_contain": ["create", "export"]
"flags": ["--file"],
"must_not_contain": ["create", "export", "--list-id"]
}
},
{
Expand Down
Loading