Source file src/image/png/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 png
     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(), ".png") {
    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 != "png" {
    42  			return
    43  		}
    44  		levels := []CompressionLevel{
    45  			DefaultCompression,
    46  			NoCompression,
    47  			BestSpeed,
    48  			BestCompression,
    49  		}
    50  		for _, l := range levels {
    51  			var w bytes.Buffer
    52  			e := &Encoder{CompressionLevel: l}
    53  			err = e.Encode(&w, img)
    54  			if err != nil {
    55  				t.Fatalf("failed to encode valid image: %s", err)
    56  			}
    57  			img1, err := Decode(&w)
    58  			if err != nil {
    59  				t.Fatalf("failed to decode roundtripped image: %s", err)
    60  			}
    61  			got := img1.Bounds()
    62  			want := img.Bounds()
    63  			if !got.Eq(want) {
    64  				t.Fatalf("roundtripped image bounds have changed, got: %s, want: %s", got, want)
    65  			}
    66  		}
    67  	})
    68  }
    69  

View as plain text