| 1 | package builtin |
| 2 | |
| 3 | import ( |
| 4 | "context" |
| 5 | "encoding/json" |
| 6 | "os" |
| 7 | "path/filepath" |
| 8 | "strings" |
| 9 | "testing" |
| 10 | ) |
| 11 | |
| 12 | // TestDeleteSymbolRemovesDocComment probes whether deleting a documented symbol |
| 13 | // also removes its doc comment. AST node Pos() excludes the Doc, so a naive |
| 14 | // offset delete would orphan the comment above the gone function. |
| 15 | func TestDeleteSymbolRemovesDocComment(t *testing.T) { |
| 16 | dir := t.TempDir() |
| 17 | path := filepath.Join(dir, "f.go") |
| 18 | src := "package p\n\n// Foo does a thing.\n// Second line.\nfunc Foo() int { return 1 }\n\nfunc Bar() {}\n" |
| 19 | if err := os.WriteFile(path, []byte(src), 0o644); err != nil { |
| 20 | t.Fatal(err) |
| 21 | } |
| 22 | args, _ := json.Marshal(map[string]any{"path": path, "name": "Foo"}) |
| 23 | if _, err := (deleteSymbol{}).Execute(context.Background(), args); err != nil { |
| 24 | t.Fatalf("execute: %v", err) |
| 25 | } |
| 26 | got, _ := os.ReadFile(path) |
| 27 | if strings.Contains(string(got), "Foo does a thing") { |
| 28 | t.Fatalf("doc comment orphaned after deleting Foo:\n%s", string(got)) |
| 29 | } |
| 30 | } |
| 31 | |
| 32 | // TestDeleteSymbolGroupedSpecKeepsGroupDoc proves deleting one spec from a |
| 33 | // parenthesized block removes that spec's own doc but never the block's group |
| 34 | // doc or its siblings. |
| 35 | func TestDeleteSymbolGroupedSpecKeepsGroupDoc(t *testing.T) { |
| 36 | dir := t.TempDir() |
| 37 | path := filepath.Join(dir, "g.go") |
| 38 | src := "package p\n\n// Group doc.\nconst (\n\t// ADoc.\n\tA = 1\n\tB = 2\n)\n" |
| 39 | if err := os.WriteFile(path, []byte(src), 0o644); err != nil { |
| 40 | t.Fatal(err) |
| 41 | } |
| 42 | args, _ := json.Marshal(map[string]any{"path": path, "name": "A"}) |
| 43 | if _, err := (deleteSymbol{}).Execute(context.Background(), args); err != nil { |
| 44 | t.Fatalf("execute: %v", err) |
| 45 | } |
| 46 | got := string(mustRead(t, path)) |
| 47 | if strings.Contains(got, "ADoc") || strings.Contains(got, "A = 1") { |
| 48 | t.Fatalf("A and its own doc should be gone:\n%s", got) |
| 49 | } |
| 50 | if !strings.Contains(got, "Group doc.") || !strings.Contains(got, "B = 2") { |
| 51 | t.Fatalf("group doc and sibling B must remain:\n%s", got) |
| 52 | } |
| 53 | } |
| 54 | |
| 55 | func mustRead(t *testing.T, path string) []byte { |
| 56 | t.Helper() |
| 57 | b, err := os.ReadFile(path) |
| 58 | if err != nil { |
| 59 | t.Fatal(err) |
| 60 | } |
| 61 | return b |
| 62 | } |
| 63 |