beads/cmd/bd/update_metadata_test.go
Jim Wordelman 2ef3bd8c66
fix: 36 raw dolt.New(&Config{Path}) test sites in cmd/bd silently skip (#6679)
* feat: green — fix 36 raw dolt.New(&Config{Path}) test sites in cmd/bd silently skip (refs be-0k0dv)

Converts all 36 raw dolt.New(ctx, &dolt.Config{Path: ...}) call sites in
cmd/bd test files to the newTestStore/newTestStoreWithPrefix/
newTestStoreIsolatedDB helpers, which set CreateIfMissing: true. Without
this, missing databases caused t.Skipf("Dolt server not available") even
though the real cause was a missing DB, not a missing server — silently
hiding real coverage since 63418ae54's CreateIfMissing migration.

- cmd/bd/mol_test.go: 31 sites (26 -> newTestStore, 5 -> newTestStoreWithPrefix)
- cmd/bd/contributor_routing_e2e_test.go: 3 sites -> newTestStoreIsolatedDB
- cmd/bd/update_metadata_test.go: 1 site -> newTestStoreWithPrefix
- cmd/bd/rename_prefix_repair_test.go: 1 site -> newTestStore

Removed now-unused dolt imports where no other dolt.* usage remained in
file (mol_test.go, update_metadata_test.go, rename_prefix_repair_test.go).
contributor_routing_e2e_test.go keeps its dolt import — still used by
initProjectStore/initPlanningStore and struct fields outside the 36
converted sites.

* fix(test): finish contributor_routing_e2e_test.go's conversion; stop dbPath lying

Maintainer adoption fixup for PR #6679 (adoption review iteration 1).

contributor_routing_e2e_test.go converted 3 of its 7 raw
dolt.New(&dolt.Config{Path}) sites, leaving 4 — so one file carried two
different failure contracts for the same condition, and the harness that
backs most of the file's tests was still on the broken one. Convert the
remaining 4 to newTestStoreIsolatedDB: initProjectStore ("proj-"),
initPlanningStore ("plan-"), and the override/external stores in
TestExplicitRepoOverride ("over-") and TestBEADS_DIRPrecedence ("ext-").
Each replaced SetConfig(ctx, "issue_prefix", X) is reproduced by the
helper's prefix argument, and the co-located defer store.Close() calls go
with the sites the helper's t.Cleanup now covers.

Effect: 9 routing tests stop silently skipping. Before, at the contributor
head, TestContributorRoutingDirect / TestExplicitRepoOverride /
TestBEADS_DIRPrecedence all reported

    skipping: Dolt server not available: database "testdb_…" not found

against a live Dolt container. After, all 12 test functions in the file
PASS with 0 skips under -tags integration,gms_pure_go.

rename_prefix_repair_test.go: drop the unused global dbPath save/set/restore.
newTestStore's shared-branch path writes a metadata.json naming the shared
database with no branch qualifier while the live store sits on a per-test
branch, so setting the global to testDBPath planted the reopen-by-path
hazard the helper's own doc comment warns about. repairPrefixes takes the
store explicitly and never reopens by path, so the assignment was dead
weight pointing somewhere wrong; the comment now records why it is absent.

Remaining out of scope (tracked for follow-up): 10 raw sites in config_test.go,
sql_test.go, cli_coverage_show_test.go, rename_prefix_test.go, migrate_test.go,
and mol_ready_gated_test.go.

---------

Co-authored-by: Julian Knutsen <julianknutsen@users.noreply.github.com>
2026-09-26 07:34:49 -07:00

198 lines
5.3 KiB
Go

//go:build cgo
package main
import (
"context"
"encoding/json"
"os"
"path/filepath"
"testing"
"github.com/steveyegge/beads/internal/types"
)
// TestUpdateMetadataInlineJSON tests inline JSON metadata update
func TestUpdateMetadataInlineJSON(t *testing.T) {
tmpDir := t.TempDir()
dbPath := filepath.Join(tmpDir, ".beads", "beads.db")
// Create storage
ctx := context.Background()
store := newTestStoreWithPrefix(t, dbPath, "bd")
// Create an issue
issue := &types.Issue{
ID: "bd-test1",
Title: "Test Issue",
Status: "open",
IssueType: "task",
}
if err := store.CreateIssue(ctx, issue, "test-actor"); err != nil {
t.Fatalf("failed to create issue: %v", err)
}
// Update with inline JSON metadata
metadata := `{"key": "value", "nested": {"foo": "bar"}}`
updates := map[string]interface{}{
"metadata": json.RawMessage(metadata),
}
if err := store.UpdateIssue(ctx, "bd-test1", updates, "test-actor"); err != nil {
t.Fatalf("failed to update issue with metadata: %v", err)
}
// Verify the metadata was stored
updated, err := store.GetIssue(ctx, "bd-test1")
if err != nil {
t.Fatalf("failed to get issue: %v", err)
}
if updated.Metadata == nil {
t.Fatal("metadata should not be nil after update")
}
// Compare as parsed JSON (MySQL/Dolt normalizes JSON whitespace on storage)
var expectedJSON, actualJSON interface{}
if err := json.Unmarshal([]byte(metadata), &expectedJSON); err != nil {
t.Fatalf("failed to parse expected metadata: %v", err)
}
if err := json.Unmarshal(updated.Metadata, &actualJSON); err != nil {
t.Fatalf("failed to parse actual metadata: %v", err)
}
expectedBytes, _ := json.Marshal(expectedJSON)
actualBytes, _ := json.Marshal(actualJSON)
if string(expectedBytes) != string(actualBytes) {
t.Errorf("expected metadata %s, got %s", expectedBytes, actualBytes)
}
}
// TestUpdateMetadataFromFile tests reading metadata from a file
func TestUpdateMetadataFromFile(t *testing.T) {
tmpDir := t.TempDir()
// Create a JSON file
metadataJSON := `{"source": "file", "count": 42}`
metadataFile := filepath.Join(tmpDir, "metadata.json")
if err := os.WriteFile(metadataFile, []byte(metadataJSON), 0644); err != nil {
t.Fatalf("failed to write metadata file: %v", err)
}
// Read and validate
data, err := os.ReadFile(metadataFile)
if err != nil {
t.Fatalf("failed to read metadata file: %v", err)
}
if !json.Valid(data) {
t.Fatal("metadata file should contain valid JSON")
}
if string(data) != metadataJSON {
t.Errorf("expected %q, got %q", metadataJSON, string(data))
}
}
// TestUpdateMetadataInvalidJSON tests that invalid JSON is rejected
func TestUpdateMetadataInvalidJSON(t *testing.T) {
invalidCases := []string{
"{invalid}",
"not json",
`{"unclosed": `,
"",
}
for _, invalid := range invalidCases {
if invalid == "" {
// Empty string is not invalid for json.Valid per se, but we might want it
continue
}
if json.Valid([]byte(invalid)) {
t.Errorf("expected %q to be invalid JSON", invalid)
}
}
}
// TestUpdateMetadataValidJSON tests various valid JSON formats
func TestUpdateMetadataValidJSON(t *testing.T) {
validCases := []string{
`{}`,
`{"key": "value"}`,
`{"nested": {"deep": {"value": 123}}}`,
`{"array": [1, 2, 3]}`,
`{"mixed": [{"a": 1}, {"b": 2}]}`,
`{"unicode": "\u0048\u0065\u006c\u006c\u006f"}`,
`{"null": null}`,
`{"bool": true}`,
`{"number": 3.14159}`,
}
for _, valid := range validCases {
if !json.Valid([]byte(valid)) {
t.Errorf("expected %q to be valid JSON", valid)
}
}
}
// TestUpdateMetadataAtFileSyntax tests the @file.json parsing logic
func TestUpdateMetadataAtFileSyntax(t *testing.T) {
tests := []struct {
input string
isFile bool
filePath string
}{
{`{"inline": true}`, false, ""},
{"@metadata.json", true, "metadata.json"},
{"@/absolute/path.json", true, "/absolute/path.json"},
{"@./relative/path.json", true, "./relative/path.json"},
// Edge case: JSON that starts with @ in a string
{`{"email": "@user.com"}`, false, ""},
}
for _, tc := range tests {
// Check if starts with @ for file reference
isFile := len(tc.input) > 0 && tc.input[0] == '@'
if isFile != tc.isFile {
t.Errorf("input %q: expected isFile=%v, got %v", tc.input, tc.isFile, isFile)
}
if isFile {
filePath := tc.input[1:]
if filePath != tc.filePath {
t.Errorf("input %q: expected filePath=%q, got %q", tc.input, tc.filePath, filePath)
}
}
}
}
// TestUpdateMetadataRPCRoundtrip tests the RPC protocol for metadata
func TestUpdateMetadataRPCRoundtrip(t *testing.T) {
// Test that metadata can be marshaled/unmarshaled through RPC
metadata := `{"key": "value"}`
// Simulate UpdateArgs with metadata
type testUpdateArgs struct {
ID string `json:"id"`
Metadata *string `json:"metadata,omitempty"`
}
args := testUpdateArgs{
ID: "bd-123",
Metadata: &metadata,
}
// Marshal to JSON (as RPC would do)
data, err := json.Marshal(args)
if err != nil {
t.Fatalf("failed to marshal: %v", err)
}
// Unmarshal (as server would do)
var decoded testUpdateArgs
if err := json.Unmarshal(data, &decoded); err != nil {
t.Fatalf("failed to unmarshal: %v", err)
}
if decoded.Metadata == nil {
t.Fatal("metadata should not be nil after roundtrip")
}
if *decoded.Metadata != metadata {
t.Errorf("expected %q, got %q", metadata, *decoded.Metadata)
}
}