test(coverage): add tests for workintake, secret, forge, natsrpc
Closes coverage gaps flagged in load-bearing packages: - internal/domain/workintake: 14.3% -> 94.6% - internal/secret/enginehost: 0% -> 100% - internal/secret/secretextract: 10% -> 100% - internal/forge: 36.1% -> 77.0% - internal/natsrpc: 28.3% -> 91.3%
This commit is contained in:
1 parent
7a8a13cd88
commit
ba672965c6
9 files changed
+1269
-101
No files matched your search
@@ -0,0 +1,153 @@
|
||||
package workintake
|
||||
|
||||
import (
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestSplitLabels(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
raw string
|
||||
want []string
|
||||
}{
|
||||
{name: "empty", raw: "", want: nil},
|
||||
{name: "single", raw: "bug", want: []string{"bug"}},
|
||||
{name: "multiple", raw: "bug,feature", want: []string{"bug", "feature"}},
|
||||
{name: "drops empties", raw: "bug,,feature", want: []string{"bug", "feature"}},
|
||||
{name: "trailing comma", raw: "bug,", want: []string{"bug"}},
|
||||
{name: "trims whitespace", raw: " bug , feature ", want: []string{"bug", "feature"}},
|
||||
{name: "only commas", raw: ",,,", want: nil},
|
||||
}
|
||||
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
got := SplitLabels(tt.raw)
|
||||
if len(got) != len(tt.want) {
|
||||
t.Fatalf("SplitLabels(%q) = %v, want %v", tt.raw, got, tt.want)
|
||||
}
|
||||
for i := range got {
|
||||
if got[i] != tt.want[i] {
|
||||
t.Fatalf("SplitLabels(%q) = %v, want %v", tt.raw, got, tt.want)
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestTaskEnvelopeMarshalRoundTrip(t *testing.T) {
|
||||
original := TaskEnvelope{
|
||||
Owner: "samcharles93",
|
||||
Repo: "archie-core",
|
||||
Number: 42,
|
||||
Title: "fix the thing",
|
||||
Body: "it's broken",
|
||||
Labels: []string{"bug", "P1"},
|
||||
Identity: "archie-bot",
|
||||
Kind: KindBug,
|
||||
}
|
||||
|
||||
data, err := original.Encode()
|
||||
if err != nil {
|
||||
t.Fatalf("Encode() error = %v", err)
|
||||
}
|
||||
|
||||
decoded, err := DecodeTask(data)
|
||||
if err != nil {
|
||||
t.Fatalf("DecodeTask() error = %v", err)
|
||||
}
|
||||
|
||||
if decoded.Owner != original.Owner || decoded.Repo != original.Repo || decoded.Number != original.Number {
|
||||
t.Fatalf("round trip identity mismatch: got %+v, want %+v", decoded, original)
|
||||
}
|
||||
if decoded.Title != original.Title || decoded.Body != original.Body {
|
||||
t.Fatalf("round trip content mismatch: got %+v, want %+v", decoded, original)
|
||||
}
|
||||
if len(decoded.Labels) != len(original.Labels) {
|
||||
t.Fatalf("round trip labels = %v, want %v", decoded.Labels, original.Labels)
|
||||
}
|
||||
for i := range decoded.Labels {
|
||||
if decoded.Labels[i] != original.Labels[i] {
|
||||
t.Fatalf("round trip labels = %v, want %v", decoded.Labels, original.Labels)
|
||||
}
|
||||
}
|
||||
if decoded.Identity != original.Identity {
|
||||
t.Fatalf("round trip Identity = %q, want %q", decoded.Identity, original.Identity)
|
||||
}
|
||||
if decoded.Kind != original.Kind {
|
||||
t.Fatalf("round trip Kind = %q, want %q", decoded.Kind, original.Kind)
|
||||
}
|
||||
}
|
||||
|
||||
func TestTaskEnvelopeMarshalFlattensLabels(t *testing.T) {
|
||||
envelope := TaskEnvelope{Owner: "o", Repo: "r", Number: 1, Labels: []string{"bug", "feature"}}
|
||||
data, err := envelope.Encode()
|
||||
if err != nil {
|
||||
t.Fatalf("Encode() error = %v", err)
|
||||
}
|
||||
if !strings.Contains(string(data), `"labels":"bug,feature"`) {
|
||||
t.Fatalf("Encode() = %s, want labels flattened to comma-separated wire field", data)
|
||||
}
|
||||
}
|
||||
|
||||
func TestDecodeTaskLegacyMessageWithoutKind(t *testing.T) {
|
||||
// Messages queued before Kind existed decode with the zero value, which
|
||||
// must behave as KindDefault.
|
||||
legacy := `{"owner":"o","repo":"r","number":1,"title":"t","body":"b","labels":"bug"}`
|
||||
decoded, err := DecodeTask([]byte(legacy))
|
||||
if err != nil {
|
||||
t.Fatalf("DecodeTask() error = %v", err)
|
||||
}
|
||||
if decoded.Kind != "" {
|
||||
t.Fatalf("Kind = %q, want empty (decodes as KindDefault)", decoded.Kind)
|
||||
}
|
||||
if decoded.Subject() != SubjectTaskDefault {
|
||||
t.Fatalf("Subject() = %q, want %q", decoded.Subject(), SubjectTaskDefault)
|
||||
}
|
||||
if len(decoded.Labels) != 1 || decoded.Labels[0] != "bug" {
|
||||
t.Fatalf("Labels = %v, want [bug]", decoded.Labels)
|
||||
}
|
||||
}
|
||||
|
||||
func TestDecodeTaskInvalidJSON(t *testing.T) {
|
||||
if _, err := DecodeTask([]byte("not json")); err == nil {
|
||||
t.Fatal("DecodeTask() error = nil, want error for invalid JSON")
|
||||
}
|
||||
}
|
||||
|
||||
func TestTaskEnvelopeRef(t *testing.T) {
|
||||
e := TaskEnvelope{Owner: "samcharles93", Repo: "archie-core", Number: 42}
|
||||
if got, want := e.Ref(), "samcharles93/archie-core#42"; got != want {
|
||||
t.Fatalf("Ref() = %q, want %q", got, want)
|
||||
}
|
||||
}
|
||||
|
||||
func TestTaskEnvelopeIdempotencyKey(t *testing.T) {
|
||||
e := TaskEnvelope{Owner: "samcharles93", Repo: "archie-core", Number: 42}
|
||||
if got, want := e.IdempotencyKey(), "archie:samcharles93/archie-core/42"; got != want {
|
||||
t.Fatalf("IdempotencyKey() = %q, want %q", got, want)
|
||||
}
|
||||
}
|
||||
|
||||
func TestTaskEnvelopeSubject(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
kind Kind
|
||||
want string
|
||||
}{
|
||||
{name: "bug", kind: KindBug, want: SubjectTaskBug},
|
||||
{name: "feature", kind: KindFeature, want: SubjectTaskFeature},
|
||||
{name: "bootstrap", kind: KindBootstrap, want: SubjectTaskBootstrap},
|
||||
{name: "default", kind: KindDefault, want: SubjectTaskDefault},
|
||||
{name: "empty", kind: "", want: SubjectTaskDefault},
|
||||
{name: "unknown", kind: Kind("nonsense"), want: SubjectTaskDefault},
|
||||
}
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
e := TaskEnvelope{Kind: tt.kind}
|
||||
if got := e.Subject(); got != tt.want {
|
||||
t.Fatalf("Subject() = %q, want %q", got, tt.want)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,107 @@
|
||||
package workintake
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestKindValidate(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
kind Kind
|
||||
wantErr bool
|
||||
}{
|
||||
{name: "empty is accepted", kind: "", wantErr: false},
|
||||
{name: "bug", kind: KindBug, wantErr: false},
|
||||
{name: "feature", kind: KindFeature, wantErr: false},
|
||||
{name: "bootstrap", kind: KindBootstrap, wantErr: false},
|
||||
{name: "default", kind: KindDefault, wantErr: false},
|
||||
{name: "unknown", kind: Kind("nonsense"), wantErr: true},
|
||||
}
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
err := tt.kind.Validate()
|
||||
if tt.wantErr && err == nil {
|
||||
t.Fatal("Validate() error = nil, want error")
|
||||
}
|
||||
if !tt.wantErr && err != nil {
|
||||
t.Fatalf("Validate() error = %v, want nil", err)
|
||||
}
|
||||
if tt.wantErr && !errors.Is(err, ErrUnknownKind) {
|
||||
t.Fatalf("Validate() error = %v, want wrapping ErrUnknownKind", err)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestSubjectForKind(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
kind Kind
|
||||
want string
|
||||
}{
|
||||
{name: "bug", kind: KindBug, want: SubjectTaskBug},
|
||||
{name: "feature", kind: KindFeature, want: SubjectTaskFeature},
|
||||
{name: "bootstrap", kind: KindBootstrap, want: SubjectTaskBootstrap},
|
||||
{name: "default", kind: KindDefault, want: SubjectTaskDefault},
|
||||
{name: "empty falls back to default", kind: "", want: SubjectTaskDefault},
|
||||
{name: "unrecognised falls back to default", kind: Kind("nonsense"), want: SubjectTaskDefault},
|
||||
}
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
if got := SubjectForKind(tt.kind); got != tt.want {
|
||||
t.Fatalf("SubjectForKind(%q) = %q, want %q", tt.kind, got, tt.want)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestKindForLabels(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
labels []string
|
||||
want Kind
|
||||
}{
|
||||
{name: "nil labels", labels: nil, want: KindDefault},
|
||||
{name: "empty labels", labels: []string{}, want: KindDefault},
|
||||
{name: "unrecognised label", labels: []string{"wontfix"}, want: KindDefault},
|
||||
{name: "single recognised", labels: []string{"bug"}, want: KindBug},
|
||||
{name: "first recognised wins", labels: []string{"feature", "bug"}, want: KindFeature},
|
||||
{name: "unrecognised then recognised", labels: []string{"wontfix", "bootstrap"}, want: KindBootstrap},
|
||||
{name: "trims whitespace", labels: []string{" bug "}, want: KindBug},
|
||||
}
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
if got := KindForLabels(tt.labels); got != tt.want {
|
||||
t.Fatalf("KindForLabels(%v) = %q, want %q", tt.labels, got, tt.want)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestKindsForLabels(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
labels []string
|
||||
want []Kind
|
||||
}{
|
||||
{name: "nil labels", labels: nil, want: nil},
|
||||
{name: "no recognised labels", labels: []string{"wontfix", "help wanted"}, want: nil},
|
||||
{name: "single", labels: []string{"bug"}, want: []Kind{KindBug}},
|
||||
{name: "preserves order", labels: []string{"bug", "feature"}, want: []Kind{KindBug, KindFeature}},
|
||||
{name: "skips unrecognised", labels: []string{"wontfix", "bug", "triage", "feature"}, want: []Kind{KindBug, KindFeature}},
|
||||
}
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
got := KindsForLabels(tt.labels)
|
||||
if len(got) != len(tt.want) {
|
||||
t.Fatalf("KindsForLabels(%v) = %v, want %v", tt.labels, got, tt.want)
|
||||
}
|
||||
for i := range got {
|
||||
if got[i] != tt.want[i] {
|
||||
t.Fatalf("KindsForLabels(%v) = %v, want %v", tt.labels, got, tt.want)
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,72 @@
|
||||
package forge
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestNewDispatchesByForgeType(t *testing.T) {
|
||||
// Gitea client construction makes a network call to /api/v1/version, so
|
||||
// its happy path is covered separately in TestNewGitea against a fake
|
||||
// server rather than here.
|
||||
tests := []struct {
|
||||
name string
|
||||
forgeType string
|
||||
wantErr bool
|
||||
}{
|
||||
{name: "github", forgeType: "github"},
|
||||
{name: "none", forgeType: "none"},
|
||||
{name: "off", forgeType: "off"},
|
||||
{name: "disabled", forgeType: "disabled"},
|
||||
{name: "empty defaults to noop", forgeType: ""},
|
||||
{name: "unsupported type errors", forgeType: "bitbucket", wantErr: true},
|
||||
}
|
||||
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
f, err := New(tt.forgeType, "token", "", nil)
|
||||
if tt.wantErr {
|
||||
if err == nil {
|
||||
t.Fatalf("New(%q) error = nil, want error", tt.forgeType)
|
||||
}
|
||||
if f != nil {
|
||||
t.Fatalf("New(%q) forge = %v, want nil on error", tt.forgeType, f)
|
||||
}
|
||||
return
|
||||
}
|
||||
if err != nil {
|
||||
t.Fatalf("New(%q) error = %v, want nil", tt.forgeType, err)
|
||||
}
|
||||
if f == nil {
|
||||
t.Fatalf("New(%q) forge = nil, want non-nil", tt.forgeType)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestNewGitea(t *testing.T) {
|
||||
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
if r.URL.Path == "/api/v1/version" {
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
_, _ = w.Write([]byte(`{"version":"1.21.0"}`))
|
||||
return
|
||||
}
|
||||
w.WriteHeader(http.StatusNotFound)
|
||||
}))
|
||||
defer srv.Close()
|
||||
|
||||
f, err := New("gitea", "token", srv.URL, nil)
|
||||
if err != nil {
|
||||
t.Fatalf("New(\"gitea\") error = %v, want nil", err)
|
||||
}
|
||||
if f == nil {
|
||||
t.Fatal("New(\"gitea\") forge = nil, want non-nil")
|
||||
}
|
||||
}
|
||||
|
||||
func TestNewGiteaUnreachableHost(t *testing.T) {
|
||||
if _, err := New("gitea", "token", "http://127.0.0.1:0", nil); err == nil {
|
||||
t.Fatal("New(\"gitea\") with unreachable host error = nil, want error")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,381 @@
|
||||
package forge
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestGiteaAssignedIssuesExcludesPRs(t *testing.T) {
|
||||
c, mux := newTestGiteaClient(t)
|
||||
mux.HandleFunc("GET /api/v1/repos/o/r/issues", func(w http.ResponseWriter, r *http.Request) {
|
||||
if got := r.URL.Query().Get("assigned_by"); got != "archie-bot" {
|
||||
t.Errorf("assigned_by = %q", got)
|
||||
}
|
||||
writeJSON(t, w, []map[string]any{
|
||||
{"number": 1, "title": "real issue", "body": "b", "labels": []map[string]any{{"name": "bug"}}},
|
||||
{"number": 2, "title": "a pr", "pull_request": map[string]any{"url": "x"}},
|
||||
})
|
||||
})
|
||||
|
||||
issues, err := c.AssignedIssues(t.Context(), "o", "r", "archie-bot")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if len(issues) != 1 || issues[0].Number != 1 || issues[0].Title != "real issue" || len(issues[0].Labels) != 1 || issues[0].Labels[0] != "bug" {
|
||||
t.Fatalf("issues = %+v", issues)
|
||||
}
|
||||
}
|
||||
|
||||
func TestGiteaIssuesWithLabelExcludesPRs(t *testing.T) {
|
||||
c, mux := newTestGiteaClient(t)
|
||||
mux.HandleFunc("GET /api/v1/repos/o/r/issues", func(w http.ResponseWriter, r *http.Request) {
|
||||
if got := r.URL.Query().Get("labels"); got != "widget" {
|
||||
t.Errorf("labels = %q", got)
|
||||
}
|
||||
writeJSON(t, w, []map[string]any{
|
||||
{"number": 3, "title": "labelled", "body": "b"},
|
||||
})
|
||||
})
|
||||
|
||||
issues, err := c.IssuesWithLabel(t.Context(), "o", "r", "widget")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if len(issues) != 1 || issues[0].Number != 3 {
|
||||
t.Fatalf("issues = %+v", issues)
|
||||
}
|
||||
}
|
||||
|
||||
func TestGiteaAssignedIssuesError(t *testing.T) {
|
||||
c, mux := newTestGiteaClient(t)
|
||||
mux.HandleFunc("GET /api/v1/repos/o/r/issues", func(w http.ResponseWriter, r *http.Request) {
|
||||
w.WriteHeader(http.StatusInternalServerError)
|
||||
})
|
||||
|
||||
if _, err := c.AssignedIssues(t.Context(), "o", "r", "archie-bot"); err == nil {
|
||||
t.Fatal("AssignedIssues() error = nil, want error")
|
||||
}
|
||||
}
|
||||
|
||||
func TestGiteaComment(t *testing.T) {
|
||||
c, mux := newTestGiteaClient(t)
|
||||
mux.HandleFunc("POST /api/v1/repos/o/r/issues/5/comments", func(w http.ResponseWriter, r *http.Request) {
|
||||
writeJSON(t, w, map[string]any{"id": 42})
|
||||
})
|
||||
|
||||
id, err := c.Comment(t.Context(), "o", "r", 5, "hello")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if id != 42 {
|
||||
t.Fatalf("id = %d, want 42", id)
|
||||
}
|
||||
}
|
||||
|
||||
func TestGiteaRepliesAfterExcludesOldAndSelf(t *testing.T) {
|
||||
c, mux := newTestGiteaClient(t)
|
||||
mux.HandleFunc("GET /api/v1/repos/o/r/issues/5/comments", func(w http.ResponseWriter, r *http.Request) {
|
||||
writeJSON(t, w, []map[string]any{
|
||||
{"id": 1, "body": "old", "user": map[string]any{"login": "someone"}},
|
||||
{"id": 3, "body": "mine", "user": map[string]any{"login": "archie-bot"}},
|
||||
{"id": 4, "body": "new reply", "user": map[string]any{"login": "someone"}},
|
||||
})
|
||||
})
|
||||
|
||||
replies, err := c.RepliesAfter(t.Context(), "o", "r", 5, 2, "archie-bot")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if len(replies) != 1 || replies[0].ID != 4 || replies[0].Body != "new reply" {
|
||||
t.Fatalf("replies = %+v", replies)
|
||||
}
|
||||
}
|
||||
|
||||
func TestGiteaCreatePR(t *testing.T) {
|
||||
c, mux := newTestGiteaClient(t)
|
||||
mux.HandleFunc("POST /api/v1/repos/o/r/pulls", func(w http.ResponseWriter, r *http.Request) {
|
||||
writeJSON(t, w, map[string]any{"number": 7})
|
||||
})
|
||||
|
||||
num, err := c.CreatePR(t.Context(), "o", "r", "title", "head", "base", "body")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if num != 7 {
|
||||
t.Fatalf("num = %d, want 7", num)
|
||||
}
|
||||
}
|
||||
|
||||
func TestGiteaCreatePRError(t *testing.T) {
|
||||
c, mux := newTestGiteaClient(t)
|
||||
mux.HandleFunc("POST /api/v1/repos/o/r/pulls", func(w http.ResponseWriter, r *http.Request) {
|
||||
w.WriteHeader(http.StatusUnprocessableEntity)
|
||||
})
|
||||
|
||||
if _, err := c.CreatePR(t.Context(), "o", "r", "title", "head", "base", "body"); err == nil {
|
||||
t.Fatal("CreatePR() error = nil, want error")
|
||||
}
|
||||
}
|
||||
|
||||
func TestGiteaPRState(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
status int
|
||||
body map[string]any
|
||||
want string
|
||||
wantErr bool
|
||||
}{
|
||||
{name: "open", status: http.StatusOK, body: map[string]any{"number": 1, "state": "open", "merged": false}, want: "open"},
|
||||
{name: "merged", status: http.StatusOK, body: map[string]any{"number": 1, "state": "closed", "merged": true}, want: "merged"},
|
||||
{name: "not found treated as closed", status: http.StatusNotFound, body: map[string]any{"message": "not found"}, want: "closed"},
|
||||
}
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
c, mux := newTestGiteaClient(t)
|
||||
mux.HandleFunc("GET /api/v1/repos/o/r/pulls/1", func(w http.ResponseWriter, r *http.Request) {
|
||||
w.WriteHeader(tt.status)
|
||||
if tt.body != nil {
|
||||
writeJSON(t, w, tt.body)
|
||||
}
|
||||
})
|
||||
|
||||
state, err := c.PRState(t.Context(), "o", "r", 1)
|
||||
if tt.wantErr {
|
||||
if err == nil {
|
||||
t.Fatal("PRState() error = nil, want error")
|
||||
}
|
||||
return
|
||||
}
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if state != tt.want {
|
||||
t.Fatalf("state = %q, want %q", state, tt.want)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestGiteaCloseIssueWithComment(t *testing.T) {
|
||||
c, mux := newTestGiteaClient(t)
|
||||
var commented, closed bool
|
||||
mux.HandleFunc("POST /api/v1/repos/o/r/issues/9/comments", func(w http.ResponseWriter, r *http.Request) {
|
||||
commented = true
|
||||
writeJSON(t, w, map[string]any{"id": 1})
|
||||
})
|
||||
mux.HandleFunc("PATCH /api/v1/repos/o/r/issues/9", func(w http.ResponseWriter, r *http.Request) {
|
||||
closed = true
|
||||
writeJSON(t, w, map[string]any{"number": 9, "state": "closed"})
|
||||
})
|
||||
|
||||
if err := c.CloseIssue(t.Context(), "o", "r", 9, "final comment"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if !commented || !closed {
|
||||
t.Fatalf("commented=%t closed=%t, want both true", commented, closed)
|
||||
}
|
||||
}
|
||||
|
||||
func TestGiteaCloseIssueWithoutComment(t *testing.T) {
|
||||
c, mux := newTestGiteaClient(t)
|
||||
var commented bool
|
||||
mux.HandleFunc("POST /api/v1/repos/o/r/issues/9/comments", func(w http.ResponseWriter, r *http.Request) {
|
||||
commented = true
|
||||
})
|
||||
mux.HandleFunc("PATCH /api/v1/repos/o/r/issues/9", func(w http.ResponseWriter, r *http.Request) {
|
||||
writeJSON(t, w, map[string]any{"number": 9, "state": "closed"})
|
||||
})
|
||||
|
||||
if err := c.CloseIssue(t.Context(), "o", "r", 9, ""); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if commented {
|
||||
t.Fatal("commented = true, want false when comment is empty")
|
||||
}
|
||||
}
|
||||
|
||||
func TestGiteaCreateIssue(t *testing.T) {
|
||||
c, mux := newTestGiteaClient(t)
|
||||
mux.HandleFunc("POST /api/v1/repos/o/r/issues", func(w http.ResponseWriter, r *http.Request) {
|
||||
writeJSON(t, w, map[string]any{"number": 11})
|
||||
})
|
||||
|
||||
num, err := c.CreateIssue(t.Context(), "o", "r", "title", "body", nil)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if num != 11 {
|
||||
t.Fatalf("num = %d, want 11", num)
|
||||
}
|
||||
}
|
||||
|
||||
func TestGiteaReact(t *testing.T) {
|
||||
c, mux := newTestGiteaClient(t)
|
||||
var got string
|
||||
mux.HandleFunc("POST /api/v1/repos/o/r/issues/1/reactions", func(w http.ResponseWriter, r *http.Request) {
|
||||
got = "called"
|
||||
writeJSON(t, w, map[string]any{"content": "+1"})
|
||||
})
|
||||
|
||||
if err := c.React(t.Context(), "o", "r", 1, "+1"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if got != "called" {
|
||||
t.Fatal("reaction endpoint was not called")
|
||||
}
|
||||
}
|
||||
|
||||
func TestGiteaAcceptInvitationsIsNoop(t *testing.T) {
|
||||
c, _ := newTestGiteaClient(t)
|
||||
if err := c.AcceptInvitations(t.Context()); err != nil {
|
||||
t.Fatalf("AcceptInvitations() = %v, want nil", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestGiteaVerifyPush(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
status int
|
||||
body map[string]any
|
||||
wantErr bool
|
||||
}{
|
||||
{name: "has push", status: http.StatusOK, body: map[string]any{"permissions": map[string]any{"push": true}}},
|
||||
{name: "no push", status: http.StatusOK, body: map[string]any{"permissions": map[string]any{"push": false}}, wantErr: true},
|
||||
{name: "not found", status: http.StatusNotFound, wantErr: true},
|
||||
}
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
c, mux := newTestGiteaClient(t)
|
||||
mux.HandleFunc("GET /api/v1/repos/o/r", func(w http.ResponseWriter, r *http.Request) {
|
||||
w.WriteHeader(tt.status)
|
||||
if tt.body != nil {
|
||||
writeJSON(t, w, tt.body)
|
||||
}
|
||||
})
|
||||
|
||||
err := c.VerifyPush(t.Context(), "o", "r")
|
||||
if tt.wantErr && err == nil {
|
||||
t.Fatal("VerifyPush() error = nil, want error")
|
||||
}
|
||||
if !tt.wantErr && err != nil {
|
||||
t.Fatalf("VerifyPush() error = %v, want nil", err)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestGiteaLinkBranch(t *testing.T) {
|
||||
c, mux := newTestGiteaClient(t)
|
||||
mux.HandleFunc("POST /api/v1/repos/o/r/issues/3/refs", func(w http.ResponseWriter, r *http.Request) {
|
||||
if got := r.Header.Get("Authorization"); got != "token token" {
|
||||
t.Errorf("Authorization = %q", got)
|
||||
}
|
||||
w.WriteHeader(http.StatusOK)
|
||||
})
|
||||
|
||||
if err := c.LinkBranch(t.Context(), "o", "r", 3, "feature-branch"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestGiteaLinkBranchError(t *testing.T) {
|
||||
c, mux := newTestGiteaClient(t)
|
||||
mux.HandleFunc("POST /api/v1/repos/o/r/issues/3/refs", func(w http.ResponseWriter, r *http.Request) {
|
||||
w.WriteHeader(http.StatusInternalServerError)
|
||||
})
|
||||
|
||||
if err := c.LinkBranch(t.Context(), "o", "r", 3, "feature-branch"); err == nil {
|
||||
t.Fatal("LinkBranch() error = nil, want error")
|
||||
}
|
||||
}
|
||||
|
||||
func TestGiteaSetStateLabelSwapsLabels(t *testing.T) {
|
||||
c, mux := newTestGiteaClient(t)
|
||||
mux.HandleFunc("GET /api/v1/repos/o/r/issues/4", func(w http.ResponseWriter, r *http.Request) {
|
||||
writeJSON(t, w, map[string]any{
|
||||
"number": 4,
|
||||
"labels": []map[string]any{
|
||||
{"id": 1, "name": "archie:queued"},
|
||||
{"id": 2, "name": "keep-me"},
|
||||
},
|
||||
})
|
||||
})
|
||||
var deletedID int64
|
||||
mux.HandleFunc("DELETE /api/v1/repos/o/r/issues/4/labels/1", func(w http.ResponseWriter, r *http.Request) {
|
||||
deletedID = 1
|
||||
w.WriteHeader(http.StatusOK)
|
||||
})
|
||||
mux.HandleFunc("GET /api/v1/repos/o/r/labels", func(w http.ResponseWriter, r *http.Request) {
|
||||
writeJSON(t, w, []map[string]any{{"id": 9, "name": "archie:working"}})
|
||||
})
|
||||
var added []int64
|
||||
mux.HandleFunc("POST /api/v1/repos/o/r/issues/4/labels", func(w http.ResponseWriter, r *http.Request) {
|
||||
added = []int64{9}
|
||||
writeJSON(t, w, []map[string]any{{"id": 9, "name": "archie:working"}})
|
||||
})
|
||||
|
||||
known := []string{"archie:queued", "archie:working", "archie:waiting"}
|
||||
c.SetStateLabel(t.Context(), "o", "r", 4, "archie:working", known)
|
||||
|
||||
if deletedID != 1 {
|
||||
t.Errorf("deletedID = %d, want 1 (archie:queued removed)", deletedID)
|
||||
}
|
||||
if len(added) != 1 || added[0] != 9 {
|
||||
t.Errorf("added = %v, want [9]", added)
|
||||
}
|
||||
}
|
||||
|
||||
func TestGiteaSetStateLabelAlreadyPresentIsNoop(t *testing.T) {
|
||||
c, mux := newTestGiteaClient(t)
|
||||
mux.HandleFunc("GET /api/v1/repos/o/r/issues/4", func(w http.ResponseWriter, r *http.Request) {
|
||||
writeJSON(t, w, map[string]any{
|
||||
"number": 4,
|
||||
"labels": []map[string]any{{"id": 9, "name": "archie:working"}},
|
||||
})
|
||||
})
|
||||
called := false
|
||||
mux.HandleFunc("POST /api/v1/repos/o/r/issues/4/labels", func(w http.ResponseWriter, r *http.Request) {
|
||||
called = true
|
||||
})
|
||||
|
||||
c.SetStateLabel(t.Context(), "o", "r", 4, "archie:working", []string{"archie:working"})
|
||||
|
||||
if called {
|
||||
t.Fatal("AddIssueLabels was called, want no-op when label already present")
|
||||
}
|
||||
}
|
||||
|
||||
func TestGiteaSetStateLabelEmptyClearsAll(t *testing.T) {
|
||||
c, mux := newTestGiteaClient(t)
|
||||
mux.HandleFunc("GET /api/v1/repos/o/r/issues/4", func(w http.ResponseWriter, r *http.Request) {
|
||||
writeJSON(t, w, map[string]any{
|
||||
"number": 4,
|
||||
"labels": []map[string]any{{"id": 1, "name": "archie:queued"}},
|
||||
})
|
||||
})
|
||||
deleted := false
|
||||
mux.HandleFunc("DELETE /api/v1/repos/o/r/issues/4/labels/1", func(w http.ResponseWriter, r *http.Request) {
|
||||
deleted = true
|
||||
w.WriteHeader(http.StatusOK)
|
||||
})
|
||||
added := false
|
||||
mux.HandleFunc("POST /api/v1/repos/o/r/issues/4/labels", func(w http.ResponseWriter, r *http.Request) {
|
||||
added = true
|
||||
})
|
||||
|
||||
c.SetStateLabel(t.Context(), "o", "r", 4, "", []string{"archie:queued"})
|
||||
|
||||
if !deleted {
|
||||
t.Error("deleted = false, want true (archie:queued removed)")
|
||||
}
|
||||
if added {
|
||||
t.Error("added = true, want false (empty label clears all)")
|
||||
}
|
||||
}
|
||||
|
||||
func TestLabelNamesGitea(t *testing.T) {
|
||||
names := labelNamesGitea(nil)
|
||||
if names != nil {
|
||||
t.Fatalf("labelNamesGitea(nil) = %v, want nil", names)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,31 @@
|
||||
package forge
|
||||
|
||||
import (
|
||||
"log/slog"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"testing"
|
||||
|
||||
"code.gitea.io/sdk/gitea"
|
||||
)
|
||||
|
||||
// newTestGiteaClient wires a GiteaClient at a local httptest server so its
|
||||
// methods can be exercised without hitting a real Gitea instance. The
|
||||
// caller's mux handles every route except /api/v1/version, which this
|
||||
// registers so client construction (which probes it) succeeds.
|
||||
func newTestGiteaClient(t *testing.T) (*GiteaClient, *http.ServeMux) {
|
||||
t.Helper()
|
||||
mux := http.NewServeMux()
|
||||
mux.HandleFunc("GET /api/v1/version", func(w http.ResponseWriter, r *http.Request) {
|
||||
writeJSON(t, w, map[string]string{"version": "1.21.0"})
|
||||
})
|
||||
srv := httptest.NewServer(mux)
|
||||
t.Cleanup(srv.Close)
|
||||
|
||||
cli, err := gitea.NewClient(srv.URL, gitea.SetToken("token"))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
return &GiteaClient{cli: cli, host: srv.URL, token: "token", log: slog.New(slog.DiscardHandler)}, mux
|
||||
}
|
||||
@@ -0,0 +1,76 @@
|
||||
package forge
|
||||
|
||||
import (
|
||||
"context"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestNewNoopDefaultsLogger(t *testing.T) {
|
||||
f := NewNoop(nil)
|
||||
if f == nil {
|
||||
t.Fatal("NewNoop(nil) = nil, want non-nil Forge")
|
||||
}
|
||||
}
|
||||
|
||||
func TestNoopForgeIsAllZeroValue(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
f := NewNoop(nil)
|
||||
|
||||
issues, err := f.AssignedIssues(ctx, "o", "r", "a")
|
||||
if issues != nil || err != nil {
|
||||
t.Errorf("AssignedIssues() = (%v, %v), want (nil, nil)", issues, err)
|
||||
}
|
||||
|
||||
issues, err = f.IssuesWithLabel(ctx, "o", "r", "label")
|
||||
if issues != nil || err != nil {
|
||||
t.Errorf("IssuesWithLabel() = (%v, %v), want (nil, nil)", issues, err)
|
||||
}
|
||||
|
||||
id, err := f.Comment(ctx, "o", "r", 1, "body")
|
||||
if id != 0 || err != nil {
|
||||
t.Errorf("Comment() = (%d, %v), want (0, nil)", id, err)
|
||||
}
|
||||
|
||||
replies, err := f.RepliesAfter(ctx, "o", "r", 1, 0, "")
|
||||
if replies != nil || err != nil {
|
||||
t.Errorf("RepliesAfter() = (%v, %v), want (nil, nil)", replies, err)
|
||||
}
|
||||
|
||||
if err := f.CloseIssue(ctx, "o", "r", 1, "comment"); err != nil {
|
||||
t.Errorf("CloseIssue() = %v, want nil", err)
|
||||
}
|
||||
|
||||
num, err := f.CreateIssue(ctx, "o", "r", "title", "body", nil)
|
||||
if num != 0 || err != nil {
|
||||
t.Errorf("CreateIssue() = (%d, %v), want (0, nil)", num, err)
|
||||
}
|
||||
|
||||
if err := f.React(ctx, "o", "r", 1, "+1"); err != nil {
|
||||
t.Errorf("React() = %v, want nil", err)
|
||||
}
|
||||
|
||||
// SetStateLabel has no return value; just confirm it does not panic.
|
||||
f.SetStateLabel(ctx, "o", "r", 1, "label", nil)
|
||||
|
||||
prNum, err := f.CreatePR(ctx, "o", "r", "title", "head", "base", "body")
|
||||
if prNum != 0 || err != nil {
|
||||
t.Errorf("CreatePR() = (%d, %v), want (0, nil)", prNum, err)
|
||||
}
|
||||
|
||||
state, err := f.PRState(ctx, "o", "r", 1)
|
||||
if state != "closed" || err != nil {
|
||||
t.Errorf("PRState() = (%q, %v), want (\"closed\", nil)", state, err)
|
||||
}
|
||||
|
||||
if err := f.AcceptInvitations(ctx); err != nil {
|
||||
t.Errorf("AcceptInvitations() = %v, want nil", err)
|
||||
}
|
||||
|
||||
if err := f.VerifyPush(ctx, "o", "r"); err != nil {
|
||||
t.Errorf("VerifyPush() = %v, want nil", err)
|
||||
}
|
||||
|
||||
if err := f.LinkBranch(ctx, "o", "r", 1, "branch"); err != nil {
|
||||
t.Errorf("LinkBranch() = %v, want nil", err)
|
||||
}
|
||||
}
|
||||
+309
-101
@@ -1,125 +1,333 @@
|
||||
package natsrpc_test
|
||||
package natsrpc
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"log/slog"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/natsrpc"
|
||||
"github.com/nats-io/nats-server/v2/server"
|
||||
natssrv "github.com/nats-io/nats-server/v2/test"
|
||||
"github.com/nats-io/nats.go"
|
||||
)
|
||||
|
||||
func TestEnvelopeRoundTrip(t *testing.T) {
|
||||
if err := natsrpc.NewEnvelope(nil).Err(); err != nil {
|
||||
t.Errorf("NewEnvelope(nil).Err() = %v, want nil", err)
|
||||
func startEmbedded(t *testing.T) *server.Server {
|
||||
t.Helper()
|
||||
srv := natssrv.RunRandClientPortServer()
|
||||
t.Cleanup(srv.Shutdown)
|
||||
return srv
|
||||
}
|
||||
|
||||
func connect(t *testing.T, url string) *nats.Conn {
|
||||
t.Helper()
|
||||
nc, err := nats.Connect(url)
|
||||
if err != nil {
|
||||
t.Fatalf("nats connect: %v", err)
|
||||
}
|
||||
t.Cleanup(nc.Close)
|
||||
return nc
|
||||
}
|
||||
|
||||
func TestNewEnvelopeAndErr(t *testing.T) {
|
||||
if e := NewEnvelope(nil); e.Error != "" {
|
||||
t.Fatalf("NewEnvelope(nil).Error = %q, want empty", e.Error)
|
||||
}
|
||||
if err := (Envelope{}).Err(); err != nil {
|
||||
t.Fatalf("Envelope{}.Err() = %v, want nil", err)
|
||||
}
|
||||
|
||||
want := "boom"
|
||||
env := natsrpc.NewEnvelope(errBoom{want})
|
||||
if env.Error != want {
|
||||
t.Errorf("Error = %q, want %q", env.Error, want)
|
||||
wantErr := "boom"
|
||||
e := NewEnvelope(errString(wantErr))
|
||||
if e.Error != wantErr {
|
||||
t.Fatalf("NewEnvelope(err).Error = %q, want %q", e.Error, wantErr)
|
||||
}
|
||||
if got := env.Err(); got == nil || got.Error() != want {
|
||||
t.Errorf("Err() = %v, want %q", got, want)
|
||||
if got := e.Err(); got == nil || got.Error() != wantErr {
|
||||
t.Fatalf("Err() = %v, want error %q", got, wantErr)
|
||||
}
|
||||
}
|
||||
|
||||
type errBoom struct{ msg string }
|
||||
type errString string
|
||||
|
||||
func (e errBoom) Error() string { return e.msg }
|
||||
func (e errString) Error() string { return string(e) }
|
||||
|
||||
// ── Regression tests ───────────────────────────────────────────────
|
||||
func TestClientRequest(t *testing.T) {
|
||||
srv := startEmbedded(t)
|
||||
nc := connect(t, srv.ClientURL())
|
||||
|
||||
func TestNewEnvelopeEdgeCases(t *testing.T) {
|
||||
t.Run("empty error string produces nil Err", func(t *testing.T) {
|
||||
env := natsrpc.NewEnvelope(errors.New(""))
|
||||
if env.Error != "" {
|
||||
t.Errorf("empty error string should produce empty Error field, got %q", env.Error)
|
||||
}
|
||||
sub, err := nc.Subscribe("echo.subject", func(msg *nats.Msg) {
|
||||
_ = msg.Respond(append([]byte("echo:"), msg.Data...))
|
||||
})
|
||||
|
||||
t.Run("zero-value Envelope Err returns nil", func(t *testing.T) {
|
||||
var env natsrpc.Envelope
|
||||
if err := env.Err(); err != nil {
|
||||
t.Errorf("zero Envelope.Err() = %v, want nil", err)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
func TestEnvelopeJSONRoundTrip(t *testing.T) {
|
||||
// Simulate a full server→client JSON round trip through the envelope.
|
||||
type Response struct {
|
||||
natsrpc.Envelope
|
||||
Result string `json:"result,omitempty"`
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
t.Run("success response", func(t *testing.T) {
|
||||
resp := Response{Result: "ok"}
|
||||
data, err := json.Marshal(resp)
|
||||
if err != nil {
|
||||
t.Fatalf("marshal: %v", err)
|
||||
}
|
||||
var decoded Response
|
||||
if err := json.Unmarshal(data, &decoded); err != nil {
|
||||
t.Fatalf("unmarshal: %v", err)
|
||||
}
|
||||
if decoded.Result != "ok" {
|
||||
t.Errorf("Result = %q", decoded.Result)
|
||||
}
|
||||
if decoded.Err() != nil {
|
||||
t.Errorf("expected nil error, got %v", decoded.Err())
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("error response", func(t *testing.T) {
|
||||
resp := Response{Envelope: natsrpc.NewEnvelope(errors.New("request failed"))}
|
||||
data, err := json.Marshal(resp)
|
||||
if err != nil {
|
||||
t.Fatalf("marshal: %v", err)
|
||||
}
|
||||
var decoded Response
|
||||
if err := json.Unmarshal(data, &decoded); err != nil {
|
||||
t.Fatalf("unmarshal: %v", err)
|
||||
}
|
||||
if decoded.Err() == nil || decoded.Err().Error() != "request failed" {
|
||||
t.Errorf("expected error 'request failed', got %v", decoded.Err())
|
||||
}
|
||||
// Error field flattens into parent JSON.
|
||||
if decoded.Error != "request failed" {
|
||||
t.Errorf("Error = %q", decoded.Error)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
func TestClientRequestTimeoutFallback(t *testing.T) {
|
||||
// Without a real NATS connection, we can test the context deadline
|
||||
// fallback logic by checking what Client.Request does with a nil conn.
|
||||
// It panics on nil, but we can verify the timeout is computed correctly
|
||||
// by testing the context setup logic indirectly.
|
||||
|
||||
// Client with no deadline on ctx and Timeout > 0 should call
|
||||
// context.WithTimeout.
|
||||
c := &natsrpc.Client{Timeout: 100 * time.Millisecond}
|
||||
ctx := context.Background()
|
||||
// Since Conn is nil, this will panic. But the context setup happens
|
||||
// before the panic, so verifying the context has a deadline is what
|
||||
// matters. We can't easily test without a mock NATS, so validate the
|
||||
// Client struct accepts the Timeout.
|
||||
if c.Timeout != 100*time.Millisecond {
|
||||
t.Errorf("Timeout = %v", c.Timeout)
|
||||
if err := nc.Flush(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
_ = ctx
|
||||
}
|
||||
t.Cleanup(func() { _ = sub.Unsubscribe() })
|
||||
|
||||
func TestRegisterAllRollbackOnError(t *testing.T) {
|
||||
// RegisterAll should unsubscribe already-registered handlers when a
|
||||
// later registration fails. Without a real NATS connection we verify
|
||||
// the function signature and zero-registrations case.
|
||||
unsub, err := natsrpc.RegisterAll(nil, []natsrpc.Registration{})
|
||||
if unsub == nil && err == nil {
|
||||
// Both nil is fine for empty regs with nil conn.
|
||||
} else {
|
||||
t.Logf("RegisterAll with nil conn and empty regs: err=%v", err)
|
||||
c := &Client{Conn: nc, Timeout: 2 * time.Second}
|
||||
reply, err := c.Request(context.Background(), "echo.subject", []byte("hi"))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if string(reply) != "echo:hi" {
|
||||
t.Fatalf("reply = %q, want %q", reply, "echo:hi")
|
||||
}
|
||||
}
|
||||
|
||||
func TestClientRequestNoResponders(t *testing.T) {
|
||||
srv := startEmbedded(t)
|
||||
nc := connect(t, srv.ClientURL())
|
||||
|
||||
c := &Client{Conn: nc, Timeout: 200 * time.Millisecond}
|
||||
if _, err := c.Request(context.Background(), "nobody.listening", []byte("hi")); err == nil {
|
||||
t.Fatal("Request() error = nil, want error when no responder is subscribed")
|
||||
}
|
||||
}
|
||||
|
||||
func TestClientRequestUsesContextDeadlineWhenSet(t *testing.T) {
|
||||
srv := startEmbedded(t)
|
||||
nc := connect(t, srv.ClientURL())
|
||||
|
||||
c := &Client{Conn: nc, Timeout: 10 * time.Second} // large default, ctx deadline should win
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 50*time.Millisecond)
|
||||
defer cancel()
|
||||
|
||||
start := time.Now()
|
||||
_, err := c.Request(ctx, "nobody.listening.either", []byte("hi"))
|
||||
elapsed := time.Since(start)
|
||||
if err == nil {
|
||||
t.Fatal("Request() error = nil, want error (no responder)")
|
||||
}
|
||||
if elapsed > 2*time.Second {
|
||||
t.Fatalf("Request() took %v, want it to respect the short context deadline rather than the 10s client timeout", elapsed)
|
||||
}
|
||||
}
|
||||
|
||||
type callReq struct {
|
||||
Value string `json:"value"`
|
||||
}
|
||||
|
||||
type callResp struct {
|
||||
Envelope
|
||||
Echo string `json:"echo"`
|
||||
}
|
||||
|
||||
func TestCallMarshalsRequestAndUnmarshalsResponse(t *testing.T) {
|
||||
srv := startEmbedded(t)
|
||||
nc := connect(t, srv.ClientURL())
|
||||
|
||||
sub, err := nc.Subscribe("call.subject", func(msg *nats.Msg) {
|
||||
var req callReq
|
||||
if err := json.Unmarshal(msg.Data, &req); err != nil {
|
||||
_ = msg.Respond([]byte(`{"error":"bad request"}`))
|
||||
return
|
||||
}
|
||||
resp := callResp{Echo: req.Value}
|
||||
data, _ := json.Marshal(resp)
|
||||
_ = msg.Respond(data)
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := nc.Flush(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
t.Cleanup(func() { _ = sub.Unsubscribe() })
|
||||
|
||||
c := &Client{Conn: nc, Timeout: 2 * time.Second}
|
||||
resp, err := Call[callResp](context.Background(), c, "call.subject", callReq{Value: "hello"})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if resp.Echo != "hello" {
|
||||
t.Fatalf("resp.Echo = %q, want %q", resp.Echo, "hello")
|
||||
}
|
||||
if err := resp.Err(); err != nil {
|
||||
t.Fatalf("resp.Err() = %v, want nil", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestCallPropagatesEnvelopeError(t *testing.T) {
|
||||
srv := startEmbedded(t)
|
||||
nc := connect(t, srv.ClientURL())
|
||||
|
||||
sub, err := nc.Subscribe("call.error", func(msg *nats.Msg) {
|
||||
_ = msg.Respond([]byte(`{"error":"handler failed"}`))
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := nc.Flush(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
t.Cleanup(func() { _ = sub.Unsubscribe() })
|
||||
|
||||
c := &Client{Conn: nc, Timeout: 2 * time.Second}
|
||||
resp, err := Call[callResp](context.Background(), c, "call.error", callReq{Value: "x"})
|
||||
if err != nil {
|
||||
t.Fatalf("Call() transport error = %v, want nil (envelope errors are not transport errors)", err)
|
||||
}
|
||||
if envErr := resp.Err(); envErr == nil || envErr.Error() != "handler failed" {
|
||||
t.Fatalf("resp.Err() = %v, want \"handler failed\"", envErr)
|
||||
}
|
||||
}
|
||||
|
||||
func TestCallUnmarshalError(t *testing.T) {
|
||||
srv := startEmbedded(t)
|
||||
nc := connect(t, srv.ClientURL())
|
||||
|
||||
sub, err := nc.Subscribe("call.badjson", func(msg *nats.Msg) {
|
||||
_ = msg.Respond([]byte("not json"))
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := nc.Flush(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
t.Cleanup(func() { _ = sub.Unsubscribe() })
|
||||
|
||||
c := &Client{Conn: nc, Timeout: 2 * time.Second}
|
||||
if _, err := Call[callResp](context.Background(), c, "call.badjson", callReq{Value: "x"}); err == nil {
|
||||
t.Fatal("Call() error = nil, want decode error for invalid JSON reply")
|
||||
}
|
||||
}
|
||||
|
||||
func TestCallMarshalError(t *testing.T) {
|
||||
srv := startEmbedded(t)
|
||||
nc := connect(t, srv.ClientURL())
|
||||
c := &Client{Conn: nc, Timeout: 2 * time.Second}
|
||||
|
||||
// A channel cannot be marshalled to JSON, so Call must fail before ever
|
||||
// sending a request.
|
||||
if _, err := Call[callResp](context.Background(), c, "call.never-reached", make(chan int)); err == nil {
|
||||
t.Fatal("Call() error = nil, want encode error for unmarshalable request")
|
||||
}
|
||||
}
|
||||
|
||||
func TestRegisterAllSubscribesAndFlushes(t *testing.T) {
|
||||
srv := startEmbedded(t)
|
||||
nc := connect(t, srv.ClientURL())
|
||||
|
||||
var calledA, calledB bool
|
||||
regs := []Registration{
|
||||
{Subject: "reg.a", Handler: func(msg *nats.Msg) { calledA = true; _ = msg.Respond(nil) }},
|
||||
{Subject: "reg.b", Handler: func(msg *nats.Msg) { calledB = true; _ = msg.Respond(nil) }},
|
||||
}
|
||||
|
||||
unsubscribe, err := RegisterAll(nc, regs)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
t.Cleanup(unsubscribe)
|
||||
|
||||
if _, err := nc.Request("reg.a", nil, time.Second); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := nc.Request("reg.b", nil, time.Second); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if !calledA || !calledB {
|
||||
t.Fatalf("calledA=%t calledB=%t, want both true", calledA, calledB)
|
||||
}
|
||||
|
||||
unsubscribe()
|
||||
if _, err := nc.Request("reg.a", nil, 200*time.Millisecond); err == nil {
|
||||
t.Fatal("Request() after unsubscribe error = nil, want no-responder error")
|
||||
}
|
||||
}
|
||||
|
||||
func TestRegisterAllRollsBackOnPartialFailure(t *testing.T) {
|
||||
srv := startEmbedded(t)
|
||||
nc := connect(t, srv.ClientURL())
|
||||
|
||||
regs := []Registration{
|
||||
{Subject: "reg.ok", Handler: func(msg *nats.Msg) { _ = msg.Respond(nil) }},
|
||||
// An empty subject is invalid and Subscribe rejects it, forcing the
|
||||
// rollback path.
|
||||
{Subject: "", Handler: func(msg *nats.Msg) {}},
|
||||
}
|
||||
|
||||
if _, err := RegisterAll(nc, regs); err == nil {
|
||||
t.Fatal("RegisterAll() error = nil, want error for invalid subject")
|
||||
}
|
||||
|
||||
// The first, valid subscription must have been rolled back too.
|
||||
if _, err := nc.Request("reg.ok", nil, 200*time.Millisecond); err == nil {
|
||||
t.Fatal("Request(\"reg.ok\") after rollback error = nil, want no-responder error")
|
||||
}
|
||||
}
|
||||
|
||||
func TestRespondSuccess(t *testing.T) {
|
||||
srv := startEmbedded(t)
|
||||
nc := connect(t, srv.ClientURL())
|
||||
|
||||
sub, err := nc.Subscribe("respond.subject", func(msg *nats.Msg) {
|
||||
Respond(msg, slog.New(slog.DiscardHandler), "test", callResp{Echo: "ok"})
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := nc.Flush(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
t.Cleanup(func() { _ = sub.Unsubscribe() })
|
||||
|
||||
reply, err := nc.Request("respond.subject", nil, time.Second)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
var resp callResp
|
||||
if err := json.Unmarshal(reply.Data, &resp); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if resp.Echo != "ok" {
|
||||
t.Fatalf("resp.Echo = %q, want %q", resp.Echo, "ok")
|
||||
}
|
||||
}
|
||||
|
||||
func TestRespondEncodeFailureDoesNotPanic(t *testing.T) {
|
||||
srv := startEmbedded(t)
|
||||
nc := connect(t, srv.ClientURL())
|
||||
|
||||
sub, err := nc.Subscribe("respond.badvalue", func(msg *nats.Msg) {
|
||||
// A channel cannot be marshalled to JSON; Respond must log and
|
||||
// return rather than respond or panic.
|
||||
Respond(msg, slog.New(slog.DiscardHandler), "test", make(chan int))
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := nc.Flush(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
t.Cleanup(func() { _ = sub.Unsubscribe() })
|
||||
|
||||
if _, err := nc.Request("respond.badvalue", nil, 200*time.Millisecond); err == nil {
|
||||
t.Fatal("Request() error = nil, want timeout since Respond never replies on encode failure")
|
||||
}
|
||||
}
|
||||
|
||||
func TestRespondWithNilLoggerDoesNotPanic(t *testing.T) {
|
||||
srv := startEmbedded(t)
|
||||
nc := connect(t, srv.ClientURL())
|
||||
|
||||
sub, err := nc.Subscribe("respond.nillogger", func(msg *nats.Msg) {
|
||||
Respond(msg, nil, "test", make(chan int))
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := nc.Flush(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
t.Cleanup(func() { _ = sub.Unsubscribe() })
|
||||
|
||||
// Just confirm the subscriber survives a nil logger without panicking;
|
||||
// no reply is expected on encode failure.
|
||||
if _, err := nc.Request("respond.nillogger", nil, 200*time.Millisecond); err == nil {
|
||||
t.Fatal("Request() error = nil, want timeout")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,83 @@
|
||||
package enginehost
|
||||
|
||||
import (
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestRun(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
cmd string
|
||||
args []string
|
||||
want string
|
||||
wantErr bool
|
||||
}{
|
||||
{
|
||||
name: "trims stdout",
|
||||
cmd: "echo",
|
||||
args: []string{" hello world "},
|
||||
want: "hello world",
|
||||
},
|
||||
{
|
||||
name: "multi-word args",
|
||||
cmd: "printf",
|
||||
args: []string{"%s-%s", "a", "b"},
|
||||
want: "a-b",
|
||||
},
|
||||
{
|
||||
name: "nonexistent binary",
|
||||
cmd: "definitely-not-a-real-binary-archie-core-test",
|
||||
args: nil,
|
||||
wantErr: true,
|
||||
},
|
||||
{
|
||||
name: "non-zero exit",
|
||||
cmd: "false",
|
||||
args: nil,
|
||||
wantErr: true,
|
||||
},
|
||||
}
|
||||
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
got, err := Run(tt.cmd, tt.args)
|
||||
if tt.wantErr {
|
||||
if err == nil {
|
||||
t.Fatalf("Run(%q, %v) error = nil, want error", tt.cmd, tt.args)
|
||||
}
|
||||
return
|
||||
}
|
||||
if err != nil {
|
||||
t.Fatalf("Run(%q, %v) error = %v, want nil", tt.cmd, tt.args, err)
|
||||
}
|
||||
if got != tt.want {
|
||||
t.Fatalf("Run(%q, %v) = %q, want %q", tt.cmd, tt.args, got, tt.want)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestRunErrorWrapsCommandName(t *testing.T) {
|
||||
_, err := Run("false", nil)
|
||||
if err == nil {
|
||||
t.Fatal("Run() error = nil, want error")
|
||||
}
|
||||
if !strings.Contains(err.Error(), "run false") {
|
||||
t.Fatalf("Run() error = %v, want it to mention the command name", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestSymbolsExposesRun(t *testing.T) {
|
||||
pkg, ok := Symbols["github.com/samcharles93/archie-core/internal/secret/enginehost/enginehost"]
|
||||
if !ok {
|
||||
t.Fatal("Symbols missing the enginehost package entry")
|
||||
}
|
||||
fn, ok := pkg["Run"]
|
||||
if !ok {
|
||||
t.Fatal("Symbols missing Run")
|
||||
}
|
||||
if fn.Kind().String() != "func" {
|
||||
t.Fatalf("Symbols[\"Run\"].Kind() = %v, want func", fn.Kind())
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,57 @@
|
||||
package secretextract
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestEngineWrapperDelegatesToFields(t *testing.T) {
|
||||
w := _github_com_samcharles93_archie_core_internal_secret_Engine{
|
||||
WName: func() string { return "vault" },
|
||||
WVersion: func() string { return "1.0" },
|
||||
WResolve: func(key string) (string, error) { return "resolved:" + key, nil },
|
||||
}
|
||||
|
||||
if got, want := w.Name(), "vault"; got != want {
|
||||
t.Errorf("Name() = %q, want %q", got, want)
|
||||
}
|
||||
if got, want := w.Version(), "1.0"; got != want {
|
||||
t.Errorf("Version() = %q, want %q", got, want)
|
||||
}
|
||||
got, err := w.Resolve("key")
|
||||
if err != nil {
|
||||
t.Fatalf("Resolve() error = %v, want nil", err)
|
||||
}
|
||||
if want := "resolved:key"; got != want {
|
||||
t.Errorf("Resolve() = %q, want %q", got, want)
|
||||
}
|
||||
}
|
||||
|
||||
func TestEngineWrapperResolvePropagatesError(t *testing.T) {
|
||||
wantErr := errors.New("boom")
|
||||
w := _github_com_samcharles93_archie_core_internal_secret_Engine{
|
||||
WResolve: func(key string) (string, error) { return "", wantErr },
|
||||
}
|
||||
_, err := w.Resolve("key")
|
||||
if !errors.Is(err, wantErr) {
|
||||
t.Fatalf("Resolve() error = %v, want %v", err, wantErr)
|
||||
}
|
||||
}
|
||||
|
||||
func TestEngineWrapperNilGuards(t *testing.T) {
|
||||
// The zero-value wrapper (all function fields nil) must not panic; this
|
||||
// is the nil-guard behaviour TestGeneratedWrapperHasNilGuards protects
|
||||
// against regenerate wiping out (see package doc comment).
|
||||
var w _github_com_samcharles93_archie_core_internal_secret_Engine
|
||||
|
||||
if got, want := w.Name(), ""; got != want {
|
||||
t.Errorf("Name() with nil WName = %q, want %q", got, want)
|
||||
}
|
||||
if got, want := w.Version(), ""; got != want {
|
||||
t.Errorf("Version() with nil WVersion = %q, want %q", got, want)
|
||||
}
|
||||
got, err := w.Resolve("key")
|
||||
if got != "" || err != nil {
|
||||
t.Errorf("Resolve() with nil WResolve = (%q, %v), want (\"\", nil)", got, err)
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user