github.com/moov-io/imagecashletter@v0.10.1/test/fuzz/fuzz_test.go (about)

     1  // Copyright 2020 The Moov Authors
     2  // Use of this source code is governed by an Apache License
     3  // license that can be found in the LICENSE file.
     4  
     5  package main
     6  
     7  import (
     8  	"io"
     9  	"io/fs"
    10  	"os"
    11  	"path/filepath"
    12  	"strings"
    13  	"testing"
    14  
    15  	"github.com/moov-io/imagecashletter"
    16  )
    17  
    18  func FuzzReaderWriterICL(f *testing.F) {
    19  	populateCorpus(f, true)
    20  
    21  	f.Fuzz(func(t *testing.T, contents string) {
    22  		file, _ := imagecashletter.NewReader(strings.NewReader(contents)).Read()
    23  
    24  		checkFileHeader(file.Header)
    25  		file.Validate()
    26  
    27  		w := imagecashletter.NewWriter(io.Discard, imagecashletter.WriteVariableLineLengthOption())
    28  		w.Write(&file)
    29  
    30  		w = imagecashletter.NewWriter(io.Discard, imagecashletter.WriteEbcdicEncodingOption())
    31  		w.Write(&file)
    32  	})
    33  }
    34  
    35  func FuzzReaderWriterJSON(f *testing.F) {
    36  	populateCorpus(f, false)
    37  
    38  	f.Fuzz(func(t *testing.T, contents string) {
    39  		file, _ := imagecashletter.FileFromJSON([]byte(contents))
    40  		if file == nil {
    41  			return
    42  		}
    43  
    44  		checkFileHeader(file.Header)
    45  		file.Validate()
    46  
    47  		w := imagecashletter.NewWriter(io.Discard, imagecashletter.WriteVariableLineLengthOption())
    48  		w.Write(file)
    49  
    50  		w = imagecashletter.NewWriter(io.Discard, imagecashletter.WriteEbcdicEncodingOption())
    51  		w.Write(file)
    52  	})
    53  }
    54  
    55  func populateCorpus(f *testing.F, icl bool) {
    56  	f.Helper()
    57  
    58  	err := filepath.Walk(filepath.Join("..", "..", "test", "testdata"), func(path string, info fs.FileInfo, err error) error {
    59  		if info.IsDir() {
    60  			return nil
    61  		}
    62  
    63  		ext := filepath.Ext(strings.ToLower(path))
    64  		if ((ext == ".x937" || ext == "") && icl) || (ext == ".json" && !icl) {
    65  			bs, err := os.ReadFile(path)
    66  			if err != nil {
    67  				f.Fatal(err)
    68  			}
    69  			f.Add(string(bs))
    70  		}
    71  		return nil
    72  	})
    73  	if err != nil {
    74  		f.Fatal(err)
    75  	}
    76  }
    77  
    78  func checkFileHeader(h imagecashletter.FileHeader) int {
    79  	if h.ImmediateDestination != "" || h.ImmediateOrigin != "" {
    80  		return 1
    81  	}
    82  	if !h.FileCreationDate.IsZero() || !h.FileCreationTime.IsZero() {
    83  		return 1
    84  	}
    85  	if h.ImmediateDestinationName != "" || h.ImmediateOriginName != "" {
    86  		return 1
    87  	}
    88  	if h.CountryCode != "" {
    89  		return 1
    90  	}
    91  	return 0
    92  }