gogcli/internal/cmd/execute_gmail_labels_text_test.go
2025-12-26 10:15:12 +00:00

69 lines
1.9 KiB
Go

package cmd
import (
"context"
"encoding/json"
"net/http"
"net/http/httptest"
"strings"
"testing"
"google.golang.org/api/gmail/v1"
"google.golang.org/api/option"
)
func TestExecute_GmailLabelsGet_Text(t *testing.T) {
origNew := newGmailService
t.Cleanup(func() { newGmailService = origNew })
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
switch {
case strings.Contains(r.URL.Path, "/gmail/v1/users/me/labels") && r.Method == http.MethodGet && !strings.Contains(r.URL.Path, "/labels/"):
w.Header().Set("Content-Type", "application/json")
_ = json.NewEncoder(w).Encode(map[string]any{
"labels": []map[string]any{
{"id": "INBOX", "name": "INBOX", "type": "system"},
},
})
return
case strings.Contains(r.URL.Path, "/gmail/v1/users/me/labels/INBOX") && r.Method == http.MethodGet:
w.Header().Set("Content-Type", "application/json")
_ = json.NewEncoder(w).Encode(map[string]any{
"id": "INBOX",
"name": "INBOX",
"type": "system",
"messagesTotal": 1,
"messagesUnread": 2,
"threadsTotal": 3,
"threadsUnread": 4,
})
return
default:
http.NotFound(w, r)
return
}
}))
defer srv.Close()
svc, err := gmail.NewService(context.Background(),
option.WithoutAuthentication(),
option.WithHTTPClient(srv.Client()),
option.WithEndpoint(srv.URL+"/"),
)
if err != nil {
t.Fatalf("NewService: %v", err)
}
newGmailService = func(context.Context, string) (*gmail.Service, error) { return svc, nil }
out := captureStdout(t, func() {
_ = captureStderr(t, func() {
if err := Execute([]string{"--account", "a@b.com", "gmail", "labels", "get", "INBOX"}); err != nil {
t.Fatalf("Execute: %v", err)
}
})
})
if !strings.Contains(out, "id\tINBOX") || !strings.Contains(out, "messages_total\t1") || !strings.Contains(out, "threads_unread\t4") {
t.Fatalf("unexpected out=%q", out)
}
}