package confluence import ( "context" "encoding/json" "errors" "fmt" "io" "log/slog" "net/http" "net/http/httptest" "testing" "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, Auth: atlassian.Auth{Type: atlassian.AuthBearer, Token: "t"}, Logger: slog.New(slog.NewTextHandler(io.Discard, nil))}) if err != nil { t.Fatal(err) } return c } func TestPrefixesAndURLs(t *testing.T) { noop := func(http.ResponseWriter, *http.Request) {} cloud := newTestClient(t, noop, atlassian.Cloud) dc := newTestClient(t, noop, atlassian.DataCenter) if cloud.APIPrefix() != "/wiki/rest/api" || dc.APIPrefix() != "/rest/api" { t.Errorf("prefixes = %q, %q", cloud.APIPrefix(), dc.APIPrefix()) } if got := cloud.PageURL("5", &Links{WebUI: "/spaces/IT/pages/5"}); got != cloud.BaseURL()+"/wiki/spaces/IT/pages/5" { t.Errorf("PageURL with links = %q", got) } if got := dc.PageURL("5", nil); got != dc.BaseURL()+"/pages/viewpage.action?pageId=5" { t.Errorf("PageURL fallback = %q", got) } } func TestSearchBuildsCQLFromFilters(t *testing.T) { var gotCQL, gotPath string c := newTestClient(t, func(w http.ResponseWriter, r *http.Request) { gotPath, gotCQL = r.URL.Path, r.URL.Query().Get("cql") fmt.Fprint(w, `{"results":[{"id":"1","title":"A","version":{"number":2}}],"size":1}`) }, atlassian.Cloud) res, err := c.Search(context.Background(), SearchOptions{CQL: `text ~ "x"`, SpaceKey: "IT", ContentType: "page", Limit: 5}) if err != nil || len(res.Results) != 1 || res.Results[0].Version.Number != 2 { t.Fatalf("res = %+v, %v", res, err) } if gotPath != "/wiki/rest/api/content/search" || gotCQL != `text ~ "x" AND space = "IT" AND type = "page"` { t.Errorf("path = %q, cql = %q", gotPath, gotCQL) } } 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() errs := map[string]error{} _, errs["Search"] = c.Search(ctx, SearchOptions{}) _, errs["Page"] = c.Page(ctx, "") _, errs["Space"] = c.Space(ctx, "") _, errs["AddComment"] = c.AddComment(ctx, "", "x") for name, err := range errs { if !errors.Is(err, atlassian.ErrInvalidArgument) { t.Errorf("%s: err = %v, want ErrInvalidArgument", name, err) } } } func pageHandler(t *testing.T, onPut func(body map[string]any)) http.HandlerFunc { return func(w http.ResponseWriter, r *http.Request) { if r.Method == http.MethodGet { fmt.Fprint(w, `{"id":"123","title":"Page","space":{"key":"IT"},"version":{"number":5}}`) return } if onPut == nil { t.Fatalf("unexpected %s", r.Method) } var body map[string]any _ = json.NewDecoder(r.Body).Decode(&body) onPut(body) fmt.Fprint(w, `{}`) } } func TestUpdatePageRefusesStaleVersion(t *testing.T) { c := newTestClient(t, pageHandler(t, nil), atlassian.Cloud) err := c.UpdatePage(context.Background(), UpdatePageInput{ID: "123", Content: "new", ExpectedVersion: 3}) var vc *VersionConflictError if !errors.As(err, &vc) || vc.Current != 5 || vc.Expected != 3 { t.Fatalf("err = %v, want VersionConflictError 5/3", err) } } func TestUpdatePageWritesNextVersion(t *testing.T) { var put map[string]any c := newTestClient(t, pageHandler(t, func(b map[string]any) { put = b }), atlassian.Cloud) if err := c.UpdatePage(context.Background(), UpdatePageInput{ID: "123", Content: "a \n\nc", ExpectedVersion: 5}); err != nil { t.Fatal(err) } if put["version"].(map[string]any)["number"].(float64) != 6 || put["title"] != "Page" { t.Errorf("PUT = %v", put) } storage := put["body"].(map[string]any)["storage"].(map[string]any) if storage["value"] != "

a <b>

c

" || storage["representation"] != "storage" { t.Errorf("storage = %v", storage) } } func TestCreatePageCommentLabel(t *testing.T) { bodies := map[string]any{} c := newTestClient(t, func(w http.ResponseWriter, r *http.Request) { var body any _ = json.NewDecoder(r.Body).Decode(&body) key := r.Method + " " + r.URL.Path if m, ok := body.(map[string]any); ok && m["type"] == "comment" { key += " comment" } bodies[key] = body fmt.Fprint(w, `{"id":"9"}`) }, atlassian.DataCenter) ctx := context.Background() if id, err := c.CreatePage(ctx, CreatePageInput{SpaceKey: "IT", Title: "T", Content: "x", ParentPageID: "1"}); err != nil || id != "9" { t.Fatalf("create = %q, %v", id, err) } if id, err := c.AddComment(ctx, "9", "hi"); err != nil || id != "9" { t.Fatalf("comment = %q, %v", id, err) } if err := c.AddLabel(ctx, "9", "ops"); err != nil { t.Fatal(err) } page := bodies["POST /rest/api/content"].(map[string]any) if page["ancestors"].([]any)[0].(map[string]any)["id"] != "1" || page["space"].(map[string]any)["key"] != "IT" { t.Errorf("create body = %v", page) } comment := bodies["POST /rest/api/content comment"].(map[string]any) if comment["container"].(map[string]any)["id"] != "9" { t.Errorf("comment body = %v", comment) } label := bodies["POST /rest/api/content/9/label"].([]any)[0].(map[string]any) if label["prefix"] != "global" || label["name"] != "ops" { t.Errorf("label body = %v", label) } } func TestPingAndCurrentUser(t *testing.T) { c := newTestClient(t, func(w http.ResponseWriter, r *http.Request) { if r.Header.Get("Authorization") != "Bearer t" { t.Errorf("auth header = %q", r.Header.Get("Authorization")) } switch r.URL.Path { case "/wiki/rest/api/space": fmt.Fprint(w, `{"results":[],"size":0}`) case "/wiki/rest/api/user/current": fmt.Fprint(w, `{"accountId":"a1","displayName":"Ada"}`) default: w.WriteHeader(http.StatusNotFound) } }, atlassian.Cloud) if err := c.Ping(context.Background()); err != nil { t.Fatal(err) } u, err := c.CurrentUser(context.Background()) if err != nil || u.DisplayName != "Ada" { t.Fatalf("user = %+v, %v", u, err) } }