aboutsummaryrefslogtreecommitdiff
path: root/libgo/go/image/jpeg/fuzz_test.go
blob: 716f06f43cff2476d38a4ca788c290ad42e35f8a (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
// Copyright 2021 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.

package jpeg

import (
	"bytes"
	"image"
	"os"
	"path/filepath"
	"strings"
	"testing"
)

func FuzzDecode(f *testing.F) {
	testdata, err := os.ReadDir("../testdata")
	if err != nil {
		f.Fatalf("failed to read testdata directory: %s", err)
	}
	for _, de := range testdata {
		if de.IsDir() || !strings.HasSuffix(de.Name(), ".jpeg") {
			continue
		}
		b, err := os.ReadFile(filepath.Join("../testdata", de.Name()))
		if err != nil {
			f.Fatalf("failed to read testdata: %s", err)
		}
		f.Add(b)
	}

	f.Fuzz(func(t *testing.T, b []byte) {
		cfg, _, err := image.DecodeConfig(bytes.NewReader(b))
		if err != nil {
			return
		}
		if cfg.Width*cfg.Height > 1e6 {
			return
		}
		img, typ, err := image.Decode(bytes.NewReader(b))
		if err != nil || typ != "jpeg" {
			return
		}
		for q := 1; q <= 100; q++ {
			var w bytes.Buffer
			err := Encode(&w, img, &Options{Quality: q})
			if err != nil {
				t.Fatalf("failed to encode valid image: %s", err)
			}
			img1, err := Decode(&w)
			if err != nil {
				t.Fatalf("failed to decode roundtripped image: %s", err)
			}
			got := img1.Bounds()
			want := img.Bounds()
			if !got.Eq(want) {
				t.Fatalf("roundtripped image bounds have changed, got: %s, want: %s", got, want)
			}
		}
	})
}