feat(cli): api --input + completion smoke
api (3-11):
- `--input <file>` reads the request body from disk; `--input -` reads
from stdin. Matches gh CLI canonical naming verified against the gh
manual ("The file to use as body for the HTTP request — use \"-\" to
read from standard input"). `--data` / `--input` are mutually
exclusive.
- Options.StdinReader (defaults to iostreams.IO.In) for test injection.
completion (3-13 smoke only — release-artifact ship deferred to release
milestone):
- Smoke test asserts cobra's auto-registered bash/zsh/fish/powershell
scripts produce non-trivially-sized output with the per-shell
signature (#compdef / complete -c weknora / etc.). Guards against
cobra bumps silently breaking completion for one shell.
3-14 doctor --no-cache: already implemented (factory.go:297) with
TestDoctor_NoCache_BypassesCache covering it — verified, no change
needed.
Roadmap: 3-11, 3-13 (smoke), 3-14 (verified).
This commit is contained in:
+43
-21
@@ -1,12 +1,11 @@
|
|||||||
// Package api implements the `weknora api` raw HTTP passthrough command.
|
// Package api implements the `weknora api` raw HTTP passthrough command.
|
||||||
//
|
//
|
||||||
// Mirrors `gh api` ergonomics: 1 positional (path) + `-X/--method` flag,
|
// Mirrors `gh api` ergonomics (verified against the gh manual): one
|
||||||
// default GET (auto-promoted to POST when a body is supplied via --data /
|
// positional (path) + `-X/--method` flag, default GET (auto-promoted to
|
||||||
// --data-file). The two body-source flags are mutually exclusive. Default
|
// POST when a body is supplied via --data or --input). The two body-
|
||||||
// raw response body to stdout; --json wraps in CLI envelope. Reuses
|
// source flags are mutually exclusive. Default raw response body to
|
||||||
// sdk.Client.Raw which already applies tenant + auth headers; v0.2 does not
|
// stdout; --json wraps in CLI envelope. Reuses sdk.Client.Raw which
|
||||||
// support --header (SDK Raw signature lacks header param) — that's planned
|
// already applies tenant + auth headers.
|
||||||
// for v0.3.
|
|
||||||
package api
|
package api
|
||||||
|
|
||||||
import (
|
import (
|
||||||
@@ -29,12 +28,13 @@ import (
|
|||||||
|
|
||||||
// Options captures `weknora api` flag state.
|
// Options captures `weknora api` flag state.
|
||||||
type Options struct {
|
type Options struct {
|
||||||
Method string
|
Method string
|
||||||
Data string
|
Data string
|
||||||
DataFile string
|
Input string // --input: file path, "-" for stdin
|
||||||
JSONOut bool
|
JSONOut bool
|
||||||
DryRun bool
|
DryRun bool
|
||||||
Yes bool
|
Yes bool
|
||||||
|
StdinReader io.Reader // overridden by tests; defaults to iostreams.IO.In
|
||||||
}
|
}
|
||||||
|
|
||||||
// Service is the narrow SDK surface this command depends on. The production
|
// Service is the narrow SDK surface this command depends on. The production
|
||||||
@@ -53,7 +53,7 @@ func NewCmd(f *cmdutil.Factory) *cobra.Command {
|
|||||||
Short: "Make a raw API request to the WeKnora server",
|
Short: "Make a raw API request to the WeKnora server",
|
||||||
Long: `Send an HTTP request through the SDK and print the response.
|
Long: `Send an HTTP request through the SDK and print the response.
|
||||||
|
|
||||||
The default method is GET; passing --data / --data-file auto-promotes it to
|
The default method is GET; passing --data / --input auto-promotes it to
|
||||||
POST. Use -X/--method to override (DELETE / PUT / PATCH / HEAD).
|
POST. Use -X/--method to override (DELETE / PUT / PATCH / HEAD).
|
||||||
|
|
||||||
Auth, tenant, and request-id headers are applied automatically from the
|
Auth, tenant, and request-id headers are applied automatically from the
|
||||||
@@ -89,20 +89,42 @@ Examples:
|
|||||||
}
|
}
|
||||||
cmd.Flags().StringVarP(&opts.Method, "method", "X", "", "HTTP method (default: GET, or POST when a body is supplied)")
|
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.Data, "data", "d", "", "Request body as raw string (e.g. JSON)")
|
||||||
cmd.Flags().StringVar(&opts.DataFile, "data-file", "", "Read request body from file")
|
cmd.Flags().StringVar(&opts.Input, "input", "", "Read request body from file (use `-` for stdin); gh CLI parity")
|
||||||
cmd.Flags().BoolVar(&opts.JSONOut, "json", false, "Wrap response in JSON envelope (status/headers/body)")
|
cmd.Flags().BoolVar(&opts.JSONOut, "json", false, "Wrap response in JSON envelope (status/headers/body)")
|
||||||
cmd.MarkFlagsMutuallyExclusive("data", "data-file")
|
cmd.MarkFlagsMutuallyExclusive("data", "input")
|
||||||
agent.SetAgentHelp(cmd, "Raw HTTP passthrough to the WeKnora server. Use when no typed command exists for the endpoint. Headers (auth / tenant / request-id) are injected from the active context.")
|
agent.SetAgentHelp(cmd, "Raw HTTP passthrough to the WeKnora server. Use when no typed command exists for the endpoint. Headers (auth / tenant / request-id) are injected from the active context.")
|
||||||
return cmd
|
return cmd
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// readInput reads opts.Input and returns its contents. "-" reads from
|
||||||
|
// opts.StdinReader (or iostreams.IO.In as the production default).
|
||||||
|
// Mirrors gh `api --input -` for piped JSON payloads.
|
||||||
|
func readInput(opts *Options) ([]byte, error) {
|
||||||
|
if opts.Input == "-" {
|
||||||
|
r := opts.StdinReader
|
||||||
|
if r == nil {
|
||||||
|
r = iostreams.IO.In
|
||||||
|
}
|
||||||
|
b, err := io.ReadAll(r)
|
||||||
|
if err != nil {
|
||||||
|
return nil, cmdutil.Wrapf(cmdutil.CodeLocalFileIO, err, "read request body from stdin")
|
||||||
|
}
|
||||||
|
return b, nil
|
||||||
|
}
|
||||||
|
b, err := os.ReadFile(opts.Input)
|
||||||
|
if err != nil {
|
||||||
|
return nil, cmdutil.Wrapf(cmdutil.CodeLocalFileIO, err, "read input file %s", opts.Input)
|
||||||
|
}
|
||||||
|
return b, nil
|
||||||
|
}
|
||||||
|
|
||||||
// resolveMethod implements gh's auto-method behavior: explicit -X wins;
|
// resolveMethod implements gh's auto-method behavior: explicit -X wins;
|
||||||
// otherwise body presence promotes GET → POST.
|
// otherwise body presence promotes GET → POST.
|
||||||
func resolveMethod(opts *Options) string {
|
func resolveMethod(opts *Options) string {
|
||||||
if opts.Method != "" {
|
if opts.Method != "" {
|
||||||
return strings.ToUpper(opts.Method)
|
return strings.ToUpper(opts.Method)
|
||||||
}
|
}
|
||||||
if opts.Data != "" || opts.DataFile != "" {
|
if opts.Data != "" || opts.Input != "" {
|
||||||
return "POST"
|
return "POST"
|
||||||
}
|
}
|
||||||
return "GET"
|
return "GET"
|
||||||
@@ -124,16 +146,16 @@ func runAPI(ctx context.Context, opts *Options, svc Service, method, path string
|
|||||||
return cmdutil.NewError(cmdutil.CodeInputInvalidArgument, fmt.Sprintf("path must start with /: %s", path))
|
return cmdutil.NewError(cmdutil.CodeInputInvalidArgument, fmt.Sprintf("path must start with /: %s", path))
|
||||||
}
|
}
|
||||||
|
|
||||||
// Resolve request body. --data and --data-file are mutually exclusive at
|
// Resolve request body. --data and --input are mutually exclusive at
|
||||||
// the cobra layer; the second branch is reachable only when --data is
|
// the cobra layer; the second branch is reachable only when --data is
|
||||||
// empty.
|
// empty.
|
||||||
var body any
|
var body any
|
||||||
if opts.Data != "" {
|
if opts.Data != "" {
|
||||||
body = json.RawMessage(opts.Data)
|
body = json.RawMessage(opts.Data)
|
||||||
} else if opts.DataFile != "" {
|
} else if opts.Input != "" {
|
||||||
contents, err := os.ReadFile(opts.DataFile)
|
contents, err := readInput(opts)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return cmdutil.Wrapf(cmdutil.CodeLocalFileIO, err, "read data file %s", opts.DataFile)
|
return err
|
||||||
}
|
}
|
||||||
body = json.RawMessage(contents)
|
body = json.RawMessage(contents)
|
||||||
}
|
}
|
||||||
|
|||||||
+26
-3
@@ -117,7 +117,9 @@ func TestAPI_PostWithData(t *testing.T) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func TestAPI_DataFile(t *testing.T) {
|
// TestAPI_InputFile verifies --input <file> reads the request body from
|
||||||
|
// disk. gh CLI parity (verified against gh manual: `--input <file>`).
|
||||||
|
func TestAPI_InputFile(t *testing.T) {
|
||||||
_, _ = iostreams.SetForTest(t)
|
_, _ = iostreams.SetForTest(t)
|
||||||
tmp := filepath.Join(t.TempDir(), "body.json")
|
tmp := filepath.Join(t.TempDir(), "body.json")
|
||||||
payload := `{"k":"from-file"}`
|
payload := `{"k":"from-file"}`
|
||||||
@@ -131,12 +133,33 @@ func TestAPI_DataFile(t *testing.T) {
|
|||||||
})
|
})
|
||||||
defer stop()
|
defer stop()
|
||||||
|
|
||||||
opts := &Options{DataFile: tmp}
|
opts := &Options{Input: tmp}
|
||||||
if err := runAPI(context.Background(), opts, cli, "POST", "/api/v1/x"); err != nil {
|
if err := runAPI(context.Background(), opts, cli, "POST", "/api/v1/x"); err != nil {
|
||||||
t.Fatalf("runAPI: %v", err)
|
t.Fatalf("runAPI: %v", err)
|
||||||
}
|
}
|
||||||
if string(seenBody) != payload {
|
if string(seenBody) != payload {
|
||||||
t.Errorf("body from --data-file: got %q, want %q", seenBody, payload)
|
t.Errorf("body from --input: got %q, want %q", seenBody, payload)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// TestAPI_InputDash_Stdin verifies the gh-style "--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, cli, "POST", "/api/v1/x"); err != nil {
|
||||||
|
t.Fatalf("runAPI: %v", err)
|
||||||
|
}
|
||||||
|
if string(seenBody) != payload {
|
||||||
|
t.Errorf("body from --input -: got %q, want %q", seenBody, payload)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,46 @@
|
|||||||
|
package cmd
|
||||||
|
|
||||||
|
import (
|
||||||
|
"bytes"
|
||||||
|
"strings"
|
||||||
|
"testing"
|
||||||
|
|
||||||
|
"github.com/Tencent/WeKnora/cli/internal/cmdutil"
|
||||||
|
)
|
||||||
|
|
||||||
|
// TestCompletion_AllShells smoke-tests cobra's auto-registered completion
|
||||||
|
// command. The output is shell-specific bytecode/script; the test just
|
||||||
|
// asserts each shell produces a non-trivially-sized script and references
|
||||||
|
// the binary name. Guards against future cobra bumps silently breaking
|
||||||
|
// completion for one shell.
|
||||||
|
func TestCompletion_AllShells(t *testing.T) {
|
||||||
|
cases := []struct {
|
||||||
|
shell string
|
||||||
|
mustContain string // signature byte sequence specific to the shell
|
||||||
|
minSizeBytes int
|
||||||
|
}{
|
||||||
|
{"bash", "bash completion", 1024},
|
||||||
|
{"zsh", "#compdef", 1024},
|
||||||
|
{"fish", "complete -c weknora", 1024},
|
||||||
|
{"powershell", "Register-ArgumentCompleter", 1024},
|
||||||
|
}
|
||||||
|
for _, tc := range cases {
|
||||||
|
t.Run(tc.shell, func(t *testing.T) {
|
||||||
|
cmd := NewRootCmd(&cmdutil.Factory{})
|
||||||
|
var buf bytes.Buffer
|
||||||
|
cmd.SetOut(&buf)
|
||||||
|
cmd.SetErr(&buf)
|
||||||
|
cmd.SetArgs([]string{"completion", tc.shell})
|
||||||
|
if err := cmd.Execute(); err != nil {
|
||||||
|
t.Fatalf("completion %s: %v", tc.shell, err)
|
||||||
|
}
|
||||||
|
if buf.Len() < tc.minSizeBytes {
|
||||||
|
t.Errorf("%s script suspiciously short: %d bytes", tc.shell, buf.Len())
|
||||||
|
}
|
||||||
|
if !strings.Contains(buf.String(), tc.mustContain) {
|
||||||
|
t.Errorf("%s script missing signature %q (first 200 bytes: %q)",
|
||||||
|
tc.shell, tc.mustContain, buf.String()[:min(200, buf.Len())])
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
Reference in New Issue
Block a user