WeKnora deployment source with the reviewed wiki identity, summary and recovery fixes
Anydoc / anydoc parser engine (push) Canceled after 0s
App / Format, vet, test, and build (push) Canceled after 0s
CLI / test (macos-latest / go 1.26) (push) Canceled after 0s
CLI / test (ubuntu-latest / go 1.26) (push) Canceled after 0s
CLI / test (windows-latest / go 1.26) (push) Canceled after 0s
Build and Push Docker Image / build-ui (push) Canceled after 0s
Build and Push Docker Image / build-docreader (push) Canceled after 0s
Build and Push Docker Image / build-sandbox (push) Canceled after 0s
Build and Push Docker Image / build-app (amd64, linux/amd64, ubuntu-latest) (push) Canceled after 0s
Build and Push Docker Image / build-app (arm64, linux/arm64, ubuntu-24.04-arm) (push) Canceled after 0s
DocReader / Python tests and Go client tests (push) Canceled after 0s
Build & Publish (dsh-weknora) / Typecheck, test, pack (push) Canceled after 0s
Build & Publish (dsh-weknora) / End-to-end inside dsh (pinned) (push) Canceled after 0s
Build & Publish (dsh-weknora) / End-to-end inside dsh (latest, advisory) (push) Canceled after 0s
Frontend / Test, type-check, and build (push) Canceled after 0s
Go Lint Cache / warm lint cache (.) (push) Canceled after 0s
Go Lint Cache / warm lint cache (cli) (push) Canceled after 0s
Go Lint Cache / warm lint cache (client) (push) Canceled after 0s
Build & Publish (mcp-server) / Test (Python 3.10) (push) Canceled after 0s
Build & Publish (mcp-server) / Test (Python 3.11) (push) Canceled after 0s
Build & Publish (mcp-server) / Test (Python 3.12) (push) Canceled after 0s
Build & Publish (mcp-server) / Test (Python 3.13) (push) Canceled after 0s
Build and Push Docker Image / merge (push) Canceled after 0s
Build & Publish (dsh-weknora) / Publish to npm (push) Canceled after 0s
Build & Publish (mcp-server) / Build sdist + wheel (push) Canceled after 0s
Build & Publish (mcp-server) / Publish to PyPI (push) Canceled after 0s

