* test(cmd/bd): reset cobra flags between in-process runs; keep them out of parallel tests
runBDInProcess and runBDInProcessAllowError execute the package-level
rootCmd tree again and again in one process, and cobra never resets a
flag between Execute calls: a value one invocation parsed (create's
--title, --labels, list's --status, ...) and its Changed bit stayed on the
FlagSet, so the next invocation saw it, and a slice flag that had been
set appended to the stale value instead of replacing it. With a Dolt test
server (the only setup in which these tests run) that failed about 20
TestCLI_* tests depending on suite order.
TestMain now snapshots every flag of the tree (snapshotCommandFlags,
after all init()s registered them, before any test runs) and both runners
put the tree back before and after each run (resetCommandFlags): the
pointee of each flag.Value is restored (for pflag's scalar types that is
the bound variable; for slice types it also clears the internal "changed"
bit, so the next Set replaces), slice contents via SliceValue.Replace,
and Changed=false. TestResetCommandFlagsRestoresEveryFlag sets every flag
of the real tree and checks the reset. The ad-hoc --title reset in
TestCLI_CreateRejectsEmptyTitle_ProxiedServerMode is no longer needed.
Seven TestCLI_Comment* tests called t.Parallel() around the runners.
inProcessMutex serializes the runners only against each other, so their
chdir, stdio swap, env and config re-initialization raced every other
parallel test (data races on config globals; TestCobraParallelPolicyGuard
failing to read its own source files after a concurrent chdir). They run
serially now, and the guard treats the two runners like rootCmd.Execute.
Also two stale TestCLI_Create* cases: DryRunWithRigPrefix exercised a
create --prefix flag that no longer exists, and the flag-like-title cases
passed "--help" or "--foo-bar" where cobra parses them as flags; they now
pass the title after "--", the only way it reaches create's own guard.
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
* test(cmd/bd): fix the ADO round-trip and bulk-delete tests that rotted unseen
Both need the integration tag and a Dolt test server, which no CI lane
gave cmd/bd (BEADS_TEST_SKIP=dolt everywhere), so they failed unnoticed:
- TestADORoundTrip* stored ado.pat in the database. ado.pat is a secret
read only from config.yaml or AZURE_DEVOPS_PAT (config.IsYamlOnlyKey),
so the tracker found no PAT. The fixture sets AZURE_DEVOPS_PAT.
- TestBulkDeleteNoResurrection expected GetIssue to return (nil, nil) for
a deleted issue; the Dolt store reports storage.ErrNotFound.
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
* test(cmd/bd): fix parity, completion and notion tests that only fail with a Dolt server
These are Dolt-gated (integration tag + test server), so no CI lane ran
them and they rotted:
- TestParityCreate*/TestParityReopenErrorExits1Silently: bd create
auto-routes via routing.DetectUserRole("."), which warns "beads.role
not configured (GH#2950)" on stderr when the working directory's git
config has no beads.role. The suite pins the configured case, so the
parity env now sets beads.role=maintainer in a test-owned global git
config ($XDG_CONFIG_HOME/git/config; the role lookup scrubs every
GIT_CONFIG_* variable, so those cannot be used).
- TestIssueIDCompletion: issueIDCompletion resolves a database path
before looking at the open store and returns nothing when there is
none; the test now sets dbPath to its store's path.
- TestIssueIDCompletion_UsesWorktreeFallbackWhenStoreNil and
TestGetNotionConfigReadsDBPathWhenStoreUnset: the code under test
reopens the store from metadata.json, which names a database but not
the per-test branch of the shared database that newTestStore uses, so
the reopened store saw none of the test's rows. They now use their own
database (newTestStoreIsolatedDB).
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
* test(cmd/bd): fix stale doctor/e2e/autocommit/readonly Dolt-gated tests
These need the integration tag and a Dolt test server, which no CI lane
gave cmd/bd, so they rotted unseen:
- TestE2E_DoctorFixMetadataRoundtrip, TestE2E_MigrateDoltMetadata,
TestDoctorCheckHealthReportsVersionMismatchOnRepoLocalPort: bd init now
defaults to embedded mode, where `bd sql` and `bd dolt start` are
refused. Init with --server on a repo-local server of their own
(repoLocalServerEnv: the suite's shared-server port vars cleared, server
stopped at cleanup) and start it explicitly, since BEADS_TEST_MODE=1 never
auto-starts one. MigrateDoltMetadata's DELETE also needed `key` quoted.
- TestDoctor{Conventions,Pollution}MaxRows_EnvOnly_Exits2: bdRunRaw drops
every BEADS_* variable, so the subprocess hit dolt.New's test-database
firewall (exit 1) before the row cap; pass BEADS_TEST_SERVER=1.
- TestDoltAutoCommit_On_WritesAdvanceHead: the embedded engine keeps its
data under .beads/embeddeddolt, not .beads/dolt; findDoltRepoDir looks
in both.
- TestValidateCheck_AllClean: bd doctor validate runs five checks since
the cross-table duplicates check was added.
- TestConfigValidateReadOnlyIsHermetic: readonly commands take a shared
workspace gate, whose lock file (.beads/dolt.gate.lock) workspacegate
creates on first use by design; compare the .beads tree without gate
lock files.
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
* test(cmd/bd): undo each in-process execution's env and storage-mode leaks
Every in-process run of the bd command tree (runBDInProcess and the many
tests that call rootCmd.Execute directly) leaves process state behind:
PersistentPreRun exports the selected workspace as BEADS_DIR, loads its
.beads/.env, and records the workspace's mode in serverMode /
proxiedServerMode. With a Dolt test server, later tests in the same shard
then resolved a deleted fixture ("no active beads workspace found",
"migration sidecar is missing"), ran subprocess bd against the wrong
workspace ("recorded as proxied-server in .beads/metadata.json"), or took
the proxied path in RunE-level tests ("proxied-server UOW provider not
initialized", a nil-UOW panic in reopenProxiedResolve that killed a shard).
TestMain now registers a cobra initializer/finalizer pair
(installExecuteIsolation) that snapshots the environment and the two mode
globals when an execution starts and restores them when it ends; the
runners' restoreEnvSnapshot shares the helper. TestDoltConfigEnvironmentOverrides
used os.Setenv + defer os.Unsetenv, which deleted the suite's
BEADS_DOLT_SERVER_PORT (the test server's port) for every later test; it
uses t.Setenv now.
Full integration-tagged cmd/bd suite against a hermetic dolt (16 shards):
18 order-dependent failures and the shard panic gone; the 27 remaining
failures all fail alone too.
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
* fix(init): keep --quiet quiet through the Claude/Codex/Cursor auto-setup
`bd init --quiet` ("Suppress output") still printed the project
integration installers' progress to stdout ("Installing Claude hooks for
this project...", "Claude Code integration installed", ...): the
installers write to os.Stdout unconditionally. Point stdout at the null
device around them while quiet; their failures keep going to stderr as
before. Found by TestInitCommand's quiet case, which asserts no output and
had not run in CI (Dolt-gated).
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
* test(init): bring the Dolt-gated init tests up to the current init contract
These tests need a Dolt test server, so no CI lane ran them and they
drifted from the product:
- Embedded is init's default mode, so the server-mode assertions
(.beads/dolt, opening the database on the test server, dolt_mode
"server" in metadata.json) now pass --server (TestInitCommand,
TestInitAlreadyInitialized, TestInitRedirect, TestInitBEADS_DIR,
TestInitDoltMetadata, TestInitDoltMetadataNoGit, TestInitDatabaseFlag's
metadata subtests). The in-process ones reset rootCmd's flags around
themselves so --server cannot leak into later in-process inits.
- Each server init gets its own --database: the suite shares one test
server, and a "test" database another test created belongs to another
project (init refuses: PROJECT IDENTITY MISMATCH).
- The marker tests seed a current-era version witness: the legacy-upgrade
guard refuses a non-empty .beads/dolt without one.
- The redirect test provisions the canonical target with config.yaml: bd
ignores a redirect to a directory with no project files (#4692).
- Shared-server inits get a free port of their own
(sharedServerTestEnv): the inherited BEADS_DOLT_SERVER_PORT is the
suite's test server, which a shared-server start refuses as another
project's, and the default shared port is 3308, a developer's live
server.
- --shared-server's config.yaml is now nested YAML (dolt: shared-server:
true); parse it instead of matching the old flat line.
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
* test(cmd/bd): run the Dolt-gated tests that skipped on a bare dolt.New
setupTestDB (config, kv and Linear round-trip tests), setupGatedTestDB
(mol ready --gated) and the rename-prefix and bd sql tests opened stores
with dolt.New(&dolt.Config{Path: ...}): no server port, no
CreateIfMissing, so against a running test server they got "database ...
not found" and skipped as "Dolt server not available". They now use the
suite's newTestStore helpers (skip only when no test server runs), and
what that exposed is fixed test-side:
- TestCustomStatusConfig: custom_statuses is read back ORDER BY name;
look statuses up by name / expect name order.
- TestLinearRoundTripCoreFields, TestLinearPullMilestonesCreatesEpicHierarchy:
linear.api_key is a yaml-only secret (LINEAR_API_KEY), push now needs an
explicit linear.state_map, and batch push uses TeamLabels and
issueBatchCreate, which the mock server now answers.
- TestSqlCommand: bd sql refuses in the default embedded mode; set
serverMode for the server-backed store, and stop discarding RunE errors.
- TestE2E_AutoStartedRepoLocalServerPersistsAcrossCommands skipped on
this process's embedded mode although every bd it runs is a subprocess
on a --server workspace; gate on the dolt binary instead and stop the
auto-started server at cleanup.
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
* test(cmd/bd): no fixed "unused" port, no swallowed JSON, no leaked front-door server
Three more things the Dolt-backed cmd/bd run exposed:
- TestTestServerConnection, TestSharedServerCfgNilHonorsSharedServer and
the two TestLegacyGuard* e2e tests pointed bd at 127.0.0.1:59999 as a
port nothing listens on. Any process on the host may hold it; a
listener that accepts and resets turns the expected "connection
refused" / "Dolt server unreachable" into another error. They take a
just-freed port from closedLoopbackPort (testutil.FindFreePort) now.
- TestDoltSetConfigJSONOutput and TestDoltSetConfigWithUpdateConfig
created .beads 0755, so bd's permissions warning landed in the JSON
under test and the tests skipped ("output not pure JSON") every run.
The fixture uses 0700, and non-JSON output fails instead of skipping.
- TestMigrateDoltModeFrontDoor's closing show/list auto-start a
repo-local server after the reverse migration; nothing stopped it, so
the suite's leak check failed (when the opt-in
BEADS_TEST_MIGRATION_FRONTDOOR suite runs). It stops it at cleanup.
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
* ci(bazel): advisory cmd/bd Dolt-server tier (bazel-cmd-dolt)
No CI lane ran cmd/bd's Dolt-gated tests (TestCLI_*, the init and
store-backed suites, the doctor/e2e tests): main.yml's integration shards,
nightly's Full Test Suite, and Bazel's --config=prcore/ci and
--config=integration all pass BEADS_TEST_SKIP=dolt, so cmd/bd's TestMain
never starts a test server and those tests skip; the proxied and embedded
tiers run only their manifests' tests. They rotted unseen.
//cmd/bd:bd_dolt_server_test (tag dolt-server-cmd) runs the whole
integration-tagged cmd/bd suite, the integration build's bd_test, against
a hermetic dolt sql-server: BEADS_TEST_DOLT_SERVER=local starts it from
the pinned dolt in the test wrapper's runfiles, and
BEADS_TEST_REQUIRE_DOLT_CONTAINER=1 fails the target instead of skipping
into a cached pass. No test selection: the Go binary shards itself over
every top-level test (32 shards), so each runs exactly once, and
check_testcases.py fails a shard that ran none. --config=doltserver-cmd
has exactly --config=integration's build flags, so the two lanes share
bd_test's compile; prcore/ci and integration exclude the tag.
bazel.yml's new bazel-cmd-dolt job runs it exactly where bazel-integration
runs (same if: remotely on the farm for same-repo PRs, fork-ro/fork-rw,
and locally with the read-only cache in mode cache for forks). It is
advisory: job-level continue-on-error keeps a failure out of the call's
aggregate (BAZEL), and pr.yml's ci-gate reads its result (BAZEL_CMD_DOLT)
but requires it only while the committed top-level flag
BAZEL_CMD_DOLT_REQUIRED is "true" (now "false"; flipping it is the one
change needed). bazel-gate.sh accepts its skip in modes skip and local.
Policy tests: a third lane category in TestBazelLaneIsGatedAlongsideLegacy
(bazelFlagGatedLanes: gate env wired, never statically required, added by
the run script exactly when the pinned flag is "true"), the gate
simulation over every mode with the flag off (advisory: nothing it
reports reddens the gate) and on (exactly a gated lane), the cache-mode
and execution-mode checks, the tag taxonomy and prcore/integration
exclusions, and TestBazelCmdDoltJob (job steps, timeouts, .bazelrc
config equal to integration's build with no dolt skip or test selection,
the target's dolt-server rules, and bd_test's env repeated).
Measured locally (all fixes in this series, 32 shards, 16 at a time on a
shared host): 3267 top-level tests, all shards pass, max shard 313s (one
5001-issue export test, 214s, sets it), mean 100s.
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
* fix(init): hand the project installers a writer instead of swapping os.Stdout
The --quiet fix earlier in this series pointed the process-global
os.Stdout at the null device around the Claude/Codex/Cursor installers.
That works, but it mutates a global from inside a cobra Run: anything else
writing to stdout meanwhile (a goroutine, a future concurrent installer)
would vanish, and a concurrent read of os.Stdout is a data race.
The installers already write through env structs with stdout/stderr
fields. setup.ProjectInstallOutput carries the two writers, and
InstallClaudeProjectTo / InstallCodexProjectTo / InstallCursorProjectTo
use them (the old entry points keep the process streams). init passes
QuietProjectInstallOutput() under --quiet: progress discarded, error lines
still on stderr. The proxied-server init path (domain adapter
InstallClaudeProject now takes quiet) does the same, so its
"Installing Claude hooks..." is quiet too.
Consistent error policy under --quiet: errors still reach stderr. init's
own "Warning: failed to setup <installer>" lines were suppressed under
--quiet while the installers' "Error:" lines were not, and some installer
failures (Cursor rules) print nothing themselves; the warnings now print
whether or not quiet, like the installers' errors.
Coverage in required lanes: TestProjectInstallersReportToTheGivenOutput
(cmd/bd/setup) and TestEmbeddedInitA/basic, which now asserts that
`bd init --quiet` with agents enabled installs the Claude hooks and prints
none of the installers' progress (verified to fail with the quiet output
disabled).
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
* test(export): exercise the incremental-export fallback with a small threshold
TestTryIncrementalExport_ThresholdExceededFallsBack seeded
incrementalExportThreshold+1 = 5001 issues to cross the threshold. Batch
create is one transaction but still several statements per issue, so under
-race against the shared test server it took ~214 s, the longest test in
cmd/bd's Dolt-backed suite by far. The behaviour under test is only
"more changed issues than the threshold -> full export fallback".
incrementalExportThreshold becomes a var (same value), and the test, which
is not parallel, sets it to 20 and seeds 21 issues: 214 s -> 0.6 s.
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
* test(cmd/bd): tighten the flag-reset self-test, guards and canaries
Review follow-ups:
- TestResetCommandFlagsRestoresEveryFlag no longer skips a flag it cannot
set: a flag type without a sample value, a Set error, or a non-pointer
Value (which resetCommandFlags could not restore) is an error, so a new
flag type cannot go untested. resetCommandFlags documents that it also
resets flag-bound package globals.
- TestCobraParallelPolicyGuard treats .ExecuteC/.ExecuteContext/
.ExecuteContextC like .Execute (the per-execution isolation writes the
mode globals; a parallel execution would race).
- TestConfigValidateReadOnlyIsHermetic ignores only the gate a readonly
command takes (.beads/dolt.gate.lock and its .info sidecar), not any
"*.gate.lock*" file, so a new unexpected gate still trips the canary.
- TestCLI_CreateRejectsFlagLikeTitles: a bare `bd create --foo-bar` must
fail and create no issue (bd-2c0's intent), next to the "--" cases.
- TestCustomStatusConfig cites why statuses come back in name order: the
normalized custom_statuses table (#2961, 8537d943b) has no ordinal and is
read ORDER BY name, like custom_types; the test predates it.
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
* ci(bazel): run the cmd/bd Dolt-server tier in 16 shards
Each shard pays ~30-40 s of fixed cost (TestMain plus its own dolt
sql-server), so 32 shards spent roughly 40% of the lane's executor time on
setup and added 32 farm actions to every PR touching cmd/bd. With the
5001-issue export test cut to under a second, 16 shards measure (locally,
--nocache_test_results): max 186 s, mean 137 s, 2,187 executor-seconds
(vs ~2,800-3,200 at 32), all 3,267 top-level tests, every shard passing.
TestBazelCmdDoltJob pins the count; bazel.yml's timing comment is
restated (cache mode ~20-30 minutes).
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
---------
Co-authored-by: Gas City Adopt-PR <adopt-pr@gascity.local>
Co-authored-by: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2324 lines
87 KiB
Go
2324 lines
87 KiB
Go
//go:build cgo && integration
|
|
|
|
package main
|
|
|
|
import (
|
|
"bytes"
|
|
"encoding/json"
|
|
"fmt"
|
|
"os"
|
|
"os/exec"
|
|
"path/filepath"
|
|
"runtime"
|
|
"strings"
|
|
"sync"
|
|
"testing"
|
|
"time"
|
|
|
|
"github.com/steveyegge/beads/internal/testutil/bazeltest"
|
|
"github.com/steveyegge/beads/internal/testutil/credentialcmd"
|
|
)
|
|
|
|
// Fast CLI tests converted from scripttest suite
|
|
// These use in-process testing (calling rootCmd.Execute directly) for speed
|
|
// A few tests still use exec.Command for end-to-end validation
|
|
//
|
|
// Performance improvement (bd-ky74):
|
|
// - Before: exec.Command() tests took 2-4 seconds each (~40s total)
|
|
// - After: in-process tests take <1 second each, ~10x faster
|
|
// - End-to-end test (TestCLI_EndToEnd) still validates binary with exec.Command
|
|
|
|
var (
|
|
inProcessMutex sync.Mutex // Protects concurrent access to rootCmd and global state
|
|
)
|
|
|
|
// templateDB holds a pre-initialized bd database directory.
|
|
// Created once via sync.Once, then copied for each test to avoid
|
|
// running bd init (which creates SQLite DB, config files, etc.) per test.
|
|
// This optimization eliminates ~2s per test from repeated initialization.
|
|
var (
|
|
templateDBDir string
|
|
templateDBOnce sync.Once
|
|
templateDBErr error
|
|
)
|
|
|
|
// initTemplateDB creates a single template database that can be copied for each test.
|
|
// Uses exec.Command (subprocess) to avoid polluting Cobra global state.
|
|
// The testBD binary is already built once in init().
|
|
func initTemplateDB() {
|
|
templateDBOnce.Do(func() {
|
|
tmpDir, err := os.MkdirTemp("", "bd-cli-template-*")
|
|
if err != nil {
|
|
templateDBErr = fmt.Errorf("failed to create template dir: %w", err)
|
|
return
|
|
}
|
|
templateDBDir = tmpDir
|
|
|
|
// Use exec.Command to run bd init in a subprocess.
|
|
// This avoids any Cobra global state pollution that would affect subsequent
|
|
// in-process test runs.
|
|
cmd := exec.Command(testBD, "init", "--prefix", "test", "--quiet")
|
|
cmd.Dir = tmpDir
|
|
cmd.Env = os.Environ()
|
|
if out, err := cmd.CombinedOutput(); err != nil {
|
|
templateDBErr = fmt.Errorf("template bd init failed: %v\n%s", err, out)
|
|
return
|
|
}
|
|
})
|
|
}
|
|
|
|
// copyDir recursively copies a directory tree.
|
|
func copyDir(src, dst string) error {
|
|
entries, err := os.ReadDir(src)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
if err := os.MkdirAll(dst, 0750); err != nil {
|
|
return err
|
|
}
|
|
for _, entry := range entries {
|
|
srcPath := filepath.Join(src, entry.Name())
|
|
dstPath := filepath.Join(dst, entry.Name())
|
|
if entry.IsDir() {
|
|
if err := copyDir(srcPath, dstPath); err != nil {
|
|
return err
|
|
}
|
|
} else {
|
|
data, err := os.ReadFile(srcPath)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
if err := os.WriteFile(dstPath, data, 0600); err != nil {
|
|
return err
|
|
}
|
|
}
|
|
}
|
|
return nil
|
|
}
|
|
|
|
// setupCLITestDB creates a fresh initialized bd database for CLI tests.
|
|
// Uses a cached template directory to avoid running bd init for every test.
|
|
// The template is created once via sync.Once and copied for each test.
|
|
func setupCLITestDB(t *testing.T) string {
|
|
t.Helper()
|
|
if testDoltServerPort == 0 {
|
|
t.Skip("skipping: Dolt test container not available")
|
|
}
|
|
initTemplateDB()
|
|
if templateDBErr != nil {
|
|
t.Fatalf("Template DB initialization failed: %v", templateDBErr)
|
|
}
|
|
tmpDir := createTempDirWithCleanup(t)
|
|
if err := copyDir(templateDBDir, tmpDir); err != nil {
|
|
t.Fatalf("Failed to copy template DB: %v", err)
|
|
}
|
|
return tmpDir
|
|
}
|
|
|
|
// createTempDirWithCleanup creates a temp directory with non-fatal cleanup
|
|
// This prevents test failures from SQLite file lock cleanup issues
|
|
func createTempDirWithCleanup(t *testing.T) string {
|
|
t.Helper()
|
|
|
|
tmpDir, err := os.MkdirTemp("", "bd-cli-test-*")
|
|
if err != nil {
|
|
t.Fatalf("Failed to create temp dir: %v", err)
|
|
}
|
|
|
|
t.Cleanup(func() {
|
|
// Retry cleanup with delays to handle SQLite file locks
|
|
// Don't fail the test if cleanup fails - just log it
|
|
for i := 0; i < 5; i++ {
|
|
err := os.RemoveAll(tmpDir)
|
|
if err == nil {
|
|
return // Success
|
|
}
|
|
if i < 4 {
|
|
time.Sleep(50 * time.Millisecond)
|
|
}
|
|
}
|
|
// Final attempt failed - log but don't fail test
|
|
t.Logf("Warning: Failed to clean up temp dir %s (SQLite file locks)", tmpDir)
|
|
})
|
|
|
|
return tmpDir
|
|
}
|
|
|
|
// restoreEnvSnapshot puts the process environment back to before, a prior
|
|
// os.Environ(): an in-process rootCmd.Execute mutates the environment with
|
|
// raw os.Setenv and restores nothing (see installExecuteIsolation, which now
|
|
// does this for every execution; kept here so the runners do not depend on
|
|
// TestMain having installed it).
|
|
func restoreEnvSnapshot(before []string) { restoreProcessEnv(before) }
|
|
|
|
// runBDInProcess runs bd commands in-process by calling rootCmd.Execute
|
|
// This is ~10-20x faster than exec.Command because it avoids process spawn overhead
|
|
func runBDInProcess(t *testing.T, dir string, args ...string) string {
|
|
t.Helper()
|
|
|
|
// Serialize all in-process test execution to avoid race conditions
|
|
// rootCmd, cobra state, and viper are not thread-safe
|
|
inProcessMutex.Lock()
|
|
defer inProcessMutex.Unlock()
|
|
|
|
// Save original state
|
|
oldStdout := os.Stdout
|
|
oldStderr := os.Stderr
|
|
oldDir, _ := os.Getwd()
|
|
oldArgs := os.Args
|
|
|
|
// Change to test directory
|
|
if err := os.Chdir(dir); err != nil {
|
|
t.Fatalf("Failed to chdir to %s: %v", dir, err)
|
|
}
|
|
|
|
// Capture stdout/stderr
|
|
rOut, wOut, _ := os.Pipe()
|
|
rErr, wErr, _ := os.Pipe()
|
|
os.Stdout = wOut
|
|
os.Stderr = wErr
|
|
defer func() {
|
|
os.Stdout = oldStdout
|
|
os.Stderr = oldStderr
|
|
}()
|
|
|
|
// Start from the registered flag defaults: cobra keeps every parsed
|
|
// value (and Changed) on the shared command tree across Execute calls.
|
|
resetCommandFlags(rootCmd)
|
|
defer resetCommandFlags(rootCmd)
|
|
|
|
// Set args for rootCmd
|
|
rootCmd.SetArgs(args)
|
|
os.Args = append([]string{"bd"}, args...)
|
|
|
|
// Execute command
|
|
envBefore := os.Environ()
|
|
err := rootCmd.Execute()
|
|
restoreEnvSnapshot(envBefore)
|
|
|
|
// Close and clean up all global state to prevent contamination between tests
|
|
if store != nil {
|
|
store.Close()
|
|
store = nil
|
|
}
|
|
// Reset all global flags and state
|
|
dbPath = ""
|
|
actor = ""
|
|
jsonOutput = false
|
|
sandboxMode = false
|
|
// Reset context state
|
|
rootCtx = nil
|
|
rootCancel = nil
|
|
|
|
// Give SQLite time to release file locks before cleanup
|
|
time.Sleep(10 * time.Millisecond)
|
|
|
|
// Close writers and restore
|
|
wOut.Close()
|
|
wErr.Close()
|
|
os.Chdir(oldDir)
|
|
os.Args = oldArgs
|
|
rootCmd.SetArgs(nil)
|
|
|
|
// Read output (keep stdout and stderr separate)
|
|
var outBuf, errBuf bytes.Buffer
|
|
outBuf.ReadFrom(rOut)
|
|
errBuf.ReadFrom(rErr)
|
|
|
|
stdout := outBuf.String()
|
|
stderr := errBuf.String()
|
|
|
|
if err != nil {
|
|
t.Fatalf("bd %v failed: %v\nStdout: %s\nStderr: %s", args, err, stdout, stderr)
|
|
}
|
|
|
|
// Return only stdout (stderr contains warnings that break JSON parsing)
|
|
return stdout
|
|
}
|
|
|
|
func TestCLI_Ready(t *testing.T) {
|
|
// Note: Not using t.Parallel() because inProcessMutex serializes execution anyway
|
|
tmpDir := setupCLITestDB(t)
|
|
runBDInProcess(t, tmpDir, "create", "Ready issue", "-p", "1")
|
|
out := runBDInProcess(t, tmpDir, "ready")
|
|
if !strings.Contains(out, "Ready issue") {
|
|
t.Errorf("Expected 'Ready issue' in output, got: %s", out)
|
|
}
|
|
}
|
|
|
|
func TestCLI_Create(t *testing.T) {
|
|
// Note: Not using t.Parallel() because inProcessMutex serializes execution anyway
|
|
tmpDir := setupCLITestDB(t)
|
|
out := runBDInProcess(t, tmpDir, "create", "Test issue", "-p", "1", "--json")
|
|
|
|
// Extract JSON from output (may contain warnings before JSON)
|
|
jsonStart := strings.Index(out, "{")
|
|
if jsonStart == -1 {
|
|
t.Fatalf("No JSON found in output: %s", out)
|
|
}
|
|
jsonOut := out[jsonStart:]
|
|
|
|
var result map[string]interface{}
|
|
if err := json.Unmarshal([]byte(jsonOut), &result); err != nil {
|
|
t.Fatalf("Failed to parse JSON: %v\nOutput: %s", err, jsonOut)
|
|
}
|
|
if result["title"] != "Test issue" {
|
|
t.Errorf("Expected title 'Test issue', got: %v", result["title"])
|
|
}
|
|
}
|
|
|
|
// TestCLI_CreateActorPrecedence is a CLI-level regression test for GH#4645:
|
|
// with both BEADS_ACTOR and the deprecated BD_ACTOR set, `bd create` must
|
|
// stamp created_by with BEADS_ACTOR's value. Unlike TestResolveConfiguredActor
|
|
// (which calls resolveConfiguredActor() directly), this drives the real
|
|
// command through rootCmd.Execute() so it also covers the root
|
|
// PersistentPreRunE / refreshBoundCommandConfig wiring that pre-populates the
|
|
// global actor before create.go ever runs — reverting either call site would
|
|
// leave TestResolveConfiguredActor green but this test red.
|
|
func TestCLI_CreateActorPrecedence(t *testing.T) {
|
|
// Note: Not using t.Parallel() because inProcessMutex serializes execution anyway
|
|
tmpDir := setupCLITestDB(t)
|
|
t.Setenv("BD_ACTOR", "from-bd-actor")
|
|
t.Setenv("BEADS_ACTOR", "from-beads-actor")
|
|
|
|
out := runBDInProcess(t, tmpDir, "create", "Actor precedence test", "-p", "1", "--json")
|
|
|
|
jsonStart := strings.Index(out, "{")
|
|
if jsonStart == -1 {
|
|
t.Fatalf("No JSON found in output: %s", out)
|
|
}
|
|
jsonOut := out[jsonStart:]
|
|
|
|
var result map[string]interface{}
|
|
if err := json.Unmarshal([]byte(jsonOut), &result); err != nil {
|
|
t.Fatalf("Failed to parse JSON: %v\nOutput: %s", err, jsonOut)
|
|
}
|
|
if result["created_by"] != "from-beads-actor" {
|
|
t.Errorf("created_by = %v, want %q (BEADS_ACTOR must outrank deprecated BD_ACTOR)", result["created_by"], "from-beads-actor")
|
|
}
|
|
}
|
|
|
|
func TestCLI_List(t *testing.T) {
|
|
// Note: Not using t.Parallel() because inProcessMutex serializes execution anyway
|
|
tmpDir := setupCLITestDB(t)
|
|
runBDInProcess(t, tmpDir, "create", "First", "-p", "1")
|
|
runBDInProcess(t, tmpDir, "create", "Second", "-p", "2")
|
|
|
|
out := runBDInProcess(t, tmpDir, "list", "--json")
|
|
var issues []map[string]interface{}
|
|
if err := json.Unmarshal([]byte(out), &issues); err != nil {
|
|
t.Fatalf("Failed to parse JSON: %v", err)
|
|
}
|
|
if len(issues) != 2 {
|
|
t.Errorf("Expected 2 issues, got %d", len(issues))
|
|
}
|
|
}
|
|
|
|
func TestCLI_Update(t *testing.T) {
|
|
// Note: Not using t.Parallel() because inProcessMutex serializes execution anyway
|
|
tmpDir := setupCLITestDB(t)
|
|
out := runBDInProcess(t, tmpDir, "create", "Issue to update", "-p", "1", "--json")
|
|
|
|
var issue map[string]interface{}
|
|
json.Unmarshal([]byte(out), &issue)
|
|
id := issue["id"].(string)
|
|
|
|
runBDInProcess(t, tmpDir, "update", id, "--status", "in_progress")
|
|
|
|
out = runBDInProcess(t, tmpDir, "show", id, "--json")
|
|
var updated []map[string]interface{}
|
|
json.Unmarshal([]byte(out), &updated)
|
|
if updated[0]["status"] != "in_progress" {
|
|
t.Errorf("Expected status 'in_progress', got: %v", updated[0]["status"])
|
|
}
|
|
}
|
|
|
|
func TestCLI_UpdateLabels(t *testing.T) {
|
|
// Note: Not using t.Parallel() because inProcessMutex serializes execution anyway
|
|
tmpDir := setupCLITestDB(t)
|
|
out := runBDInProcess(t, tmpDir, "create", "Issue for label testing", "-p", "2", "--json")
|
|
|
|
var issue map[string]interface{}
|
|
json.Unmarshal([]byte(out), &issue)
|
|
id := issue["id"].(string)
|
|
|
|
// Test adding labels
|
|
runBDInProcess(t, tmpDir, "update", id, "--add-label", "feature", "--add-label", "backend")
|
|
|
|
out = runBDInProcess(t, tmpDir, "show", id, "--json")
|
|
var updated []map[string]interface{}
|
|
json.Unmarshal([]byte(out), &updated)
|
|
labels := updated[0]["labels"].([]interface{})
|
|
if len(labels) != 2 {
|
|
t.Errorf("Expected 2 labels after add, got: %d", len(labels))
|
|
}
|
|
hasBackend, hasFeature := false, false
|
|
for _, l := range labels {
|
|
if l.(string) == "backend" {
|
|
hasBackend = true
|
|
}
|
|
if l.(string) == "feature" {
|
|
hasFeature = true
|
|
}
|
|
}
|
|
if !hasBackend || !hasFeature {
|
|
t.Errorf("Expected labels 'backend' and 'feature', got: %v", labels)
|
|
}
|
|
|
|
// Test removing a label
|
|
runBDInProcess(t, tmpDir, "update", id, "--remove-label", "backend")
|
|
|
|
out = runBDInProcess(t, tmpDir, "show", id, "--json")
|
|
json.Unmarshal([]byte(out), &updated)
|
|
labels = updated[0]["labels"].([]interface{})
|
|
if len(labels) != 1 {
|
|
t.Errorf("Expected 1 label after remove, got: %d", len(labels))
|
|
}
|
|
if labels[0].(string) != "feature" {
|
|
t.Errorf("Expected label 'feature', got: %v", labels[0])
|
|
}
|
|
|
|
// Test setting labels (replaces all)
|
|
runBDInProcess(t, tmpDir, "update", id, "--set-labels", "api,database,critical")
|
|
|
|
out = runBDInProcess(t, tmpDir, "show", id, "--json")
|
|
json.Unmarshal([]byte(out), &updated)
|
|
labels = updated[0]["labels"].([]interface{})
|
|
if len(labels) != 3 {
|
|
t.Errorf("Expected 3 labels after set, got: %d", len(labels))
|
|
}
|
|
expectedLabels := map[string]bool{"api": true, "database": true, "critical": true}
|
|
for _, l := range labels {
|
|
if !expectedLabels[l.(string)] {
|
|
t.Errorf("Unexpected label: %v", l)
|
|
}
|
|
}
|
|
}
|
|
|
|
func TestCLI_UpdateEphemeral(t *testing.T) {
|
|
// Note: Not using t.Parallel() because inProcessMutex serializes execution anyway
|
|
tmpDir := setupCLITestDB(t)
|
|
out := runBDInProcess(t, tmpDir, "create", "Issue for ephemeral testing", "-p", "2", "--json")
|
|
|
|
var issue map[string]interface{}
|
|
if err := json.Unmarshal([]byte(out), &issue); err != nil {
|
|
t.Fatalf("Failed to parse create output: %v", err)
|
|
}
|
|
id := issue["id"].(string)
|
|
|
|
// Mark as ephemeral
|
|
runBDInProcess(t, tmpDir, "update", id, "--ephemeral")
|
|
|
|
out = runBDInProcess(t, tmpDir, "show", id, "--json")
|
|
var updated []map[string]interface{}
|
|
if err := json.Unmarshal([]byte(out), &updated); err != nil {
|
|
t.Fatalf("Failed to parse show output: %v", err)
|
|
}
|
|
if updated[0]["ephemeral"] != true {
|
|
t.Errorf("Expected ephemeral to be true after --ephemeral, got: %v", updated[0]["ephemeral"])
|
|
}
|
|
}
|
|
|
|
func TestCLI_UpdatePersistent(t *testing.T) {
|
|
// Note: Not using t.Parallel() because inProcessMutex serializes execution anyway
|
|
tmpDir := setupCLITestDB(t)
|
|
|
|
// Create ephemeral issue directly
|
|
out := runBDInProcess(t, tmpDir, "create", "Ephemeral issue", "-p", "2", "--ephemeral", "--json")
|
|
|
|
var issue map[string]interface{}
|
|
if err := json.Unmarshal([]byte(out), &issue); err != nil {
|
|
t.Fatalf("Failed to parse create output: %v", err)
|
|
}
|
|
id := issue["id"].(string)
|
|
|
|
// Verify it's ephemeral
|
|
out = runBDInProcess(t, tmpDir, "show", id, "--json")
|
|
var initial []map[string]interface{}
|
|
if err := json.Unmarshal([]byte(out), &initial); err != nil {
|
|
t.Fatalf("Failed to parse show output: %v", err)
|
|
}
|
|
if initial[0]["ephemeral"] != true {
|
|
t.Fatalf("Expected issue to be ephemeral initially, got: %v", initial[0]["ephemeral"])
|
|
}
|
|
|
|
// Promote to persistent
|
|
runBDInProcess(t, tmpDir, "update", id, "--persistent")
|
|
|
|
out = runBDInProcess(t, tmpDir, "show", id, "--json")
|
|
var updated []map[string]interface{}
|
|
if err := json.Unmarshal([]byte(out), &updated); err != nil {
|
|
t.Fatalf("Failed to parse show output after persistent: %v", err)
|
|
}
|
|
if updated[0]["ephemeral"] == true {
|
|
t.Errorf("Expected ephemeral to be false after --persistent, got: %v", updated[0]["ephemeral"])
|
|
}
|
|
}
|
|
|
|
func TestCLI_UpdateEphemeralMutualExclusion(t *testing.T) {
|
|
// Note: Not using t.Parallel() because inProcessMutex serializes execution anyway
|
|
tmpDir := setupCLITestDB(t)
|
|
out := runBDInProcess(t, tmpDir, "create", "Issue for mutual exclusion test", "-p", "2", "--json")
|
|
|
|
var issue map[string]interface{}
|
|
json.Unmarshal([]byte(out), &issue)
|
|
id := issue["id"].(string)
|
|
|
|
// Both flags should error
|
|
_, stderr, err := runBDInProcessAllowError(t, tmpDir, "update", id, "--ephemeral", "--persistent")
|
|
if err == nil {
|
|
t.Errorf("Expected error when both flags specified, got none")
|
|
}
|
|
if !strings.Contains(stderr, "cannot specify both") {
|
|
t.Errorf("Expected mutual exclusion error message, got: %v", stderr)
|
|
}
|
|
}
|
|
|
|
func TestCLI_UpdateAppendNotes(t *testing.T) {
|
|
tmpDir := setupCLITestDB(t)
|
|
out := runBDInProcess(t, tmpDir, "create", "Issue for append-notes test", "-p", "2", "--notes", "Original notes", "--json")
|
|
|
|
var issue map[string]interface{}
|
|
json.Unmarshal([]byte(out), &issue)
|
|
id := issue["id"].(string)
|
|
|
|
// Test appending notes
|
|
runBDInProcess(t, tmpDir, "update", id, "--append-notes", "Appended content")
|
|
|
|
out = runBDInProcess(t, tmpDir, "show", id, "--json")
|
|
var updated []map[string]interface{}
|
|
json.Unmarshal([]byte(out), &updated)
|
|
notes := updated[0]["notes"].(string)
|
|
if notes != "Original notes\nAppended content" {
|
|
t.Errorf("Expected 'Original notes\\nAppended content', got: %q", notes)
|
|
}
|
|
|
|
// Test appending to empty notes
|
|
out = runBDInProcess(t, tmpDir, "create", "Issue with empty notes", "-p", "2", "--json")
|
|
json.Unmarshal([]byte(out), &issue)
|
|
id2 := issue["id"].(string)
|
|
|
|
runBDInProcess(t, tmpDir, "update", id2, "--append-notes", "First note")
|
|
|
|
out = runBDInProcess(t, tmpDir, "show", id2, "--json")
|
|
json.Unmarshal([]byte(out), &updated)
|
|
notes = updated[0]["notes"].(string)
|
|
if notes != "First note" {
|
|
t.Errorf("Expected 'First note', got: %q", notes)
|
|
}
|
|
}
|
|
|
|
func TestCLI_UpdateAppendNotesMutualExclusion(t *testing.T) {
|
|
tmpDir := setupCLITestDB(t)
|
|
out := runBDInProcess(t, tmpDir, "create", "Issue for notes mutual exclusion", "-p", "2", "--json")
|
|
|
|
var issue map[string]interface{}
|
|
json.Unmarshal([]byte(out), &issue)
|
|
id := issue["id"].(string)
|
|
|
|
// Both --notes and --append-notes should error
|
|
_, stderr, err := runBDInProcessAllowError(t, tmpDir, "update", id, "--notes", "New notes", "--append-notes", "Appended")
|
|
if err == nil {
|
|
t.Errorf("Expected error when both --notes and --append-notes specified, got none")
|
|
}
|
|
if !strings.Contains(stderr, "cannot specify both --notes and --append-notes") {
|
|
t.Errorf("Expected mutual exclusion error message, got: %v", stderr)
|
|
}
|
|
}
|
|
|
|
func TestCLI_NoteCommand(t *testing.T) {
|
|
tmpDir := setupCLITestDB(t)
|
|
|
|
// Create an issue with initial notes
|
|
out := runBDInProcess(t, tmpDir, "create", "Issue for note test", "-p", "2", "--notes", "Original notes", "--json")
|
|
var issue map[string]interface{}
|
|
json.Unmarshal([]byte(out), &issue)
|
|
id := issue["id"].(string)
|
|
|
|
// Test: bd note <id> <text> appends to existing notes
|
|
runBDInProcess(t, tmpDir, "note", id, "Added via note command")
|
|
out = runBDInProcess(t, tmpDir, "show", id, "--json")
|
|
var updated []map[string]interface{}
|
|
json.Unmarshal([]byte(out), &updated)
|
|
notes := updated[0]["notes"].(string)
|
|
if notes != "Original notes\nAdded via note command" {
|
|
t.Errorf("Expected 'Original notes\\nAdded via note command', got: %q", notes)
|
|
}
|
|
|
|
// Test: bd note <id> with multiple words joins them
|
|
runBDInProcess(t, tmpDir, "note", id, "second", "note", "here")
|
|
out = runBDInProcess(t, tmpDir, "show", id, "--json")
|
|
json.Unmarshal([]byte(out), &updated)
|
|
notes = updated[0]["notes"].(string)
|
|
if notes != "Original notes\nAdded via note command\nsecond note here" {
|
|
t.Errorf("Expected three lines, got: %q", notes)
|
|
}
|
|
|
|
// Test: bd note on issue with no existing notes
|
|
out = runBDInProcess(t, tmpDir, "create", "Issue with no notes", "-p", "2", "--json")
|
|
json.Unmarshal([]byte(out), &issue)
|
|
id2 := issue["id"].(string)
|
|
|
|
runBDInProcess(t, tmpDir, "note", id2, "First note ever")
|
|
out = runBDInProcess(t, tmpDir, "show", id2, "--json")
|
|
json.Unmarshal([]byte(out), &updated)
|
|
notes = updated[0]["notes"].(string)
|
|
if notes != "First note ever" {
|
|
t.Errorf("Expected 'First note ever', got: %q", notes)
|
|
}
|
|
|
|
// Test: bd note with no text should fail
|
|
_, stderr, err := runBDInProcessAllowError(t, tmpDir, "note", id)
|
|
if err == nil {
|
|
t.Errorf("Expected error when no note text provided, got none")
|
|
}
|
|
if !strings.Contains(stderr, "no note text provided") {
|
|
t.Errorf("Expected 'no note text provided' error, got: %v", stderr)
|
|
}
|
|
}
|
|
|
|
// TestCLI_NoteListMisplacedSyntax is a regression test for "note" silently
|
|
// mis-resolving a subcommand-like typo as an issue id (GH#5370). Mirrors
|
|
// TestCLI_CommentListMisplacedSyntax (#5369): "bd note list <text>" used to
|
|
// parse as id="list", text=[<text>...] with no validation on the id — since
|
|
// no issue is literally named "list", ResolvePartialID's substring/prefix
|
|
// fallback would silently match it against whatever existing bead or wisp id
|
|
// happened to contain "list" and append the note there instead of erroring.
|
|
// This asserts both halves of the fix: the command is rejected with a
|
|
// helpful hint, AND no note silently landed on an unrelated real issue.
|
|
func TestCLI_NoteListMisplacedSyntax(t *testing.T) {
|
|
tmpDir := setupCLITestDB(t)
|
|
|
|
out := runBDInProcess(t, tmpDir, "create", "Bystander issue", "-p", "1", "--json")
|
|
jsonStart := strings.Index(out, "{")
|
|
if jsonStart < 0 {
|
|
t.Fatalf("No JSON found in create output: %s", out)
|
|
}
|
|
var issue map[string]interface{}
|
|
if err := json.Unmarshal([]byte(out[jsonStart:]), &issue); err != nil {
|
|
t.Fatalf("Failed to parse create JSON: %v\nOutput: %s", err, out)
|
|
}
|
|
fullID := issue["id"].(string)
|
|
|
|
// Snapshot notes BEFORE the rejected command. runBDInProcess reuses the
|
|
// package-level rootCmd without resetting cobra flag state, so an earlier
|
|
// test's --notes value can leak into this create. Asserting before==after
|
|
// is immune to that leak and is a stronger regression check: the rejected
|
|
// command wrote nothing (GH#5370 review fix-round).
|
|
beforeShow := runBDInProcess(t, tmpDir, "show", fullID, "--json")
|
|
var beforeShown []map[string]interface{}
|
|
if err := json.Unmarshal([]byte(beforeShow), &beforeShown); err != nil {
|
|
t.Fatalf("Failed to parse pre-reject show JSON: %v\nOutput: %s", err, beforeShow)
|
|
}
|
|
if len(beforeShown) == 0 {
|
|
t.Fatalf("expected show to return the bystander issue before reject, got: %s", beforeShow)
|
|
}
|
|
notesBefore, _ := beforeShown[0]["notes"].(string)
|
|
|
|
stdout, stderr, err := runBDInProcessAllowError(t, tmpDir, "note", "list", "accidental stray text")
|
|
if err == nil {
|
|
t.Fatalf("expected non-zero exit, got stdout=%q stderr=%q", stdout, stderr)
|
|
}
|
|
combined := stdout + stderr
|
|
if !strings.Contains(combined, "bd note") || !strings.Contains(combined, "<issue-id>") {
|
|
t.Fatalf("expected hint pointing at bd note <issue-id>, got stdout=%q stderr=%q", stdout, stderr)
|
|
}
|
|
|
|
// The regression check: the bystander issue's notes must be UNCHANGED.
|
|
// Pre-fix, this could silently succeed and land a note on whatever
|
|
// bead's id happened to contain "list" as a substring.
|
|
showOut := runBDInProcess(t, tmpDir, "show", fullID, "--json")
|
|
var shown []map[string]interface{}
|
|
if err := json.Unmarshal([]byte(showOut), &shown); err != nil {
|
|
t.Fatalf("Failed to parse show JSON: %v\nOutput: %s", err, showOut)
|
|
}
|
|
if len(shown) == 0 {
|
|
t.Fatalf("expected show to return the bystander issue, got: %s", showOut)
|
|
}
|
|
notesAfter, _ := shown[0]["notes"].(string)
|
|
if notesAfter != notesBefore {
|
|
t.Fatalf("expected bystander issue %s notes unchanged after rejected 'note list' (before=%q after=%q)", fullID, notesBefore, notesAfter)
|
|
}
|
|
}
|
|
|
|
// TestCLI_NoteAddMisplacedSyntax mirrors TestCLI_NoteListMisplacedSyntax
|
|
// for the symmetric "add" typo — a caller who types "bd note add <id> <text>"
|
|
// (confusing note with comments-style "add") would parse as id="add",
|
|
// text=[<id>, <text>...].
|
|
func TestCLI_NoteAddMisplacedSyntax(t *testing.T) {
|
|
tmpDir := setupCLITestDB(t)
|
|
|
|
out := runBDInProcess(t, tmpDir, "create", "Bystander issue for add-typo", "-p", "1", "--json")
|
|
jsonStart := strings.Index(out, "{")
|
|
if jsonStart < 0 {
|
|
t.Fatalf("No JSON found in create output: %s", out)
|
|
}
|
|
var issue map[string]interface{}
|
|
if err := json.Unmarshal([]byte(out[jsonStart:]), &issue); err != nil {
|
|
t.Fatalf("Failed to parse create JSON: %v\nOutput: %s", err, out)
|
|
}
|
|
fullID := issue["id"].(string)
|
|
|
|
// Snapshot notes BEFORE the rejected command (same order-independence
|
|
// rationale as TestCLI_NoteListMisplacedSyntax).
|
|
beforeShow := runBDInProcess(t, tmpDir, "show", fullID, "--json")
|
|
var beforeShown []map[string]interface{}
|
|
if err := json.Unmarshal([]byte(beforeShow), &beforeShown); err != nil {
|
|
t.Fatalf("Failed to parse pre-reject show JSON: %v\nOutput: %s", err, beforeShow)
|
|
}
|
|
if len(beforeShown) == 0 {
|
|
t.Fatalf("expected show to return the bystander issue before reject, got: %s", beforeShow)
|
|
}
|
|
notesBefore, _ := beforeShown[0]["notes"].(string)
|
|
|
|
stdout, stderr, err := runBDInProcessAllowError(t, tmpDir, "note", "add", fullID, "accidental stray text")
|
|
if err == nil {
|
|
t.Fatalf("expected non-zero exit, got stdout=%q stderr=%q", stdout, stderr)
|
|
}
|
|
combined := stdout + stderr
|
|
if !strings.Contains(combined, "bd note") || !strings.Contains(combined, "<issue-id>") {
|
|
t.Fatalf("expected hint pointing at bd note <issue-id>, got stdout=%q stderr=%q", stdout, stderr)
|
|
}
|
|
|
|
showOut := runBDInProcess(t, tmpDir, "show", fullID, "--json")
|
|
var shown []map[string]interface{}
|
|
if err := json.Unmarshal([]byte(showOut), &shown); err != nil {
|
|
t.Fatalf("Failed to parse show JSON: %v\nOutput: %s", err, showOut)
|
|
}
|
|
if len(shown) == 0 {
|
|
t.Fatalf("expected show to return the bystander issue, got: %s", showOut)
|
|
}
|
|
notesAfter, _ := shown[0]["notes"].(string)
|
|
if notesAfter != notesBefore {
|
|
t.Fatalf("expected bystander issue %s notes unchanged after rejected 'note add' (before=%q after=%q)", fullID, notesBefore, notesAfter)
|
|
}
|
|
}
|
|
|
|
// TestCLI_NoteMisplacedSyntaxRejectedBeforeStoreOpen proves the guard
|
|
// fires from noteCmd's Args validator, before PersistentPreRunE ever
|
|
// opens a store, mirroring
|
|
// TestCLI_CommentMisplacedSyntaxRejectedBeforeStoreOpen for the comment
|
|
// sibling. Using a directory with no .beads/ at all proves the store was
|
|
// never touched: a RunE-only check would have failed first with "no beads
|
|
// database found".
|
|
func TestCLI_NoteMisplacedSyntaxRejectedBeforeStoreOpen(t *testing.T) {
|
|
noBeadsCwd := t.TempDir()
|
|
if _, err := os.Stat(filepath.Join(noBeadsCwd, ".beads")); err == nil {
|
|
t.Fatalf("test setup: %s unexpectedly has a .beads dir", noBeadsCwd)
|
|
}
|
|
|
|
stdout, stderr, err := runBDInProcessAllowError(t, noBeadsCwd, "note", "list", "should not be stored")
|
|
if err == nil {
|
|
t.Fatalf("expected non-zero exit for misplaced 'note list', got success:\nstdout: %s", stdout)
|
|
}
|
|
combined := stdout + stderr
|
|
if strings.Contains(combined, "no beads database found") {
|
|
t.Fatalf("Args validation did not run before store open: got the pre-fix error.\nOutput:\n%s", combined)
|
|
}
|
|
if !strings.Contains(combined, "bd note") {
|
|
t.Errorf("expected hint pointing to `bd note`, got:\n%s", combined)
|
|
}
|
|
}
|
|
|
|
// TestCLI_NoteMisplacedSyntaxRejectedInProxiedServerMode is the
|
|
// proxied-server counterpart, mirroring
|
|
// TestCLI_CommentMisplacedSyntaxRejectedInProxiedServerMode: because
|
|
// validateNoteArgs runs in Args — before RunE ever branches on
|
|
// usesProxiedServer() — the rejection fires identically regardless of
|
|
// backend, without needing a real proxied server.
|
|
func TestCLI_NoteMisplacedSyntaxRejectedInProxiedServerMode(t *testing.T) {
|
|
origProxied := proxiedServerMode
|
|
t.Cleanup(func() { proxiedServerMode = origProxied })
|
|
proxiedServerMode = true
|
|
|
|
tmpDir := setupCLITestDB(t)
|
|
stdout, stderr, err := runBDInProcessAllowError(t, tmpDir, "note", "list", "should not be stored")
|
|
if err == nil {
|
|
t.Fatalf("expected non-zero exit for misplaced 'note list' in proxied-server mode, got success:\nstdout: %s", stdout)
|
|
}
|
|
combined := stdout + stderr
|
|
if !strings.Contains(combined, "bd note") {
|
|
t.Errorf("expected hint pointing to `bd note`, got:\n%s", combined)
|
|
}
|
|
}
|
|
|
|
// TestCLI_NoteTextStartingWithReservedWordStillWorks confirms the fix is
|
|
// scoped to the id positional argument only: a real id followed by note
|
|
// TEXT that happens to start with "list" or "add" must still work exactly
|
|
// as before, since args[0] (the id slot) is what's checked, never the text.
|
|
func TestCLI_NoteTextStartingWithReservedWordStillWorks(t *testing.T) {
|
|
tmpDir := setupCLITestDB(t)
|
|
|
|
out := runBDInProcess(t, tmpDir, "create", "Issue for reserved-word-text test", "-p", "1", "--json")
|
|
jsonStart := strings.Index(out, "{")
|
|
if jsonStart < 0 {
|
|
t.Fatalf("No JSON found in create output: %s", out)
|
|
}
|
|
var issue map[string]interface{}
|
|
if err := json.Unmarshal([]byte(out[jsonStart:]), &issue); err != nil {
|
|
t.Fatalf("Failed to parse create JSON: %v\nOutput: %s", err, out)
|
|
}
|
|
fullID := issue["id"].(string)
|
|
|
|
stdout, stderr, err := runBDInProcessAllowError(t, tmpDir, "note", fullID, "list", "of", "things", "to", "do")
|
|
if err != nil {
|
|
t.Fatalf("note with text starting in 'list' unexpectedly failed: %v\nstdout: %s\nstderr: %s", err, stdout, stderr)
|
|
}
|
|
if !strings.Contains(stdout, "Note added") {
|
|
t.Errorf("Expected 'Note added' in output, got: %s", stdout)
|
|
}
|
|
|
|
showOut := runBDInProcess(t, tmpDir, "show", fullID, "--json")
|
|
if !strings.Contains(showOut, "list of things to do") {
|
|
t.Fatalf("expected note text to be stored verbatim, got: %s", showOut)
|
|
}
|
|
}
|
|
|
|
func TestCLI_Close(t *testing.T) {
|
|
// Note: Not using t.Parallel() because inProcessMutex serializes execution anyway
|
|
tmpDir := setupCLITestDB(t)
|
|
out := runBDInProcess(t, tmpDir, "create", "Issue to close", "-p", "1", "--json")
|
|
|
|
var issue map[string]interface{}
|
|
json.Unmarshal([]byte(out), &issue)
|
|
id := issue["id"].(string)
|
|
|
|
runBDInProcess(t, tmpDir, "close", id, "--reason", "Done")
|
|
|
|
out = runBDInProcess(t, tmpDir, "show", id, "--json")
|
|
var closed []map[string]interface{}
|
|
json.Unmarshal([]byte(out), &closed)
|
|
if closed[0]["status"] != "closed" {
|
|
t.Errorf("Expected status 'closed', got: %v", closed[0]["status"])
|
|
}
|
|
if closed[0]["close_reason"] != "Done" {
|
|
t.Errorf("Expected close_reason 'Done', got: %v", closed[0]["close_reason"])
|
|
}
|
|
}
|
|
|
|
func TestCLI_DepAdd(t *testing.T) {
|
|
// Note: Not using t.Parallel() because inProcessMutex serializes execution anyway
|
|
tmpDir := setupCLITestDB(t)
|
|
|
|
out1 := runBDInProcess(t, tmpDir, "create", "First", "-p", "1", "--json")
|
|
out2 := runBDInProcess(t, tmpDir, "create", "Second", "-p", "1", "--json")
|
|
|
|
var issue1, issue2 map[string]interface{}
|
|
json.Unmarshal([]byte(out1), &issue1)
|
|
json.Unmarshal([]byte(out2), &issue2)
|
|
|
|
id1 := issue1["id"].(string)
|
|
id2 := issue2["id"].(string)
|
|
|
|
out := runBDInProcess(t, tmpDir, "dep", "add", id2, id1)
|
|
if !strings.Contains(out, "Added dependency") {
|
|
t.Errorf("Expected 'Added dependency', got: %s", out)
|
|
}
|
|
}
|
|
|
|
// TestCLI_DepAdd_TypeBlockedByAliasGates is the regression test for GH#5069:
|
|
// `bd dep add A B --type blocked-by` used to store the literal custom type
|
|
// "blocked-by" instead of normalizing it to the canonical "blocks" type, so
|
|
// the dependency was displayed everywhere but silently never gated `bd
|
|
// ready`/`bd blocked`. Assert the alias now gates exactly like the default
|
|
// (canonical) type does.
|
|
func TestCLI_DepAdd_TypeBlockedByAliasGates(t *testing.T) {
|
|
// Note: Not using t.Parallel() because inProcessMutex serializes execution anyway
|
|
tmpDir := setupCLITestDB(t)
|
|
|
|
out1 := runBDInProcess(t, tmpDir, "create", "Blocker", "-p", "1", "--json")
|
|
out2 := runBDInProcess(t, tmpDir, "create", "Blocked", "-p", "1", "--json")
|
|
|
|
var issue1, issue2 map[string]interface{}
|
|
json.Unmarshal([]byte(out1), &issue1)
|
|
json.Unmarshal([]byte(out2), &issue2)
|
|
|
|
blockerID := issue1["id"].(string)
|
|
blockedID := issue2["id"].(string)
|
|
|
|
// blockedID depends on (is blocked by) blockerID, using the --type
|
|
// blocked-by alias rather than the default "blocks" type.
|
|
out := runBDInProcess(t, tmpDir, "dep", "add", blockedID, blockerID, "--type", "blocked-by")
|
|
if !strings.Contains(out, "Added dependency") {
|
|
t.Fatalf("Expected 'Added dependency', got: %s", out)
|
|
}
|
|
|
|
blockedOut := runBDInProcess(t, tmpDir, "blocked")
|
|
if !strings.Contains(blockedOut, "Blocked") {
|
|
t.Errorf("Expected 'Blocked' issue in `bd blocked` output after --type blocked-by dep, got: %s", blockedOut)
|
|
}
|
|
|
|
readyOut := runBDInProcess(t, tmpDir, "ready")
|
|
if strings.Contains(readyOut, "Blocked") {
|
|
t.Errorf("Expected blocked issue to be excluded from `bd ready` after --type blocked-by dep, got: %s", readyOut)
|
|
}
|
|
}
|
|
|
|
// TestCLI_Show_SupersedesIsNotABlocker is the regression test for bd show
|
|
// grouping every dependency type it did not name explicitly into the blocks
|
|
// bucket. A supersedes edge printed under "DEPENDS ON" on the replaced issue
|
|
// and "BLOCKS" on the replacement — a blocking claim that is false, since
|
|
// supersedes takes no part in the ready-work calculation.
|
|
func TestCLI_Show_SupersedesIsNotABlocker(t *testing.T) {
|
|
// Note: Not using t.Parallel() because inProcessMutex serializes execution anyway
|
|
tmpDir := setupCLITestDB(t)
|
|
|
|
outOld := runBDInProcess(t, tmpDir, "create", "V1 spec", "-p", "1", "--json")
|
|
outNew := runBDInProcess(t, tmpDir, "create", "V2 spec", "-p", "1", "--json")
|
|
|
|
var oldIssue, newIssue map[string]interface{}
|
|
json.Unmarshal([]byte(outOld), &oldIssue)
|
|
json.Unmarshal([]byte(outNew), &newIssue)
|
|
|
|
oldID := oldIssue["id"].(string)
|
|
newID := newIssue["id"].(string)
|
|
|
|
runBDInProcess(t, tmpDir, "supersede", oldID, "--with", newID)
|
|
|
|
// `bd supersede old --with new` stores (old, new), so the replaced issue is
|
|
// the edge's source and names its replacement.
|
|
replaced := runBDInProcess(t, tmpDir, "show", oldID)
|
|
if !strings.Contains(replaced, "SUPERSEDED BY") {
|
|
t.Errorf("expected SUPERSEDED BY section on the replaced issue, got: %s", replaced)
|
|
}
|
|
if strings.Contains(replaced, "DEPENDS ON") {
|
|
t.Errorf("replaced issue must not claim it depends on its replacement, got: %s", replaced)
|
|
}
|
|
|
|
replacement := runBDInProcess(t, tmpDir, "show", newID)
|
|
if !strings.Contains(replacement, "SUPERSEDES") {
|
|
t.Errorf("expected SUPERSEDES section on the replacement, got: %s", replacement)
|
|
}
|
|
if strings.Contains(replacement, "BLOCKS") {
|
|
t.Errorf("replacement must not claim it blocks the issue it replaced, got: %s", replacement)
|
|
}
|
|
}
|
|
|
|
func TestCLI_DepRemove(t *testing.T) {
|
|
// Note: Not using t.Parallel() because inProcessMutex serializes execution anyway
|
|
tmpDir := setupCLITestDB(t)
|
|
|
|
out1 := runBDInProcess(t, tmpDir, "create", "First", "-p", "1", "--json")
|
|
out2 := runBDInProcess(t, tmpDir, "create", "Second", "-p", "1", "--json")
|
|
|
|
var issue1, issue2 map[string]interface{}
|
|
json.Unmarshal([]byte(out1), &issue1)
|
|
json.Unmarshal([]byte(out2), &issue2)
|
|
|
|
id1 := issue1["id"].(string)
|
|
id2 := issue2["id"].(string)
|
|
|
|
runBDInProcess(t, tmpDir, "dep", "add", id2, id1)
|
|
out := runBDInProcess(t, tmpDir, "dep", "remove", id2, id1)
|
|
if !strings.Contains(out, "Removed dependency") {
|
|
t.Errorf("Expected 'Removed dependency', got: %s", out)
|
|
}
|
|
}
|
|
|
|
func TestCLI_DepTree(t *testing.T) {
|
|
// Note: Not using t.Parallel() because inProcessMutex serializes execution anyway
|
|
tmpDir := setupCLITestDB(t)
|
|
|
|
out1 := runBDInProcess(t, tmpDir, "create", "Parent", "-p", "1", "--json")
|
|
out2 := runBDInProcess(t, tmpDir, "create", "Child", "-p", "1", "--json")
|
|
|
|
var issue1, issue2 map[string]interface{}
|
|
json.Unmarshal([]byte(out1), &issue1)
|
|
json.Unmarshal([]byte(out2), &issue2)
|
|
|
|
id1 := issue1["id"].(string)
|
|
id2 := issue2["id"].(string)
|
|
|
|
runBDInProcess(t, tmpDir, "dep", "add", id2, id1)
|
|
out := runBDInProcess(t, tmpDir, "dep", "tree", id1)
|
|
if !strings.Contains(out, "Parent") {
|
|
t.Errorf("Expected 'Parent' in tree, got: %s", out)
|
|
}
|
|
}
|
|
|
|
func TestCLI_Blocked(t *testing.T) {
|
|
// Note: Not using t.Parallel() because inProcessMutex serializes execution anyway
|
|
tmpDir := setupCLITestDB(t)
|
|
|
|
out1 := runBDInProcess(t, tmpDir, "create", "Blocker", "-p", "1", "--json")
|
|
out2 := runBDInProcess(t, tmpDir, "create", "Blocked", "-p", "1", "--json")
|
|
|
|
var issue1, issue2 map[string]interface{}
|
|
json.Unmarshal([]byte(out1), &issue1)
|
|
json.Unmarshal([]byte(out2), &issue2)
|
|
|
|
id1 := issue1["id"].(string)
|
|
id2 := issue2["id"].(string)
|
|
|
|
runBDInProcess(t, tmpDir, "dep", "add", id2, id1)
|
|
out := runBDInProcess(t, tmpDir, "blocked")
|
|
if !strings.Contains(out, "Blocked") {
|
|
t.Errorf("Expected 'Blocked' in output, got: %s", out)
|
|
}
|
|
}
|
|
|
|
func TestCLI_Stats(t *testing.T) {
|
|
// Note: Not using t.Parallel() because inProcessMutex serializes execution anyway
|
|
tmpDir := setupCLITestDB(t)
|
|
runBDInProcess(t, tmpDir, "create", "Issue 1", "-p", "1")
|
|
runBDInProcess(t, tmpDir, "create", "Issue 2", "-p", "1")
|
|
|
|
out := runBDInProcess(t, tmpDir, "stats")
|
|
if !strings.Contains(out, "Total") || !strings.Contains(out, "2") {
|
|
t.Errorf("Expected stats to show 2 issues, got: %s", out)
|
|
}
|
|
}
|
|
|
|
func TestCLI_Show(t *testing.T) {
|
|
// Note: Not using t.Parallel() because inProcessMutex serializes execution anyway
|
|
tmpDir := setupCLITestDB(t)
|
|
out := runBDInProcess(t, tmpDir, "create", "Show test", "-p", "1", "--json")
|
|
|
|
var issue map[string]interface{}
|
|
json.Unmarshal([]byte(out), &issue)
|
|
id := issue["id"].(string)
|
|
|
|
out = runBDInProcess(t, tmpDir, "show", id)
|
|
if !strings.Contains(out, "Show test") {
|
|
t.Errorf("Expected 'Show test' in output, got: %s", out)
|
|
}
|
|
}
|
|
|
|
func TestCLI_Export(t *testing.T) {
|
|
// Note: Not using t.Parallel() because inProcessMutex serializes execution anyway
|
|
tmpDir := setupCLITestDB(t)
|
|
runBDInProcess(t, tmpDir, "create", "Export test", "-p", "1")
|
|
|
|
exportFile := filepath.Join(tmpDir, "export.jsonl")
|
|
runBDInProcess(t, tmpDir, "export", "-o", exportFile)
|
|
|
|
if _, err := os.Stat(exportFile); os.IsNotExist(err) {
|
|
t.Errorf("Export file not created: %s", exportFile)
|
|
}
|
|
}
|
|
|
|
func TestCLI_Import(t *testing.T) {
|
|
// Note: Not using t.Parallel() because inProcessMutex serializes execution anyway
|
|
tmpDir := setupCLITestDB(t)
|
|
runBDInProcess(t, tmpDir, "create", "Import test", "-p", "1")
|
|
|
|
exportFile := filepath.Join(tmpDir, "export.jsonl")
|
|
runBDInProcess(t, tmpDir, "export", "-o", exportFile)
|
|
|
|
// Create new db and import
|
|
tmpDir2 := createTempDirWithCleanup(t)
|
|
runBDInProcess(t, tmpDir2, "init", "--prefix", "test", "--quiet")
|
|
runBDInProcess(t, tmpDir2, "import", "-i", exportFile)
|
|
|
|
out := runBDInProcess(t, tmpDir2, "list", "--json")
|
|
var issues []map[string]interface{}
|
|
json.Unmarshal([]byte(out), &issues)
|
|
if len(issues) != 1 {
|
|
t.Errorf("Expected 1 imported issue, got %d", len(issues))
|
|
}
|
|
}
|
|
|
|
var testBD string
|
|
|
|
func init() {
|
|
// Helper-process re-execs (worktree_remove_test.go's
|
|
// runWorktreeRemoveProcess) run this init in a child whose cwd is a temp
|
|
// git repo: the repo-root probe below misses and the `go build .`
|
|
// fallback panics with "cannot find main module" — which is what six
|
|
// Main integration shards reported at cd25e0919. The helper never uses
|
|
// testBD, so skip the work entirely in that child.
|
|
if os.Getenv(worktreeRemoveHelperEnv) != "" {
|
|
return
|
|
}
|
|
// Likewise the credential-command helper (internal/testutil/credentialcmd):
|
|
// this init runs before TestMain dispatches it, in the helper's cwd, where
|
|
// the `go build .` fallback panics and the fixture reports exit 2.
|
|
if credentialcmd.IsHelperProcess() {
|
|
return
|
|
}
|
|
// Prebuilt fast path (scripts/test.sh and CI export this), else build
|
|
// once. No repo-root ./bd reuse: a stale checkout-root binary silently
|
|
// substitutes itself for the source under test (wy-4mtr0).
|
|
if prebuilt, err := findPrebuiltBDBinary(); err == nil && prebuilt != "" {
|
|
testBD = prebuilt
|
|
return
|
|
} else if bazeltest.IsBazel() {
|
|
panic(fmt.Sprintf("bd binary for tests: %v", err))
|
|
}
|
|
bdBinary := "bd"
|
|
if runtime.GOOS == "windows" {
|
|
bdBinary = "bd.exe"
|
|
}
|
|
|
|
// Fall back to building once (for CI or fresh checkouts)
|
|
tmpDir, err := os.MkdirTemp("", "bd-cli-test-*")
|
|
if err != nil {
|
|
panic(err)
|
|
}
|
|
testBD = filepath.Join(tmpDir, bdBinary)
|
|
cmd := goBuildBDCommand(testBD)
|
|
if out, err := cmd.CombinedOutput(); err != nil {
|
|
panic(string(out))
|
|
}
|
|
}
|
|
|
|
// runBDExec runs bd via exec.Command for end-to-end testing
|
|
// This is kept for a few tests to ensure the actual binary works correctly
|
|
func runBDExec(t *testing.T, dir string, args ...string) string {
|
|
t.Helper()
|
|
|
|
cmd := exec.Command(testBD, args...)
|
|
cmd.Dir = dir
|
|
cmd.Env = os.Environ()
|
|
|
|
out, err := cmd.CombinedOutput()
|
|
if err != nil {
|
|
t.Fatalf("bd %v failed: %v\nOutput: %s", args, err, out)
|
|
}
|
|
return string(out)
|
|
}
|
|
|
|
// runBDExecAllowErrorWithEnv runs bd via exec.Command with custom env vars,
|
|
// returning combined output and any error (does not fail the test on error).
|
|
func runBDExecAllowErrorWithEnv(t *testing.T, dir string, env []string, args ...string) (string, error) {
|
|
t.Helper()
|
|
|
|
cmd := exec.Command(testBD, args...)
|
|
cmd.Dir = dir
|
|
cmd.Env = env
|
|
|
|
out, err := cmd.CombinedOutput()
|
|
return string(out), err
|
|
}
|
|
|
|
// TestCLI_EndToEnd performs end-to-end testing using the actual binary
|
|
// This ensures the compiled binary works correctly when executed normally
|
|
func TestCLI_EndToEnd(t *testing.T) {
|
|
if testDoltServerPort == 0 {
|
|
t.Skip("skipping: Dolt test container not available")
|
|
}
|
|
// Note: Not using t.Parallel() because inProcessMutex serializes execution anyway
|
|
|
|
tmpDir := createTempDirWithCleanup(t)
|
|
|
|
// Test full workflow with exec.Command to validate binary
|
|
runBDExec(t, tmpDir, "init", "--prefix", "test", "--quiet")
|
|
|
|
out := runBDExec(t, tmpDir, "create", "E2E test", "-p", "1", "--json")
|
|
var issue map[string]interface{}
|
|
jsonStart := strings.Index(out, "{")
|
|
json.Unmarshal([]byte(out[jsonStart:]), &issue)
|
|
id := issue["id"].(string)
|
|
|
|
runBDExec(t, tmpDir, "update", id, "--status", "in_progress")
|
|
runBDExec(t, tmpDir, "close", id, "--reason", "Done")
|
|
|
|
out = runBDExec(t, tmpDir, "show", id, "--json")
|
|
var closed []map[string]interface{}
|
|
json.Unmarshal([]byte(out), &closed)
|
|
|
|
if closed[0]["status"] != "closed" {
|
|
t.Errorf("Expected status 'closed', got: %v", closed[0]["status"])
|
|
}
|
|
|
|
// Test export
|
|
exportFile := filepath.Join(tmpDir, "export.jsonl")
|
|
runBDExec(t, tmpDir, "export", "-o", exportFile)
|
|
|
|
if _, err := os.Stat(exportFile); os.IsNotExist(err) {
|
|
t.Errorf("Export file not created: %s", exportFile)
|
|
}
|
|
}
|
|
|
|
func TestCLI_Labels(t *testing.T) {
|
|
// Note: Not using t.Parallel() because inProcessMutex serializes execution anyway
|
|
tmpDir := setupCLITestDB(t)
|
|
out := runBDInProcess(t, tmpDir, "create", "Label test", "-p", "1", "--json")
|
|
|
|
jsonStart := strings.Index(out, "{")
|
|
jsonOut := out[jsonStart:]
|
|
|
|
var issue map[string]interface{}
|
|
json.Unmarshal([]byte(jsonOut), &issue)
|
|
id := issue["id"].(string)
|
|
|
|
// Add label
|
|
runBDInProcess(t, tmpDir, "label", "add", id, "urgent")
|
|
|
|
// List labels
|
|
out = runBDInProcess(t, tmpDir, "label", "list", id)
|
|
if !strings.Contains(out, "urgent") {
|
|
t.Errorf("Expected 'urgent' label, got: %s", out)
|
|
}
|
|
|
|
// Remove label
|
|
runBDInProcess(t, tmpDir, "label", "remove", id, "urgent")
|
|
out = runBDInProcess(t, tmpDir, "label", "list", id)
|
|
if strings.Contains(out, "urgent") {
|
|
t.Errorf("Label should be removed, got: %s", out)
|
|
}
|
|
}
|
|
|
|
func TestCLI_PriorityFormats(t *testing.T) {
|
|
// Note: Not using t.Parallel() because inProcessMutex serializes execution anyway
|
|
tmpDir := setupCLITestDB(t)
|
|
|
|
// Test numeric priority
|
|
out := runBDInProcess(t, tmpDir, "create", "Test P0", "-p", "0", "--json")
|
|
jsonStart := strings.Index(out, "{")
|
|
jsonOut := out[jsonStart:]
|
|
var issue map[string]interface{}
|
|
json.Unmarshal([]byte(jsonOut), &issue)
|
|
if issue["priority"].(float64) != 0 {
|
|
t.Errorf("Expected priority 0, got: %v", issue["priority"])
|
|
}
|
|
|
|
// Test P-format priority
|
|
out = runBDInProcess(t, tmpDir, "create", "Test P3", "-p", "P3", "--json")
|
|
jsonStart = strings.Index(out, "{")
|
|
jsonOut = out[jsonStart:]
|
|
json.Unmarshal([]byte(jsonOut), &issue)
|
|
if issue["priority"].(float64) != 3 {
|
|
t.Errorf("Expected priority 3, got: %v", issue["priority"])
|
|
}
|
|
|
|
// Test update with P-format
|
|
id := issue["id"].(string)
|
|
runBDInProcess(t, tmpDir, "update", id, "-p", "P1")
|
|
|
|
out = runBDInProcess(t, tmpDir, "show", id, "--json")
|
|
var updated []map[string]interface{}
|
|
json.Unmarshal([]byte(out), &updated)
|
|
if updated[0]["priority"].(float64) != 1 {
|
|
t.Errorf("Expected priority 1 after update, got: %v", updated[0]["priority"])
|
|
}
|
|
}
|
|
|
|
func TestCLI_Reopen(t *testing.T) {
|
|
// Note: Not using t.Parallel() because inProcessMutex serializes execution anyway
|
|
tmpDir := setupCLITestDB(t)
|
|
out := runBDInProcess(t, tmpDir, "create", "Reopen test", "-p", "1", "--json")
|
|
|
|
jsonStart := strings.Index(out, "{")
|
|
jsonOut := out[jsonStart:]
|
|
var issue map[string]interface{}
|
|
json.Unmarshal([]byte(jsonOut), &issue)
|
|
id := issue["id"].(string)
|
|
|
|
// Close it
|
|
runBDInProcess(t, tmpDir, "close", id)
|
|
|
|
// Reopen it
|
|
runBDInProcess(t, tmpDir, "reopen", id)
|
|
|
|
out = runBDInProcess(t, tmpDir, "show", id, "--json")
|
|
var reopened []map[string]interface{}
|
|
json.Unmarshal([]byte(out), &reopened)
|
|
if reopened[0]["status"] != "open" {
|
|
t.Errorf("Expected status 'open', got: %v", reopened[0]["status"])
|
|
}
|
|
}
|
|
|
|
// runBDInProcessAllowError is like runBDInProcess but doesn't fail on error
|
|
// Returns stdout, stderr, and any error from command execution
|
|
func runBDInProcessAllowError(t *testing.T, dir string, args ...string) (string, string, error) {
|
|
t.Helper()
|
|
|
|
inProcessMutex.Lock()
|
|
defer inProcessMutex.Unlock()
|
|
|
|
oldStdout := os.Stdout
|
|
oldStderr := os.Stderr
|
|
oldDir, _ := os.Getwd()
|
|
oldArgs := os.Args
|
|
|
|
if err := os.Chdir(dir); err != nil {
|
|
t.Fatalf("Failed to chdir to %s: %v", dir, err)
|
|
}
|
|
|
|
rOut, wOut, _ := os.Pipe()
|
|
rErr, wErr, _ := os.Pipe()
|
|
os.Stdout = wOut
|
|
os.Stderr = wErr
|
|
defer func() {
|
|
os.Stdout = oldStdout
|
|
os.Stderr = oldStderr
|
|
}()
|
|
|
|
resetCommandFlags(rootCmd)
|
|
defer resetCommandFlags(rootCmd)
|
|
rootCmd.SetArgs(args)
|
|
os.Args = append([]string{"bd"}, args...)
|
|
|
|
envBefore := os.Environ()
|
|
cmdErr := rootCmd.Execute()
|
|
restoreEnvSnapshot(envBefore)
|
|
|
|
if store != nil {
|
|
store.Close()
|
|
store = nil
|
|
}
|
|
dbPath = ""
|
|
actor = ""
|
|
jsonOutput = false
|
|
sandboxMode = false
|
|
rootCtx = nil
|
|
rootCancel = nil
|
|
|
|
// Give SQLite time to release file locks before cleanup
|
|
time.Sleep(10 * time.Millisecond)
|
|
|
|
wOut.Close()
|
|
wErr.Close()
|
|
os.Chdir(oldDir)
|
|
os.Args = oldArgs
|
|
rootCmd.SetArgs(nil)
|
|
|
|
var outBuf, errBuf bytes.Buffer
|
|
outBuf.ReadFrom(rOut)
|
|
errBuf.ReadFrom(rErr)
|
|
|
|
return outBuf.String(), errBuf.String(), cmdErr
|
|
}
|
|
|
|
// TestCLI_CreateDryRun tests the --dry-run flag for bd create command (bd-nib2)
|
|
func TestCLI_CreateDryRun(t *testing.T) {
|
|
if testDoltServerPort == 0 {
|
|
t.Skip("skipping: Dolt test container not available")
|
|
}
|
|
|
|
t.Run("BasicDryRunPreview", func(t *testing.T) {
|
|
// Note: Not using t.Parallel() because inProcessMutex serializes execution anyway
|
|
tmpDir := setupCLITestDB(t)
|
|
|
|
// Run create with --dry-run
|
|
out := runBDInProcess(t, tmpDir, "create", "Test dry run issue", "-p", "1", "--dry-run")
|
|
|
|
// Verify output contains dry-run indicator
|
|
if !strings.Contains(out, "[DRY RUN]") {
|
|
t.Errorf("Expected '[DRY RUN]' in output, got: %s", out)
|
|
}
|
|
if !strings.Contains(out, "Would create issue") {
|
|
t.Errorf("Expected 'Would create issue' in output, got: %s", out)
|
|
}
|
|
if !strings.Contains(out, "Test dry run issue") {
|
|
t.Errorf("Expected title in output, got: %s", out)
|
|
}
|
|
if !strings.Contains(out, "(will be generated)") {
|
|
t.Errorf("Expected '(will be generated)' for ID, got: %s", out)
|
|
}
|
|
|
|
// Verify no issue was actually created
|
|
listOut := runBDInProcess(t, tmpDir, "list", "--json")
|
|
var issues []map[string]interface{}
|
|
json.Unmarshal([]byte(listOut), &issues)
|
|
if len(issues) != 0 {
|
|
t.Errorf("Expected 0 issues after dry-run, got %d", len(issues))
|
|
}
|
|
})
|
|
|
|
t.Run("DryRunWithJSONOutput", func(t *testing.T) {
|
|
tmpDir := setupCLITestDB(t)
|
|
|
|
// Run create with --dry-run --json
|
|
out := runBDInProcess(t, tmpDir, "create", "JSON dry run test", "-p", "2", "-t", "bug", "--dry-run", "--json")
|
|
|
|
// Find JSON in output (may have warnings before it)
|
|
jsonStart := strings.Index(out, "{")
|
|
if jsonStart < 0 {
|
|
t.Fatalf("No JSON found in output: %s", out)
|
|
}
|
|
jsonOut := out[jsonStart:]
|
|
|
|
var issue map[string]interface{}
|
|
if err := json.Unmarshal([]byte(jsonOut), &issue); err != nil {
|
|
t.Fatalf("Failed to parse JSON: %v\nOutput: %s", err, jsonOut)
|
|
}
|
|
|
|
// Verify JSON has empty ID (not a placeholder string)
|
|
id, ok := issue["id"]
|
|
if !ok {
|
|
t.Error("Expected 'id' field in JSON output")
|
|
}
|
|
if id != "" {
|
|
t.Errorf("Expected empty ID in dry-run JSON, got: %v", id)
|
|
}
|
|
|
|
// Verify other fields are populated
|
|
if issue["title"] != "JSON dry run test" {
|
|
t.Errorf("Expected title 'JSON dry run test', got: %v", issue["title"])
|
|
}
|
|
if issue["issue_type"] != "bug" {
|
|
t.Errorf("Expected issue_type 'bug', got: %v", issue["issue_type"])
|
|
}
|
|
if issue["priority"].(float64) != 2 {
|
|
t.Errorf("Expected priority 2, got: %v", issue["priority"])
|
|
}
|
|
|
|
// Verify no issue was actually created
|
|
listOut := runBDInProcess(t, tmpDir, "list", "--json")
|
|
var issues []map[string]interface{}
|
|
json.Unmarshal([]byte(listOut), &issues)
|
|
if len(issues) != 0 {
|
|
t.Errorf("Expected 0 issues after dry-run, got %d", len(issues))
|
|
}
|
|
})
|
|
|
|
t.Run("DryRunWithLabelsAndDeps", func(t *testing.T) {
|
|
tmpDir := setupCLITestDB(t)
|
|
|
|
// Run create with --dry-run including labels and deps
|
|
out := runBDInProcess(t, tmpDir, "create", "Issue with extras", "-p", "1",
|
|
"--labels", "urgent,backend",
|
|
"--deps", "blocks:test-123",
|
|
"--dry-run")
|
|
|
|
// Verify labels are shown in preview
|
|
if !strings.Contains(out, "Labels:") {
|
|
t.Errorf("Expected 'Labels:' in output, got: %s", out)
|
|
}
|
|
if !strings.Contains(out, "urgent") {
|
|
t.Errorf("Expected 'urgent' label in output, got: %s", out)
|
|
}
|
|
if !strings.Contains(out, "backend") {
|
|
t.Errorf("Expected 'backend' label in output, got: %s", out)
|
|
}
|
|
|
|
// Verify dependencies are shown
|
|
if !strings.Contains(out, "Dependencies:") {
|
|
t.Errorf("Expected 'Dependencies:' in output, got: %s", out)
|
|
}
|
|
if !strings.Contains(out, "blocks:test-123") {
|
|
t.Errorf("Expected 'blocks:test-123' dependency in output, got: %s", out)
|
|
}
|
|
})
|
|
|
|
t.Run("DryRunWithFileReturnsError", func(t *testing.T) {
|
|
tmpDir := createTempDirWithCleanup(t)
|
|
|
|
// Initialize the database first
|
|
initCmd := exec.Command(testBD, "init", "--prefix", "test", "--quiet")
|
|
initCmd.Dir = tmpDir
|
|
initCmd.Env = os.Environ()
|
|
if out, err := initCmd.CombinedOutput(); err != nil {
|
|
t.Fatalf("init failed: %v\n%s", err, out)
|
|
}
|
|
|
|
// Create a dummy markdown file
|
|
mdFile := filepath.Join(tmpDir, "issues.md")
|
|
os.WriteFile(mdFile, []byte("# Test Issue\n\nDescription here"), 0644)
|
|
|
|
// Run create with --dry-run and --file (should error)
|
|
cmd := exec.Command(testBD, "create", "--file", mdFile, "--dry-run")
|
|
cmd.Dir = tmpDir
|
|
cmd.Env = os.Environ()
|
|
out, err := cmd.CombinedOutput()
|
|
|
|
if err == nil {
|
|
t.Error("Expected error when using --dry-run with --file, but got none")
|
|
}
|
|
|
|
// Verify error message is informative
|
|
if !strings.Contains(string(out), "--dry-run is not supported with --file") {
|
|
t.Errorf("Expected error about --dry-run with --file, got: %s", out)
|
|
}
|
|
})
|
|
|
|
t.Run("DryRunWithEventType", func(t *testing.T) {
|
|
tmpDir := setupCLITestDB(t)
|
|
|
|
// Run create with --dry-run and event-specific fields
|
|
out := runBDInProcess(t, tmpDir, "create", "Event issue", "-p", "1",
|
|
"--type", "event",
|
|
"--event-category", "agent.started",
|
|
"--dry-run")
|
|
|
|
// Verify event category is shown in preview
|
|
if !strings.Contains(out, "Event category:") {
|
|
t.Errorf("Expected 'Event category:' in output, got: %s", out)
|
|
}
|
|
if !strings.Contains(out, "agent.started") {
|
|
t.Errorf("Expected 'agent.started' in output, got: %s", out)
|
|
}
|
|
})
|
|
|
|
t.Run("DryRunWithExplicitID", func(t *testing.T) {
|
|
tmpDir := setupCLITestDB(t)
|
|
|
|
// Run create with --dry-run and explicit ID
|
|
out := runBDInProcess(t, tmpDir, "create", "Explicit ID issue", "-p", "1",
|
|
"--id", "test-explicit123",
|
|
"--dry-run")
|
|
|
|
// Verify explicit ID is shown (not "(will be generated)")
|
|
if strings.Contains(out, "(will be generated)") {
|
|
t.Errorf("Expected explicit ID in output, but got '(will be generated)': %s", out)
|
|
}
|
|
if !strings.Contains(out, "test-explicit123") {
|
|
t.Errorf("Expected 'test-explicit123' in output, got: %s", out)
|
|
}
|
|
})
|
|
}
|
|
|
|
// TestCLI_CommentsListMisplacedSyntax ensures "bd comments list" gets a helpful error (GH#3542).
|
|
func TestCLI_CommentsListMisplacedSyntax(t *testing.T) {
|
|
tmpDir := setupCLITestDB(t)
|
|
stdout, stderr, err := runBDInProcessAllowError(t, tmpDir, "comments", "list")
|
|
if err == nil {
|
|
t.Fatalf("expected non-zero exit, got stdout=%q stderr=%q", stdout, stderr)
|
|
}
|
|
combined := stdout + stderr
|
|
if !strings.Contains(combined, "bd comments") || !strings.Contains(combined, "<issue-id>") {
|
|
t.Fatalf("expected hint with bd comments and issue-id placeholder, got stdout=%q stderr=%q", stdout, stderr)
|
|
}
|
|
}
|
|
|
|
// TestCLI_CommentsSwappedAddRejectedBeforeStoreOpen is a regression test for
|
|
// GH#4642's should-fix: the swapped-order rejection (`bd comments <id> add
|
|
// <text>`) must fire from commentsCmd's Args validator, before
|
|
// PersistentPreRunE ever opens a store or runs a migration, and before
|
|
// RunE's usesProxiedServer() dispatch — not from a check inside RunE that
|
|
// only the local-store branch reaches. Using a directory with no .beads/ at
|
|
// all proves the store was never touched: the old RunE-only check needed an
|
|
// already-initialized store (PersistentPreRunE would have failed first with
|
|
// "no beads database found"), so this would fail with the wrong error before
|
|
// the fix.
|
|
func TestCLI_CommentsSwappedAddRejectedBeforeStoreOpen(t *testing.T) {
|
|
noBeadsCwd := t.TempDir()
|
|
if _, err := os.Stat(filepath.Join(noBeadsCwd, ".beads")); err == nil {
|
|
t.Fatalf("test setup: %s unexpectedly has a .beads dir", noBeadsCwd)
|
|
}
|
|
|
|
stdout, stderr, err := runBDInProcessAllowError(t, noBeadsCwd, "comments", "bd-123", "add", "should not be stored")
|
|
if err == nil {
|
|
t.Fatalf("expected non-zero exit for swapped-order add, got success:\nstdout: %s", stdout)
|
|
}
|
|
combined := stdout + stderr
|
|
if strings.Contains(combined, "no beads database found") {
|
|
t.Fatalf("Args validation did not run before store open: got the pre-fix error.\nOutput:\n%s", combined)
|
|
}
|
|
if !strings.Contains(combined, "bd comments add") {
|
|
t.Errorf("expected hint pointing to `bd comments add`, got:\n%s", combined)
|
|
}
|
|
}
|
|
|
|
// TestCLI_CommentsSwappedAddRejectedInProxiedServerMode is the proxied-server
|
|
// counterpart: forcing proxiedServerMode simulates the dispatch that GH#4642's
|
|
// merge-base drift routes around a RunE-only check (main added
|
|
// runCommentsProxiedServer after this fix branched, consuming only args[0]
|
|
// and ignoring trailing `add <text>`). Because validateCommentsArgs runs in
|
|
// Args — before RunE ever branches on usesProxiedServer() — the rejection
|
|
// fires identically regardless of backend, without needing a real proxied
|
|
// server.
|
|
func TestCLI_CommentsSwappedAddRejectedInProxiedServerMode(t *testing.T) {
|
|
origProxied := proxiedServerMode
|
|
t.Cleanup(func() { proxiedServerMode = origProxied })
|
|
proxiedServerMode = true
|
|
|
|
tmpDir := setupCLITestDB(t)
|
|
stdout, stderr, err := runBDInProcessAllowError(t, tmpDir, "comments", "bd-123", "add", "should not be stored")
|
|
if err == nil {
|
|
t.Fatalf("expected non-zero exit for swapped-order add in proxied-server mode, got success:\nstdout: %s", stdout)
|
|
}
|
|
combined := stdout + stderr
|
|
if strings.Contains(combined, "not supported in proxied-server mode") {
|
|
t.Fatalf("Args validation did not run before the proxied dispatch: got RunE's proxied-mode stub error instead.\nOutput:\n%s", combined)
|
|
}
|
|
if !strings.Contains(combined, "bd comments add") {
|
|
t.Errorf("expected hint pointing to `bd comments add`, got:\n%s", combined)
|
|
}
|
|
}
|
|
|
|
// TestCLI_CommentsAddShortID tests that 'comments add' accepts a bare full
|
|
// hash without its issue prefix (e.g. "5wbm" for "mike.vibe-coding-5wbm",
|
|
// issue #1070) — full IDs used to be required. It does NOT test genuine
|
|
// abbreviation (a hash shorter than the real one): since PR #5393, comment
|
|
// writes require an exact id (see resolveAndGetIssueForMutationExact /
|
|
// utils.ResolvePartialIDExact) and PartialIDWithCommentsAdd below asserts
|
|
// that a real abbreviation is refused, not accepted.
|
|
func TestCLI_CommentsAddShortID(t *testing.T) {
|
|
|
|
t.Run("ShortIDWithCommentsAdd", func(t *testing.T) {
|
|
tmpDir := setupCLITestDB(t)
|
|
|
|
// Create an issue and get its full ID
|
|
out := runBDInProcess(t, tmpDir, "create", "Issue for comment test", "-p", "1", "--json")
|
|
|
|
jsonStart := strings.Index(out, "{")
|
|
if jsonStart < 0 {
|
|
t.Fatalf("No JSON found in output: %s", out)
|
|
}
|
|
jsonOut := out[jsonStart:]
|
|
|
|
var issue map[string]interface{}
|
|
if err := json.Unmarshal([]byte(jsonOut), &issue); err != nil {
|
|
t.Fatalf("Failed to parse JSON: %v\nOutput: %s", err, jsonOut)
|
|
}
|
|
|
|
fullID := issue["id"].(string)
|
|
t.Logf("Created issue with full ID: %s", fullID)
|
|
|
|
// Extract short ID (the part after the last hyphen in prefix-hash format)
|
|
// For IDs like "test-abc123", the short ID is "abc123"
|
|
parts := strings.Split(fullID, "-")
|
|
if len(parts) < 2 {
|
|
t.Fatalf("Unexpected ID format: %s", fullID)
|
|
}
|
|
shortID := parts[len(parts)-1]
|
|
t.Logf("Using short ID: %s", shortID)
|
|
|
|
// Add a comment using the SHORT ID (not full ID)
|
|
stdout, stderr, err := runBDInProcessAllowError(t, tmpDir, "comments", "add", shortID, "Test comment with short ID")
|
|
if err != nil {
|
|
t.Fatalf("comments add failed: %v\nstdout: %s\nstderr: %s", err, stdout, stderr)
|
|
}
|
|
|
|
if !strings.Contains(stdout, "Comment added") {
|
|
t.Errorf("Expected 'Comment added' in output, got: %s", stdout)
|
|
}
|
|
|
|
// Verify the comment was actually added by listing comments (use full ID for list)
|
|
stdout, stderr, err = runBDInProcessAllowError(t, tmpDir, "comments", fullID)
|
|
if err != nil {
|
|
t.Fatalf("comments list failed: %v\nstdout: %s\nstderr: %s", err, stdout, stderr)
|
|
}
|
|
|
|
if !strings.Contains(stdout, "Test comment with short ID") {
|
|
t.Errorf("Expected comment text in list output, got: %s", stdout)
|
|
}
|
|
})
|
|
|
|
// PartialIDWithCommentsAdd used to assert that a genuinely abbreviated id
|
|
// (shorter than the full hash) succeeded on "comments add" — true when
|
|
// this test was written (issue #1070), but no longer the contract: PR
|
|
// #5393 review item M1 established that "comments add" must refuse an
|
|
// abbreviation exactly like "comment" (singular) does (see
|
|
// TestCLI_CommentAbbreviatedIDRejectedWithTruthfulMessage), since the two
|
|
// are documented as guarded twins (CHANGELOG.md, hash-ids.md). This
|
|
// subtest now asserts the refusal instead of the old silent-accept.
|
|
t.Run("PartialIDWithCommentsAdd", func(t *testing.T) {
|
|
tmpDir := setupCLITestDB(t)
|
|
|
|
// Create an issue
|
|
out := runBDInProcess(t, tmpDir, "create", "Issue for partial ID test", "-p", "1", "--json")
|
|
|
|
jsonStart := strings.Index(out, "{")
|
|
jsonOut := out[jsonStart:]
|
|
|
|
var issue map[string]interface{}
|
|
json.Unmarshal([]byte(jsonOut), &issue)
|
|
fullID := issue["id"].(string)
|
|
|
|
// Derive the abbreviation as a strict, one-character-shorter leading
|
|
// prefix of the real hash — the same derivation
|
|
// comment_proxied_integration_test.go:247 already uses. The previous
|
|
// "truncate to 4 chars, only if longer than 4" logic never fired
|
|
// against a fresh test DB's fixture hashes (min_hash_length unset,
|
|
// hashes as short as 3 chars), so shortID stayed equal to the full
|
|
// hash and this subtest was dead-red in its own setup, never reaching
|
|
// the assertions below (PR #5393 review R2, bee-ghosttrack) — and
|
|
// mutation P-B (reverting comments.go's resolver back to the
|
|
// abbreviation-tolerant one) went uncaught as a result.
|
|
parts := strings.Split(fullID, "-")
|
|
hash := parts[len(parts)-1]
|
|
if len(hash) < 2 {
|
|
t.Fatalf("test setup: hash %q too short to abbreviate", hash)
|
|
}
|
|
shortID := hash[:len(hash)-1]
|
|
t.Logf("Full ID: %s, Partial ID: %s", fullID, shortID)
|
|
|
|
// Sanity check: the same abbreviation still works on a READ path
|
|
// (show), proving this is a real, resolvable abbreviation and not an
|
|
// accident of the fixture — the refusal below is specific to writes.
|
|
showOut, showErr, err := runBDInProcessAllowError(t, tmpDir, "show", shortID, "--json")
|
|
if err != nil {
|
|
t.Fatalf("fixture sanity check failed: 'bd show %s' unexpectedly failed: %v\nstdout: %s\nstderr: %s", shortID, err, showOut, showErr)
|
|
}
|
|
if !strings.Contains(showOut, fullID) {
|
|
t.Fatalf("fixture sanity check failed: 'bd show %s' did not resolve to %s, got: %s", shortID, fullID, showOut)
|
|
}
|
|
|
|
// Add comment using partial ID — must now be refused, truthfully.
|
|
stdout, stderr, err := runBDInProcessAllowError(t, tmpDir, "comments", "add", shortID, "Comment via partial ID")
|
|
if err == nil {
|
|
t.Fatalf("expected non-zero exit for 'bd comments add %s ...' (abbreviation on a write path), got stdout=%q stderr=%q", shortID, stdout, stderr)
|
|
}
|
|
combined := stdout + stderr
|
|
if !strings.Contains(combined, "abbreviations are not accepted") {
|
|
t.Errorf("expected the truthful abbreviation-refusal message, got stdout=%q stderr=%q", stdout, stderr)
|
|
}
|
|
if strings.Contains(combined, "not found") {
|
|
t.Errorf("message must not claim the issue was not found — %s exists, only the abbreviation was refused; got stdout=%q stderr=%q", fullID, stdout, stderr)
|
|
}
|
|
|
|
// Regression check: no comment silently landed on the real issue.
|
|
commentsOut := runBDInProcess(t, tmpDir, "comments", fullID, "--json")
|
|
trimmed := strings.TrimSpace(commentsOut)
|
|
if trimmed != "[]" && trimmed != "null" {
|
|
t.Fatalf("expected no comments on %s after rejected abbreviated 'comments add', got: %s", fullID, commentsOut)
|
|
}
|
|
})
|
|
|
|
t.Run("CommentAliasWithShortID", func(t *testing.T) {
|
|
tmpDir := setupCLITestDB(t)
|
|
|
|
// Create an issue
|
|
out := runBDInProcess(t, tmpDir, "create", "Issue for alias test", "-p", "1", "--json")
|
|
|
|
jsonStart := strings.Index(out, "{")
|
|
jsonOut := out[jsonStart:]
|
|
|
|
var issue map[string]interface{}
|
|
json.Unmarshal([]byte(jsonOut), &issue)
|
|
fullID := issue["id"].(string)
|
|
|
|
// Extract short ID
|
|
parts := strings.Split(fullID, "-")
|
|
shortID := parts[len(parts)-1]
|
|
|
|
// Use the 'comment' alias (deprecated but should still work)
|
|
stdout, stderr, err := runBDInProcessAllowError(t, tmpDir, "comment", shortID, "Comment via alias with short ID")
|
|
if err != nil {
|
|
t.Fatalf("comment alias failed: %v\nstdout: %s\nstderr: %s", err, stdout, stderr)
|
|
}
|
|
|
|
if !strings.Contains(stdout, "Comment added") {
|
|
t.Errorf("Expected 'Comment added' in output, got: %s", stdout)
|
|
}
|
|
})
|
|
}
|
|
|
|
// TestCLI_CommentListMisplacedSyntax is a regression test for the singular
|
|
// "comment" shorthand silently mis-resolving a subcommand-like typo as an
|
|
// issue id. "bd comment list <text>" (meant as an attempt to list comments,
|
|
// using the singular noun by mistake) used to parse as id="list",
|
|
// text=[<text>...] with no validation on the id — since no issue is
|
|
// literally named "list", ResolvePartialID's substring/prefix fallback
|
|
// would silently match it against whatever existing bead or wisp id
|
|
// happened to contain "list" and post the comment there instead of
|
|
// erroring. This asserts both halves of the fix: the command is rejected
|
|
// with a helpful hint (mirroring TestCLI_CommentsListMisplacedSyntax for
|
|
// the plural sibling), AND — the part that actually matters for this
|
|
// specific bug — no comment silently landed on an unrelated real issue.
|
|
func TestCLI_CommentListMisplacedSyntax(t *testing.T) {
|
|
tmpDir := setupCLITestDB(t)
|
|
|
|
out := runBDInProcess(t, tmpDir, "create", "Bystander issue", "-p", "1", "--json")
|
|
jsonStart := strings.Index(out, "{")
|
|
if jsonStart < 0 {
|
|
t.Fatalf("No JSON found in create output: %s", out)
|
|
}
|
|
var issue map[string]interface{}
|
|
if err := json.Unmarshal([]byte(out[jsonStart:]), &issue); err != nil {
|
|
t.Fatalf("Failed to parse create JSON: %v\nOutput: %s", err, out)
|
|
}
|
|
fullID := issue["id"].(string)
|
|
|
|
stdout, stderr, err := runBDInProcessAllowError(t, tmpDir, "comment", "list", "accidental stray text")
|
|
if err == nil {
|
|
t.Fatalf("expected non-zero exit, got stdout=%q stderr=%q", stdout, stderr)
|
|
}
|
|
combined := stdout + stderr
|
|
if !strings.Contains(combined, "bd comments") || !strings.Contains(combined, "<issue-id>") {
|
|
t.Fatalf("expected hint pointing at bd comments <issue-id>, got stdout=%q stderr=%q", stdout, stderr)
|
|
}
|
|
|
|
// The regression check: the bystander issue must have received NO
|
|
// comment. Pre-fix, this could silently succeed and land a comment on
|
|
// whatever bead's id happened to contain "list" as a substring — this
|
|
// DB has exactly one issue, so any stray write would show up here.
|
|
commentsOut := runBDInProcess(t, tmpDir, "comments", fullID, "--json")
|
|
trimmed := strings.TrimSpace(commentsOut)
|
|
if trimmed != "[]" && trimmed != "null" {
|
|
t.Fatalf("expected no comments on bystander issue %s after rejected 'comment list', got: %s", fullID, commentsOut)
|
|
}
|
|
}
|
|
|
|
// TestCLI_CommentAddMisplacedSyntax mirrors TestCLI_CommentListMisplacedSyntax
|
|
// for the symmetric "add" typo — a caller who confuses the singular shorthand
|
|
// with the plural's "bd comments add <id> <text>" form might type
|
|
// "bd comment add <id> <text>", which the same unguarded id-resolution bug
|
|
// would parse as id="add", text=[<id>, <text>...].
|
|
func TestCLI_CommentAddMisplacedSyntax(t *testing.T) {
|
|
tmpDir := setupCLITestDB(t)
|
|
|
|
out := runBDInProcess(t, tmpDir, "create", "Bystander issue for add-typo", "-p", "1", "--json")
|
|
jsonStart := strings.Index(out, "{")
|
|
if jsonStart < 0 {
|
|
t.Fatalf("No JSON found in create output: %s", out)
|
|
}
|
|
var issue map[string]interface{}
|
|
if err := json.Unmarshal([]byte(out[jsonStart:]), &issue); err != nil {
|
|
t.Fatalf("Failed to parse create JSON: %v\nOutput: %s", err, out)
|
|
}
|
|
fullID := issue["id"].(string)
|
|
|
|
stdout, stderr, err := runBDInProcessAllowError(t, tmpDir, "comment", "add", fullID, "accidental stray text")
|
|
if err == nil {
|
|
t.Fatalf("expected non-zero exit, got stdout=%q stderr=%q", stdout, stderr)
|
|
}
|
|
combined := stdout + stderr
|
|
if !strings.Contains(combined, "bd comments add") {
|
|
t.Fatalf("expected hint pointing at bd comments add <issue-id>, got stdout=%q stderr=%q", stdout, stderr)
|
|
}
|
|
|
|
commentsOut := runBDInProcess(t, tmpDir, "comments", fullID, "--json")
|
|
trimmed := strings.TrimSpace(commentsOut)
|
|
if trimmed != "[]" && trimmed != "null" {
|
|
t.Fatalf("expected no comments on bystander issue %s after rejected 'comment add', got: %s", fullID, commentsOut)
|
|
}
|
|
}
|
|
|
|
// TestCLI_CommentMisplacedSyntaxRejectedBeforeStoreOpen proves the guard
|
|
// fires from commentCmd's Args validator, before PersistentPreRunE ever
|
|
// opens a store, mirroring
|
|
// TestCLI_CommentsSwappedAddRejectedBeforeStoreOpen for the plural sibling.
|
|
// Using a directory with no .beads/ at all proves the store was never
|
|
// touched: a RunE-only check would have failed first with "no beads
|
|
// database found".
|
|
func TestCLI_CommentMisplacedSyntaxRejectedBeforeStoreOpen(t *testing.T) {
|
|
noBeadsCwd := t.TempDir()
|
|
if _, err := os.Stat(filepath.Join(noBeadsCwd, ".beads")); err == nil {
|
|
t.Fatalf("test setup: %s unexpectedly has a .beads dir", noBeadsCwd)
|
|
}
|
|
|
|
stdout, stderr, err := runBDInProcessAllowError(t, noBeadsCwd, "comment", "list", "should not be stored")
|
|
if err == nil {
|
|
t.Fatalf("expected non-zero exit for misplaced 'comment list', got success:\nstdout: %s", stdout)
|
|
}
|
|
combined := stdout + stderr
|
|
if strings.Contains(combined, "no beads database found") {
|
|
t.Fatalf("Args validation did not run before store open: got the pre-fix error.\nOutput:\n%s", combined)
|
|
}
|
|
if !strings.Contains(combined, "bd comments") {
|
|
t.Errorf("expected hint pointing to `bd comments`, got:\n%s", combined)
|
|
}
|
|
}
|
|
|
|
// TestCLI_CommentMisplacedSyntaxRejectedInProxiedServerMode is the
|
|
// proxied-server counterpart, mirroring
|
|
// TestCLI_CommentsSwappedAddRejectedInProxiedServerMode: because
|
|
// validateCommentArgs runs in Args — before RunE ever branches on
|
|
// usesProxiedServer() — the rejection fires identically regardless of
|
|
// backend, without needing a real proxied server.
|
|
func TestCLI_CommentMisplacedSyntaxRejectedInProxiedServerMode(t *testing.T) {
|
|
origProxied := proxiedServerMode
|
|
t.Cleanup(func() { proxiedServerMode = origProxied })
|
|
proxiedServerMode = true
|
|
|
|
tmpDir := setupCLITestDB(t)
|
|
stdout, stderr, err := runBDInProcessAllowError(t, tmpDir, "comment", "list", "should not be stored")
|
|
if err == nil {
|
|
t.Fatalf("expected non-zero exit for misplaced 'comment list' in proxied-server mode, got success:\nstdout: %s", stdout)
|
|
}
|
|
combined := stdout + stderr
|
|
if !strings.Contains(combined, "bd comments") {
|
|
t.Errorf("expected hint pointing to `bd comments`, got:\n%s", combined)
|
|
}
|
|
}
|
|
|
|
// TestCLI_CommentTextStartingWithReservedWordStillWorks confirms the fix is
|
|
// scoped to the id positional argument only: a real id followed by comment
|
|
// TEXT that happens to start with "list" or "add" must still work exactly
|
|
// as before, since args[0] (the id slot) is what's checked, never the text.
|
|
func TestCLI_CommentTextStartingWithReservedWordStillWorks(t *testing.T) {
|
|
tmpDir := setupCLITestDB(t)
|
|
|
|
out := runBDInProcess(t, tmpDir, "create", "Issue for reserved-word-text test", "-p", "1", "--json")
|
|
jsonStart := strings.Index(out, "{")
|
|
if jsonStart < 0 {
|
|
t.Fatalf("No JSON found in create output: %s", out)
|
|
}
|
|
var issue map[string]interface{}
|
|
if err := json.Unmarshal([]byte(out[jsonStart:]), &issue); err != nil {
|
|
t.Fatalf("Failed to parse create JSON: %v\nOutput: %s", err, out)
|
|
}
|
|
fullID := issue["id"].(string)
|
|
|
|
stdout, stderr, err := runBDInProcessAllowError(t, tmpDir, "comment", fullID, "list", "of", "things", "to", "do")
|
|
if err != nil {
|
|
t.Fatalf("comment with text starting in 'list' unexpectedly failed: %v\nstdout: %s\nstderr: %s", err, stdout, stderr)
|
|
}
|
|
if !strings.Contains(stdout, "Comment added") {
|
|
t.Errorf("Expected 'Comment added' in output, got: %s", stdout)
|
|
}
|
|
|
|
commentsOut := runBDInProcess(t, tmpDir, "comments", fullID, "--json")
|
|
if !strings.Contains(commentsOut, "list of things to do") {
|
|
t.Fatalf("expected comment text to be stored verbatim, got: %s", commentsOut)
|
|
}
|
|
}
|
|
|
|
// TestCLI_CommentRmDeleteReservedWordsRejected covers the two reserved words
|
|
// TestCLI_CommentListMisplacedSyntax/TestCLI_CommentAddMisplacedSyntax do not:
|
|
// "rm" and "delete" carry no hand-written case in validateCommentArgs (unlike
|
|
// "list"/"add"), so they fall through to checkCommentIDNotReservedWord's
|
|
// generic message and, before this test, had no CLI-level (cobra-dispatch)
|
|
// coverage at all — steveyegge's PR #5393 review (item a) flagged that
|
|
// generic message as potentially misleading for these two specifically, since
|
|
// neither is an actual "bd comments" subcommand the way "list"/"add" are.
|
|
// This pins both halves: the command is rejected, AND — the part that
|
|
// actually matters — no comment silently lands on an unrelated real issue.
|
|
func TestCLI_CommentRmDeleteReservedWordsRejected(t *testing.T) {
|
|
for _, word := range []string{"rm", "delete"} {
|
|
t.Run(word, func(t *testing.T) {
|
|
tmpDir := setupCLITestDB(t)
|
|
|
|
out := runBDInProcess(t, tmpDir, "create", "Bystander issue for "+word+"-typo", "-p", "1", "--json")
|
|
jsonStart := strings.Index(out, "{")
|
|
if jsonStart < 0 {
|
|
t.Fatalf("No JSON found in create output: %s", out)
|
|
}
|
|
var issue map[string]interface{}
|
|
if err := json.Unmarshal([]byte(out[jsonStart:]), &issue); err != nil {
|
|
t.Fatalf("Failed to parse create JSON: %v\nOutput: %s", err, out)
|
|
}
|
|
fullID := issue["id"].(string)
|
|
|
|
stdout, stderr, err := runBDInProcessAllowError(t, tmpDir, "comment", word, "accidental stray text")
|
|
if err == nil {
|
|
t.Fatalf("expected non-zero exit for 'bd comment %s ...', got stdout=%q stderr=%q", word, stdout, stderr)
|
|
}
|
|
combined := stdout + stderr
|
|
// Must be refused as an id/reserved word — but, unlike "list"/"add",
|
|
// must NOT claim it is a misplaced "bd comments" subcommand: there is
|
|
// no "bd comments rm" or "bd comments delete".
|
|
if !strings.Contains(combined, "not a valid issue id") {
|
|
t.Errorf("expected a not-a-valid-issue-id refusal, got stdout=%q stderr=%q", stdout, stderr)
|
|
}
|
|
if strings.Contains(combined, "misplaced") {
|
|
t.Errorf("message falsely implies %q is a misplaced \"bd comments\" subcommand (it isn't one), got stdout=%q stderr=%q", word, stdout, stderr)
|
|
}
|
|
|
|
// The regression check: the bystander issue must have received NO
|
|
// comment.
|
|
commentsOut := runBDInProcess(t, tmpDir, "comments", fullID, "--json")
|
|
trimmed := strings.TrimSpace(commentsOut)
|
|
if trimmed != "[]" && trimmed != "null" {
|
|
t.Fatalf("expected no comments on bystander issue %s after rejected 'comment %s', got: %s", fullID, word, commentsOut)
|
|
}
|
|
})
|
|
}
|
|
}
|
|
|
|
// TestCLI_CommentsAddReservedWordRejectedThroughCobraDispatch closes PR #5393
|
|
// review R2's "NEW MINOR — the guard's wiring is untested": comments_add_test.go
|
|
// unit-tests validateCommentsAddArgs directly, and that catches a gutted
|
|
// function body (mutation P-C), but nothing drove "bd comments add
|
|
// <reserved-word> ..." through actual cobra dispatch — unwiring
|
|
// commentsAddCmd's Args field back to cobra.MinimumNArgs(1) left every
|
|
// existing test green (mutation P-D). This runs the real command line, the
|
|
// way a caller or an automated session actually invokes it, for every word in
|
|
// commentReservedIDWords (validateCommentsAddArgs has no singular/plural
|
|
// special-casing, unlike "comment"'s validateCommentArgs, so all four take
|
|
// the same generic-message path and are equally worth covering here).
|
|
func TestCLI_CommentsAddReservedWordRejectedThroughCobraDispatch(t *testing.T) {
|
|
for _, word := range []string{"list", "add", "rm", "delete"} {
|
|
t.Run(word, func(t *testing.T) {
|
|
tmpDir := setupCLITestDB(t)
|
|
|
|
out := runBDInProcess(t, tmpDir, "create", "Bystander issue for comments-add "+word+"-typo", "-p", "1", "--json")
|
|
jsonStart := strings.Index(out, "{")
|
|
if jsonStart < 0 {
|
|
t.Fatalf("No JSON found in create output: %s", out)
|
|
}
|
|
var issue map[string]interface{}
|
|
if err := json.Unmarshal([]byte(out[jsonStart:]), &issue); err != nil {
|
|
t.Fatalf("Failed to parse create JSON: %v\nOutput: %s", err, out)
|
|
}
|
|
fullID := issue["id"].(string)
|
|
|
|
stdout, stderr, err := runBDInProcessAllowError(t, tmpDir, "comments", "add", word, "accidental stray text")
|
|
if err == nil {
|
|
t.Fatalf("expected non-zero exit for 'bd comments add %s ...', got stdout=%q stderr=%q", word, stdout, stderr)
|
|
}
|
|
combined := stdout + stderr
|
|
if !strings.Contains(combined, "not a valid issue id") {
|
|
t.Errorf("expected a not-a-valid-issue-id refusal, got stdout=%q stderr=%q", stdout, stderr)
|
|
}
|
|
|
|
// The regression check: the bystander issue must have received NO
|
|
// comment — this is exactly what unwiring commentsAddCmd.Args back
|
|
// to cobra.MinimumNArgs(1) would silently allow through.
|
|
commentsOut := runBDInProcess(t, tmpDir, "comments", fullID, "--json")
|
|
trimmed := strings.TrimSpace(commentsOut)
|
|
if trimmed != "[]" && trimmed != "null" {
|
|
t.Fatalf("expected no comments on bystander issue %s after rejected 'comments add %s', got: %s", fullID, word, commentsOut)
|
|
}
|
|
})
|
|
}
|
|
}
|
|
|
|
// TestCLI_CommentAbbreviatedIDRejectedWithTruthfulMessage is the CLI-level
|
|
// regression test for steveyegge's PR #5393 review item (c): a leading-prefix
|
|
// abbreviation of a REAL issue's id is refused on comment writes (exact-only
|
|
// policy, unchanged), but the refusal message must not claim the issue does
|
|
// not exist — it does, the abbreviation was just refused. Before this fix,
|
|
// resolveAndGetIssueForMutationExact surfaced ResolvePartialIDExact's plain
|
|
// "no issue found matching %q", which is false in exactly this case; every
|
|
// other command family (show/close/update) still accepts the same
|
|
// abbreviation, so a truthful, distinguishing message matters here more than
|
|
// most refusals.
|
|
func TestCLI_CommentAbbreviatedIDRejectedWithTruthfulMessage(t *testing.T) {
|
|
tmpDir := setupCLITestDB(t)
|
|
|
|
out := runBDInProcess(t, tmpDir, "create", "Needs an exact id on comment", "-p", "1", "--json")
|
|
jsonStart := strings.Index(out, "{")
|
|
if jsonStart < 0 {
|
|
t.Fatalf("No JSON found in create output: %s", out)
|
|
}
|
|
var issue map[string]interface{}
|
|
if err := json.Unmarshal([]byte(out[jsonStart:]), &issue); err != nil {
|
|
t.Fatalf("Failed to parse create JSON: %v\nOutput: %s", err, out)
|
|
}
|
|
fullID := issue["id"].(string)
|
|
if len(fullID) < 4 {
|
|
t.Fatalf("test setup: generated id %q too short to abbreviate", fullID)
|
|
}
|
|
abbrev := fullID[:len(fullID)-1]
|
|
|
|
// Sanity check: the same abbreviation still works on a READ path (show),
|
|
// proving this is a real, resolvable abbreviation and not an accident of
|
|
// the fixture — the gap this test guards is specific to comment WRITES.
|
|
showOut, showErr, err := runBDInProcessAllowError(t, tmpDir, "show", abbrev, "--json")
|
|
if err != nil {
|
|
t.Fatalf("fixture sanity check failed: 'bd show %s' unexpectedly failed: %v\nstdout: %s\nstderr: %s", abbrev, err, showOut, showErr)
|
|
}
|
|
if !strings.Contains(showOut, fullID) {
|
|
t.Fatalf("fixture sanity check failed: 'bd show %s' did not resolve to %s, got: %s", abbrev, fullID, showOut)
|
|
}
|
|
|
|
stdout, stderr, err := runBDInProcessAllowError(t, tmpDir, "comment", abbrev, "should not be written")
|
|
if err == nil {
|
|
t.Fatalf("expected non-zero exit for 'bd comment %s ...' (abbreviation on a write path), got stdout=%q stderr=%q", abbrev, stdout, stderr)
|
|
}
|
|
combined := stdout + stderr
|
|
if !strings.Contains(combined, "abbreviations are not accepted") {
|
|
t.Errorf("expected the truthful abbreviation-refusal message, got stdout=%q stderr=%q", stdout, stderr)
|
|
}
|
|
if !strings.Contains(combined, "bd show") {
|
|
t.Errorf("expected the message to point at the full id via `bd show`, got stdout=%q stderr=%q", stdout, stderr)
|
|
}
|
|
if strings.Contains(combined, "not found") {
|
|
t.Errorf("message must not claim the issue was not found — %s exists, only the abbreviation was refused; got stdout=%q stderr=%q", fullID, stdout, stderr)
|
|
}
|
|
|
|
// The regression check: no comment silently landed on the real issue.
|
|
commentsOut := runBDInProcess(t, tmpDir, "comments", fullID, "--json")
|
|
trimmed := strings.TrimSpace(commentsOut)
|
|
if trimmed != "[]" && trimmed != "null" {
|
|
t.Fatalf("expected no comments on %s after rejected abbreviated 'comment', got: %s", fullID, commentsOut)
|
|
}
|
|
}
|
|
|
|
// TestCLI_CreateRejectsFlagLikeTitles verifies that positional arguments starting
|
|
// with - or -- are rejected as likely misinterpreted flags (bd-2c0).
|
|
func TestCLI_CreateRejectsFlagLikeTitles(t *testing.T) {
|
|
if testDoltServerPort == 0 {
|
|
t.Skip("skipping: Dolt test container not available")
|
|
}
|
|
|
|
tests := []struct {
|
|
name string
|
|
title string
|
|
}{
|
|
{"DoubleDashHelp", "--help"},
|
|
{"DoubleDashVersion", "--version"},
|
|
{"SingleDashFlag", "-p"},
|
|
{"DoubleDashArbitrary", "--foo-bar"},
|
|
}
|
|
|
|
for _, tc := range tests {
|
|
t.Run(tc.name, func(t *testing.T) {
|
|
tmpDir := createTempDirWithCleanup(t)
|
|
|
|
// Initialize the database
|
|
initCmd := exec.Command(testBD, "init", "--prefix", "test", "--quiet")
|
|
initCmd.Dir = tmpDir
|
|
initCmd.Env = os.Environ()
|
|
if out, err := initCmd.CombinedOutput(); err != nil {
|
|
t.Fatalf("init failed: %v\n%s", err, out)
|
|
}
|
|
|
|
// Attempt to create with a flag-like positional title
|
|
// "--" ends flag parsing, so the title reaches create's own
|
|
// positional-title guard instead of cobra's flag parser
|
|
// (which answers --help with help and --foo-bar with
|
|
// "unknown flag").
|
|
cmd := exec.Command(testBD, "create", "--", tc.title)
|
|
cmd.Dir = tmpDir
|
|
cmd.Env = os.Environ()
|
|
out, err := cmd.CombinedOutput()
|
|
|
|
if err == nil {
|
|
t.Errorf("Expected error for flag-like title %q, but got none.\nOutput: %s", tc.title, out)
|
|
}
|
|
|
|
if !strings.Contains(string(out), "looks like a flag") {
|
|
t.Errorf("Expected 'looks like a flag' error for %q, got: %s", tc.title, out)
|
|
}
|
|
})
|
|
}
|
|
|
|
// Without "--" cobra rejects an unknown flag-like word before create's
|
|
// guard runs; either way bd-2c0's point holds: no garbage issue.
|
|
t.Run("BareUnknownFlagCreatesNothing", func(t *testing.T) {
|
|
tmpDir := createTempDirWithCleanup(t)
|
|
initCmd := exec.Command(testBD, "init", "--prefix", "test", "--quiet")
|
|
initCmd.Dir = tmpDir
|
|
initCmd.Env = os.Environ()
|
|
if out, err := initCmd.CombinedOutput(); err != nil {
|
|
t.Fatalf("init failed: %v\n%s", err, out)
|
|
}
|
|
cmd := exec.Command(testBD, "create", "--foo-bar")
|
|
cmd.Dir = tmpDir
|
|
cmd.Env = os.Environ()
|
|
if out, err := cmd.CombinedOutput(); err == nil {
|
|
t.Fatalf("bd create --foo-bar succeeded:\n%s", out)
|
|
}
|
|
list := exec.Command(testBD, "list", "--json", "--all")
|
|
list.Dir = tmpDir
|
|
list.Env = os.Environ()
|
|
out, err := list.Output()
|
|
if err != nil {
|
|
t.Fatalf("bd list: %v\n%s", err, out)
|
|
}
|
|
var issues []map[string]any
|
|
if err := json.Unmarshal(out, &issues); err != nil {
|
|
t.Fatalf("bd list --json: %v\n%s", err, out)
|
|
}
|
|
if len(issues) != 0 {
|
|
t.Fatalf("bd create --foo-bar created %d issue(s): %s", len(issues), out)
|
|
}
|
|
})
|
|
|
|
// Verify that --title flag with dash-prefixed value is still allowed
|
|
t.Run("TitleFlagAllowsDashes", func(t *testing.T) {
|
|
tmpDir := setupCLITestDB(t)
|
|
|
|
out := runBDInProcess(t, tmpDir, "create", "--title", "--unusual-title", "-p", "1", "--json")
|
|
if !strings.Contains(out, "--unusual-title") {
|
|
t.Errorf("Expected title '--unusual-title' in output, got: %s", out)
|
|
}
|
|
})
|
|
}
|
|
|
|
// TestCLI_CreateRejectsEmptyTitle verifies that a whitespace-only title is
|
|
// refused rather than silently creating a title-less bead (GH#4771). Such a
|
|
// bead is functionally invisible in title-based views.
|
|
func TestCLI_CreateRejectsEmptyTitle(t *testing.T) {
|
|
cases := []struct {
|
|
name string
|
|
args []string
|
|
}{
|
|
{"FlagSpaces", []string{"create", "--title", " ", "-p", "2"}},
|
|
{"FlagTab", []string{"create", "--title", "\t", "-p", "2"}},
|
|
{"PositionalSpaces", []string{"create", " ", "-p", "2"}},
|
|
}
|
|
for _, tc := range cases {
|
|
t.Run(tc.name, func(t *testing.T) {
|
|
tmpDir := setupCLITestDB(t)
|
|
stdout, stderr, err := runBDInProcessAllowError(t, tmpDir, tc.args...)
|
|
if err == nil {
|
|
t.Fatalf("expected error for whitespace-only title, got success\nstdout: %s", stdout)
|
|
}
|
|
combined := stdout + stderr
|
|
if !strings.Contains(combined, "title cannot be empty") {
|
|
t.Errorf("expected 'title cannot be empty' error, got: %s", combined)
|
|
}
|
|
})
|
|
}
|
|
}
|
|
|
|
// TestCLI_CreateRejectsEmptyTitle_ProxiedServerMode is a proxied-server
|
|
// regression for GH#4771. Before this fix, the whitespace-only guard lived
|
|
// only in create's local-store RunE branch: gatherCreateInput/
|
|
// runCreateProxiedServer (the path taken when usesProxiedServer() is true)
|
|
// never re-checked, so proxied-mode create still minted a blank-titled bead.
|
|
// The fix moved the check into resolveTitle, invoked from createCmd's Args
|
|
// validator — which runs for every invocation regardless of backend, before
|
|
// RunE ever branches on usesProxiedServer(). Setting proxiedServerMode here
|
|
// exercises that dispatch without needing a real proxied server: Args
|
|
// validation must reject before gatherCreateInput/runCreateProxiedServer (or
|
|
// any store open) ever runs.
|
|
func TestCLI_CreateRejectsEmptyTitle_ProxiedServerMode(t *testing.T) {
|
|
origProxied := proxiedServerMode
|
|
t.Cleanup(func() { proxiedServerMode = origProxied })
|
|
proxiedServerMode = true
|
|
|
|
// A --title left on createCmd by an earlier in-process run cannot leak
|
|
// in: runBDInProcessAllowError resets every flag first
|
|
// (resetCommandFlags).
|
|
tmpDir := setupCLITestDB(t)
|
|
stdout, stderr, err := runBDInProcessAllowError(t, tmpDir, "create", " ", "-p", "2")
|
|
if err == nil {
|
|
t.Fatalf("expected error for whitespace-only title in proxied-server mode, got success\nstdout: %s", stdout)
|
|
}
|
|
combined := stdout + stderr
|
|
if !strings.Contains(combined, "title cannot be empty") {
|
|
t.Errorf("expected 'title cannot be empty' error, got: %s", combined)
|
|
}
|
|
}
|
|
|
|
// TestCLI_CreateNoHistory tests that the --no-history CLI flag is wired through
|
|
// to the created issue (GH#2619). A storage-layer test already covers the DB
|
|
// semantics; this test verifies the CLI flag is actually parsed and passed.
|
|
func TestCLI_CreateNoHistory(t *testing.T) {
|
|
|
|
t.Run("NoHistoryFlagSetOnCreatedIssue", func(t *testing.T) {
|
|
tmpDir := setupCLITestDB(t)
|
|
out := runBDInProcess(t, tmpDir, "create", "No-history agent bead", "-p", "2", "--no-history", "--json")
|
|
|
|
var result map[string]interface{}
|
|
if err := json.Unmarshal([]byte(out), &result); err != nil {
|
|
t.Fatalf("Failed to parse JSON: %v\nOutput: %s", err, out)
|
|
}
|
|
if result["no_history"] != true {
|
|
t.Errorf("Expected no_history=true on created issue, got: %v", result["no_history"])
|
|
}
|
|
// Must NOT be ephemeral (mutually exclusive)
|
|
if result["ephemeral"] == true {
|
|
t.Errorf("no-history issue must not be ephemeral, but ephemeral=true")
|
|
}
|
|
})
|
|
|
|
t.Run("NoHistoryPersistedAfterShow", func(t *testing.T) {
|
|
tmpDir := setupCLITestDB(t)
|
|
out := runBDInProcess(t, tmpDir, "create", "No-history bead for show test", "-p", "2", "--no-history", "--json")
|
|
|
|
var created map[string]interface{}
|
|
if err := json.Unmarshal([]byte(out), &created); err != nil {
|
|
t.Fatalf("Failed to parse create output: %v\nOutput: %s", err, out)
|
|
}
|
|
id := created["id"].(string)
|
|
|
|
showOut := runBDInProcess(t, tmpDir, "show", id, "--json")
|
|
var issues []map[string]interface{}
|
|
if err := json.Unmarshal([]byte(showOut), &issues); err != nil {
|
|
t.Fatalf("Failed to parse show output: %v\nOutput: %s", err, showOut)
|
|
}
|
|
if len(issues) == 0 {
|
|
t.Fatalf("show returned no issues for id %s", id)
|
|
}
|
|
if issues[0]["no_history"] != true {
|
|
t.Errorf("Expected no_history=true after show, got: %v", issues[0]["no_history"])
|
|
}
|
|
})
|
|
|
|
t.Run("EphemeralAndNoHistoryMutuallyExclusive", func(t *testing.T) {
|
|
tmpDir := setupCLITestDB(t)
|
|
_, stderr, err := runBDInProcessAllowError(t, tmpDir, "create", "Should fail", "--ephemeral", "--no-history")
|
|
if err == nil {
|
|
t.Error("Expected error when combining --ephemeral and --no-history, got none")
|
|
}
|
|
if !strings.Contains(stderr, "mutually exclusive") {
|
|
t.Errorf("Expected 'mutually exclusive' in stderr, got: %s", stderr)
|
|
}
|
|
})
|
|
}
|
|
|
|
// TestCLI_WispListTypeFilter tests that bd mol wisp list --type filters correctly.
|
|
func TestCLI_WispListTypeFilter(t *testing.T) {
|
|
|
|
tmpDir := setupCLITestDB(t)
|
|
|
|
// Create two ephemeral wisps of different built-in types
|
|
runBDInProcess(t, tmpDir, "create", "Bug wisp", "--ephemeral", "--type", "bug", "-p", "2")
|
|
runBDInProcess(t, tmpDir, "create", "Task wisp", "--ephemeral", "--type", "task", "-p", "2")
|
|
|
|
// --type bug should return only the bug wisp
|
|
out := runBDInProcess(t, tmpDir, "mol", "wisp", "list", "--type", "bug", "--json")
|
|
var result map[string]interface{}
|
|
if err := json.Unmarshal([]byte(out), &result); err != nil {
|
|
t.Fatalf("Failed to parse JSON: %v\nOutput: %s", err, out)
|
|
}
|
|
wisps, ok := result["wisps"].([]interface{})
|
|
if !ok {
|
|
t.Fatalf("Expected 'wisps' array in JSON output, got: %v", result)
|
|
}
|
|
if len(wisps) != 1 {
|
|
t.Errorf("Expected 1 wisp with type=bug, got %d: %v", len(wisps), wisps)
|
|
}
|
|
if len(wisps) == 1 {
|
|
w := wisps[0].(map[string]interface{})
|
|
if w["type"] != "bug" {
|
|
t.Errorf("Expected wisp type=bug, got: %v", w["type"])
|
|
}
|
|
}
|
|
|
|
// --type task should return only the task wisp
|
|
out = runBDInProcess(t, tmpDir, "mol", "wisp", "list", "--type", "task", "--json")
|
|
if err := json.Unmarshal([]byte(out), &result); err != nil {
|
|
t.Fatalf("Failed to parse JSON: %v\nOutput: %s", err, out)
|
|
}
|
|
wisps, ok = result["wisps"].([]interface{})
|
|
if !ok {
|
|
t.Fatalf("Expected 'wisps' array, got: %v", result)
|
|
}
|
|
if len(wisps) != 1 {
|
|
t.Errorf("Expected 1 wisp with type=task, got %d", len(wisps))
|
|
}
|
|
if len(wisps) == 1 {
|
|
w := wisps[0].(map[string]interface{})
|
|
if w["type"] != "task" {
|
|
t.Errorf("Expected wisp type=task, got: %v", w["type"])
|
|
}
|
|
}
|
|
|
|
// No --type filter returns both
|
|
out = runBDInProcess(t, tmpDir, "mol", "wisp", "list", "--json")
|
|
if err := json.Unmarshal([]byte(out), &result); err != nil {
|
|
t.Fatalf("Failed to parse JSON: %v\nOutput: %s", err, out)
|
|
}
|
|
wisps = result["wisps"].([]interface{})
|
|
if len(wisps) != 2 {
|
|
t.Errorf("Expected 2 wisps without type filter, got %d", len(wisps))
|
|
}
|
|
}
|
|
|
|
// TestCLI_WispGCExcludeType tests that bd mol wisp gc --exclude-type skips
|
|
// wisps of the excluded type during garbage collection.
|
|
func TestCLI_WispGCExcludeType(t *testing.T) {
|
|
|
|
tmpDir := setupCLITestDB(t)
|
|
|
|
// Create two ephemeral wisps of different built-in types.
|
|
// Use --age=0s so that ALL wisps (regardless of actual age) are treated
|
|
// as abandoned GC candidates.
|
|
bugOut := runBDInProcess(t, tmpDir, "create", "Bug wisp to keep", "--ephemeral", "--type", "bug", "-p", "2", "--json")
|
|
taskOut := runBDInProcess(t, tmpDir, "create", "Task wisp to gc", "--ephemeral", "--type", "task", "-p", "2", "--json")
|
|
|
|
var bugCreated, taskCreated map[string]interface{}
|
|
if err := json.Unmarshal([]byte(bugOut), &bugCreated); err != nil {
|
|
t.Fatalf("Failed to parse bug create output: %v\nOutput: %s", err, bugOut)
|
|
}
|
|
if err := json.Unmarshal([]byte(taskOut), &taskCreated); err != nil {
|
|
t.Fatalf("Failed to parse task create output: %v\nOutput: %s", err, taskOut)
|
|
}
|
|
bugID := bugCreated["id"].(string)
|
|
taskID := taskCreated["id"].(string)
|
|
|
|
// Dry-run GC with --exclude-type bug, --age=0s (treats all wisps as abandoned).
|
|
// The WispGCResult dry-run JSON uses cleaned_ids to list what would be deleted.
|
|
gcOut := runBDInProcess(t, tmpDir, "mol", "wisp", "gc", "--exclude-type", "bug", "--age", "0s", "--dry-run", "--json")
|
|
var gcResult map[string]interface{}
|
|
if err := json.Unmarshal([]byte(gcOut), &gcResult); err != nil {
|
|
t.Fatalf("Failed to parse gc JSON: %v\nOutput: %s", err, gcOut)
|
|
}
|
|
|
|
// cleaned_ids holds the IDs that would be deleted (dry_run=true).
|
|
cleanedRaw, _ := gcResult["cleaned_ids"].([]interface{})
|
|
cleanedIDs := make(map[string]bool, len(cleanedRaw))
|
|
for _, v := range cleanedRaw {
|
|
if id, ok := v.(string); ok {
|
|
cleanedIDs[id] = true
|
|
}
|
|
}
|
|
|
|
if !cleanedIDs[taskID] {
|
|
t.Errorf("Expected task wisp %s in GC candidates (not excluded), got cleaned_ids: %v", taskID, cleanedRaw)
|
|
}
|
|
if cleanedIDs[bugID] {
|
|
t.Errorf("Bug wisp %s should be excluded from GC via --exclude-type bug, but appeared in cleaned_ids", bugID)
|
|
}
|
|
}
|