1// Copyright 2021 The Go Authors. All rights reserved.
2// Use of this source code is governed by a BSD-style
3// license that can be found in the LICENSE file.
4
5package jpeg
6
7import (
8	"bytes"
9	"image"
10	"os"
11	"path/filepath"
12	"strings"
13	"testing"
14)
15
16func FuzzDecode(f *testing.F) {
17	if testing.Short() {
18		f.Skip("Skipping in short mode")
19	}
20
21	testdata, err := os.ReadDir("../testdata")
22	if err != nil {
23		f.Fatalf("failed to read testdata directory: %s", err)
24	}
25	for _, de := range testdata {
26		if de.IsDir() || !strings.HasSuffix(de.Name(), ".jpeg") {
27			continue
28		}
29		b, err := os.ReadFile(filepath.Join("../testdata", de.Name()))
30		if err != nil {
31			f.Fatalf("failed to read testdata: %s", err)
32		}
33		f.Add(b)
34	}
35
36	f.Fuzz(func(t *testing.T, b []byte) {
37		cfg, _, err := image.DecodeConfig(bytes.NewReader(b))
38		if err != nil {
39			return
40		}
41		if cfg.Width*cfg.Height > 1e6 {
42			return
43		}
44		img, typ, err := image.Decode(bytes.NewReader(b))
45		if err != nil || typ != "jpeg" {
46			return
47		}
48		for q := 1; q <= 100; q++ {
49			var w bytes.Buffer
50			err := Encode(&w, img, &Options{Quality: q})
51			if err != nil {
52				t.Errorf("failed to encode valid image: %s", err)
53				continue
54			}
55			img1, err := Decode(&w)
56			if err != nil {
57				t.Errorf("failed to decode roundtripped image: %s", err)
58				continue
59			}
60			got := img1.Bounds()
61			want := img.Bounds()
62			if !got.Eq(want) {
63				t.Errorf("roundtripped image bounds have changed, got: %s, want: %s", got, want)
64			}
65		}
66	})
67}
68