2026-05-12 15:33:44 +00:00
|
|
|
package contextcmd
|
|
|
|
|
|
|
|
|
|
import (
|
|
|
|
|
"encoding/json"
|
|
|
|
|
"strings"
|
|
|
|
|
"testing"
|
|
|
|
|
|
|
|
|
|
"github.com/Tencent/WeKnora/cli/internal/cmdutil"
|
|
|
|
|
"github.com/Tencent/WeKnora/cli/internal/config"
|
|
|
|
|
"github.com/Tencent/WeKnora/cli/internal/iostreams"
|
|
|
|
|
)
|
|
|
|
|
|
|
|
|
|
func TestAdd_HappyPath(t *testing.T) {
|
|
|
|
|
t.Setenv("XDG_CONFIG_HOME", t.TempDir())
|
|
|
|
|
out, _ := iostreams.SetForTest(t)
|
|
|
|
|
|
feat(cli): --json field-select, --jq, auth token, doc --from-url
Output ergonomics:
- `--json` accepts a comma-separated field list (gh-parity); selects
named keys from the per-command payload. Bare `--json` keeps the
full shape.
- `--jq <expr>` evaluates a gojq expression over the JSON; pairs with
`--json field-list` so projection runs before jq.
- `--version` is a global cobra flag in addition to the `version`
subcommand; both render the same line.
- Per-command `--help` now renders the available JSON field list under
"JSON fields available via `--json id,name,...`" (field-discovery
parity with gh / kubectl `-o jsonpath`).
New commands:
- `auth token` — print the active context's credential to stdout for
shell command substitution (`WEKNORA_TOKEN=$(weknora auth token)`).
Default: raw secret, no trailing newline. `--json` emits
`{token, mode, context}`.
- `doc upload --from-url <URL>` — ingest a remote URL via the SDK
`CreateKnowledgeFromURL`. `--name` forwarded as `FileName` so the
server's known-extension heuristic upgrades crawl-mode to
file-download-mode where appropriate.
Includes the simplify post-review polish pass (field-filter unit
tests, --json/--jq compose check, agent_help copy fixes).
2026-05-14 15:28:14 +00:00
|
|
|
if err := runAdd(&AddOptions{Host: "https://my.example.com", User: "alice@example.com"}, nil, "staging"); err != nil {
|
2026-05-12 15:33:44 +00:00
|
|
|
t.Fatalf("runAdd: %v", err)
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
cfg, err := config.Load()
|
|
|
|
|
if err != nil {
|
|
|
|
|
t.Fatalf("Load: %v", err)
|
|
|
|
|
}
|
|
|
|
|
c, ok := cfg.Contexts["staging"]
|
|
|
|
|
if !ok {
|
|
|
|
|
t.Fatalf("staging not in Contexts; got keys=%v", contextKeys(cfg.Contexts))
|
|
|
|
|
}
|
|
|
|
|
if c.Host != "https://my.example.com" {
|
|
|
|
|
t.Errorf("Host=%q, want https://my.example.com", c.Host)
|
|
|
|
|
}
|
|
|
|
|
if c.User != "alice@example.com" {
|
|
|
|
|
t.Errorf("User=%q, want alice@example.com", c.User)
|
|
|
|
|
}
|
|
|
|
|
// First context auto-becomes current.
|
|
|
|
|
if cfg.CurrentContext != "staging" {
|
|
|
|
|
t.Errorf("first context should auto-become current, got CurrentContext=%q", cfg.CurrentContext)
|
|
|
|
|
}
|
|
|
|
|
if !strings.Contains(out.String(), "staging") {
|
|
|
|
|
t.Errorf("output should mention added name, got %q", out.String())
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
func TestAdd_DuplicateName(t *testing.T) {
|
|
|
|
|
t.Setenv("XDG_CONFIG_HOME", t.TempDir())
|
|
|
|
|
_, _ = iostreams.SetForTest(t)
|
|
|
|
|
|
|
|
|
|
cfg := &config.Config{
|
|
|
|
|
CurrentContext: "staging",
|
|
|
|
|
Contexts: map[string]config.Context{"staging": {Host: "https://old.example.com"}},
|
|
|
|
|
}
|
|
|
|
|
if err := config.Save(cfg); err != nil {
|
|
|
|
|
t.Fatalf("Save: %v", err)
|
|
|
|
|
}
|
|
|
|
|
|
feat(cli): --json field-select, --jq, auth token, doc --from-url
Output ergonomics:
- `--json` accepts a comma-separated field list (gh-parity); selects
named keys from the per-command payload. Bare `--json` keeps the
full shape.
- `--jq <expr>` evaluates a gojq expression over the JSON; pairs with
`--json field-list` so projection runs before jq.
- `--version` is a global cobra flag in addition to the `version`
subcommand; both render the same line.
- Per-command `--help` now renders the available JSON field list under
"JSON fields available via `--json id,name,...`" (field-discovery
parity with gh / kubectl `-o jsonpath`).
New commands:
- `auth token` — print the active context's credential to stdout for
shell command substitution (`WEKNORA_TOKEN=$(weknora auth token)`).
Default: raw secret, no trailing newline. `--json` emits
`{token, mode, context}`.
- `doc upload --from-url <URL>` — ingest a remote URL via the SDK
`CreateKnowledgeFromURL`. `--name` forwarded as `FileName` so the
server's known-extension heuristic upgrades crawl-mode to
file-download-mode where appropriate.
Includes the simplify post-review polish pass (field-filter unit
tests, --json/--jq compose check, agent_help copy fixes).
2026-05-14 15:28:14 +00:00
|
|
|
err := runAdd(&AddOptions{Host: "https://new.example.com"}, nil, "staging")
|
2026-05-12 15:33:44 +00:00
|
|
|
if err == nil {
|
|
|
|
|
t.Fatal("expected error on duplicate name")
|
|
|
|
|
}
|
|
|
|
|
cm, ok := err.(*cmdutil.Error)
|
|
|
|
|
if !ok {
|
|
|
|
|
t.Fatalf("expected *cmdutil.Error, got %T", err)
|
|
|
|
|
}
|
|
|
|
|
if cm.Code != cmdutil.CodeResourceAlreadyExists {
|
|
|
|
|
t.Errorf("code=%q, want %q", cm.Code, cmdutil.CodeResourceAlreadyExists)
|
|
|
|
|
}
|
|
|
|
|
// Existing entry must NOT be overwritten.
|
|
|
|
|
got, _ := config.Load()
|
|
|
|
|
if got.Contexts["staging"].Host != "https://old.example.com" {
|
|
|
|
|
t.Errorf("existing context overwritten; Host=%q", got.Contexts["staging"].Host)
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
func TestAdd_BadHost(t *testing.T) {
|
|
|
|
|
t.Setenv("XDG_CONFIG_HOME", t.TempDir())
|
|
|
|
|
_, _ = iostreams.SetForTest(t)
|
|
|
|
|
|
|
|
|
|
bad := []string{
|
|
|
|
|
"", // empty
|
|
|
|
|
"my.example.com", // missing scheme
|
|
|
|
|
"ftp://my.example.com", // wrong scheme
|
|
|
|
|
"http://", // missing host
|
|
|
|
|
}
|
|
|
|
|
for _, h := range bad {
|
feat(cli): --json field-select, --jq, auth token, doc --from-url
Output ergonomics:
- `--json` accepts a comma-separated field list (gh-parity); selects
named keys from the per-command payload. Bare `--json` keeps the
full shape.
- `--jq <expr>` evaluates a gojq expression over the JSON; pairs with
`--json field-list` so projection runs before jq.
- `--version` is a global cobra flag in addition to the `version`
subcommand; both render the same line.
- Per-command `--help` now renders the available JSON field list under
"JSON fields available via `--json id,name,...`" (field-discovery
parity with gh / kubectl `-o jsonpath`).
New commands:
- `auth token` — print the active context's credential to stdout for
shell command substitution (`WEKNORA_TOKEN=$(weknora auth token)`).
Default: raw secret, no trailing newline. `--json` emits
`{token, mode, context}`.
- `doc upload --from-url <URL>` — ingest a remote URL via the SDK
`CreateKnowledgeFromURL`. `--name` forwarded as `FileName` so the
server's known-extension heuristic upgrades crawl-mode to
file-download-mode where appropriate.
Includes the simplify post-review polish pass (field-filter unit
tests, --json/--jq compose check, agent_help copy fixes).
2026-05-14 15:28:14 +00:00
|
|
|
err := runAdd(&AddOptions{Host: h}, nil, "staging")
|
2026-05-12 15:33:44 +00:00
|
|
|
if err == nil {
|
|
|
|
|
t.Errorf("host=%q: expected error", h)
|
|
|
|
|
continue
|
|
|
|
|
}
|
|
|
|
|
cm, ok := err.(*cmdutil.Error)
|
|
|
|
|
if !ok {
|
|
|
|
|
t.Errorf("host=%q: expected *cmdutil.Error, got %T", h, err)
|
|
|
|
|
continue
|
|
|
|
|
}
|
|
|
|
|
if cm.Code != cmdutil.CodeInputInvalidArgument {
|
|
|
|
|
t.Errorf("host=%q: code=%q, want %q", h, cm.Code, cmdutil.CodeInputInvalidArgument)
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
func TestAdd_SecondContextDoesNotChangeCurrent(t *testing.T) {
|
|
|
|
|
t.Setenv("XDG_CONFIG_HOME", t.TempDir())
|
|
|
|
|
_, _ = iostreams.SetForTest(t)
|
|
|
|
|
|
|
|
|
|
cfg := &config.Config{
|
|
|
|
|
CurrentContext: "production",
|
|
|
|
|
Contexts: map[string]config.Context{"production": {Host: "https://prod.example.com"}},
|
|
|
|
|
}
|
|
|
|
|
if err := config.Save(cfg); err != nil {
|
|
|
|
|
t.Fatalf("Save: %v", err)
|
|
|
|
|
}
|
|
|
|
|
|
feat(cli): --json field-select, --jq, auth token, doc --from-url
Output ergonomics:
- `--json` accepts a comma-separated field list (gh-parity); selects
named keys from the per-command payload. Bare `--json` keeps the
full shape.
- `--jq <expr>` evaluates a gojq expression over the JSON; pairs with
`--json field-list` so projection runs before jq.
- `--version` is a global cobra flag in addition to the `version`
subcommand; both render the same line.
- Per-command `--help` now renders the available JSON field list under
"JSON fields available via `--json id,name,...`" (field-discovery
parity with gh / kubectl `-o jsonpath`).
New commands:
- `auth token` — print the active context's credential to stdout for
shell command substitution (`WEKNORA_TOKEN=$(weknora auth token)`).
Default: raw secret, no trailing newline. `--json` emits
`{token, mode, context}`.
- `doc upload --from-url <URL>` — ingest a remote URL via the SDK
`CreateKnowledgeFromURL`. `--name` forwarded as `FileName` so the
server's known-extension heuristic upgrades crawl-mode to
file-download-mode where appropriate.
Includes the simplify post-review polish pass (field-filter unit
tests, --json/--jq compose check, agent_help copy fixes).
2026-05-14 15:28:14 +00:00
|
|
|
if err := runAdd(&AddOptions{Host: "https://stg.example.com"}, nil, "staging"); err != nil {
|
2026-05-12 15:33:44 +00:00
|
|
|
t.Fatalf("runAdd: %v", err)
|
|
|
|
|
}
|
|
|
|
|
got, _ := config.Load()
|
|
|
|
|
if got.CurrentContext != "production" {
|
|
|
|
|
t.Errorf("adding a second context must not switch current; got %q", got.CurrentContext)
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
func TestAdd_JSON(t *testing.T) {
|
|
|
|
|
t.Setenv("XDG_CONFIG_HOME", t.TempDir())
|
|
|
|
|
out, _ := iostreams.SetForTest(t)
|
|
|
|
|
|
feat(cli): --json field-select, --jq, auth token, doc --from-url
Output ergonomics:
- `--json` accepts a comma-separated field list (gh-parity); selects
named keys from the per-command payload. Bare `--json` keeps the
full shape.
- `--jq <expr>` evaluates a gojq expression over the JSON; pairs with
`--json field-list` so projection runs before jq.
- `--version` is a global cobra flag in addition to the `version`
subcommand; both render the same line.
- Per-command `--help` now renders the available JSON field list under
"JSON fields available via `--json id,name,...`" (field-discovery
parity with gh / kubectl `-o jsonpath`).
New commands:
- `auth token` — print the active context's credential to stdout for
shell command substitution (`WEKNORA_TOKEN=$(weknora auth token)`).
Default: raw secret, no trailing newline. `--json` emits
`{token, mode, context}`.
- `doc upload --from-url <URL>` — ingest a remote URL via the SDK
`CreateKnowledgeFromURL`. `--name` forwarded as `FileName` so the
server's known-extension heuristic upgrades crawl-mode to
file-download-mode where appropriate.
Includes the simplify post-review polish pass (field-filter unit
tests, --json/--jq compose check, agent_help copy fixes).
2026-05-14 15:28:14 +00:00
|
|
|
if err := runAdd(&AddOptions{Host: "https://my.example.com"}, &cmdutil.JSONOptions{}, "staging"); err != nil {
|
2026-05-12 15:33:44 +00:00
|
|
|
t.Fatalf("runAdd: %v", err)
|
|
|
|
|
}
|
refactor(cli): drop --dry-run + introduce bare-JSON output path
Two intertwined mainstream-alignment moves bundled because they share
the migration target (every command's --json path):
1. Drop --dry-run entirely. Survey of comparable API-wrapper CLIs
(gh, aws, stripe, lark): none expose --dry-run. The mainstream that
does (kubectl/git/helm/ansible) operates on declarative manifests
or local state where the preview is materially different from the
executed action. WeKnora's CLI just echoed the same parameters
that would have gone on the wire — the preview added no real
signal over `--help` + reading the call site. Removes:
- root --dry-run persistent flag + cmdutil/dryrun.go
- DryRun fields + EmitDryRun calls in 12 write commands
- format.Envelope.DryRun field
- 8 corresponding *_test.go cases
- --dry-run mention from README.md and CHANGELOG.md
- "dry_run":false from 16 golden envelopes
2. Migrate every --json output to bare data:
- New format.WriteJSON / WriteJSONFiltered helpers
(cli/internal/format/bare.go) share filterArrayItems /
filterObjectKeys / writeJQ with the (still-live for now) envelope
filter helpers.
- Read commands (kb/doc/session list+view, search chunks/docs/
sessions/kb, auth list/status, agent list/view, context list,
doctor) emit bare arrays / objects on stdout.
- Write commands (kb create/edit/delete/pin/empty, doc upload/
upload_recursive/delete, session delete, auth login/logout/
refresh/token, link/unlink, context add/use/remove, agent
invoke, chat, api, version) emit bare result objects. Risk
classification dropped — the resource + exit code already
convey the action.
Per-command shape changes:
list / search → []T (was {ok, data:{items:[…]}})
view → T (was {ok, data:T, _meta:…})
create / edit → T
delete / pin / etc. → {id, …action result…}
doctor → {summary, checks}
api → {status, headers, body}
_meta dropped on the read path:
pagination (page/page_size/total/has_more) — agents iterate with
--all-pages or accept --limit (gh CLI parity);
kb_id / context echo — caller already knows what it asked for.
Acceptance contract goldens regenerated for the new bare shape.
Error envelope on stdout (PrintErrorEnvelope) stays live for now —
the envelope-infra deletion lands in the next commit.
2026-05-14 15:28:14 +00:00
|
|
|
var got map[string]any
|
|
|
|
|
if err := json.Unmarshal(out.Bytes(), &got); err != nil {
|
|
|
|
|
t.Fatalf("invalid JSON: %v\noutput=%q", err, out.String())
|
2026-05-12 15:33:44 +00:00
|
|
|
}
|
refactor(cli): drop --dry-run + introduce bare-JSON output path
Two intertwined mainstream-alignment moves bundled because they share
the migration target (every command's --json path):
1. Drop --dry-run entirely. Survey of comparable API-wrapper CLIs
(gh, aws, stripe, lark): none expose --dry-run. The mainstream that
does (kubectl/git/helm/ansible) operates on declarative manifests
or local state where the preview is materially different from the
executed action. WeKnora's CLI just echoed the same parameters
that would have gone on the wire — the preview added no real
signal over `--help` + reading the call site. Removes:
- root --dry-run persistent flag + cmdutil/dryrun.go
- DryRun fields + EmitDryRun calls in 12 write commands
- format.Envelope.DryRun field
- 8 corresponding *_test.go cases
- --dry-run mention from README.md and CHANGELOG.md
- "dry_run":false from 16 golden envelopes
2. Migrate every --json output to bare data:
- New format.WriteJSON / WriteJSONFiltered helpers
(cli/internal/format/bare.go) share filterArrayItems /
filterObjectKeys / writeJQ with the (still-live for now) envelope
filter helpers.
- Read commands (kb/doc/session list+view, search chunks/docs/
sessions/kb, auth list/status, agent list/view, context list,
doctor) emit bare arrays / objects on stdout.
- Write commands (kb create/edit/delete/pin/empty, doc upload/
upload_recursive/delete, session delete, auth login/logout/
refresh/token, link/unlink, context add/use/remove, agent
invoke, chat, api, version) emit bare result objects. Risk
classification dropped — the resource + exit code already
convey the action.
Per-command shape changes:
list / search → []T (was {ok, data:{items:[…]}})
view → T (was {ok, data:T, _meta:…})
create / edit → T
delete / pin / etc. → {id, …action result…}
doctor → {summary, checks}
api → {status, headers, body}
_meta dropped on the read path:
pagination (page/page_size/total/has_more) — agents iterate with
--all-pages or accept --limit (gh CLI parity);
kb_id / context echo — caller already knows what it asked for.
Acceptance contract goldens regenerated for the new bare shape.
Error envelope on stdout (PrintErrorEnvelope) stays live for now —
the envelope-infra deletion lands in the next commit.
2026-05-14 15:28:14 +00:00
|
|
|
if got["name"] != "staging" {
|
|
|
|
|
t.Errorf("name should be staging, got %v", got)
|
2026-05-12 15:33:44 +00:00
|
|
|
}
|
refactor(cli): drop --dry-run + introduce bare-JSON output path
Two intertwined mainstream-alignment moves bundled because they share
the migration target (every command's --json path):
1. Drop --dry-run entirely. Survey of comparable API-wrapper CLIs
(gh, aws, stripe, lark): none expose --dry-run. The mainstream that
does (kubectl/git/helm/ansible) operates on declarative manifests
or local state where the preview is materially different from the
executed action. WeKnora's CLI just echoed the same parameters
that would have gone on the wire — the preview added no real
signal over `--help` + reading the call site. Removes:
- root --dry-run persistent flag + cmdutil/dryrun.go
- DryRun fields + EmitDryRun calls in 12 write commands
- format.Envelope.DryRun field
- 8 corresponding *_test.go cases
- --dry-run mention from README.md and CHANGELOG.md
- "dry_run":false from 16 golden envelopes
2. Migrate every --json output to bare data:
- New format.WriteJSON / WriteJSONFiltered helpers
(cli/internal/format/bare.go) share filterArrayItems /
filterObjectKeys / writeJQ with the (still-live for now) envelope
filter helpers.
- Read commands (kb/doc/session list+view, search chunks/docs/
sessions/kb, auth list/status, agent list/view, context list,
doctor) emit bare arrays / objects on stdout.
- Write commands (kb create/edit/delete/pin/empty, doc upload/
upload_recursive/delete, session delete, auth login/logout/
refresh/token, link/unlink, context add/use/remove, agent
invoke, chat, api, version) emit bare result objects. Risk
classification dropped — the resource + exit code already
convey the action.
Per-command shape changes:
list / search → []T (was {ok, data:{items:[…]}})
view → T (was {ok, data:T, _meta:…})
create / edit → T
delete / pin / etc. → {id, …action result…}
doctor → {summary, checks}
api → {status, headers, body}
_meta dropped on the read path:
pagination (page/page_size/total/has_more) — agents iterate with
--all-pages or accept --limit (gh CLI parity);
kb_id / context echo — caller already knows what it asked for.
Acceptance contract goldens regenerated for the new bare shape.
Error envelope on stdout (PrintErrorEnvelope) stays live for now —
the envelope-infra deletion lands in the next commit.
2026-05-14 15:28:14 +00:00
|
|
|
if got["host"] != "https://my.example.com" {
|
|
|
|
|
t.Errorf("host wrong: %v", got)
|
|
|
|
|
}
|
|
|
|
|
if got["current"] != true {
|
|
|
|
|
t.Errorf("first added context must be current=true, got %v", got)
|
2026-05-12 15:33:44 +00:00
|
|
|
}
|
|
|
|
|
}
|