|
5 | 5 | package diff_test
|
6 | 6 |
|
7 | 7 | import (
|
| 8 | + "bytes" |
8 | 9 | "math/rand"
|
| 10 | + "os" |
| 11 | + "os/exec" |
| 12 | + "path/filepath" |
9 | 13 | "reflect"
|
| 14 | + "strings" |
10 | 15 | "testing"
|
11 | 16 | "unicode/utf8"
|
12 | 17 |
|
13 | 18 | "golang.org/x/tools/internal/diff"
|
14 | 19 | "golang.org/x/tools/internal/diff/difftest"
|
| 20 | + "golang.org/x/tools/internal/testenv" |
15 | 21 | )
|
16 | 22 |
|
17 | 23 | func TestApply(t *testing.T) {
|
@@ -99,31 +105,50 @@ func TestLineEdits(t *testing.T) {
|
99 | 105 | t.Fatalf("LineEdits: %v", err)
|
100 | 106 | }
|
101 | 107 | if !reflect.DeepEqual(got, edits) {
|
102 |
| - t.Errorf("LineEdits got %q, want %q", got, edits) |
| 108 | + t.Errorf("LineEdits got\n%q, want\n%q\n%#v", got, edits, tc) |
103 | 109 | }
|
104 | 110 | })
|
105 | 111 | }
|
106 | 112 | }
|
107 | 113 |
|
108 | 114 | func TestToUnified(t *testing.T) {
|
| 115 | + testenv.NeedsTool(t, "patch") |
109 | 116 | for _, tc := range difftest.TestCases {
|
110 | 117 | t.Run(tc.Name, func(t *testing.T) {
|
111 | 118 | unified, err := diff.ToUnified(difftest.FileA, difftest.FileB, tc.In, tc.Edits)
|
112 | 119 | if err != nil {
|
113 | 120 | t.Fatal(err)
|
114 | 121 | }
|
115 |
| - if unified != tc.Unified { |
116 |
| - t.Errorf("Unified(Edits): got diff:\n%v\nexpected:\n%v", unified, tc.Unified) |
| 122 | + if unified == "" { |
| 123 | + return |
117 | 124 | }
|
118 |
| - if tc.LineEdits != nil { |
119 |
| - unified, err := diff.ToUnified(difftest.FileA, difftest.FileB, tc.In, tc.LineEdits) |
120 |
| - if err != nil { |
121 |
| - t.Fatal(err) |
122 |
| - } |
123 |
| - if unified != tc.Unified { |
124 |
| - t.Errorf("Unified(LineEdits): got diff:\n%v\nexpected:\n%v", unified, tc.Unified) |
125 |
| - } |
| 125 | + orig := filepath.Join(t.TempDir(), "original") |
| 126 | + err = os.WriteFile(orig, []byte(tc.In), 0644) |
| 127 | + if err != nil { |
| 128 | + t.Fatal(err) |
126 | 129 | }
|
| 130 | + temp := filepath.Join(t.TempDir(), "patched") |
| 131 | + err = os.WriteFile(temp, []byte(tc.In), 0644) |
| 132 | + if err != nil { |
| 133 | + t.Fatal(err) |
| 134 | + } |
| 135 | + cmd := exec.Command("patch", "-p0", "-u", "-s", "-o", temp, orig) |
| 136 | + cmd.Stdin = strings.NewReader(unified) |
| 137 | + cmd.Stdout = new(bytes.Buffer) |
| 138 | + cmd.Stderr = new(bytes.Buffer) |
| 139 | + if err = cmd.Run(); err != nil { |
| 140 | + t.Fatalf("%v: %q (%q) (%q)", err, cmd.String(), |
| 141 | + cmd.Stderr, cmd.Stdout) |
| 142 | + } |
| 143 | + got, err := os.ReadFile(temp) |
| 144 | + if err != nil { |
| 145 | + t.Fatal(err) |
| 146 | + } |
| 147 | + if string(got) != tc.Out { |
| 148 | + t.Errorf("applying unified failed: got\n%q, wanted\n%q unified\n%q", |
| 149 | + got, tc.Out, unified) |
| 150 | + } |
| 151 | + |
127 | 152 | })
|
128 | 153 | }
|
129 | 154 | }
|
|
0 commit comments