Shared Atlassian clients: atlassian/jira and atlassian/confluence
New library module yetano.dev/yetano/yetano-clients (owner decision 2026-11-01) replacing the three own Jira clients in yareco, yabaratla and yamcp: - atlassian: Options, Auth (api_token, basic, bearer/pat, cookie), Deployment (Cloud/Data Center), TLS, APIError and sentinel errors. - atlassian/internal/transport: retry with backoff on 5xx/connection errors, shared adaptive 429 throttle honouring Retry-After (from yabaratla/yareco), CA file, proxy, cross-host redirect hardening, response cap (from yamcp), startAt pagination, file downloads. - atlassian/jira: typed reads (projects, versions, fields, issues, comments, changelog, editmeta, transitions), JQL search on Cloud (/search/jql) and Data Center, classic search pages, issue writes, ADF/plain-text bodies per deployment, custom-field helpers. - atlassian/confluence: small content API client (CQL search, pages, spaces, current user, create/update page with version check, comment, label), taken over from yamcp. Standard library only; tests against httptest servers. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
commit
6a97dbd4c6
24 files changed
+3524
No files matched your search
@@ -0,0 +1,358 @@
|
||||
package jira
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"log/slog"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"yetano.dev/yetano/yetano-clients/atlassian"
|
||||
)
|
||||
|
||||
func newTestClient(t *testing.T, h http.HandlerFunc, dep atlassian.Deployment) *Client {
|
||||
t.Helper()
|
||||
srv := httptest.NewServer(h)
|
||||
t.Cleanup(srv.Close)
|
||||
c, err := New(atlassian.Options{BaseURL: srv.URL + "/", Deployment: dep, MaxRetries: 1,
|
||||
Auth: atlassian.Auth{Type: atlassian.AuthAPIToken, Username: "e@example.com", Password: "t"},
|
||||
Logger: slog.New(slog.NewTextHandler(io.Discard, nil))})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
c.SetSleep(func(ctx context.Context, _ time.Duration) error { return ctx.Err() })
|
||||
return c
|
||||
}
|
||||
|
||||
func TestAPIPrefixByDeployment(t *testing.T) {
|
||||
noop := func(http.ResponseWriter, *http.Request) {}
|
||||
if p := newTestClient(t, noop, "").APIPrefix(); p != "/rest/api/3" {
|
||||
t.Errorf("zero deployment prefix = %q, want Cloud's /rest/api/3", p)
|
||||
}
|
||||
if p := newTestClient(t, noop, atlassian.DataCenter).APIPrefix(); p != "/rest/api/2" {
|
||||
t.Errorf("datacenter prefix = %q", p)
|
||||
}
|
||||
}
|
||||
|
||||
func TestSearchCloudFollowsNextPageToken(t *testing.T) {
|
||||
var bodies []map[string]any
|
||||
c := newTestClient(t, func(w http.ResponseWriter, r *http.Request) {
|
||||
if r.Method != http.MethodPost || r.URL.Path != "/rest/api/3/search/jql" {
|
||||
t.Errorf("unexpected %s %s", r.Method, r.URL.Path)
|
||||
}
|
||||
var body map[string]any
|
||||
_ = json.NewDecoder(r.Body).Decode(&body)
|
||||
bodies = append(bodies, body)
|
||||
if body["nextPageToken"] == nil {
|
||||
fmt.Fprint(w, `{"issues":[{"key":"DEV-1","fields":{"summary":"a","customfield_1":[{"value":"PI28.15"}]}}],"nextPageToken":"p2"}`)
|
||||
return
|
||||
}
|
||||
fmt.Fprint(w, `{"issues":[{"key":"DEV-2","fields":{"summary":"b"}}],"isLast":true}`)
|
||||
}, atlassian.Cloud)
|
||||
issues, err := c.SearchAll(context.Background(), SearchQuery{JQL: "project = DEV", Fields: []string{"summary", "customfield_1"}, PageSize: 1})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if len(issues) != 2 || issues[0].Key != "DEV-1" || issues[1].Key != "DEV-2" {
|
||||
t.Fatalf("issues = %+v", issues)
|
||||
}
|
||||
if bodies[1]["nextPageToken"] != "p2" || bodies[0]["maxResults"].(float64) != 1 {
|
||||
t.Errorf("request bodies = %v", bodies)
|
||||
}
|
||||
pis, err := OptionValues(issues[0].Fields.Raw["customfield_1"])
|
||||
if err != nil || len(pis) != 1 || pis[0] != "PI28.15" {
|
||||
t.Errorf("custom field = %v, %v", pis, err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestSearchDataCenterUsesOffsets(t *testing.T) {
|
||||
var starts []float64
|
||||
c := newTestClient(t, func(w http.ResponseWriter, r *http.Request) {
|
||||
if r.URL.Path != "/rest/api/2/search" {
|
||||
t.Errorf("unexpected path %s", r.URL.Path)
|
||||
}
|
||||
var body map[string]any
|
||||
_ = json.NewDecoder(r.Body).Decode(&body)
|
||||
start := body["startAt"].(float64)
|
||||
starts = append(starts, start)
|
||||
if exp, _ := body["expand"].([]any); len(exp) != 2 {
|
||||
t.Errorf("expand = %v, want a list of 2", body["expand"])
|
||||
}
|
||||
fmt.Fprintf(w, `{"startAt":%v,"total":3,"issues":[{"key":"OPS-%v"},{"key":"OPS-x"}]}`, start, start)
|
||||
}, atlassian.DataCenter)
|
||||
issues, err := c.SearchAll(context.Background(), SearchQuery{JQL: "project = OPS", PageSize: 2, Expand: "renderedFields, changelog"})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if len(issues) != 4 || len(starts) != 2 || starts[1] != 2 {
|
||||
t.Errorf("issues = %d, starts = %v", len(issues), starts)
|
||||
}
|
||||
}
|
||||
|
||||
func TestSearchPageClassic(t *testing.T) {
|
||||
c := newTestClient(t, func(w http.ResponseWriter, r *http.Request) {
|
||||
if r.URL.Path != "/rest/api/3/search" {
|
||||
t.Errorf("unexpected path %s", r.URL.Path)
|
||||
}
|
||||
var body PageQuery
|
||||
_ = json.NewDecoder(r.Body).Decode(&body)
|
||||
if body.JQL != "project = OPS" || body.MaxResults != 25 || body.StartAt != 25 {
|
||||
t.Errorf("body = %+v", body)
|
||||
}
|
||||
fmt.Fprint(w, `{"startAt":25,"maxResults":25,"total":100,"issues":[{"key":"OPS-1","fields":{"summary":"first"}}]}`)
|
||||
}, atlassian.Cloud)
|
||||
res, err := c.SearchPage(context.Background(), PageQuery{JQL: "project = OPS", StartAt: 25, MaxResults: 25})
|
||||
if err != nil || res.Total != 100 || len(res.Issues) != 1 || res.Issues[0].Fields.Summary != "first" {
|
||||
t.Fatalf("res = %+v, %v", res, err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestEmptyArgumentsSendNothing(t *testing.T) {
|
||||
c := newTestClient(t, func(w http.ResponseWriter, r *http.Request) {
|
||||
t.Errorf("request sent: %s %s", r.Method, r.URL.Path)
|
||||
}, atlassian.Cloud)
|
||||
ctx := context.Background()
|
||||
checks := map[string]error{}
|
||||
_, checks["Issue"] = c.Issue(ctx, "", nil)
|
||||
_, checks["Project"] = c.Project(ctx, "")
|
||||
_, checks["SearchPage"] = c.SearchPage(ctx, PageQuery{})
|
||||
checks["Search"] = c.Search(ctx, SearchQuery{JQL: " "}, func([]Issue) error { return nil })
|
||||
checks["EditIssue"] = c.EditIssue(ctx, "", IssueEdit{})
|
||||
for name, err := range checks {
|
||||
if !errors.Is(err, atlassian.ErrInvalidArgument) {
|
||||
t.Errorf("%s: err = %v, want ErrInvalidArgument", name, err)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestListProjectsPerDeployment(t *testing.T) {
|
||||
var paths []string
|
||||
cloud := newTestClient(t, func(w http.ResponseWriter, r *http.Request) {
|
||||
paths = append(paths, r.URL.Path+"?"+r.URL.Query().Get("orderBy")+"@"+r.URL.Query().Get("startAt"))
|
||||
if r.URL.Query().Get("startAt") == "0" {
|
||||
fmt.Fprint(w, `{"isLast":false,"values":[{"id":"1","key":"DEV","name":"Development","projectTypeKey":"software"}]}`)
|
||||
return
|
||||
}
|
||||
fmt.Fprint(w, `{"isLast":true,"values":[{"id":"2","key":"OPS","projectTypeKey":"service_desk"}]}`)
|
||||
}, atlassian.Cloud)
|
||||
got, err := cloud.ListProjects(context.Background())
|
||||
if err != nil || len(got) != 2 || got[1].ProjectTypeKey != "service_desk" {
|
||||
t.Fatalf("cloud projects = %+v, %v", got, err)
|
||||
}
|
||||
if strings.Join(paths, ",") != "/rest/api/3/project/search?key@0,/rest/api/3/project/search?key@1" {
|
||||
t.Errorf("cloud requests = %v", paths)
|
||||
}
|
||||
|
||||
dc := newTestClient(t, func(w http.ResponseWriter, r *http.Request) {
|
||||
if r.URL.Path != "/rest/api/2/project" {
|
||||
t.Errorf("datacenter path = %s", r.URL.Path)
|
||||
}
|
||||
fmt.Fprint(w, `[{"key":"OPS"}]`)
|
||||
}, atlassian.DataCenter)
|
||||
if got, err := dc.ListProjects(context.Background()); err != nil || len(got) != 1 {
|
||||
t.Fatalf("dc projects = %+v, %v", got, err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestCommentsFromOffset(t *testing.T) {
|
||||
c := newTestClient(t, func(w http.ResponseWriter, r *http.Request) {
|
||||
q := r.URL.Query()
|
||||
if q.Get("startAt") != "2" || q.Get("orderBy") != "created" {
|
||||
t.Errorf("query = %v", q)
|
||||
}
|
||||
fmt.Fprint(w, `{"total":3,"comments":[{"id":"3","created":"2026-05-01T10:00:00.000+0200"}]}`)
|
||||
}, atlassian.Cloud)
|
||||
cs, err := c.Comments(context.Background(), "DEV-1", 2)
|
||||
if err != nil || len(cs) != 1 || cs[0].ID != "3" {
|
||||
t.Fatalf("comments = %+v, %v", cs, err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestEditIssueSendsOnlyNonEmptyParts(t *testing.T) {
|
||||
var got []string
|
||||
c := newTestClient(t, func(w http.ResponseWriter, r *http.Request) {
|
||||
b, _ := io.ReadAll(r.Body)
|
||||
got = append(got, string(b))
|
||||
w.WriteHeader(http.StatusNoContent)
|
||||
}, atlassian.Cloud)
|
||||
ctx := context.Background()
|
||||
if err := c.EditIssue(ctx, "DEV-1", IssueEdit{Update: map[string][]map[string]any{"labels": {{"add": "x"}}}}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := c.UpdateIssue(ctx, "DEV-1", map[string]any{"summary": "s"}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if got[0] != `{"update":{"labels":[{"add":"x"}]}}` || got[1] != `{"fields":{"summary":"s"}}` {
|
||||
t.Errorf("bodies = %v", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestWritesPerDeployment(t *testing.T) {
|
||||
for _, dep := range []atlassian.Deployment{atlassian.Cloud, atlassian.DataCenter} {
|
||||
var bodies = map[string]map[string]any{}
|
||||
c := newTestClient(t, func(w http.ResponseWriter, r *http.Request) {
|
||||
var body map[string]any
|
||||
_ = json.NewDecoder(r.Body).Decode(&body)
|
||||
bodies[r.Method+" "+r.URL.Path] = body
|
||||
switch {
|
||||
case strings.HasSuffix(r.URL.Path, "/comment"):
|
||||
fmt.Fprint(w, `{"id":"77"}`)
|
||||
case strings.HasSuffix(r.URL.Path, "/issue"):
|
||||
fmt.Fprint(w, `{"id":"1","key":"OPS-9"}`)
|
||||
default:
|
||||
w.WriteHeader(http.StatusNoContent)
|
||||
}
|
||||
}, dep)
|
||||
ctx := context.Background()
|
||||
key, err := c.CreateIssue(ctx, CreateIssueInput{ProjectKey: "OPS", IssueType: "Task", Summary: "s", Description: "d", ParentKey: "OPS-1"})
|
||||
if err != nil || key != "OPS-9" {
|
||||
t.Fatalf("%s: create = %q, %v", dep, key, err)
|
||||
}
|
||||
id, err := c.AddComment(ctx, "OPS-9", "hello")
|
||||
if err != nil || id != "77" {
|
||||
t.Fatalf("%s: comment = %q, %v", dep, id, err)
|
||||
}
|
||||
if err := c.AssignIssue(ctx, "OPS-9", ""); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := c.DoTransition(ctx, "OPS-9", "31"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := c.LinkIssues(ctx, "Blocks", "OPS-1", "OPS-9"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
p := c.APIPrefix()
|
||||
fields := bodies["POST "+p+"/issue"]["fields"].(map[string]any)
|
||||
desc := fields["description"]
|
||||
comment := bodies["POST "+p+"/issue/OPS-9/comment"]["body"]
|
||||
assign := bodies["PUT "+p+"/issue/OPS-9/assignee"]
|
||||
if dep == atlassian.Cloud {
|
||||
if m, ok := desc.(map[string]any); !ok || m["type"] != "doc" {
|
||||
t.Errorf("cloud description = %v, want ADF", desc)
|
||||
}
|
||||
if _, ok := comment.(map[string]any); !ok {
|
||||
t.Errorf("cloud comment = %v, want ADF", comment)
|
||||
}
|
||||
if v, ok := assign["accountId"]; !ok || v != nil {
|
||||
t.Errorf("cloud unassign = %v, want accountId null", assign)
|
||||
}
|
||||
} else {
|
||||
if desc != "d" || comment != "hello" {
|
||||
t.Errorf("dc description/comment = %v / %v, want plain strings", desc, comment)
|
||||
}
|
||||
if v, ok := assign["name"]; !ok || v != nil {
|
||||
t.Errorf("dc unassign = %v, want name null", assign)
|
||||
}
|
||||
}
|
||||
if fields["parent"].(map[string]any)["key"] != "OPS-1" {
|
||||
t.Errorf("parent = %v", fields["parent"])
|
||||
}
|
||||
if tr := bodies["POST "+p+"/issue/OPS-9/transitions"]["transition"].(map[string]any); tr["id"] != "31" {
|
||||
t.Errorf("transition = %v", tr)
|
||||
}
|
||||
if l := bodies["POST "+p+"/issueLink"]; l["type"].(map[string]any)["name"] != "Blocks" {
|
||||
t.Errorf("link = %v", l)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestEditMetaAndTransitions(t *testing.T) {
|
||||
c := newTestClient(t, func(w http.ResponseWriter, r *http.Request) {
|
||||
switch r.URL.Path {
|
||||
case "/rest/api/3/issue/DEV-1/editmeta":
|
||||
fmt.Fprint(w, `{"fields":{"components":{"operations":["add","set","remove"]}}}`)
|
||||
case "/rest/api/3/issue/DEV-1/transitions":
|
||||
fmt.Fprint(w, `{"transitions":[{"id":"31","name":"Done","to":{"name":"Done"}}]}`)
|
||||
default:
|
||||
t.Errorf("unexpected %s", r.URL.Path)
|
||||
}
|
||||
}, atlassian.Cloud)
|
||||
meta, err := c.EditMeta(context.Background(), "DEV-1")
|
||||
if err != nil || len(meta["components"]) != 3 {
|
||||
t.Fatalf("editmeta = %v, %v", meta, err)
|
||||
}
|
||||
trs, err := c.Transitions(context.Background(), "DEV-1")
|
||||
if err != nil || len(trs) != 1 || trs[0].To.StatusName() != "Done" {
|
||||
t.Fatalf("transitions = %+v, %v", trs, err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestIssueRoundTripKeepsRawFields(t *testing.T) {
|
||||
in := `{"id":"1","key":"DEV-1","fields":{"summary":"s","customfield_9":{"value":"x"},"parent":{"key":"DEV-0"},"subtasks":[{"key":"DEV-2"}]}}`
|
||||
var is Issue
|
||||
if err := json.Unmarshal([]byte(in), &is); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if is.Fields.Parent.Key != "DEV-0" || len(is.Fields.Subtasks) != 1 || is.Fields.Raw["customfield_9"] == nil {
|
||||
t.Fatalf("issue = %+v", is)
|
||||
}
|
||||
out, _ := json.Marshal(is)
|
||||
if !strings.Contains(string(out), `"customfield_9":{"value":"x"}`) {
|
||||
t.Errorf("round trip lost a custom field: %s", out)
|
||||
}
|
||||
}
|
||||
|
||||
func TestOptionValuesShapes(t *testing.T) {
|
||||
cases := map[string][]string{
|
||||
`null`: nil,
|
||||
`"PI28.15"`: {"PI28.15"},
|
||||
`["PI28.15","PI28.22"]`: {"PI28.15", "PI28.22"},
|
||||
`{"value":"PI29.2"}`: {"PI29.2"},
|
||||
`{"name":"label"}`: {"label"},
|
||||
`[{"value":"PI29.2"},{"value":"PI29.3"}]`: {"PI29.2", "PI29.3"},
|
||||
}
|
||||
for in, want := range cases {
|
||||
got, err := OptionValues(json.RawMessage(in))
|
||||
if err != nil || strings.Join(got, "|") != strings.Join(want, "|") {
|
||||
t.Errorf("OptionValues(%s) = %v, %v; want %v", in, got, err, want)
|
||||
}
|
||||
}
|
||||
for _, bad := range []string{`{"foo":1}`, `42`} {
|
||||
if _, err := OptionValues(json.RawMessage(bad)); err == nil {
|
||||
t.Errorf("OptionValues(%s): unexpected shape must be an error", bad)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestSprintValuesShapes(t *testing.T) {
|
||||
cases := map[string]string{
|
||||
`null`: "",
|
||||
`[]`: "",
|
||||
`[{"id":1,"name":"Sprint 41","state":"closed","boardId":3},{"id":2,"name":"Sprint 42","state":"ACTIVE"}]`: "Sprint 41/closed|Sprint 42/active",
|
||||
`["com.atlassian.greenhopper.service.sprint.Sprint@1a2b[id=7,rapidViewId=3,state=FUTURE,name=Sprint 43,startDate=<null>]"]`: "Sprint 43/future",
|
||||
}
|
||||
for in, want := range cases {
|
||||
got, err := SprintValues(json.RawMessage(in))
|
||||
var parts []string
|
||||
for _, sp := range got {
|
||||
parts = append(parts, sp.Name+"/"+sp.State)
|
||||
}
|
||||
if err != nil || strings.Join(parts, "|") != want {
|
||||
t.Errorf("SprintValues(%s) = %v, %v; want %s", in, got, err, want)
|
||||
}
|
||||
}
|
||||
for _, bad := range []string{`"Sprint 1"`, `{"name":"Sprint 1"}`, `[{"id":1}]`, `[42]`} {
|
||||
if _, err := SprintValues(json.RawMessage(bad)); err == nil {
|
||||
t.Errorf("SprintValues(%s): unexpected shape must be an error", bad)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestCustomFieldNumberAndNames(t *testing.T) {
|
||||
if n, ok := CustomFieldNumber("customfield_11411"); !ok || n != "11411" {
|
||||
t.Errorf("CustomFieldNumber = %q %v", n, ok)
|
||||
}
|
||||
if _, ok := CustomFieldNumber("summary"); ok {
|
||||
t.Error("system field reported as custom")
|
||||
}
|
||||
if got := Names([]Version{{Name: "a"}, {Name: "b"}}); strings.Join(got, ",") != "a,b" {
|
||||
t.Errorf("Names = %v", got)
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user