theStandardOutputShouldContain looks at the standard output (stdout) of the last invoked ec command and compares the expected output with the resulted output. Special handling is done for JSON output, it is compared disregarding key order in objects, and values can contain regular expressions to mat
(ctx context.Context, expected *godog.DocString)
| 453 | // regular expressions to match the expected to resulted output even when dealing with dynamic |
| 454 | // values such as port numbers or temporary paths |
| 455 | func theStandardOutputShouldContain(ctx context.Context, expected *godog.DocString) error { |
| 456 | status, err := ecStatusFrom(ctx) |
| 457 | if err != nil { |
| 458 | return err |
| 459 | } |
| 460 | |
| 461 | if expected == nil { |
| 462 | return errors.New("must provide expected output") |
| 463 | } |
| 464 | |
| 465 | expectedStdOut := os.Expand(expected.Content, func(key string) string { |
| 466 | return status.vars[key] |
| 467 | }) |
| 468 | |
| 469 | stdout := status.stdout.String() |
| 470 | |
| 471 | // shortcut, if the output is exactly as expected |
| 472 | if stdout == expectedStdOut { |
| 473 | return nil |
| 474 | } |
| 475 | |
| 476 | if matched, err := regexp.MatchString(expectedStdOut, stdout); matched && err == nil { |
| 477 | return nil |
| 478 | } |
| 479 | |
| 480 | // see if the expected value is JSON, i.e. if it starts with either { or [ |
| 481 | expectedTrimmed := strings.TrimLeftFunc(expectedStdOut, unicode.IsSpace) |
| 482 | expectdIsJSONMap := expectedTrimmed[0] == '{' |
| 483 | expectdIsJSONArray := expectedTrimmed[0] == '[' |
| 484 | stdoutTrimmed := strings.TrimLeftFunc(stdout, unicode.IsSpace) |
| 485 | stdoutIsJSON := len(stdoutTrimmed) > 0 && (stdoutTrimmed[0] == '{' || stdoutTrimmed[0] == '[') |
| 486 | if (expectdIsJSONMap || expectdIsJSONArray) && stdoutIsJSON { |
| 487 | expectedBytes := []byte(expectedStdOut) |
| 488 | |
| 489 | diff, err := compareJSON(expectedBytes, status.stdout.Bytes(), expectdIsJSONArray) |
| 490 | if err != nil { |
| 491 | return err |
| 492 | } |
| 493 | |
| 494 | if !diff.Modified() { |
| 495 | // expected and resulting JSON is the same |
| 496 | return nil |
| 497 | } |
| 498 | |
| 499 | // we need to unmarshal the expected (left) JSON for output formatting |
| 500 | // and to check for any regular expressions in the expected JSON's values |
| 501 | var left any |
| 502 | err = json.Unmarshal(expectedBytes, &left) |
| 503 | if err != nil { |
| 504 | return err |
| 505 | } |
| 506 | |
| 507 | diff = filterMatchedByRegexp(left, diff) |
| 508 | |
| 509 | if !diff.Modified() { |
| 510 | // there was a difference, but the values matched regular expression |
| 511 | // given in the expected JSON |
| 512 | return nil |
no test coverage detected