| 1 | package tool |
| 2 | |
| 3 | import ( |
| 4 | "context" |
| 5 | "encoding/json" |
| 6 | "errors" |
| 7 | "testing" |
| 8 | |
| 9 | "reasonix/internal/diff" |
| 10 | ) |
| 11 | |
| 12 | type fakeWriter struct { |
| 13 | readOnly bool |
| 14 | change diff.Change |
| 15 | err error |
| 16 | } |
| 17 | |
| 18 | func (f fakeWriter) Name() string { return "fake" } |
| 19 | func (f fakeWriter) Description() string { return "fake" } |
| 20 | func (f fakeWriter) Schema() json.RawMessage { return json.RawMessage(`{}`) } |
| 21 | func (f fakeWriter) Execute(context.Context, json.RawMessage) (string, error) { return "", nil } |
| 22 | func (f fakeWriter) ReadOnly() bool { return f.readOnly } |
| 23 | func (f fakeWriter) Preview(json.RawMessage) (diff.Change, error) { return f.change, f.err } |
| 24 | |
| 25 | type plainWriter struct{} |
| 26 | |
| 27 | func (plainWriter) Name() string { return "plain" } |
| 28 | func (plainWriter) Description() string { return "plain" } |
| 29 | func (plainWriter) Schema() json.RawMessage { return json.RawMessage(`{}`) } |
| 30 | func (plainWriter) Execute(context.Context, json.RawMessage) (string, error) { return "", nil } |
| 31 | func (plainWriter) ReadOnly() bool { return false } |
| 32 | |
| 33 | func TestPreviewChange(t *testing.T) { |
| 34 | good := diff.Change{Diff: "@@\n+a\n", Added: 1} |
| 35 | cases := []struct { |
| 36 | name string |
| 37 | tool Tool |
| 38 | want bool |
| 39 | }{ |
| 40 | {"nil tool", nil, false}, |
| 41 | {"read-only skipped", fakeWriter{readOnly: true, change: good}, false}, |
| 42 | {"writer without previewer", plainWriter{}, false}, |
| 43 | {"preview error", fakeWriter{err: errors.New("boom")}, false}, |
| 44 | {"binary skipped", fakeWriter{change: diff.Change{Binary: true}}, false}, |
| 45 | {"textual change", fakeWriter{change: good}, true}, |
| 46 | } |
| 47 | for _, c := range cases { |
| 48 | t.Run(c.name, func(t *testing.T) { |
| 49 | ch, ok := PreviewChange(c.tool, json.RawMessage(`{}`)) |
| 50 | if ok != c.want { |
| 51 | t.Fatalf("ok = %v, want %v", ok, c.want) |
| 52 | } |
| 53 | if ok && ch.Diff == "" { |
| 54 | t.Fatal("expected a non-empty diff on success") |
| 55 | } |
| 56 | }) |
| 57 | } |
| 58 | } |
| 59 |