CheckPlotApprox checks a generated plot against a previously created reference. The normalized delta parameter describes how tight the matching should be performed, where delta=0 expresses a perfect match, and delta=1 a very loose match. If GenerateTestData = true, it regenerates the reference. For
(ExampleFunc func(), t *testing.T, delta float64, filenames ...string)
| 41 | // For image.Image formats, a base64 encoded png representation is output to |
| 42 | // the testing log when a difference is identified. |
| 43 | func CheckPlotApprox(ExampleFunc func(), t *testing.T, delta float64, filenames ...string) { |
| 44 | t.Helper() |
| 45 | |
| 46 | paths := make([]string, len(filenames)) |
| 47 | for i, fn := range filenames { |
| 48 | paths[i] = filepath.Join("testdata", fn) |
| 49 | } |
| 50 | |
| 51 | if *GenerateTestData { |
| 52 | // Recreate Golden images and exit. |
| 53 | ExampleFunc() |
| 54 | for _, path := range paths { |
| 55 | golden := goldenPath(path) |
| 56 | _ = os.Remove(golden) |
| 57 | if err := os.Rename(path, golden); err != nil { |
| 58 | t.Fatal(err) |
| 59 | } |
| 60 | } |
| 61 | return |
| 62 | } |
| 63 | |
| 64 | // Run the example. |
| 65 | ExampleFunc() |
| 66 | |
| 67 | // Read the images we've just generated and check them against the |
| 68 | // Golden Images. |
| 69 | for _, path := range paths { |
| 70 | got, err := os.ReadFile(path) |
| 71 | if err != nil { |
| 72 | t.Errorf("Failed to read %s: %v", path, err) |
| 73 | continue |
| 74 | } |
| 75 | golden := goldenPath(path) |
| 76 | want, err := os.ReadFile(golden) |
| 77 | if err != nil { |
| 78 | t.Errorf("Failed to read golden file %s: %v", golden, err) |
| 79 | continue |
| 80 | } |
| 81 | typ := filepath.Ext(path)[1:] // remove the dot in e.g. ".pdf" |
| 82 | ok, err := EqualApprox(typ, got, want, delta) |
| 83 | if err != nil { |
| 84 | t.Errorf("failed to compare image for %s: %v", path, err) |
| 85 | continue |
| 86 | } |
| 87 | if !ok { |
| 88 | t.Errorf("image mismatch for %s\n", path) |
| 89 | |
| 90 | switch typ { |
| 91 | case "jpeg", "jpg", "png", "tiff", "tif": |
| 92 | v1, _, err := image.Decode(bytes.NewReader(got)) |
| 93 | if err != nil { |
| 94 | t.Errorf("failed to decode %s: %v", path, err) |
| 95 | continue |
| 96 | } |
| 97 | v2, _, err := image.Decode(bytes.NewReader(want)) |
| 98 | if err != nil { |
| 99 | t.Errorf("failed to decode %s: %v", golden, err) |
| 100 | continue |