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

View as plain text