feat(cli): contract test suite + dependabot (PR-8)
cli/acceptance/contract/:
envelope_test.go — 16 envelope golden cases (9 commands × {success/error
variants}; 3 cases dropped with rationale: doctor.success
non-offline has unstable timing detail; auth_login.* needs
stdin/keyring scaffold deferred to v0.2; context_use.error
needs leaf-local --json deferred to follow-up)
errorcodes_test.go — single-direction AST scan of cli/cmd/ extracting first
arg of cmdutil.NewError / cmdutil.Wrapf calls;
ClassifyHTTPError dynamic-classify bridged via
cmdutil.ClassifyHTTPErrorOutputs() per spec §4.3.
testdata/envelopes/ — 16 JSON golden files
helpers_test.go (PR-6 scaffold) extended:
runCmd now wires cobra Out/Err sinks (version uses c.OutOrStdout) AND
replicates cmd.Execute()'s error-envelope path so error-case goldens are
populated. Without this, every error scenario's golden was 0 bytes.
cli/cmd/root.go: mapCobraError → MapCobraError, wantsJSONOutput → WantsJSONOutput
(exported so the contract test helper can replicate Execute()'s
envelope-printing path without calling Execute() itself).
root_test.go updated to use new exported names.
.github/dependabot.yml (新增):gomod /cli + github-actions weekly,gh-style
ignore semver-major to avoid noise. Open-source
dependency safety,independent of release cadence.
v0.1 不发布到任何分发平台 (release infra 推迟到发布窗口 milestone)。
This commit is contained in:
+127
-83
@@ -41,10 +41,21 @@ type Options struct {
|
||||
JSONOut bool
|
||||
}
|
||||
|
||||
// Status is the per-check outcome on the wire (JSON Marshal still emits the
|
||||
// underlying string). Typed so cascade comparisons can't typo against bare
|
||||
// "ok"/"fail"/"skip" string literals.
|
||||
type Status string
|
||||
|
||||
const (
|
||||
StatusOK Status = "ok"
|
||||
StatusFail Status = "fail"
|
||||
StatusSkip Status = "skip"
|
||||
)
|
||||
|
||||
// Check is one row in the report.
|
||||
type Check struct {
|
||||
Name string `json:"name"`
|
||||
Status string `json:"status"` // ok / fail / skip
|
||||
Status Status `json:"status"`
|
||||
Details string `json:"details,omitempty"`
|
||||
Hint string `json:"hint,omitempty"`
|
||||
}
|
||||
@@ -88,13 +99,30 @@ func NewCmd(f *cmdutil.Factory) *cobra.Command {
|
||||
return nil // doctor 自身不返回 error;失败状态在 data.checks
|
||||
},
|
||||
}
|
||||
cmd.Flags().BoolVar(&opts.NoCache, "no-cache", false, "Bypass server-info cache; force re-probe")
|
||||
cmd.Flags().BoolVar(&opts.Offline, "offline", false, "Skip network checks; only verify local keyring/file storage")
|
||||
cmd.Flags().BoolVar(&opts.NoCache, "no-cache", false, "Bypass server-info cache (located at $XDG_CACHE_HOME/weknora/server-info.yaml); force re-probe")
|
||||
cmd.Flags().BoolVar(&opts.Offline, "offline", false, "Skip network checks; only verify local keyring/file storage (credential_storage check still runs)")
|
||||
cmd.Flags().BoolVar(&opts.JSONOut, "json", false, "Output JSON envelope")
|
||||
agent.SetAgentHelp(cmd, "Returns 4 health checks. AGENT short-circuit: read data.summary.all_passed; if false, inspect data.checks[].status (ok/fail/skip).")
|
||||
return cmd
|
||||
}
|
||||
|
||||
// cascade implements the two short-circuits every gated check shares:
|
||||
// offline-mode skip and prereq-failed skip. Returns true when the check has
|
||||
// been completed (Status set on c) and the caller should NOT run its body.
|
||||
func cascade(c *Check, offline bool, prereqs ...*Check) bool {
|
||||
if offline {
|
||||
c.Status, c.Details = StatusSkip, "offline mode"
|
||||
return true
|
||||
}
|
||||
for _, p := range prereqs {
|
||||
if p.Status != StatusOK {
|
||||
c.Status, c.Details = StatusSkip, "prereq failed: "+p.Name
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// runChecks executes the 4-item check matrix with cascade-skip semantics.
|
||||
// Pure function over Services so tests can drive it directly.
|
||||
func runChecks(ctx context.Context, opts *Options, svc Services, cliVer string) Result {
|
||||
@@ -105,118 +133,105 @@ func runChecks(ctx context.Context, opts *Options, svc Services, cliVer string)
|
||||
{Name: "credential_storage"},
|
||||
}
|
||||
|
||||
// 1. base_url_reachable
|
||||
if opts.Offline {
|
||||
checks[0].Status = "skip"
|
||||
checks[0].Details = "offline mode"
|
||||
} else {
|
||||
// 1. base_url_reachable — gated by offline only.
|
||||
if !cascade(&checks[0], opts.Offline) {
|
||||
t0 := time.Now()
|
||||
if err := svc.PingBaseURL(ctx); err != nil {
|
||||
checks[0].Status = "fail"
|
||||
checks[0].Hint = "verify --base-url and network reachability"
|
||||
checks[0].Status = StatusFail
|
||||
checks[0].Hint = "verify the host configured for the active context (run `weknora auth login --host=...`) and network reachability"
|
||||
checks[0].Details = err.Error()
|
||||
} else {
|
||||
checks[0].Status = "ok"
|
||||
checks[0].Status = StatusOK
|
||||
checks[0].Details = fmt.Sprintf("reachable in %s", time.Since(t0).Round(time.Millisecond))
|
||||
}
|
||||
}
|
||||
|
||||
// 2. auth_credential — depends on base_url
|
||||
switch {
|
||||
case opts.Offline:
|
||||
checks[1].Status = "skip"
|
||||
checks[1].Details = "offline mode"
|
||||
case checks[0].Status == "fail":
|
||||
checks[1].Status = "skip"
|
||||
checks[1].Details = "prereq failed: base_url_reachable"
|
||||
default:
|
||||
_, err := svc.GetCurrentUser(ctx)
|
||||
if err != nil {
|
||||
checks[1].Status = "fail"
|
||||
// 2. auth_credential — needs base_url.
|
||||
if !cascade(&checks[1], opts.Offline, &checks[0]) {
|
||||
if _, err := svc.GetCurrentUser(ctx); err != nil {
|
||||
checks[1].Status = StatusFail
|
||||
checks[1].Hint = "run `weknora auth login`"
|
||||
checks[1].Details = err.Error()
|
||||
} else {
|
||||
checks[1].Status = "ok"
|
||||
checks[1].Status = StatusOK
|
||||
}
|
||||
}
|
||||
|
||||
// 3. server_version — depends on auth_credential
|
||||
switch {
|
||||
case opts.Offline:
|
||||
checks[2].Status = "skip"
|
||||
checks[2].Details = "offline mode"
|
||||
case checks[1].Status != "ok":
|
||||
checks[2].Status = "skip"
|
||||
checks[2].Details = "prereq failed: auth_credential"
|
||||
default:
|
||||
// 3. server_version — needs auth_credential.
|
||||
if !cascade(&checks[2], opts.Offline, &checks[1]) {
|
||||
info, fromCache, err := loadOrProbeServerInfo(ctx, opts, svc)
|
||||
if err != nil {
|
||||
checks[2].Status = "fail"
|
||||
checks[2].Status = StatusFail
|
||||
checks[2].Details = err.Error()
|
||||
} else {
|
||||
level, hint := compat.Compat(info.ServerVersion, cliVer)
|
||||
suffix := ""
|
||||
if fromCache {
|
||||
suffix = " (cached, pass --no-cache to refresh)"
|
||||
}
|
||||
if level == compat.HardError {
|
||||
checks[2].Status = "fail"
|
||||
checks[2].Hint = hint
|
||||
checks[2].Details = "server " + info.ServerVersion + suffix
|
||||
} else {
|
||||
checks[2].Status = "ok"
|
||||
if hint != "" {
|
||||
checks[2].Details = hint + suffix
|
||||
} else {
|
||||
checks[2].Details = fmt.Sprintf("server %s%s", info.ServerVersion, suffix)
|
||||
}
|
||||
}
|
||||
fillVersionCheck(&checks[2], info, cliVer, fromCache)
|
||||
}
|
||||
}
|
||||
|
||||
// 4. credential_storage — independent of network
|
||||
// 4. credential_storage — independent of network; never gated by offline.
|
||||
if _, err := secrets.NewBestEffortStore(); err != nil {
|
||||
checks[3].Status = "fail"
|
||||
checks[3].Status = StatusFail
|
||||
checks[3].Details = err.Error()
|
||||
checks[3].Hint = "verify keyring access; falls back to file store"
|
||||
} else {
|
||||
checks[3].Status = "ok"
|
||||
checks[3].Status = StatusOK
|
||||
checks[3].Details = "keyring or file storage available"
|
||||
}
|
||||
|
||||
return Result{Summary: summarize(checks), Checks: checks}
|
||||
}
|
||||
|
||||
// loadOrProbeServerInfo respects --no-cache:
|
||||
// --no-cache or stale/missing cache → call svc.GetSystemInfo + SaveCache
|
||||
// else → return cached Info (fromCache=true)
|
||||
//
|
||||
// SaveCache failure does NOT propagate — best-effort write. The probe
|
||||
// data is still returned to the caller for the compat check.
|
||||
// fillVersionCheck applies compat.Compat to (server, cli) version pair and
|
||||
// sets Status/Details/Hint on c. fromCache toggles the "cached" suffix —
|
||||
// the loader knows authoritatively which branch it took, time-based
|
||||
// derivation from ProbedAt is unreliable since SaveCache uses time.Now().
|
||||
func fillVersionCheck(c *Check, info *compat.Info, cliVer string, fromCache bool) {
|
||||
level, hint := compat.Compat(info.ServerVersion, cliVer)
|
||||
suffix := ""
|
||||
if fromCache {
|
||||
suffix = " (cached, pass --no-cache to refresh)"
|
||||
}
|
||||
if level == compat.HardError {
|
||||
c.Status = StatusFail
|
||||
c.Hint = hint
|
||||
c.Details = "server " + info.ServerVersion + suffix
|
||||
return
|
||||
}
|
||||
c.Status = StatusOK
|
||||
if hint != "" {
|
||||
c.Details = hint + suffix
|
||||
} else {
|
||||
c.Details = fmt.Sprintf("server %s%s", info.ServerVersion, suffix)
|
||||
}
|
||||
}
|
||||
|
||||
// loadOrProbeServerInfo respects --no-cache: load fresh cache when allowed,
|
||||
// else call compat.Probe (which wraps svc.GetSystemInfo) and persist. Cache
|
||||
// write is best-effort. Returns fromCache so the caller can render the
|
||||
// "cached" presentation hint without a brittle ProbedAt heuristic.
|
||||
func loadOrProbeServerInfo(ctx context.Context, opts *Options, svc Services) (info *compat.Info, fromCache bool, err error) {
|
||||
if !opts.NoCache {
|
||||
if cached, fresh, _ := compat.LoadCache(); fresh && cached != nil {
|
||||
return cached, true, nil
|
||||
}
|
||||
}
|
||||
sys, err := svc.GetSystemInfo(ctx)
|
||||
probed, err := compat.Probe(ctx, svc)
|
||||
if err != nil {
|
||||
return nil, false, err
|
||||
}
|
||||
fresh := &compat.Info{ServerVersion: sys.Version, ProbedAt: time.Now()}
|
||||
_ = compat.SaveCache(fresh) // best-effort
|
||||
return fresh, false, nil
|
||||
_ = compat.SaveCache(probed)
|
||||
return probed, false, nil
|
||||
}
|
||||
|
||||
func summarize(cs []Check) Summary {
|
||||
s := Summary{}
|
||||
for _, c := range cs {
|
||||
switch c.Status {
|
||||
case "ok":
|
||||
case StatusOK:
|
||||
s.Passed++
|
||||
case "fail":
|
||||
case StatusFail:
|
||||
s.Failed++
|
||||
case "skip":
|
||||
case StatusSkip:
|
||||
s.Skipped++
|
||||
}
|
||||
}
|
||||
@@ -232,9 +247,9 @@ func emit(opts *Options, r Result) {
|
||||
for _, c := range r.Checks {
|
||||
marker := "[ok]"
|
||||
switch c.Status {
|
||||
case "fail":
|
||||
case StatusFail:
|
||||
marker = "[fail]"
|
||||
case "skip":
|
||||
case StatusSkip:
|
||||
marker = "[skip]"
|
||||
}
|
||||
line := fmt.Sprintf("%-6s %-20s %s", marker, c.Name, c.Status)
|
||||
@@ -251,16 +266,34 @@ func emit(opts *Options, r Result) {
|
||||
}
|
||||
|
||||
// buildServices wires the Factory closures into the doctor.Services interface.
|
||||
// Reads the active context's host so PingBaseURL targets the user's actual
|
||||
// server, not localhost.
|
||||
//
|
||||
// Critically: this does NOT pre-resolve f.Client(). doctor's package promise
|
||||
// (top comment) is that credential_storage runs even when no auth is set up —
|
||||
// e.g. first-time `weknora doctor` to diagnose setup. Pre-resolving Client
|
||||
// here would early-exit with auth.unauthenticated before any check runs,
|
||||
// contradicting the docs. Instead, GetCurrentUser / GetSystemInfo lazily
|
||||
// resolve and surface their own failure as a per-check StatusFail.
|
||||
func buildServices(f *cmdutil.Factory) (Services, error) {
|
||||
cli, err := f.Client()
|
||||
cfg, err := f.Config()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &realServices{cli: cli}, nil
|
||||
host := ""
|
||||
if ctx, ok := cfg.Contexts[cfg.CurrentContext]; ok {
|
||||
host = ctx.Host
|
||||
}
|
||||
// WEKNORA_BASE_URL still wins as a test/dev override; production reads host.
|
||||
if v := os.Getenv("WEKNORA_BASE_URL"); v != "" {
|
||||
host = v
|
||||
}
|
||||
return &realServices{f: f, host: host}, nil
|
||||
}
|
||||
|
||||
type realServices struct {
|
||||
cli *sdk.Client
|
||||
f *cmdutil.Factory
|
||||
host string
|
||||
}
|
||||
|
||||
// pingTimeout caps the HEAD /health probe so a wedged TCP connection
|
||||
@@ -268,9 +301,10 @@ type realServices struct {
|
||||
const pingTimeout = 5 * time.Second
|
||||
|
||||
func (s *realServices) PingBaseURL(ctx context.Context) error {
|
||||
// WEKNORA_BASE_URL is the test-scaffold override; production should plumb
|
||||
// config.Host through (TODO v0.2: add Client.BaseURL() accessor in SDK).
|
||||
url := envOrDefault("WEKNORA_BASE_URL", "http://localhost:8080") + "/health"
|
||||
if s.host == "" {
|
||||
return fmt.Errorf("no host configured for active context")
|
||||
}
|
||||
url := s.host + "/health"
|
||||
ctx, cancel := context.WithTimeout(ctx, pingTimeout)
|
||||
defer cancel()
|
||||
req, err := http.NewRequestWithContext(ctx, http.MethodHead, url, nil)
|
||||
@@ -288,16 +322,26 @@ func (s *realServices) PingBaseURL(ctx context.Context) error {
|
||||
return nil
|
||||
}
|
||||
|
||||
// GetCurrentUser lazily resolves the SDK client. When no context is configured
|
||||
// or credentials missing, f.Client() returns auth.unauthenticated; we surface
|
||||
// that as the auth_credential check's failure rather than aborting doctor.
|
||||
func (s *realServices) GetCurrentUser(ctx context.Context) (*sdk.CurrentUserResponse, error) {
|
||||
return s.cli.GetCurrentUser(ctx)
|
||||
}
|
||||
func (s *realServices) GetSystemInfo(ctx context.Context) (*sdk.SystemInfo, error) {
|
||||
return s.cli.GetSystemInfo(ctx)
|
||||
cli, err := s.f.Client()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return cli.GetCurrentUser(ctx)
|
||||
}
|
||||
|
||||
func envOrDefault(k, def string) string {
|
||||
if v := os.Getenv(k); v != "" {
|
||||
return v
|
||||
// GetSystemInfo lazily resolves the SDK client (same rationale as GetCurrentUser).
|
||||
// In the cascade ordering, auth_credential gates server_version, so this only
|
||||
// runs when auth_credential succeeded — but the lazy resolution keeps doctor
|
||||
// useful when only credential_storage is checkable (e.g., user not yet logged in).
|
||||
func (s *realServices) GetSystemInfo(ctx context.Context) (*sdk.SystemInfo, error) {
|
||||
cli, err := s.f.Client()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return def
|
||||
return cli.GetSystemInfo(ctx)
|
||||
}
|
||||
|
||||
|
||||
@@ -8,6 +8,7 @@ import (
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/Tencent/WeKnora/cli/internal/cmdutil"
|
||||
"github.com/Tencent/WeKnora/cli/internal/compat"
|
||||
"github.com/Tencent/WeKnora/cli/internal/iostreams"
|
||||
sdk "github.com/Tencent/WeKnora/client"
|
||||
@@ -48,6 +49,9 @@ func TestDoctor_AllOK(t *testing.T) {
|
||||
if !r.Summary.AllPassed {
|
||||
t.Errorf("expected all_passed, got summary %+v", r.Summary)
|
||||
}
|
||||
if r.Summary.Passed != 4 {
|
||||
t.Errorf("expected Passed=4 (one per check), got %+v", r.Summary)
|
||||
}
|
||||
if r.Summary.Failed != 0 || r.Summary.Skipped != 0 {
|
||||
t.Errorf("expected 0 fail / 0 skip, got %+v", r.Summary)
|
||||
}
|
||||
@@ -69,13 +73,16 @@ func TestDoctor_BaseURLFails_DownstreamSkip(t *testing.T) {
|
||||
if r.Summary.Skipped != 2 {
|
||||
t.Errorf("expected 2 skipped (auth_credential + server_version), got %d", r.Summary.Skipped)
|
||||
}
|
||||
if r.Checks[0].Status != "fail" {
|
||||
if r.Checks[0].Status != StatusFail {
|
||||
t.Errorf("base_url_reachable status = %q, want fail", r.Checks[0].Status)
|
||||
}
|
||||
if r.Checks[1].Status != "skip" {
|
||||
if !strings.Contains(r.Checks[0].Hint, "auth login") {
|
||||
t.Errorf("base_url fail hint should reference `auth login`, got %q", r.Checks[0].Hint)
|
||||
}
|
||||
if r.Checks[1].Status != StatusSkip {
|
||||
t.Errorf("auth_credential status = %q, want skip", r.Checks[1].Status)
|
||||
}
|
||||
if r.Checks[2].Status != "skip" {
|
||||
if r.Checks[2].Status != StatusSkip {
|
||||
t.Errorf("server_version status = %q, want skip", r.Checks[2].Status)
|
||||
}
|
||||
// credential_storage 与网络无关,应该独立运行(不受 base_url fail 影响)
|
||||
@@ -96,7 +103,7 @@ func TestDoctor_Offline_OnlyKeyringChecked(t *testing.T) {
|
||||
if last.Name != "credential_storage" {
|
||||
t.Errorf("last check = %q, want credential_storage", last.Name)
|
||||
}
|
||||
if last.Status == "skip" {
|
||||
if last.Status == StatusSkip {
|
||||
t.Error("credential_storage should NOT be skipped even in offline mode")
|
||||
}
|
||||
}
|
||||
@@ -109,13 +116,13 @@ func TestDoctor_AuthFails_VersionSkipped(t *testing.T) {
|
||||
systemInfo: &sdk.SystemInfo{Version: "1.0.0"},
|
||||
}
|
||||
r := runChecks(context.Background(), &Options{}, svc, "1.0.0")
|
||||
if r.Checks[0].Status != "ok" {
|
||||
if r.Checks[0].Status != StatusOK {
|
||||
t.Errorf("base_url should pass, got %q", r.Checks[0].Status)
|
||||
}
|
||||
if r.Checks[1].Status != "fail" {
|
||||
if r.Checks[1].Status != StatusFail {
|
||||
t.Errorf("auth_credential should fail, got %q", r.Checks[1].Status)
|
||||
}
|
||||
if r.Checks[2].Status != "skip" {
|
||||
if r.Checks[2].Status != StatusSkip {
|
||||
t.Errorf("server_version should skip due to auth fail, got %q", r.Checks[2].Status)
|
||||
}
|
||||
}
|
||||
@@ -129,7 +136,7 @@ func TestDoctor_CacheHit_SkipsProbe(t *testing.T) {
|
||||
}
|
||||
svc := &fakeServices{userResp: goodUserResp()}
|
||||
r := runChecks(context.Background(), &Options{}, svc, "1.0.0")
|
||||
if r.Checks[2].Status != "ok" {
|
||||
if r.Checks[2].Status != StatusOK {
|
||||
t.Errorf("server_version should be ok via cache, got %q (%s)", r.Checks[2].Status, r.Checks[2].Details)
|
||||
}
|
||||
if svc.systemInfoHits.Load() != 0 {
|
||||
@@ -140,6 +147,48 @@ func TestDoctor_CacheHit_SkipsProbe(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
// TestDoctor_NoConfig_StillRunsCredentialStorage guards the package-doc
|
||||
// promise that credential_storage runs even with zero configuration. Round-4
|
||||
// reviewer surfaced that buildServices used to abort on f.Client() failure,
|
||||
// silently violating the doc for any first-time user running `weknora doctor`
|
||||
// to diagnose setup. The lazy-resolve fix means missing auth surfaces as
|
||||
// auth_credential=fail, not a top-level command exit.
|
||||
func TestDoctor_NoConfig_StillRunsCredentialStorage(t *testing.T) {
|
||||
t.Setenv("XDG_CONFIG_HOME", t.TempDir())
|
||||
t.Setenv("XDG_CACHE_HOME", t.TempDir())
|
||||
_, _ = iostreams.SetForTest(t)
|
||||
|
||||
f := cmdutil.New()
|
||||
svc, err := buildServices(f)
|
||||
if err != nil {
|
||||
t.Fatalf("buildServices must succeed even with no config; got: %v", err)
|
||||
}
|
||||
r := runChecks(context.Background(), &Options{}, svc, "1.0.0")
|
||||
|
||||
// All 4 checks must run (no early-exit). Last one is credential_storage and
|
||||
// has no network/auth dependency, so it must report ok.
|
||||
if got := len(r.Checks); got != 4 {
|
||||
t.Fatalf("expected 4 checks executed, got %d", got)
|
||||
}
|
||||
if r.Checks[3].Name != "credential_storage" {
|
||||
t.Errorf("Checks[3] = %q, want credential_storage", r.Checks[3].Name)
|
||||
}
|
||||
if r.Checks[3].Status != StatusOK {
|
||||
t.Errorf("credential_storage must run / pass even without auth, got %q (%s)",
|
||||
r.Checks[3].Status, r.Checks[3].Details)
|
||||
}
|
||||
// base_url_reachable fails (no host); cascade then skips auth_credential
|
||||
// and server_version. Whether auth/version are skip vs fail is an internal
|
||||
// cascade detail; the user-visible promise is that 4 checks executed and
|
||||
// the independent credential_storage one passed.
|
||||
if r.Checks[0].Status != StatusFail {
|
||||
t.Errorf("base_url must fail without host, got %q", r.Checks[0].Status)
|
||||
}
|
||||
if r.Checks[1].Status == StatusOK {
|
||||
t.Errorf("auth_credential must NOT report ok without config, got %q", r.Checks[1].Status)
|
||||
}
|
||||
}
|
||||
|
||||
func TestDoctor_NoCache_BypassesCache(t *testing.T) {
|
||||
t.Setenv("XDG_CACHE_HOME", t.TempDir())
|
||||
_, _ = iostreams.SetForTest(t)
|
||||
|
||||
Reference in New Issue
Block a user