Source file src/image/gif/fuzz_test.go

     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  
     5  package gif
     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  	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(), ".gif") {
    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 != "gif" {
    46  			return
    47  		}
    48  		for q := 1; q <= 256; q++ {
    49  			var w bytes.Buffer
    50  			err := Encode(&w, img, &Options{NumColors: q})
    51  			if err != nil {
    52  				t.Fatalf("failed to encode valid image: %s", err)
    53  			}
    54  			img1, err := Decode(&w)
    55  			if err != nil {
    56  				t.Fatalf("failed to decode roundtripped image: %s", err)
    57  			}
    58  			got := img1.Bounds()
    59  			want := img.Bounds()
    60  			if !got.Eq(want) {
    61  				t.Fatalf("roundtripped image bounds have changed, got: %v, want: %v", got, want)
    62  			}
    63  		}
    64  	})
    65  }
    66  

View as plain text