Files
WeKnora/cli/internal/format/bare_test.go
T
nullkey c87e35b34b chore(cli): polish + docs sync + pre-PR audit fixes
Code-reuse polish (post-implementation review pass):
- Extract text.OneLine(maxWidth, s) helper combining preview-row
  normalization (newline/CR/tab → space) with text.Truncate's
  UTF-8-safe truncation. Replaces agent/view.go truncate1Line (ASCII
  '...' + byte-slice CJK-unsafe) and chunk/list.go singleLine.
- Lift cmdutil.OpenInput(path) for the '-' = stdin / else os.Open
  pattern shared across agent create/edit and the api command.
  Replaces agent/create.go's private openInput.
- Strip inline doc-spec parentheticals from source comments — those
  belong in commit messages and project docs, not in source where
  they rot.

Pre-PR audit fixes:
- doc upload: reject `--metadata` paired with `--from-url` as
  input.invalid_argument up-front (the URL-ingest request type has
  no metadata field server-side, so the pair would otherwise silently
  drop). Long help and CHANGELOG updated to call out the asymmetry.
- doc upload (file path): map sdk.ErrDuplicateFile sentinel to
  resource.already_exists. The sentinel arrives with no "HTTP error <n>:"
  prefix because the SDK short-circuits on file-hash before reading the
  HTTP status, so the previous WrapHTTP fall-through misclassified it
  as network.error with a misleading "check base URL reachability" hint.
  The --from-url branch already handled ErrDuplicateURL this way; this
  closes the asymmetry. Caught by e2e re-upload of an already-ingested
  file; regression test added.
- README exit-10 enumeration adds `agent delete` and `chunk delete`
  (these were missing alongside the v0.5 destructive verbs they were
  meant to gate).

Docs sync:
- cli/README.md: command tree now includes the chunk subtree; adds
  agent / chunk lines to the 5-minute quickstart; adds a "Contributing
  / Reporting issues" section pointing at the repo's SECURITY.md and
  AGENTS.md; drops third-party CLI parallels from the surface
  description.
- cli/AGENTS.md: "Command surface design SOP" gains the
  flag-vs-escape-hatch step. "CRUD command flag canon" renamed to the
  hard-required-flags pattern with the contrast (TTY-prompts-fill)
  defined inline rather than via opaque shorthand.
- cli/CHANGELOG.md: search docs case-sensitivity shift promoted to its
  own #### Breaking changes subsection. MCP doc_list filter count
  corrected from 5 to 6. Drops the bogus go.mod yaml.v3 entry (yaml.v3
  was already a dependency on main; v0.5 added zero go.mod lines).
  Replaces internal-Go identifiers (fuzzyTime, NoOptDefVal) with
  user-language and drops the § section-symbol jargon.
2026-05-16 16:56:33 +08:00

141 lines
4.3 KiB
Go

