Debian Codegraph @

resources/images/imagetesting/testing.go

raw ◀ ▶
1 Debian patch touch this file
1 // Copyright 2024 The Hugo Authors. All rights reserved.
2 //
3 // Licensed under the Apache License, Version 2.0 (the "License");
4 // you may not use this file except in compliance with the License.
5 // You may obtain a copy of the License at
6 // http://www.apache.org/licenses/LICENSE-2.0
7 //
8 // Unless required by applicable law or agreed to in writing, software
9 // distributed under the License is distributed on an "AS IS" BASIS,
10 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
11 // See the License for the specific language governing permissions and
12 // limitations under the License.
13
14 package imagetesting
15
16 import (
17 "flag"
18 "image"
19 "io/fs"
20 "os"
21 "path/filepath"
22 "runtime"
23 "testing"
24
25 qt "github.com/frankban/quicktest"
26 "github.com/google/go-cmp/cmp"
27
28 "github.com/gohugoio/gift"
29 "github.com/gohugoio/hugo/common/hashing"
30 "github.com/gohugoio/hugo/common/himage"
31 "github.com/gohugoio/hugo/common/hugio"
32 "github.com/gohugoio/hugo/htesting"
33 "github.com/gohugoio/hugo/hugofs"
34 "github.com/gohugoio/hugo/hugolib"
35 )
36
37 var eq = qt.CmpEquals(
38 cmp.Comparer(func(p1, p2 os.FileInfo) bool {
39 return p1.Name() == p2.Name() && p1.Size() == p2.Size() && p1.IsDir() == p2.IsDir()
40 }),
41 cmp.Comparer(func(d1, d2 fs.DirEntry) bool {
42 p1, err1 := d1.Info()
43 p2, err2 := d2.Info()
44 if err1 != nil || err2 != nil {
45 return false
46 }
47 return p1.Name() == p2.Name() && p1.Size() == p2.Size() && p1.IsDir() == p2.IsDir()
48 }),
49 )
50
51 // GoldenImageTestOpts provides options for a golden image test.
52 type GoldenImageTestOpts struct {
53 // The test.
54 T testing.TB
55
56 // Name of the test. Will be used as the base folder for generated images.
57 // Slashes allowed and encouraged.
58 Name string
59
60 // The test site's files in txttar format.
61 Files string
62
63 // If not set, a temporary directory will be created.
64 WorkingDir string
65
66 // Set to true to print the temp dir used and keep it after the test.
67 PrintAndKeepTempDir bool
68
69 // Set to true to skip any assertions. Useful when adding new golden variants to a test.
70 DevMode bool
71
72 // Set to skip any assertions.
73 SkipAssertions bool
74
75 // Whether this represents a rebuild of the same site.
76 // Setting this to true will keep the previous golden image set.
77 Rebuild bool
78 }
79
80 // To rebuild all Golden image tests, run:
81 // GOARCH=amd64 go test -count 1 -run "^TestImagesGolden" ./resources/images/ ./tpl/images/ -writegoldenfiles
82 // Note that the golden files are created on amd64, so on other architectures you need to set GOARCH=amd64 as above.
83 var writeGoldenFiles = flag.Bool("writegoldenfiles", false, "Write golden image files to disk")
84
85 var DefaultGoldenOpts = GoldenImageTestOpts{}
86
87 func RunGolden(opts GoldenImageTestOpts) *hugolib.IntegrationTestBuilder {
88 opts.T.Helper()
89
90 c := hugolib.Test(opts.T, opts.Files, hugolib.TestOptWithConfig(func(conf *hugolib.IntegrationTestConfig) {
91 conf.NeedsOsFS = true
92 conf.WorkingDir = opts.WorkingDir
93 conf.PrintAndKeepTempDir = opts.PrintAndKeepTempDir
94 }))
95
96 codec := c.H.ResourceSpec.Imaging.Codec
97
98 c.AssertFileContent("public/index.html", "Home.")
99
100 outputDir := filepath.Join(c.H.Conf.WorkingDir(), "public", "images")
101 goldenBaseDir := filepath.Join("testdata", "images_golden")
102 goldenDir := filepath.Join(goldenBaseDir, filepath.FromSlash(opts.Name))
103 if *writeGoldenFiles {
104 c.Assert(htesting.IsRealCI(), qt.IsFalse)
105 if !opts.Rebuild {
106 c.Assert(os.MkdirAll(goldenBaseDir, 0o777), qt.IsNil)
107 c.Assert(os.RemoveAll(goldenDir), qt.IsNil)
108 }
109 c.Assert(hugio.CopyDir(hugofs.Os, outputDir, goldenDir, nil), qt.IsNil)
110 return c
111 }
112
113 if opts.SkipAssertions {
114 return c
115 }
116
117 if opts.DevMode {
118 c.Assert(htesting.IsRealCI(), qt.IsFalse)
119 return c
120 }
121
122 shouldSkip := func(d fs.DirEntry) bool {
123 if runtime.GOARCH == "arm64" {
124 // TODO(bep) figure out why this fails on arm64. I have inspected the images, and they look identical.
125 if d.Name() == "giphy_hu_bb052284cc220165.webp" {
126 c.Logf("skipping %s on %s", d.Name(), runtime.GOARCH)
127 return true
128 }
129 }
130 return false
131 }
132
133 decodeAll := func(f *os.File) []image.Image {
134 c.Helper()
135 var images []image.Image
136 v, err := codec.Decode(f)
137 c.Assert(err, qt.IsNil, qt.Commentf(f.Name()))
138
139 if anim, ok := v.(himage.AnimatedImage); ok {
140 images = anim.GetFrames()
141 } else {
142 images = append(images, v)
143 }
144 return images
145 }
146
147 entries1, err := os.ReadDir(outputDir)
148 c.Assert(err, qt.IsNil)
149 entries2, err := os.ReadDir(goldenDir)
150 c.Assert(err, qt.IsNil)
151 c.Assert(len(entries1), qt.Equals, len(entries2))
152 for i, e1 := range entries1 {
153 if shouldSkip(e1) {
154 continue
155 }
156 c.Assert(filepath.Ext(e1.Name()), qt.Not(qt.Equals), "")
157 func() {
158 e2 := entries2[i]
159
160 f1, err := os.Open(filepath.Join(outputDir, e1.Name()))
161 c.Assert(err, qt.IsNil)
162 defer f1.Close()
163
164 f2, err := os.Open(filepath.Join(goldenDir, e2.Name()))
165 c.Assert(err, qt.IsNil)
166 defer f2.Close()
167
168 imgs2 := decodeAll(f2)
169 imgs1 := decodeAll(f1)
170 c.Assert(len(imgs1), qt.Equals, len(imgs2))
171
172 if !UsesFMA {
173 c.Assert(e1, eq, e2)
174 _, err = f1.Seek(0, 0)
175 c.Assert(err, qt.IsNil)
176 _, err = f2.Seek(0, 0)
177 c.Assert(err, qt.IsNil)
178
179 hash1, _, err := hashing.XXHashFromReader(f1)
180 c.Assert(err, qt.IsNil)
181 hash2, _, err := hashing.XXHashFromReader(f2)
182 c.Assert(err, qt.IsNil)
183
184 c.Assert(hash1, qt.Equals, hash2)
185 }
186
187 for i, img1 := range imgs1 {
188 img2 := imgs2[i]
189 nrgba1 := image.NewNRGBA(img1.Bounds())
190 gift.New().Draw(nrgba1, img1)
191 nrgba2 := image.NewNRGBA(img2.Bounds())
192 gift.New().Draw(nrgba2, img2)
193 c.Assert(goldenEqual(nrgba1, nrgba2), qt.Equals, true, qt.Commentf(e1.Name()))
194 }
195 }()
196 }
197 return c
198 }
199
200 // goldenEqual compares two NRGBA images. It is used in golden tests only.
201 // A small tolerance is allowed on architectures using "fused multiply and add"
202 // (FMA) instruction to accommodate for floating-point rounding differences
203 // with control golden images that were generated on amd64 architecture.
204 // See https://golang.org/ref/spec#Floating_point_operators
205 // and https://github.com/gohugoio/hugo/issues/6387 for more information.
206 //
207 // Based on https://github.com/disintegration/gift/blob/a999ff8d5226e5ab14b64a94fca07c4ac3f357cf/gift_test.go#L598-L625
208 // Copyright (c) 2014-2019 Grigory Dryapak
209 // Licensed under the MIT License.
210 func goldenEqual(img1, img2 *image.NRGBA) bool {
211 maxDiff := 0
212 if runtime.GOARCH != "amd64" {
213 // The golden files are created using the AMD64 architecture.
214 // Be lenient on other platforms due to floaging point and dithering differences.
215 maxDiff = 15
216 }
217 if !img1.Rect.Eq(img2.Rect) {
218 return false
219 }
220 if len(img1.Pix) != len(img2.Pix) {
221 return false
222 }
223 for i := range img1.Pix {
224 diff := int(img1.Pix[i]) - int(img2.Pix[i])
225 if diff < 0 {
226 diff = -diff
227 }
228 if diff > maxDiff {
229 return false
230 }
231 }
232 return true
233 }
234
235 // We don't have a CI test environment for these, and there are known dithering issues that makes these time consuming to maintain.
236 // Go changed their JPEG implementation in Go 1.26, so we cannot run the golden tests on earlier versions. See https://go.dev/doc/go1.26#imagejpegpkgimagejpeg
•237 var SkipGoldenTests = htesting.GoMinorVersion() < 26 || runtime.GOARCH == "ppc64" || runtime.GOARCH == "ppc64le" || runtime.GOARCH == "s390x" || runtime.GOARCH == "arm64" || runtime.GOARCH == "arm" || runtime.GOARCH == "riscv64" || runtime.GOARCH == "386" || runtime.GOARCH == "loong64"
238
239 // UsesFMA indicates whether "fused multiply and add" (FMA) instruction is
240 // used. The command "grep FMADD go/test/codegen/floats.go" can help keep
241 // the FMA-using architecture list updated.
242 var UsesFMA = runtime.GOARCH == "s390x" ||
243 runtime.GOARCH == "ppc64" ||
244 runtime.GOARCH == "ppc64le" ||
245 runtime.GOARCH == "arm64" ||
246 runtime.GOARCH == "riscv64" ||
247 runtime.GOARCH == "loong64"