|
| 1 | +package tui |
| 2 | + |
| 3 | +import ( |
| 4 | + "encoding/json" |
| 5 | + "os" |
| 6 | + "path/filepath" |
| 7 | + "strings" |
| 8 | + "testing" |
| 9 | + |
| 10 | + tea "charm.land/bubbletea/v2" |
| 11 | + |
| 12 | + "github.com/TMHSDigital/subenum/internal/output" |
| 13 | +) |
| 14 | + |
| 15 | +func TestTUISaveConfirmsExistingFiles(t *testing.T) { |
| 16 | + for _, target := range []string{"scan output", "another file"} { |
| 17 | + t.Run(target, func(t *testing.T) { |
| 18 | + redirectConfig(t) |
| 19 | + path := filepath.Join(t.TempDir(), "out.json") |
| 20 | + m := runTUIModel(t, path, output.FormatJSON, []string{"A"}) |
| 21 | + press := func(keys ...tea.KeyPressMsg) { |
| 22 | + t.Helper() |
| 23 | + for _, key := range keys { |
| 24 | + next, _ := m.updateScan(key) |
| 25 | + m = next.(Model) |
| 26 | + } |
| 27 | + } |
| 28 | + press(typeText("/"), typeText("www"), keyEnter, typeText("s")) |
| 29 | + if target == "another file" { |
| 30 | + path = filepath.Join(t.TempDir(), "existing.json") |
| 31 | + if err := os.WriteFile(path, []byte("KEEP EXISTING FILE"), 0o600); err != nil { |
| 32 | + t.Fatal(err) |
| 33 | + } |
| 34 | + for range []rune(m.scanView.savePath) { |
| 35 | + press(keyBackspace) |
| 36 | + } |
| 37 | + press(typeText(path)) |
| 38 | + } |
| 39 | + before, err := os.ReadFile(path) |
| 40 | + if err != nil { |
| 41 | + t.Fatal(err) |
| 42 | + } |
| 43 | + unchanged := func() { |
| 44 | + t.Helper() |
| 45 | + got, err := os.ReadFile(path) |
| 46 | + if err != nil || string(got) != string(before) { |
| 47 | + t.Fatalf("save changed the existing file before confirmation: %q, err %v", got, err) |
| 48 | + } |
| 49 | + } |
| 50 | + press(keyEnter) |
| 51 | + unchanged() |
| 52 | + if !m.scanView.saving || !strings.Contains(m.scanView.doneHint(), "overwrite") { |
| 53 | + t.Fatalf("missing overwrite confirmation: %s", m.scanView.doneHint()) |
| 54 | + } |
| 55 | + |
| 56 | + // Editing and restoring the same path cancels the previous |
| 57 | + // confirmation; escape and reopening the prompt do so as well. |
| 58 | + press(keyBackspace, typeText("n"), keyEnter) |
| 59 | + unchanged() |
| 60 | + press(keyEsc, typeText("s"), keyEnter) |
| 61 | + unchanged() |
| 62 | + press(keyEnter) |
| 63 | + if m.scanView.saving { |
| 64 | + t.Fatal("confirmed save left the prompt open") |
| 65 | + } |
| 66 | + data, err := os.ReadFile(path) |
| 67 | + if err != nil { |
| 68 | + t.Fatal(err) |
| 69 | + } |
| 70 | + var results []output.Result |
| 71 | + if err := json.Unmarshal(data, &results); err != nil { |
| 72 | + t.Fatal(err) |
| 73 | + } |
| 74 | + if len(results) != 1 || results[0].Subdomain != "www.example.com" { |
| 75 | + t.Fatalf("confirmed save should contain the filtered result: %s", data) |
| 76 | + } |
| 77 | + }) |
| 78 | + } |
| 79 | +} |
0 commit comments