package format_test
import (
"bytes"
"encoding/json"
"strings"
"testing"
"github.com/Tencent/WeKnora/cli/internal/format"
)
func TestWriteJSON_BareArray(t *testing.T) {
buf := &bytes.Buffer{}
if err := format.WriteJSON(buf, []map[string]string{
{"id": "1", "name": "alpha"},
{"id": "2", "name": "beta"},
}); err != nil {
t.Fatalf("err = %v", err)
}
if !bytes.HasPrefix(buf.Bytes(), []byte("[")) {
t.Errorf("expected bare JSON array, got %q", buf.String())
}
}
func TestWriteJSON_BareObject(t *testing.T) {
buf := &bytes.Buffer{}
if err := format.WriteJSON(buf, map[string]any{"id": "kb_x", "name": "Engineering"}); err != nil {
t.Fatalf("err = %v", err)
}
if !bytes.HasPrefix(buf.Bytes(), []byte("{")) {
t.Errorf("expected bare JSON object, got %q", buf.String())
}
if bytes.Contains(buf.Bytes(), []byte(`"ok":`)) || bytes.Contains(buf.Bytes(), []byte(`"data":`)) {
t.Errorf("bare output must not carry envelope keys: %s", buf.String())
}
}
func TestWriteJSONFiltered_FieldsOnArray(t *testing.T) {
buf := &bytes.Buffer{}
items := []map[string]any{
{"id": "1", "name": "alpha", "kb_id": "kb_x", "updated_at": "2026-01-01"},
{"id": "2", "name": "beta", "kb_id": "kb_x", "updated_at": "2026-01-02"},
}
if err := format.WriteJSONFiltered(buf, items, []string{"id", "name"}, ""); err != nil {
t.Fatalf("err = %v", err)
}
var got []map[string]string
if err := json.Unmarshal(buf.Bytes(), &got); err != nil {
t.Fatalf("parse: %v\n%s", err, buf.String())
}
if len(got) != 2 {
t.Fatalf("items len = %d, want 2", len(got))
}
for i, item := range got {
if _, has := item["kb_id"]; has {
t.Errorf("item[%d] should not have kb_id: %v", i, item)
}
if item["id"] == "" || item["name"] == "" {
t.Errorf("item[%d] missing kept fields: %v", i, item)
}
}
}
func TestWriteJSONFiltered_FieldsOnObject(t *testing.T) {
buf := &bytes.Buffer{}
obj := map[string]any{"id": "kb_x", "name": "Engineering", "owner": "alice"}
if err := format.WriteJSONFiltered(buf, obj, []string{"id", "name"}, ""); err != nil {
t.Fatalf("err = %v", err)
}
var got map[string]string
if err := json.Unmarshal(buf.Bytes(), &got); err != nil {
t.Fatalf("parse: %v\n%s", err, buf.String())
}
if _, has := got["owner"]; has {
t.Errorf("should not retain owner: %v", got)
}
if got["id"] != "kb_x" || got["name"] != "Engineering" {
t.Errorf("kept fields missing: %v", got)
}
}
func TestWriteJSONFiltered_UnknownFieldSilent(t *testing.T) {
buf := &bytes.Buffer{}
if err := format.WriteJSONFiltered(buf, map[string]any{"id": "1"}, []string{"id", "nonexistent"}, ""); err != nil {
t.Fatalf("err = %v", err)
}
var got map[string]any
if err := json.Unmarshal(buf.Bytes(), &got); err != nil {
t.Fatalf("parse: %v", err)
}
if got["id"] != "1" {
t.Errorf("id missing: %v", got)
}
if _, has := got["nonexistent"]; has {
t.Errorf("nonexistent should be silently dropped: %v", got)
}
}
func TestWriteJSONFiltered_JQOnly(t *testing.T) {
buf := &bytes.Buffer{}
items := []map[string]any{
{"id": "1", "name": "alpha"},
{"id": "2", "name": "beta"},
}
if err := format.WriteJSONFiltered(buf, items, nil, ".[].id"); err != nil {
t.Fatalf("err = %v", err)
}
// String / scalar results render without JSON quotes so scalar
// projections (e.g. `--jq '.[].id'`) pipe cleanly into shell tools.
lines := strings.Split(strings.TrimRight(buf.String(), "\n"), "\n")
if len(lines) != 2 || lines[0] != "1" || lines[1] != "2" {
t.Errorf("jq output mismatch: %q", buf.String())
}
}
func TestWriteJSONFiltered_FieldsAndJQ(t *testing.T) {
buf := &bytes.Buffer{}
items := []map[string]any{
{"id": "1", "name": "alpha", "secret": "drop-me"},
{"id": "2", "name": "beta", "secret": "drop-me"},
}
// Field filter first → then jq selects from filtered shape.
if err := format.WriteJSONFiltered(buf, items, []string{"id"}, ".[].id"); err != nil {
t.Fatalf("err = %v", err)
}
out := buf.String()
if strings.Contains(out, "drop-me") {
t.Errorf("field filter must drop unrequested keys before jq: %q", out)
}
}
func TestWriteJSONFiltered_NilDataPassthrough(t *testing.T) {
buf := &bytes.Buffer{}
if err := format.WriteJSONFiltered(buf, nil, []string{"id"}, ""); err != nil {
t.Fatalf("err = %v", err)
}
if strings.TrimSpace(buf.String()) != "null" {
t.Errorf("nil should marshal to bare null, got %q", buf.String())
}
}