|
1 | 1 | package tests_test |
2 | 2 |
|
3 | 3 | import ( |
| 4 | + "errors" |
4 | 5 | "fmt" |
5 | 6 | "io" |
6 | 7 | "os" |
| 8 | + "os/exec" |
7 | 9 | "reflect" |
8 | 10 | "testing" |
9 | 11 | "time" |
10 | 12 |
|
11 | 13 | "github.com/stretchr/testify/assert" |
| 14 | + "github.com/stretchr/testify/require" |
12 | 15 |
|
13 | 16 | "github.com/sanity-io/litter" |
14 | 17 | ) |
@@ -291,10 +294,63 @@ func runTestWithCfg(t *testing.T, name string, cfg *litter.Options, cases ...any |
291 | 294 | return |
292 | 295 | } |
293 | 296 |
|
294 | | - assert.Equal(t, string(reference), dump) |
| 297 | + assertEqualStringsWithDiff(t, string(reference), dump) |
295 | 298 | }) |
296 | 299 | } |
297 | 300 |
|
| 301 | +func diffStrings(t *testing.T, expected, actual string) (*string, bool) { |
| 302 | + if actual == expected { |
| 303 | + return nil, true |
| 304 | + } |
| 305 | + |
| 306 | + dir, err := os.MkdirTemp("", "test") |
| 307 | + require.NoError(t, err) |
| 308 | + defer os.RemoveAll(dir) |
| 309 | + |
| 310 | + require.NoError(t, os.WriteFile(fmt.Sprintf("%s/expected", dir), []byte(expected), 0644)) |
| 311 | + require.NoError(t, os.WriteFile(fmt.Sprintf("%s/actual", dir), []byte(actual), 0644)) |
| 312 | + |
| 313 | + out, err := exec.Command("diff", "--side-by-side", |
| 314 | + fmt.Sprintf("%s/expected", dir), |
| 315 | + fmt.Sprintf("%s/actual", dir)).Output() |
| 316 | + |
| 317 | + var exitErr *exec.ExitError |
| 318 | + if !errors.As(err, &exitErr) { |
| 319 | + require.NoError(t, err) |
| 320 | + } |
| 321 | + |
| 322 | + diff := string(out) |
| 323 | + return &diff, false |
| 324 | +} |
| 325 | + |
| 326 | +func assertEqualStringsWithDiff(t *testing.T, expected, actual string, |
| 327 | + msgAndArgs ...interface{}) bool { |
| 328 | + diff, ok := diffStrings(t, expected, actual) |
| 329 | + if ok { |
| 330 | + return true |
| 331 | + } |
| 332 | + |
| 333 | + message := messageFromMsgAndArgs(msgAndArgs...) |
| 334 | + if message == "" { |
| 335 | + message = "Strings are different" |
| 336 | + } |
| 337 | + assert.Fail(t, fmt.Sprintf("%s (left is expected, right is actual):\n%s", message, *diff)) |
| 338 | + return false |
| 339 | +} |
| 340 | + |
| 341 | +func messageFromMsgAndArgs(msgAndArgs ...interface{}) string { |
| 342 | + if len(msgAndArgs) == 0 || msgAndArgs == nil { |
| 343 | + return "" |
| 344 | + } |
| 345 | + if len(msgAndArgs) == 1 { |
| 346 | + return msgAndArgs[0].(string) |
| 347 | + } |
| 348 | + if len(msgAndArgs) > 1 { |
| 349 | + return fmt.Sprintf(msgAndArgs[0].(string), msgAndArgs[1:]...) |
| 350 | + } |
| 351 | + return "" |
| 352 | +} |
| 353 | + |
298 | 354 | func runTests(t *testing.T, name string, cases ...any) { |
299 | 355 | runTestWithCfg(t, name, &standardCfg, cases...) |
300 | 356 | } |
0 commit comments