Source file
src/image/jpeg/fuzz_test.go
1
2
3
4
5 package jpeg
6
7 import (
8 "bytes"
9 "image"
10 "os"
11 "path/filepath"
12 "strings"
13 "testing"
14 )
15
16 func FuzzDecode(f *testing.F) {
17 testdata, err := os.ReadDir("../testdata")
18 if err != nil {
19 f.Fatalf("failed to read testdata directory: %s", err)
20 }
21 for _, de := range testdata {
22 if de.IsDir() || !strings.HasSuffix(de.Name(), ".jpeg") {
23 continue
24 }
25 b, err := os.ReadFile(filepath.Join("../testdata", de.Name()))
26 if err != nil {
27 f.Fatalf("failed to read testdata: %s", err)
28 }
29 f.Add(b)
30 }
31
32 f.Fuzz(func(t *testing.T, b []byte) {
33 cfg, _, err := image.DecodeConfig(bytes.NewReader(b))
34 if err != nil {
35 return
36 }
37 if cfg.Width*cfg.Height > 1e6 {
38 return
39 }
40 img, typ, err := image.Decode(bytes.NewReader(b))
41 if err != nil || typ != "jpeg" {
42 return
43 }
44 for q := 1; q <= 100; q++ {
45 var w bytes.Buffer
46 err := Encode(&w, img, &Options{Quality: q})
47 if err != nil {
48 t.Fatalf("failed to encode valid image: %s", err)
49 }
50 img1, err := Decode(&w)
51 if err != nil {
52 t.Fatalf("failed to decode roundtripped image: %s", err)
53 }
54 got := img1.Bounds()
55 want := img.Bounds()
56 if !got.Eq(want) {
57 t.Fatalf("roundtripped image bounds have changed, got: %s, want: %s", got, want)
58 }
59 }
60 })
61 }
62
View as plain text