refactor(cli): envelope sweep — Emit shape, batch ops, MCP StructuredContent, api flag cleanup

Sweep every CLI output path through the v0.7 envelope contract.

FormatOptions.Emit signature changes to (w, data, meta *output.Meta)
so list commands surface meta.count / has_more in the wire envelope.
TTY indent decision plumbed via FormatOptions.TTY (set by
ResolveDefault). --format and --jq promoted to persistent root flags
so unknown-subcommand paths still reach the typed-envelope guard
(per-command registration would have rejected --format on unknown
commands as cobra-prose exit 2). WEKNORA_FORMAT env-var fallback
honored before TTY-resolved default. AddFormatFlag retained for the
per-command --jq field-hint Long-text addendum.

~55 production Emit call sites swept across cli/cmd/**: list paths
populate meta.count; mutation paths pass nil meta; envelope.profile
threaded via globalProfile. Existing JSON-shape tests migrated to
decode the envelope wrapper.

Multi-target batch operations get a unified shape via new helpers:
- output.BatchItem + output.WriteBatchEnvelope (§4.5 per-item ok
  pattern; data:[{id, ok, result?|error?}], meta:{count, successes*,
  failures*}; Successes/Failures *int so explicit zero survives
  omitempty in all-fail case).
- cmdutil.RunBatch + cmdutil.EmitBatch + cmdutil.DeletedAtNow +
  cmdutil.ClassifyContextErr collapse the three previously-duplicated
  multi-delete pipelines (doc / chunk / session) into one call site
  pattern. doc upload --recursive uses the same helpers with a per-
  file resultFn. Summary error sets Silent:true so the stderr
  envelope path doesn't duplicate the stdout batch detail (exit 1
  preserved via Code → ExitCode).

ConfirmDestructive / ConfirmDestructiveBatch extended with action +
retryCmd parameters. Every destructive command (kb delete, kb edit,
doc delete, doc delete --all, agent delete, agent edit, session
delete, chunk delete, auth logout, api -X DELETE) now attaches
error.risk.{level:"destructive", action:"<noun.verb>"} +
error.retry_command on the exit-10 envelope. kb edit / agent edit
also gain the destructive guard wiring (CHANGELOG listed them as
gated but they were silently executing without -y).

MCP tool handlers' 31 error paths return CallToolResult with
IsError + Content text fallback + StructuredContent (envelope.error
shape via cmdutil.ErrorToDetail). Handler Out type changed from
typed *sdk.X to any so the go-sdk auto-marshal doesn't overwrite
StructuredContent with a zero-struct on error returns. Success path
manually populates CallToolResult.StructuredContent via successResult
helper.

weknora api cleanup:
- -d/--data flag removed; body via --input <file> or --input -
  (stdin) only. Aligns with gh / curl convention.
- HTTP method whitelist removed; any non-empty method accepted.
- HTTP Retry-After header → cmdutil.Error.RetryAfterSeconds →
  envelope.error.retry_after_seconds.
- runAPIPaginated raw-passthrough fallback now wraps response in
  envelope so --paginate never emits bare JSON to stdout.

Test sweep: ~60 cmd/** tests migrated to decode envelope shape.
9 wire-contract goldens updated under cli/acceptance/testdata/wire/.

Spec: docs/superpowers/specs/2026-05-20-weknora-cli-v0.7-design.md §4 / §5
This commit is contained in:
nullkey
2026-05-21 18:41:56 +08:00
committed by lyingbug
parent 733bb3aaa1
commit ad150c7126
96 changed files with 2354 additions and 864 deletions
+69 -40
View File
@@ -21,7 +21,6 @@ import (
"github.com/spf13/cobra"
"github.com/Tencent/WeKnora/cli/internal/cmdutil"
"github.com/Tencent/WeKnora/cli/internal/format"
"github.com/Tencent/WeKnora/cli/internal/iostreams"
sdk "github.com/Tencent/WeKnora/client"
)
@@ -33,7 +32,6 @@ var apiFields = []string{"<response-shape-varies>"}
type Options struct {
Method string
Data string
Input string // --input: file path, "-" for stdin
Yes bool
StdinReader io.Reader // overridden by tests; defaults to iostreams.IO.In
@@ -53,18 +51,19 @@ func NewCmd(f *cmdutil.Factory) *cobra.Command {
cmd := &cobra.Command{
Use: "api <path>",
Short: "Make a raw API request to the WeKnora server",
Long: `Send an HTTP request through the SDK and print the response.
Long: `Raw HTTP API access. Body via --input <file> or --input - (stdin).
The default method is GET; passing --data / --input auto-promotes it to
POST. Use -X/--method to override (DELETE / PUT / PATCH / HEAD).
The default method is GET; passing --input auto-promotes it to POST. Use
-X/--method to override (any non-empty method is accepted: DELETE / PUT /
PATCH / HEAD / OPTIONS / TRACE / custom).
Auth, tenant, and request-id headers are applied automatically from the
active context. The response body is written to stdout by default; use
--format json to emit a {status, headers, body} JSON object.
--format json to emit a {status, headers, body} envelope.
Examples:
weknora api /api/v1/knowledge-bases # GET
weknora api /api/v1/knowledge-bases --data '{"name":"foo"}' # POST (auto)
weknora api /api/v1/knowledge-bases # GET
echo '{"name":"foo"}' | weknora api /api/v1/knowledge-bases --input - # POST (auto)
weknora api /api/v1/knowledge-bases/kb_xxx -X DELETE`,
Args: cobra.ExactArgs(1),
RunE: func(c *cobra.Command, args []string) error {
@@ -78,7 +77,7 @@ Examples:
// Escape-hatch DELETE through `weknora api` is just as destructive
// as `weknora kb delete` - exit-10 protocol must apply (cli/README.md).
if method == http.MethodDelete {
if err := cmdutil.ConfirmDestructive(f.Prompter(), opts.Yes, fopts.WantsJSON(), "endpoint", args[0]); err != nil {
if err := cmdutil.ConfirmDestructive(f.Prompter(), opts.Yes, fopts.WantsJSON(), "endpoint", args[0], "api.delete", "weknora api -X DELETE "+args[0]+" -y"); err != nil {
return err
}
}
@@ -90,12 +89,10 @@ Examples:
return runAPI(c.Context(), opts, fopts, cli, method, args[0], paginate)
},
}
cmd.Flags().StringVarP(&opts.Method, "method", "X", "", "HTTP method (default: GET, or POST when a body is supplied)")
cmd.Flags().StringVarP(&opts.Data, "data", "d", "", "Request body as raw string (e.g. JSON)")
cmd.Flags().StringVarP(&opts.Method, "method", "X", "", "HTTP method (default: GET, or POST when --input is supplied). Any non-empty method is accepted.")
cmd.Flags().StringVar(&opts.Input, "input", "", "Read request body from file (use `-` for stdin)")
cmd.Flags().Bool("paginate", false, "Follow offset-based pagination (?page=N&page_size=M), merging all pages into a single {data, total} JSON response.")
cmdutil.AddFormatFlag(cmd, apiFields...)
cmd.MarkFlagsMutuallyExclusive("data", "input")
return cmd
}
@@ -127,7 +124,7 @@ func resolveMethod(opts *Options) string {
if opts.Method != "" {
return strings.ToUpper(opts.Method)
}
if opts.Data != "" || opts.Input != "" {
if opts.Input != "" {
return "POST"
}
return "GET"
@@ -151,23 +148,16 @@ func runAPI(ctx context.Context, opts *Options, fopts *cmdutil.FormatOptions, sv
// runAPISingle is the original single-call implementation of runAPI.
func runAPISingle(ctx context.Context, opts *Options, fopts *cmdutil.FormatOptions, svc Service, method, path string) error {
switch method {
case http.MethodGet, http.MethodPost, http.MethodPut,
http.MethodPatch, http.MethodDelete, http.MethodHead:
default:
return cmdutil.NewError(cmdutil.CodeInputInvalidArgument, fmt.Sprintf("unsupported method: %s", method))
if method == "" {
return cmdutil.NewFlagError(fmt.Errorf("--method cannot be empty"))
}
if !strings.HasPrefix(path, "/") {
return cmdutil.NewError(cmdutil.CodeInputInvalidArgument, fmt.Sprintf("path must start with /: %s", path))
}
// Resolve request body. --data and --input are mutually exclusive at
// the cobra layer; the second branch is reachable only when --data is
// empty.
// Resolve request body from --input (file path or `-` for stdin).
var body any
if opts.Data != "" {
body = json.RawMessage(opts.Data)
} else if opts.Input != "" {
if opts.Input != "" {
contents, err := readInput(opts)
if err != nil {
return err
@@ -190,7 +180,13 @@ func runAPISingle(ctx context.Context, opts *Options, fopts *cmdutil.FormatOptio
if resp.StatusCode < 200 || resp.StatusCode >= 300 {
code := cmdutil.ClassifyHTTPStatus(resp.StatusCode)
return cmdutil.NewError(code, fmt.Sprintf("HTTP %d: %s", resp.StatusCode, strings.TrimSpace(string(respBody))))
ce := cmdutil.NewError(code, fmt.Sprintf("HTTP %d: %s", resp.StatusCode, strings.TrimSpace(string(respBody))))
if v := resp.Header.Get("Retry-After"); v != "" {
if s, perr := strconv.Atoi(v); perr == nil && s > 0 {
ce = ce.WithRetryAfter(s)
}
}
return ce
}
out := iostreams.IO.Out
@@ -210,14 +206,15 @@ func runAPISingle(ctx context.Context, opts *Options, fopts *cmdutil.FormatOptio
hdrs[k] = v[0]
}
}
// --jq runs over the full {status, headers, body} object. Per-field
// projection isn't meaningful here since the response schema is opaque
// to the CLI.
return format.WriteJSONFiltered(out, map[string]any{
// Route through fopts.Emit so the payload lives under .data in the
// success envelope. --jq applies to the full envelope, so users
// project with ".data.status", ".data.body", etc.
payload := map[string]any{
"status": resp.StatusCode,
"headers": hdrs,
"body": bodyAny,
}, nil, fopts.JQ)
}
return fopts.Emit(out, payload, nil)
}
if _, err := out.Write(respBody); err != nil {
@@ -232,7 +229,8 @@ func runAPISingle(ctx context.Context, opts *Options, fopts *cmdutil.FormatOptio
// runAPIPaginated fetches all offset-based pages for a GET request and writes
// a single merged {data, total} JSON object to stdout. If the first page
// response does not carry pagination metadata (total + page_size), the raw
// response is passed through unchanged (single-call fallback).
// response is passed through via passThroughFallback which respects the
// --format envelope contract (same shape as runAPISingle's fallback path).
func runAPIPaginated(ctx context.Context, opts *Options, fopts *cmdutil.FormatOptions, svc Service, path string) error {
if !strings.HasPrefix(path, "/") {
return cmdutil.NewError(cmdutil.CodeInputInvalidArgument, fmt.Sprintf("path must start with /: %s", path))
@@ -243,7 +241,7 @@ func runAPIPaginated(ctx context.Context, opts *Options, fopts *cmdutil.FormatOp
pageSize = 50
}
var allData []json.RawMessage
allData := []json.RawMessage{}
var lastTotal int64
page := 1
@@ -268,18 +266,18 @@ func runAPIPaginated(ctx context.Context, opts *Options, fopts *cmdutil.FormatOp
PageSize int `json:"page_size"`
}
if err := json.Unmarshal(body, &pageResp); err != nil {
// Non-JSON response on first page — pass through verbatim.
// Non-JSON response on first page — fall back through the envelope.
if page == 1 {
return passThroughRaw(body)
return passThroughFallback(body, resp, fopts)
}
return cmdutil.NewError(cmdutil.CodeInputInvalidArgument,
fmt.Sprintf("--paginate: page %d response not in expected shape: %v", page, err))
}
// Heuristic: if the first page lacks pagination metadata, treat the
// response as non-paginated and pass through verbatim.
// response as non-paginated and fall back through the envelope.
if page == 1 && pageResp.Total == 0 && pageResp.PageSize == 0 {
return passThroughRaw(body)
return passThroughFallback(body, resp, fopts)
}
allData = append(allData, pageResp.Data...)
@@ -296,13 +294,32 @@ func runAPIPaginated(ctx context.Context, opts *Options, fopts *cmdutil.FormatOp
"data": allData,
"total": lastTotal,
}
return fopts.Emit(iostreams.IO.Out, merged)
return fopts.Emit(iostreams.IO.Out, merged, nil)
}
// passThroughRaw writes body verbatim to stdout (appending a newline if
// absent), mirroring the single-call passthrough path.
func passThroughRaw(body []byte) error {
// passThroughFallback handles the case where --paginate detects a
// non-paginated first-page response. When JSON output is requested, it routes
// the body through fopts.Emit in the same {status, headers, body} envelope
// shape that runAPISingle produces — keeping the wire contract consistent
// regardless of whether --paginate was passed. For human-readable mode it
// writes the raw body verbatim (same as the original passThroughRaw behavior).
func passThroughFallback(body []byte, resp *http.Response, fopts *cmdutil.FormatOptions) error {
out := iostreams.IO.Out
if fopts.WantsJSON() {
var bodyAny any
if len(body) > 0 {
if err := json.Unmarshal(body, &bodyAny); err != nil {
bodyAny = string(body) // best-effort string fallback
}
}
hdrs := collectHeaders(resp)
return fopts.Emit(out, map[string]any{
"status": resp.StatusCode,
"headers": hdrs,
"body": bodyAny,
}, nil)
}
// Human-readable: raw passthrough, same as before.
if _, err := out.Write(body); err != nil {
return cmdutil.Wrapf(cmdutil.CodeLocalFileIO, err, "write response body")
}
@@ -312,6 +329,18 @@ func passThroughRaw(body []byte) error {
return nil
}
// collectHeaders extracts the first value of each response header into a flat
// map, matching the shape that runAPISingle emits in its JSON envelope.
func collectHeaders(resp *http.Response) map[string]string {
hdrs := make(map[string]string, len(resp.Header))
for k, v := range resp.Header {
if len(v) > 0 {
hdrs[k] = v[0]
}
}
return hdrs
}
// extractPageSize parses the page_size query parameter from path, returning 0
// if absent or unparseable.
func extractPageSize(path string) int {
+95 -36
View File
@@ -4,6 +4,7 @@ import (
"bytes"
"context"
"encoding/json"
"errors"
"fmt"
"io"
"net/http"
@@ -52,7 +53,7 @@ func TestAPI_GetSuccess(t *testing.T) {
})
defer stop()
if err := runAPI(context.Background(), &Options{}, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, cli, "GET", "/api/v1/foo", false); err != nil {
if err := runAPI(context.Background(), &Options{}, &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}, cli, "GET", "/api/v1/foo", false); err != nil {
t.Fatalf("runAPI: %v", err)
}
got := out.String()
@@ -77,14 +78,22 @@ func TestAPI_GetSuccess_JSON(t *testing.T) {
if err := runAPI(context.Background(), &Options{}, &cmdutil.FormatOptions{Mode: cmdutil.FormatJSON}, cli, "GET", "/api/v1/foo", false); err != nil {
t.Fatalf("runAPI: %v", err)
}
var got struct {
Status int `json:"status"`
Headers map[string]string `json:"headers"`
Body map[string]any `json:"body"`
// v0.7 envelope: {ok:true, data:{status, headers, body}}
var env struct {
OK bool `json:"ok"`
Data struct {
Status int `json:"status"`
Headers map[string]string `json:"headers"`
Body map[string]any `json:"body"`
} `json:"data"`
}
if err := json.Unmarshal(out.Bytes(), &got); err != nil {
t.Fatalf("decode bare JSON: %v\n%s", err, out.String())
if err := json.Unmarshal(out.Bytes(), &env); err != nil {
t.Fatalf("decode envelope JSON: %v\n%s", err, out.String())
}
if !env.OK {
t.Errorf("envelope ok: want true, got false")
}
got := env.Data
if got.Status != 200 {
t.Errorf("status: want 200, got %d", got.Status)
}
@@ -96,7 +105,7 @@ func TestAPI_GetSuccess_JSON(t *testing.T) {
}
}
func TestAPI_PostWithData(t *testing.T) {
func TestAPI_PostWithStdinInput(t *testing.T) {
_, _ = iostreams.SetForTest(t)
var seenBody []byte
var seenMethod, seenPath string
@@ -109,15 +118,13 @@ func TestAPI_PostWithData(t *testing.T) {
})
defer stop()
opts := &Options{Data: `{"name":"foo"}`}
if err := runAPI(context.Background(), opts, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, cli, "POST", "/api/v1/things", false); err != nil {
opts := &Options{Input: "-", StdinReader: strings.NewReader(`{"name":"foo"}`)}
if err := runAPI(context.Background(), opts, &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}, cli, "POST", "/api/v1/things", false); err != nil {
t.Fatalf("runAPI: %v", err)
}
if seenMethod != http.MethodPost || seenPath != "/api/v1/things" {
t.Errorf("server saw %s %s, want POST /api/v1/things", seenMethod, seenPath)
}
// SDK marshals body via json.Marshal; json.RawMessage round-trips
// verbatim so the bytes server-side equal the --data argument.
if string(seenBody) != `{"name":"foo"}` {
t.Errorf("server received body %q, want %q", seenBody, `{"name":"foo"}`)
}
@@ -139,7 +146,7 @@ func TestAPI_InputFile(t *testing.T) {
defer stop()
opts := &Options{Input: tmp}
if err := runAPI(context.Background(), opts, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, cli, "POST", "/api/v1/x", false); err != nil {
if err := runAPI(context.Background(), opts, &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}, cli, "POST", "/api/v1/x", false); err != nil {
t.Fatalf("runAPI: %v", err)
}
if string(seenBody) != payload {
@@ -160,7 +167,7 @@ func TestAPI_InputDash_Stdin(t *testing.T) {
payload := `{"k":"from-stdin"}`
opts := &Options{Input: "-", StdinReader: strings.NewReader(payload)}
if err := runAPI(context.Background(), opts, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, cli, "POST", "/api/v1/x", false); err != nil {
if err := runAPI(context.Background(), opts, &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}, cli, "POST", "/api/v1/x", false); err != nil {
t.Fatalf("runAPI: %v", err)
}
if string(seenBody) != payload {
@@ -176,7 +183,7 @@ func TestAPI_NotFound(t *testing.T) {
})
defer stop()
err := runAPI(context.Background(), &Options{}, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, cli, "GET", "/api/v1/missing", false)
err := runAPI(context.Background(), &Options{}, &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}, cli, "GET", "/api/v1/missing", false)
if err == nil {
t.Fatal("expected error for 404")
}
@@ -185,22 +192,43 @@ func TestAPI_NotFound(t *testing.T) {
}
}
func TestAPI_InvalidMethod(t *testing.T) {
func TestAPI_AcceptsArbitraryMethod(t *testing.T) {
_, _ = iostreams.SetForTest(t)
// No server needed: validation should fail before dispatch.
err := runAPI(context.Background(), &Options{}, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, nil, "FOO", "/api/v1/things", false)
if err == nil {
t.Fatal("expected error for unsupported method")
var seenMethod string
cli, stop := newTestClient(t, func(w http.ResponseWriter, r *http.Request) {
seenMethod = r.Method
w.WriteHeader(http.StatusOK)
})
defer stop()
for _, m := range []string{"OPTIONS", "PATCH", "TRACE", "CUSTOM"} {
t.Run(m, func(t *testing.T) {
seenMethod = ""
err := runAPI(context.Background(), &Options{}, &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}, cli, m, "/api/v1/things", false)
if err != nil {
t.Fatalf("expected method %q to be accepted, got %v", m, err)
}
if seenMethod != m {
t.Errorf("server saw method %q, want %q", seenMethod, m)
}
})
}
var ce *cmdutil.Error
if !asTypedError(err, &ce) || ce.Code != cmdutil.CodeInputInvalidArgument {
t.Errorf("expected input.invalid_argument, got %v", err)
}
func TestAPI_EmptyMethodRejected(t *testing.T) {
_, _ = iostreams.SetForTest(t)
err := runAPI(context.Background(), &Options{}, &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}, nil, "", "/api/v1/things", false)
if err == nil {
t.Fatal("expected error for empty method")
}
var fe *cmdutil.FlagError
if !errors.As(err, &fe) {
t.Errorf("expected FlagError, got %T %v", err, err)
}
}
func TestAPI_PathWithoutSlash(t *testing.T) {
_, _ = iostreams.SetForTest(t)
err := runAPI(context.Background(), &Options{}, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, nil, "GET", "api/v1/things", false)
err := runAPI(context.Background(), &Options{}, &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}, nil, "GET", "api/v1/things", false)
if err == nil {
t.Fatal("expected error for missing leading slash")
}
@@ -320,13 +348,17 @@ func TestAPI_PaginateMergesPages(t *testing.T) {
if err := runAPI(context.Background(), opts, &cmdutil.FormatOptions{Mode: cmdutil.FormatJSON}, svc, "GET", "/api/v1/knowledge-base?page=1&page_size=2", true); err != nil {
t.Fatalf("runAPI: %v", err)
}
var got struct {
Data []map[string]string `json:"data"`
Total int `json:"total"`
var env struct {
OK bool `json:"ok"`
Data struct {
Data []map[string]string `json:"data"`
Total int `json:"total"`
} `json:"data"`
}
if err := json.Unmarshal(out.Bytes(), &got); err != nil {
if err := json.Unmarshal(out.Bytes(), &env); err != nil {
t.Fatalf("unmarshal: %v\n%s", err, out.String())
}
got := env.Data
if len(got.Data) != 5 || got.Total != 5 {
t.Errorf("got %d records (total %d), want 5/5", len(got.Data), got.Total)
}
@@ -350,7 +382,7 @@ func TestAPI_PaginateIgnoredForPOST(t *testing.T) {
_, _ = iostreams.SetForTest(t)
opts := &Options{Data: `{"name":"foo"}`}
opts := &Options{Input: "-", StdinReader: strings.NewReader(`{"name":"foo"}`)}
if err := runAPI(context.Background(), opts, &cmdutil.FormatOptions{Mode: cmdutil.FormatJSON}, svc, "POST", "/api/v1/knowledge-base", true); err != nil {
t.Fatalf("runAPI: %v", err)
}
@@ -361,18 +393,20 @@ func TestAPI_PaginateIgnoredForPOST(t *testing.T) {
func TestAPI_PaginateNoMetadataPassesThrough(t *testing.T) {
// If response doesn't look paginated (no total/page/page_size), --paginate
// should fall back to single-call behavior (don't crash).
// should fall back to single-call envelope behavior (same shape as api without --paginate).
called := 0
svc := &fakeAPISvc{do: func(method, path string, _ any) (*http.Response, error) {
called++
hdr := make(http.Header)
hdr.Set("Content-Type", "application/json")
return &http.Response{
StatusCode: 200,
Body: io.NopCloser(bytes.NewReader([]byte(`{"hello":"world"}`))),
Header: make(http.Header),
Header: hdr,
}, nil
}}
_, _ = iostreams.SetForTest(t)
out, _ := iostreams.SetForTest(t)
opts := &Options{}
if err := runAPI(context.Background(), opts, &cmdutil.FormatOptions{Mode: cmdutil.FormatJSON}, svc, "GET", "/api/v1/whoami", true); err != nil {
@@ -381,6 +415,27 @@ func TestAPI_PaginateNoMetadataPassesThrough(t *testing.T) {
if called != 1 {
t.Errorf("called %d times, want 1 (non-paginated response)", called)
}
// H3a: fallback must produce an envelope, not raw passthrough.
var env struct {
OK bool `json:"ok"`
Data struct {
Status int `json:"status"`
Headers map[string]string `json:"headers"`
Body map[string]any `json:"body"`
} `json:"data"`
}
if err := json.Unmarshal(out.Bytes(), &env); err != nil {
t.Fatalf("non-paginated fallback must emit envelope JSON, unmarshal failed: %v\n%s", err, out.String())
}
if !env.OK {
t.Errorf("envelope ok: want true, got false")
}
if env.Data.Status != 200 {
t.Errorf("envelope data.status: want 200, got %d", env.Data.Status)
}
if v, ok := env.Data.Body["hello"]; !ok || v.(string) != "world" {
t.Errorf("envelope data.body: want {hello:world}, got %v", env.Data.Body)
}
}
// TestAPI_PaginateServerCapsPageSize covers the case where the user
@@ -418,13 +473,17 @@ func TestAPI_PaginateServerCapsPageSize(t *testing.T) {
if err := runAPI(context.Background(), opts, &cmdutil.FormatOptions{Mode: cmdutil.FormatJSON}, svc, "GET", "/api/v1/items?page=1&page_size=10", true); err != nil {
t.Fatalf("runAPI: %v", err)
}
var got struct {
Data []map[string]string `json:"data"`
Total int `json:"total"`
var env struct {
OK bool `json:"ok"`
Data struct {
Data []map[string]string `json:"data"`
Total int `json:"total"`
} `json:"data"`
}
if err := json.Unmarshal(stdout.Bytes(), &got); err != nil {
if err := json.Unmarshal(stdout.Bytes(), &env); err != nil {
t.Fatalf("unmarshal: %v\n%s", err, stdout.String())
}
got := env.Data
if len(got.Data) != 5 {
t.Errorf("got %d records, want 5 (server-capped page_size should not cause truncation)", len(got.Data))
}