This commit is contained in:
yawan
2026-09-22 16:19:06 +08:00
commit f7fc992f57
3929 changed files with 1006607 additions and 0 deletions
+517
View File
@@ -0,0 +1,517 @@
// Package api implements the `weknora api` raw HTTP passthrough command.
//
// Shape: one positional (path) + `-X/--method` flag, default GET (auto-
// promoted to POST when a body is supplied via -d/--input). Text mode writes
// the raw response body to stdout; --format json places the parsed server
// response directly under envelope.data (no {status, headers, body} wrapper),
// so `--jq '.data...'` projects at the server's own depth. Reuses
// sdk.Client.Raw which already applies tenant + auth headers.
package api
import (
"bytes"
"context"
"encoding/json"
"fmt"
"io"
"net/http"
"net/url"
"os"
"strconv"
"strings"
"github.com/spf13/cobra"
"github.com/Tencent/WeKnora/cli/internal/cmdutil"
"github.com/Tencent/WeKnora/cli/internal/iostreams"
sdk "github.com/Tencent/WeKnora/client"
)
// apiFields is intentionally a marker - api wraps arbitrary HTTP responses
// whose schema the CLI doesn't know, so field hints are meaningless here.
// The marker shows up in --help so users can tell.
var apiFields = []string{"<response-shape-varies>"}
type Options struct {
Method string
Input string // --input: file path, "-" for stdin
Data string // -d/--data: inline JSON body (mutually exclusive with --input)
Fields []string // -F/--field: key=value pairs assembled into a JSON object body (mutually exclusive with -d/--input)
Yes bool
DryRun bool
StdinReader io.Reader // overridden by tests; defaults to iostreams.IO.In
}
// Service is the narrow SDK surface this command depends on. The production
// implementation is *sdk.Client, whose Raw method already injects auth /
// tenant / request-id headers (see client.applyAuthHeaders). Tests substitute
// either a fake or a real client pointed at httptest.Server.
type Service interface {
Raw(ctx context.Context, method, path string, body any) (*http.Response, error)
}
// NewCmd returns the `weknora api` command.
func NewCmd(f *cmdutil.Factory) *cobra.Command {
opts := &Options{}
cmd := &cobra.Command{
Use: "api <path>",
Short: "Make a raw API request to the WeKnora server",
Long: `Raw HTTP API access. JSON body via -d/--data (inline) or --input <file>/- (stdin).
The default method is GET; supplying a body (-d or --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 profile. In text mode (default) the raw server response body is written
to stdout. In --format json the parsed server response is placed directly
under envelope.data — drill in with --jq '.data...' at the server's own depth
(e.g. '.data.data[]' for a list endpoint). Only -X DELETE is confirmation-gated.
Examples:
weknora api /api/v1/knowledge-bases # GET
weknora api /api/v1/knowledge-bases -d '{"name":"foo"}' # POST (auto)
weknora api /api/v1/knowledge-bases -F name=foo -F enabled=true # POST, typed body
echo '{"name":"foo"}' | weknora api /api/v1/knowledge-bases --input - # POST via stdin
weknora api /api/v1/knowledge-bases/kb_xxx -X DELETE`,
Args: cobra.ExactArgs(1),
RunE: func(c *cobra.Command, args []string) error {
opts.Yes, _ = c.Flags().GetBool("yes")
fopts, err := cmdutil.CheckFormatFlag(c)
if err != nil {
return err
}
fopts.ResolveDefault(iostreams.IO.IsStdoutTTY())
if opts.DryRun {
// --dry-run on the raw escape-hatch is only meaningful when a
// would-be mutation exists to preview. GET (default or explicit)
// is read-only with no side effect, so previewing it is a
// likely user error — signal it via FlagError exit 2 with the
// concrete repair. Use resolveMethod so --input auto-promotes
// GET → POST identically to the live path.
method := resolveMethod(opts)
if method == http.MethodGet {
return cmdutil.NewFlagError(fmt.Errorf(
"--dry-run requires explicit -X POST/PUT/PATCH/DELETE; default GET is read-only with no side effect to preview"))
}
var body any
if hasBody(opts) {
contents, err := resolveBody(opts)
if err != nil {
return err
}
// Surface the parsed body in the plan so agents can grep
// meta.plan.body for shape; resolveBody has already validated
// it as JSON.
var parsed any
if json.Unmarshal(contents, &parsed) == nil {
body = parsed
} else {
body = string(contents)
}
}
if handled, err := cmdutil.HandleDryRun(c, true, cmdutil.DryRunPlan{
Action: "api." + strings.ToLower(method),
Method: method,
Path: args[0],
Body: body,
}); handled {
return err
}
}
method := resolveMethod(opts)
// Escape-hatch DELETE through `weknora api` is just as destructive
// as `weknora kb delete` - exit-10 destructive protocol must apply
// (cli/README.md). PUT/PATCH mutate server state like a typed
// `kb/agent/doc update`, so they get the same exit-10 WRITE gate;
// without it the raw escape hatch bypassed the "an agent cannot
// silently mutate" guarantee. POST stays ungated to match typed
// `create` (also ungated). GET/HEAD are reads.
switch method {
case http.MethodDelete:
if err := cmdutil.ConfirmDestructive(f.Prompter(), opts.Yes, fopts.WantsJSON(), "delete", "endpoint", args[0], "api.delete", []string{"weknora", "api", "-X", "DELETE", args[0], "-y"}); err != nil {
return err
}
case http.MethodPut, http.MethodPatch:
if err := cmdutil.ConfirmWrite(f.Prompter(), opts.Yes, fopts.WantsJSON(), "write", "endpoint", args[0], "api."+strings.ToLower(method), apiRetryArgv(opts, method, args[0])); err != nil {
return err
}
}
cli, err := f.Client()
if err != nil {
return err
}
paginate, _ := c.Flags().GetBool("paginate")
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 via -d/--input). Any non-empty method is accepted.")
cmd.Flags().StringVarP(&opts.Data, "data", "d", "", "Inline JSON request body (e.g. -d '{\"name\":\"x\"}'). Mutually exclusive with --input.")
cmd.Flags().StringVar(&opts.Input, "input", "", "Read JSON request body from file (use `-` for stdin). Mutually exclusive with -d/--data.")
cmd.Flags().StringArrayVarP(&opts.Fields, "field", "F", nil, "Add a key=value to a JSON object body (repeatable; e.g. -F name=foo -F enabled=true). true/false/null and numbers are typed; everything else is a string. Flat keys only. Mutually exclusive with -d/--input.")
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...)
cmdutil.AddDryRunFlag(cmd, &opts.DryRun)
cmdutil.SetAgentHelp(cmd, cmdutil.AgentHelp{
UsedFor: "raw HTTP passthrough to weknora-server API endpoints when typed subcommands are insufficient",
RequiredFlags: []string{"path (positional)"},
Examples: []string{
"weknora api /api/v1/knowledge-bases",
"weknora api /api/v1/knowledge-bases -d '{\"name\":\"foo\"}'",
"weknora api -X POST /api/v1/knowledge-bases -F name=\"Eng Docs\" -F enabled=true",
"weknora api -X DELETE /api/v1/knowledge-bases/kb_x -y",
"echo '{\"name\":\"foo\"}' | weknora api /api/v1/knowledge-bases --input -",
},
Output: "text mode (default): the raw server response body on stdout. json mode: the parsed server response is placed directly under envelope.data — project with --jq '.data...' at the server's own depth (e.g. '.data.data[]' for a list endpoint, '.data.data.id' for a created object). With --paginate, envelope.data is the merged {data, total}.",
Warnings: []string{
"-X DELETE is destructive-gated and -X PUT/PATCH are write-gated (exit 10 / input.confirmation_required unless -y), matching typed delete/update. -X POST (create-shaped) and GET are unguarded — you own the safety of creates made through this escape hatch.",
"Raw passthrough: the typed error envelope does NOT fully apply. The server's own response goes under envelope.data at its native depth; a non-2xx HTTP status surfaces via the exit code, not a typed error.type/retry_argv. Do not rely on error.type/retryable for `api` the way you do for typed subcommands.",
"Raw HTTP passthrough; agents should prefer typed subcommands (kb/doc/session/...) when available.",
},
})
return cmd
}
// readInput reads opts.Input and returns its contents. "-" reads from
// opts.StdinReader (or iostreams.IO.In as the production default) for
// piped JSON payloads.
//
// The body is sent as a JSON document (the SDK marshals it as json.RawMessage),
// so a non-JSON / malformed payload is validated and rejected here as
// input.invalid_argument (exit 5). Without this, the failure surfaced from the
// SDK's marshal step as a confusing network.error (exit 7, "retryable") —
// looping an agent on a body that can never be sent.
func readInput(opts *Options) ([]byte, error) {
var b []byte
if opts.Input == "-" {
r := opts.StdinReader
if r == nil {
r = iostreams.IO.In
}
var err error
b, err = io.ReadAll(r)
if err != nil {
return nil, cmdutil.Wrapf(cmdutil.CodeLocalFileIO, err, "read request body from stdin")
}
} else {
var err error
b, err = os.ReadFile(opts.Input)
if err != nil {
return nil, cmdutil.Wrapf(cmdutil.CodeLocalFileIO, err, "read input file %s", opts.Input)
}
}
if len(bytes.TrimSpace(b)) > 0 && !json.Valid(b) {
return nil, cmdutil.NewError(cmdutil.CodeInputInvalidArgument,
"--input must be valid JSON (the request body is sent as a JSON document)")
}
return b, nil
}
// resolveBody returns the request body bytes from -d/--data (inline) or
// --input (file/stdin), or nil when neither is set. Inline --data is
// validated as JSON here; --input is validated inside readInput. The two
// flags are mutually exclusive — checked here (rather than cobra's
// MarkFlagsMutuallyExclusive, whose violation surfaces as an unclassified
// internal.error / exit 1) so the conflict reports input.invalid_argument.
func resolveBody(opts *Options) ([]byte, error) {
set := 0
if opts.Data != "" {
set++
}
if opts.Input != "" {
set++
}
if len(opts.Fields) > 0 {
set++
}
if set > 1 {
return nil, cmdutil.NewError(cmdutil.CodeInputInvalidArgument,
"-d/--data, --input, and -F/--field are mutually exclusive; supply the body one way")
}
if len(opts.Fields) > 0 {
return buildFieldBody(opts.Fields)
}
if opts.Data != "" {
if !json.Valid([]byte(opts.Data)) {
return nil, cmdutil.NewError(cmdutil.CodeInputInvalidArgument,
"-d/--data must be valid JSON (the request body is sent as a JSON document)")
}
return []byte(opts.Data), nil
}
if opts.Input != "" {
return readInput(opts)
}
return nil, nil
}
// hasBody reports whether a request body was supplied via -d or --input.
func hasBody(opts *Options) bool {
return opts.Data != "" || opts.Input != "" || len(opts.Fields) > 0
}
// inferFieldValue maps a -F value string to a typed JSON scalar: literal
// true/false/null and integer/float literals become typed JSON; everything
// else stays a string. A value that looks numeric but must stay a string
// (e.g. a zero-padded id "007") can't be forced here — use -d/--data or
// --input for full control.
func inferFieldValue(v string) any {
switch v {
case "true":
return true
case "false":
return false
case "null":
return nil
}
if i, err := strconv.ParseInt(v, 10, 64); err == nil {
return i
}
if f, err := strconv.ParseFloat(v, 64); err == nil {
return f
}
return v
}
// buildFieldBody assembles -F/--field key=value pairs into a JSON object with
// type inference. Flat keys only. Returns input.invalid_argument (exit 5) for
// a malformed pair or an unsupported @file value.
func buildFieldBody(fields []string) ([]byte, error) {
obj := make(map[string]any, len(fields))
for _, f := range fields {
k, v, ok := strings.Cut(f, "=")
if !ok || k == "" {
return nil, cmdutil.NewError(cmdutil.CodeInputInvalidArgument,
fmt.Sprintf("-F/--field must be key=value, got %q", f))
}
if strings.HasPrefix(v, "@") {
return nil, cmdutil.NewError(cmdutil.CodeInputInvalidArgument,
fmt.Sprintf("-F %q: @file values are not supported; read a file body with --input", f))
}
obj[k] = inferFieldValue(v)
}
return json.Marshal(obj)
}
// resolveMethod implements the auto-method behavior: explicit -X wins;
// otherwise body presence (-d/--data or --input) promotes GET → POST.
func resolveMethod(opts *Options) string {
if opts.Method != "" {
return strings.ToUpper(opts.Method)
}
if hasBody(opts) {
return "POST"
}
return "GET"
}
// apiRetryArgv reconstructs a directly-executable `weknora api` argv (with -y)
// for the write-confirmation gate, preserving the method, path and body flags
// the caller passed so an agent can re-run the exact mutation after approval.
func apiRetryArgv(opts *Options, method, path string) []string {
argv := []string{"weknora", "api", "-X", method, path}
switch {
case opts.Data != "":
argv = append(argv, "-d", opts.Data)
case opts.Input != "":
argv = append(argv, "--input", opts.Input)
default:
for _, f := range opts.Fields {
argv = append(argv, "-F", f)
}
}
return append(argv, "-y")
}
// runAPI is the testable core: validate inputs, dispatch via Service.Raw,
// classify status, and emit either the raw body or a JSON object. The
// caller is responsible for resolving the method (defaults / auto-POST)
// and uppercasing it; runAPI guards against unsupported values like
// `-X PATCH-INVALID` reaching the wire.
//
// When paginate is true and method is GET, all offset-based pages are
// fetched and merged into a single {data, total} JSON response. For
// non-GET methods paginate is silently ignored (no offset semantic).
func runAPI(ctx context.Context, opts *Options, fopts *cmdutil.FormatOptions, svc Service, method, path string, paginate bool) error {
if paginate && method == http.MethodGet {
return runAPIPaginated(ctx, opts, fopts, svc, path)
}
return runAPISingle(ctx, opts, fopts, svc, method, path)
}
// 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 {
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 from -d/--data (inline) or --input (file / `-`).
// Empty input is treated as no body rather than an empty JSON document
// (which fails to marshal).
contents, err := resolveBody(opts)
if err != nil {
return err
}
var body any
if len(bytes.TrimSpace(contents)) > 0 {
body = json.RawMessage(contents)
}
resp, err := svc.Raw(ctx, method, path, body)
if err != nil {
// Transport / DNS failure (Raw never returns a typed HTTP error of its
// own; non-2xx responses still surface as resp != nil, err == nil).
return cmdutil.WrapHTTP(err, "%s %s", method, path)
}
defer resp.Body.Close()
respBody, err := io.ReadAll(resp.Body)
if err != nil {
return cmdutil.Wrapf(cmdutil.CodeNetworkError, err, "read response body")
}
if resp.StatusCode < 200 || resp.StatusCode >= 300 {
code := cmdutil.ClassifyHTTPStatus(resp.StatusCode)
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
}
return emitRawBody(respBody, fopts)
}
// emitRawBody writes a server response body under the active format. JSON mode
// places the parsed body directly under envelope.data — no {status, headers,
// body} wrapper — so `--jq '.data...'` projects at the server's own shape
// (e.g. `.data.data[]` for a list endpoint) rather than a triple-nested
// `.data.body.data[]`; non-JSON decodes best-effort to a raw string. Text mode
// writes the body verbatim with a trailing newline. Shared by the single and
// paginated-fallback paths so both project identically.
func emitRawBody(body []byte, 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)
}
}
return fopts.Emit(out, bodyAny, nil)
}
if _, err := out.Write(body); err != nil {
return cmdutil.Wrapf(cmdutil.CodeLocalFileIO, err, "write response body")
}
if len(body) > 0 && body[len(body)-1] != '\n' {
_, _ = out.Write([]byte{'\n'})
}
return nil
}
// 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 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))
}
pageSize := extractPageSize(path)
if pageSize == 0 {
pageSize = 50
}
allData := []json.RawMessage{}
var lastTotal int64
page := 1
for {
curPath := setPageParam(path, page, pageSize)
resp, err := svc.Raw(ctx, http.MethodGet, curPath, nil)
if err != nil {
return cmdutil.WrapHTTP(err, "GET %s", curPath)
}
body, _ := io.ReadAll(resp.Body)
resp.Body.Close()
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(body))))
}
var pageResp struct {
Data []json.RawMessage `json:"data"`
Total int64 `json:"total"`
Page int `json:"page"`
PageSize int `json:"page_size"`
}
if err := json.Unmarshal(body, &pageResp); err != nil {
// Non-JSON response on first page — fall back through the envelope.
if page == 1 {
return emitRawBody(body, 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 fall back through the envelope.
if page == 1 && pageResp.Total == 0 && pageResp.PageSize == 0 {
return emitRawBody(body, fopts)
}
allData = append(allData, pageResp.Data...)
lastTotal = pageResp.Total
// Termination: accumulated count (not page*pageSize) handles server-capped page sizes.
if int64(len(allData)) >= pageResp.Total || len(pageResp.Data) == 0 {
break
}
page++
}
merged := map[string]any{
"data": allData,
"total": lastTotal,
}
return fopts.Emit(iostreams.IO.Out, merged, nil)
}
// extractPageSize parses the page_size query parameter from path, returning 0
// if absent or unparseable.
func extractPageSize(path string) int {
u, err := url.Parse(path)
if err != nil {
return 0
}
if v := u.Query().Get("page_size"); v != "" {
if n, err := strconv.Atoi(v); err == nil && n > 0 {
return n
}
}
return 0
}
// setPageParam rewrites the page and page_size query parameters in path,
// preserving all other query parameters.
func setPageParam(path string, page, pageSize int) string {
u, err := url.Parse(path)
if err != nil {
return path
}
q := u.Query()
q.Set("page", strconv.Itoa(page))
q.Set("page_size", strconv.Itoa(pageSize))
u.RawQuery = q.Encode()
return u.String()
}
// compile-time check: the production SDK client implements Service.
var _ Service = (*sdk.Client)(nil)
+199
View File
@@ -0,0 +1,199 @@
package api
import (
"encoding/json"
"errors"
"strings"
"testing"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"github.com/Tencent/WeKnora/cli/internal/cmdutil"
"github.com/Tencent/WeKnora/cli/internal/iostreams"
"github.com/Tencent/WeKnora/cli/internal/prompt"
sdk "github.com/Tencent/WeKnora/client"
)
// apiDryRunFactory builds a Factory whose Client closure panics if invoked —
// dry-run must early-exit before any SDK call.
func apiDryRunFactory(t *testing.T) *cmdutil.Factory {
t.Helper()
return &cmdutil.Factory{
Client: func() (*sdk.Client, error) {
t.Fatal("dry-run path must not call Factory.Client(); SDK side effect leaked")
return nil, nil
},
Prompter: func() prompt.Prompter {
t.Fatal("dry-run path must not call Factory.Prompter(); confirm-prompt side effect leaked")
return nil
},
}
}
// TestApi_DryRunWithGet_FlagError: default-method GET + --dry-run must return
// FlagError (exit 2). The only meaningful target for --dry-run on `api` is a
// mutation method; allowing GET to silently succeed would let agents waste a
// round-trip previewing a no-op.
func TestApi_DryRunWithGet_FlagError(t *testing.T) {
iostreams.SetForTest(t)
root := withRootHarness(NewCmd(apiDryRunFactory(t)),
"/api/v1/knowledge-bases", "--dry-run")
err := root.Execute()
require.Error(t, err, "GET + --dry-run must error")
var fe *cmdutil.FlagError
require.True(t, errors.As(err, &fe), "expected *cmdutil.FlagError, got %T %v", err, err)
assert.Equal(t, 2, cmdutil.ExitCode(err), "FlagError must map to exit 2")
assert.Contains(t, err.Error(), "explicit -X POST/PUT/PATCH/DELETE",
"error message must point users to the concrete repair")
}
// TestApi_DryRunWithExplicitGet_FlagError: explicit `-X GET` + --dry-run is
// also rejected. The reject condition is "method is GET", not "method flag is
// unset"; passing -X GET explicitly must produce the same error so users
// can't bypass the guard by being verbose.
func TestApi_DryRunWithExplicitGet_FlagError(t *testing.T) {
iostreams.SetForTest(t)
root := withRootHarness(NewCmd(apiDryRunFactory(t)),
"/api/v1/knowledge-bases", "-X", "GET", "--dry-run")
err := root.Execute()
require.Error(t, err, "explicit -X GET + --dry-run must error")
var fe *cmdutil.FlagError
require.True(t, errors.As(err, &fe), "expected *cmdutil.FlagError, got %T %v", err, err)
assert.Equal(t, 2, cmdutil.ExitCode(err))
}
// TestApi_DryRunWithInputAutoPromotes_EmitsPlan: --input on its own (no
// explicit -X) must auto-promote GET → POST in the dry-run path too,
// matching the live behavior in resolveMethod. Before the fix the dry-run
// branch built `method` directly from `strings.ToUpper(opts.Method)`, which
// is empty when -X is unset, then defaulted to GET — so --input was ignored
// at preview time, producing the misleading "GET is read-only" error.
func TestApi_DryRunWithInputAutoPromotes_EmitsPlan(t *testing.T) {
out, _ := iostreams.SetForTest(t)
iostreams.IO.In = strings.NewReader(`{}`)
root := withRootHarness(NewCmd(apiDryRunFactory(t)),
"/api/v1/knowledge-bases", "--input", "-", "--dry-run", "--format", "json")
require.NoError(t, root.Execute(), "--input + --dry-run must succeed (POST auto-promotion)")
var env struct {
OK bool `json:"ok"`
Meta struct {
DryRun bool `json:"dry_run"`
Plan map[string]any `json:"plan"`
} `json:"meta"`
}
require.NoError(t, json.Unmarshal(out.Bytes(), &env), "expected valid JSON envelope, got %q", out.String())
assert.True(t, env.OK)
assert.True(t, env.Meta.DryRun)
assert.Equal(t, "api.post", env.Meta.Plan["action"], "plan.action must reflect auto-promoted POST")
assert.Equal(t, "POST", env.Meta.Plan["method"])
}
// TestApi_DryRunWithPost_EmitsPlan: POST + --dry-run + --input - must emit
// the standard envelope with action=api.post, method/path echoed, and the
// stdin body parsed as JSON under plan.body. No SDK call expected (factory
// would panic if Client() were touched).
func TestApi_DryRunWithPost_EmitsPlan(t *testing.T) {
out, _ := iostreams.SetForTest(t)
cmd := NewCmd(apiDryRunFactory(t))
// StdinReader is on Options; set it via the recovered options binding by
// running through the root harness with --input - and trusting iostreams.IO.In.
// Simplest path: write to IO.In directly via SetForTest's reader swap.
iostreams.IO.In = strings.NewReader(`{"name":"foo"}`)
root := withRootHarness(cmd,
"/api/v1/knowledge-bases", "-X", "POST", "--input", "-", "--dry-run", "--format", "json")
require.NoError(t, root.Execute(), "POST + --dry-run must succeed (exit 0) without SDK")
var env struct {
OK bool `json:"ok"`
Meta struct {
DryRun bool `json:"dry_run"`
Plan map[string]any `json:"plan"`
} `json:"meta"`
}
require.NoError(t, json.Unmarshal(out.Bytes(), &env), "expected valid JSON envelope, got %q", out.String())
assert.True(t, env.OK)
assert.True(t, env.Meta.DryRun)
assert.Equal(t, "api.post", env.Meta.Plan["action"], "plan.action must lowercase the method")
assert.Equal(t, "POST", env.Meta.Plan["method"], "plan.method must be uppercase")
assert.Equal(t, "/api/v1/knowledge-bases", env.Meta.Plan["path"])
// Body decoded as JSON object (best-effort) for downstream agent inspection.
body, ok := env.Meta.Plan["body"].(map[string]any)
require.True(t, ok, "plan.body must be a JSON object when --input is valid JSON, got %T", env.Meta.Plan["body"])
assert.Equal(t, "foo", body["name"])
}
// TestApi_FieldBody_TypedDryRun: -F/--field builds a typed JSON object body —
// true/false/null and numbers are typed, everything else stays a string — and
// the resolved body is surfaced in the dry-run plan for agent inspection.
func TestApi_FieldBody_TypedDryRun(t *testing.T) {
out, _ := iostreams.SetForTest(t)
root := withRootHarness(NewCmd(apiDryRunFactory(t)),
"/api/v1/x", "-X", "POST",
"-F", "name=Hello", "-F", "enabled=true", "-F", "count=3",
"-F", "ratio=1.5", "-F", "empty=null",
"--dry-run", "--format", "json")
require.NoError(t, root.Execute(), "-F + --dry-run must succeed without SDK")
var env struct {
Meta struct {
Plan map[string]any `json:"plan"`
} `json:"meta"`
}
require.NoError(t, json.Unmarshal(out.Bytes(), &env), "envelope: %q", out.String())
body, ok := env.Meta.Plan["body"].(map[string]any)
require.True(t, ok, "plan.body must be a JSON object, got %T", env.Meta.Plan["body"])
assert.Equal(t, "Hello", body["name"], "non-numeric stays string")
assert.Equal(t, true, body["enabled"], "true -> JSON bool")
assert.Equal(t, float64(3), body["count"], "integer -> JSON number")
assert.Equal(t, 1.5, body["ratio"], "float -> JSON number")
assert.Nil(t, body["empty"], "null -> JSON null")
}
// TestApi_FieldBody_AutoPromotesPost: -F on its own (no -X) auto-promotes
// GET -> POST, matching -d/--input body behavior.
func TestApi_FieldBody_AutoPromotesPost(t *testing.T) {
out, _ := iostreams.SetForTest(t)
root := withRootHarness(NewCmd(apiDryRunFactory(t)),
"/api/v1/x", "-F", "a=b", "--dry-run", "--format", "json")
require.NoError(t, root.Execute())
var env struct {
Meta struct {
Plan map[string]any `json:"plan"`
} `json:"meta"`
}
require.NoError(t, json.Unmarshal(out.Bytes(), &env))
assert.Equal(t, "POST", env.Meta.Plan["method"], "-F must auto-promote GET -> POST")
}
// TestApi_FieldBody_ConflictsWithData: -F and -d are mutually exclusive — the
// conflict is reported as input.invalid_argument (exit 5), consistent with the
// existing -d/--input conflict.
func TestApi_FieldBody_ConflictsWithData(t *testing.T) {
iostreams.SetForTest(t)
root := withRootHarness(NewCmd(apiDryRunFactory(t)),
"/api/v1/x", "-X", "POST", "-F", "a=b", "-d", "{}", "--dry-run", "--format", "json")
err := root.Execute()
require.Error(t, err, "-F + -d must conflict")
var ce *cmdutil.Error
require.ErrorAs(t, err, &ce)
assert.Equal(t, cmdutil.CodeInputInvalidArgument, ce.Code)
assert.Equal(t, 5, cmdutil.ExitCode(err))
}
// TestApi_FieldBody_Malformed: a -F value without '=' (or empty key) is a typed
// input error, not a panic or a silently-dropped field.
func TestApi_FieldBody_Malformed(t *testing.T) {
iostreams.SetForTest(t)
root := withRootHarness(NewCmd(apiDryRunFactory(t)),
"/api/v1/x", "-X", "POST", "-F", "nope", "--dry-run", "--format", "json")
err := root.Execute()
require.Error(t, err)
var ce *cmdutil.Error
require.ErrorAs(t, err, &ce)
assert.Equal(t, cmdutil.CodeInputInvalidArgument, ce.Code)
assert.Contains(t, err.Error(), "key=value")
}
+605
View File
@@ -0,0 +1,605 @@
package api
import (
"bytes"
"context"
"encoding/json"
"errors"
"fmt"
"io"
"net/http"
"net/http/httptest"
"os"
"path/filepath"
"strings"
"testing"
"github.com/spf13/cobra"
"github.com/Tencent/WeKnora/cli/internal/cmdutil"
"github.com/Tencent/WeKnora/cli/internal/iostreams"
"github.com/Tencent/WeKnora/cli/internal/prompt"
sdk "github.com/Tencent/WeKnora/client"
)
// fakeAPISvc is a test double for Service that delegates each call to a
// caller-supplied do function, giving full control over per-call responses.
type fakeAPISvc struct {
do func(method, path string, body any) (*http.Response, error)
}
func (f *fakeAPISvc) Raw(_ context.Context, method, path string, body any) (*http.Response, error) {
return f.do(method, path, body)
}
// newTestClient stands up an httptest server with the supplied handler and
// returns an *sdk.Client targeting it plus a teardown closure. The real SDK is
// used so we exercise the same Raw() code path as production (header
// injection, JSON marshalling, etc.).
func newTestClient(t *testing.T, h http.HandlerFunc) (*sdk.Client, func()) {
t.Helper()
srv := httptest.NewServer(h)
return sdk.NewClient(srv.URL), srv.Close
}
func TestAPI_GetSuccess(t *testing.T) {
out, _ := iostreams.SetForTest(t)
cli, stop := newTestClient(t, func(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodGet || r.URL.Path != "/api/v1/foo" {
t.Errorf("unexpected request: %s %s", r.Method, r.URL.Path)
}
w.Header().Set("Content-Type", "application/json")
_, _ = w.Write([]byte(`{"hello":"world"}`))
})
defer stop()
if err := runAPI(context.Background(), &Options{}, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, cli, "GET", "/api/v1/foo", false); err != nil {
t.Fatalf("runAPI: %v", err)
}
got := out.String()
if !strings.Contains(got, `"hello":"world"`) {
t.Errorf("expected raw JSON body in stdout, got %q", got)
}
if !strings.HasSuffix(got, "\n") {
t.Errorf("expected trailing newline appended, got %q", got)
}
}
func TestAPI_GetSuccess_JSON(t *testing.T) {
out, _ := iostreams.SetForTest(t)
cli, stop := newTestClient(t, func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
w.Header().Set("X-Request-Id", "req-123")
w.WriteHeader(http.StatusOK)
_, _ = w.Write([]byte(`{"value":42}`))
})
defer stop()
if err := runAPI(context.Background(), &Options{}, &cmdutil.FormatOptions{Mode: cmdutil.FormatJSON}, cli, "GET", "/api/v1/foo", false); err != nil {
t.Fatalf("runAPI: %v", err)
}
// The server response is passed through directly under envelope.data — no
// {status, headers, body} wrapper — so consumers project at the server's
// own depth (e.g. .data.value here).
var env struct {
OK bool `json:"ok"`
Data map[string]any `json:"data"`
}
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")
}
if v, ok := env.Data["value"]; !ok || v.(float64) != 42 {
t.Errorf("data.value: want 42 directly under .data (no .body nesting), got %v", env.Data)
}
}
// TestAPI_InlineDataBody verifies -d/--data sends an inline JSON body and
// auto-promotes the method to POST.
func TestAPI_InlineDataBody(t *testing.T) {
_, _ = iostreams.SetForTest(t)
var seenBody []byte
var seenMethod string
cli, stop := newTestClient(t, func(w http.ResponseWriter, r *http.Request) {
seenMethod = r.Method
seenBody, _ = io.ReadAll(r.Body)
_, _ = w.Write([]byte(`{"id":"new"}`))
})
defer stop()
opts := &Options{Data: `{"name":"foo"}`}
if err := runAPI(context.Background(), opts, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, cli, resolveMethod(opts), "/api/v1/things", false); err != nil {
t.Fatalf("runAPI: %v", err)
}
if seenMethod != http.MethodPost {
t.Errorf("inline -d should auto-promote to POST, got %s", seenMethod)
}
if string(seenBody) != `{"name":"foo"}` {
t.Errorf("server received body %q, want the inline --data JSON", seenBody)
}
}
// TestAPI_InlineDataMalformed_RejectedAsInput pins that a malformed -d body is
// rejected as input.invalid_argument before any request.
func TestAPI_InlineDataMalformed_RejectedAsInput(t *testing.T) {
_, _ = iostreams.SetForTest(t)
called := false
cli, stop := newTestClient(t, func(w http.ResponseWriter, r *http.Request) {
called = true
_, _ = w.Write([]byte(`{}`))
})
defer stop()
opts := &Options{Data: `{bad`}
err := runAPI(context.Background(), opts, &cmdutil.FormatOptions{Mode: cmdutil.FormatJSON}, cli, "POST", "/api/v1/things", false)
var typed *cmdutil.Error
if !errors.As(err, &typed) || typed.Code != cmdutil.CodeInputInvalidArgument {
t.Errorf("want input.invalid_argument for malformed -d, got %v", err)
}
if called {
t.Error("server must not be called with a malformed inline body")
}
}
func TestAPI_PostWithStdinInput(t *testing.T) {
_, _ = iostreams.SetForTest(t)
var seenBody []byte
var seenMethod, seenPath string
cli, stop := newTestClient(t, func(w http.ResponseWriter, r *http.Request) {
seenMethod = r.Method
seenPath = r.URL.Path
seenBody, _ = io.ReadAll(r.Body)
w.Header().Set("Content-Type", "application/json")
_, _ = w.Write([]byte(`{"id":"new"}`))
})
defer stop()
opts := &Options{Input: "-", StdinReader: strings.NewReader(`{"name":"foo"}`)}
if err := runAPI(context.Background(), opts, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, 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)
}
if string(seenBody) != `{"name":"foo"}` {
t.Errorf("server received body %q, want %q", seenBody, `{"name":"foo"}`)
}
}
// TestAPI_MalformedInputJSON_RejectedAsInput pins that a non-JSON --input body
// is rejected with input.invalid_argument (exit 5) at the boundary, not the
// confusing network.error (exit 7, "retryable") the SDK's marshal step
// produced. The server must never be called.
func TestAPI_MalformedInputJSON_RejectedAsInput(t *testing.T) {
_, _ = iostreams.SetForTest(t)
called := false
cli, stop := newTestClient(t, func(w http.ResponseWriter, r *http.Request) {
called = true
_, _ = w.Write([]byte(`{}`))
})
defer stop()
opts := &Options{Input: "-", StdinReader: strings.NewReader(`{bad json`)}
err := runAPI(context.Background(), opts, &cmdutil.FormatOptions{Mode: cmdutil.FormatJSON}, cli, "POST", "/api/v1/things", false)
if err == nil {
t.Fatal("expected an error for malformed --input JSON")
}
var typed *cmdutil.Error
if !errors.As(err, &typed) || typed.Code != cmdutil.CodeInputInvalidArgument {
t.Errorf("want input.invalid_argument, got %v", err)
}
if called {
t.Error("server must not be called with a malformed body")
}
}
// TestAPI_InputFile verifies --input <file> reads the request body from disk.
func TestAPI_InputFile(t *testing.T) {
_, _ = iostreams.SetForTest(t)
tmp := filepath.Join(t.TempDir(), "body.json")
payload := `{"k":"from-file"}`
if err := os.WriteFile(tmp, []byte(payload), 0o600); err != nil {
t.Fatalf("write temp: %v", err)
}
var seenBody []byte
cli, stop := newTestClient(t, func(w http.ResponseWriter, r *http.Request) {
seenBody, _ = io.ReadAll(r.Body)
_, _ = w.Write([]byte(`{}`))
})
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 {
t.Fatalf("runAPI: %v", err)
}
if string(seenBody) != payload {
t.Errorf("body from --input: got %q, want %q", seenBody, payload)
}
}
// TestAPI_InputDash_Stdin verifies the "--input -" form: the payload comes
// from opts.StdinReader (production-default iostreams.IO.In).
func TestAPI_InputDash_Stdin(t *testing.T) {
_, _ = iostreams.SetForTest(t)
var seenBody []byte
cli, stop := newTestClient(t, func(w http.ResponseWriter, r *http.Request) {
seenBody, _ = io.ReadAll(r.Body)
_, _ = w.Write([]byte(`{}`))
})
defer stop()
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 {
t.Fatalf("runAPI: %v", err)
}
if string(seenBody) != payload {
t.Errorf("body from --input -: got %q, want %q", seenBody, payload)
}
}
func TestAPI_NotFound(t *testing.T) {
_, _ = iostreams.SetForTest(t)
cli, stop := newTestClient(t, func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusNotFound)
_, _ = w.Write([]byte(`{"error":"missing"}`))
})
defer stop()
err := runAPI(context.Background(), &Options{}, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, cli, "GET", "/api/v1/missing", false)
if err == nil {
t.Fatal("expected error for 404")
}
if !cmdutil.IsNotFound(err) {
t.Errorf("expected resource.not_found, got %v", err)
}
}
func TestAPI_AcceptsArbitraryMethod(t *testing.T) {
_, _ = iostreams.SetForTest(t)
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.FormatText}, 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)
}
})
}
}
func TestAPI_EmptyMethodRejected(t *testing.T) {
_, _ = iostreams.SetForTest(t)
err := runAPI(context.Background(), &Options{}, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, 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)
if err == nil {
t.Fatal("expected error for missing leading slash")
}
var ce *cmdutil.Error
if !asTypedError(err, &ce) || ce.Code != cmdutil.CodeInputInvalidArgument {
t.Errorf("expected input.invalid_argument, got %v", err)
}
}
// withRootHarness wraps `weknora api ...` under a synthetic root cmd that
// registers the global persistent flags (mirrors addGlobalFlags in
// cmd/root.go). Required because api's NewCmd doesn't register --yes /
// --format / --jq itself — it inherits them from root in production.
func withRootHarness(api *cobra.Command, args ...string) *cobra.Command {
root := &cobra.Command{Use: "weknora"}
pf := root.PersistentFlags()
pf.BoolP("yes", "y", false, "")
pf.String("format", "", "")
pf.StringP("jq", "q", "", "")
root.AddCommand(api)
root.SetArgs(append([]string{"api"}, args...))
root.SetContext(context.Background())
root.SilenceErrors = true
root.SilenceUsage = true
return root
}
// TestAPI_DELETE_RequiresConfirmation pins the exit-10 protocol on the
// escape-hatch DELETE path: agent invokes `weknora api DELETE /...` without
// -y/--yes, must get input.confirmation_required + exit 10. Confirmation is
// enforced in NewCmd.RunE (not runAPI), so the test drives the cobra cmd.
func TestAPI_DELETE_RequiresConfirmation(t *testing.T) {
iostreams.SetForTest(t) // non-TTY
f := &cmdutil.Factory{
Client: func() (*sdk.Client, error) { return nil, nil },
Prompter: func() prompt.Prompter { return prompt.AgentPrompter{} },
}
root := withRootHarness(NewCmd(f), "/api/v1/knowledge-bases/kb_xxx", "-X", "DELETE")
err := root.Execute()
if err == nil {
t.Fatal("expected confirmation_required error for DELETE without -y")
}
var ce *cmdutil.Error
if !asTypedError(err, &ce) || ce.Code != cmdutil.CodeInputConfirmationRequired {
t.Errorf("want input.confirmation_required, got %v", err)
}
if got := cmdutil.ExitCode(err); got != 10 {
t.Errorf("exit code = %d, want 10", got)
}
}
// TestAPI_DELETE_WithYes_Proceeds: -y/--yes opt-in skips confirmation and
// dispatches to the SDK. Server returns 200 to verify the happy-path lands
// on the response body emit.
func TestAPI_DELETE_WithYes_Proceeds(t *testing.T) {
iostreams.SetForTest(t)
called := false
cli, stop := newTestClient(t, func(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodDelete {
t.Errorf("expected DELETE, got %s", r.Method)
}
called = true
w.WriteHeader(http.StatusOK)
})
defer stop()
f := &cmdutil.Factory{
Client: func() (*sdk.Client, error) { return cli, nil },
Prompter: func() prompt.Prompter { return prompt.AgentPrompter{} },
}
root := withRootHarness(NewCmd(f), "/api/v1/knowledge-bases/kb_xxx", "-X", "DELETE", "-y")
if err := root.Execute(); err != nil {
t.Fatalf("execute: %v", err)
}
if !called {
t.Error("DELETE handler not called - confirmation may have blocked")
}
}
// asTypedError is a tiny wrapper around errors.As that keeps the call sites
// concise. Returns true on success, populating dst.
func asTypedError(err error, dst **cmdutil.Error) bool {
for e := err; e != nil; {
if t, ok := e.(*cmdutil.Error); ok {
*dst = t
return true
}
type unwrapper interface{ Unwrap() error }
u, ok := e.(unwrapper)
if !ok {
return false
}
e = u.Unwrap()
}
return false
}
func TestAPI_PaginateMergesPages(t *testing.T) {
pages := [][]byte{
[]byte(`{"success":true,"data":[{"id":"1"},{"id":"2"}],"total":5,"page":1,"page_size":2}`),
[]byte(`{"success":true,"data":[{"id":"3"},{"id":"4"}],"total":5,"page":2,"page_size":2}`),
[]byte(`{"success":true,"data":[{"id":"5"}],"total":5,"page":3,"page_size":2}`),
}
idx := 0
svc := &fakeAPISvc{do: func(method, path string, _ any) (*http.Response, error) {
if idx >= len(pages) {
return nil, fmt.Errorf("too many calls; idx=%d", idx)
}
body := pages[idx]
idx++
return &http.Response{
StatusCode: 200,
Body: io.NopCloser(bytes.NewReader(body)),
Header: make(http.Header),
}, nil
}}
out, _ := iostreams.SetForTest(t)
opts := &Options{}
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 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(), &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)
}
if idx != 3 {
t.Errorf("called %d times, want 3", idx)
}
}
func TestAPI_PaginateIgnoredForPOST(t *testing.T) {
// --paginate should be a no-op for non-GET methods (no pagination
// semantic for POST/PUT/DELETE). Single call expected.
called := 0
svc := &fakeAPISvc{do: func(method, path string, _ any) (*http.Response, error) {
called++
return &http.Response{
StatusCode: 200,
Body: io.NopCloser(bytes.NewReader([]byte(`{"success":true,"data":[],"total":5,"page":1,"page_size":2}`))),
Header: make(http.Header),
}, nil
}}
_, _ = iostreams.SetForTest(t)
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)
}
if called != 1 {
t.Errorf("called %d times, want 1 (POST should not paginate)", called)
}
}
func TestAPI_PaginateNoMetadataPassesThrough(t *testing.T) {
// If response doesn't look paginated (no total/page/page_size), --paginate
// 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: hdr,
}, nil
}}
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 {
t.Fatalf("runAPI: %v", err)
}
if called != 1 {
t.Errorf("called %d times, want 1 (non-paginated response)", called)
}
// The non-paginated fallback must emit the SAME flat shape as a single
// call: the server response directly under .data (no {status,headers,body}
// wrapper), so --paginate and single-call project identically.
var env struct {
OK bool `json:"ok"`
Data map[string]any `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 v, ok := env.Data["hello"]; !ok || v.(string) != "world" {
t.Errorf("fallback must pass the body through flat under .data (.data.hello), got %v", env.Data)
}
}
// TestAPI_PaginateServerCapsPageSize covers the case where the user
// requests --page_size=50 but the server caps page_size at a smaller
// value (e.g. 2). Termination must count actually-collected records
// (len(allData)) not requested-page-count (page*pageSize) — otherwise
// we'd break early and silently truncate results.
func TestAPI_PaginateServerCapsPageSize(t *testing.T) {
// User asks page_size=10; server only ever returns 2 per page (cap).
// Total = 5 records; should make 3 calls (2+2+1) and return all 5.
pages := [][]byte{
[]byte(`{"success":true,"data":[{"id":"1"},{"id":"2"}],"total":5,"page":1,"page_size":2}`),
[]byte(`{"success":true,"data":[{"id":"3"},{"id":"4"}],"total":5,"page":2,"page_size":2}`),
[]byte(`{"success":true,"data":[{"id":"5"}],"total":5,"page":3,"page_size":2}`),
}
idx := 0
svc := &fakeAPISvc{do: func(_, _ string, _ any) (*http.Response, error) {
if idx >= len(pages) {
return nil, fmt.Errorf("too many calls; idx=%d", idx)
}
body := pages[idx]
idx++
return &http.Response{
StatusCode: 200,
Body: io.NopCloser(bytes.NewReader(body)),
Header: make(http.Header),
}, nil
}}
var stdout bytes.Buffer
iostreams.IO.Out = &stdout
defer func() { iostreams.IO.Out = os.Stdout }()
opts := &Options{}
// User requests page_size=10; server caps at 2 each response.
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 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(), &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))
}
}
// TestAPI_PUT_RequiresConfirmation pins the exit-10 write gate on the
// escape-hatch PUT path: `weknora api -X PUT /...` mutates server state the
// same way a typed `kb update` does, so it must require -y (exit 10) rather
// than silently writing. Regression: only DELETE was gated, letting an agent
// bypass the write-confirmation protocol via raw PUT/PATCH.
func TestAPI_PUT_RequiresConfirmation(t *testing.T) {
for _, method := range []string{"PUT", "PATCH"} {
t.Run(method, func(t *testing.T) {
iostreams.SetForTest(t) // non-TTY
f := &cmdutil.Factory{
Client: func() (*sdk.Client, error) { return nil, nil },
Prompter: func() prompt.Prompter { return prompt.AgentPrompter{} },
}
root := withRootHarness(NewCmd(f), "/api/v1/knowledge-bases/kb_xxx", "-X", method, "-F", "name=x")
err := root.Execute()
if err == nil {
t.Fatalf("expected confirmation_required for %s without -y", method)
}
var ce *cmdutil.Error
if !asTypedError(err, &ce) || ce.Code != cmdutil.CodeInputConfirmationRequired {
t.Errorf("want input.confirmation_required, got %v", err)
}
if got := cmdutil.ExitCode(err); got != 10 {
t.Errorf("exit code = %d, want 10", got)
}
})
}
}
// TestAPI_POST_NotGated: POST is create-shaped and, like typed `kb create`,
// intentionally ungated — it must reach the SDK without a confirmation gate.
func TestAPI_POST_NotGated(t *testing.T) {
iostreams.SetForTest(t)
called := false
cli, stop := newTestClient(t, func(w http.ResponseWriter, r *http.Request) {
called = true
w.WriteHeader(http.StatusOK)
})
defer stop()
f := &cmdutil.Factory{
Client: func() (*sdk.Client, error) { return cli, nil },
Prompter: func() prompt.Prompter { return prompt.AgentPrompter{} },
}
root := withRootHarness(NewCmd(f), "/api/v1/knowledge-bases", "-X", "POST", "-F", "name=x")
if err := root.Execute(); err != nil {
t.Fatalf("execute: %v", err)
}
if !called {
t.Error("POST handler not called - POST must not be gated")
}
}