src/archive/zip/fuzz_test.go GO 82 lines View on github.com → Search inside
1// Copyright 2021 The Go Authors. All rights reserved.2// Use of this source code is governed by a BSD-style3// license that can be found in the LICENSE file.45package zip67import (8	"bytes"9	"io"10	"os"11	"path/filepath"12	"testing"13)1415func FuzzReader(f *testing.F) {16	testdata, err := os.ReadDir("testdata")17	if err != nil {18		f.Fatalf("failed to read testdata directory: %s", err)19	}20	for _, de := range testdata {21		if de.IsDir() {22			continue23		}24		b, err := os.ReadFile(filepath.Join("testdata", de.Name()))25		if err != nil {26			f.Fatalf("failed to read testdata: %s", err)27		}28		f.Add(b)29	}3031	f.Fuzz(func(t *testing.T, b []byte) {32		r, err := NewReader(bytes.NewReader(b), int64(len(b)))33		if err != nil {34			return35		}3637		type file struct {38			header  *FileHeader39			content []byte40		}41		files := []file{}4243		for _, f := range r.File {44			fr, err := f.Open()45			if err != nil {46				continue47			}48			content, err := io.ReadAll(fr)49			if err != nil {50				continue51			}52			files = append(files, file{header: &f.FileHeader, content: content})53			if _, err := r.Open(f.Name); err != nil {54				continue55			}56		}5758		// If we were unable to read anything out of the archive don't59		// bother trying to roundtrip it.60		if len(files) == 0 {61			return62		}6364		w := NewWriter(io.Discard)65		for _, f := range files {66			ww, err := w.CreateHeader(f.header)67			if err != nil {68				t.Fatalf("unable to write previously parsed header: %s", err)69			}70			if _, err := ww.Write(f.content); err != nil {71				t.Fatalf("unable to write previously parsed content: %s", err)72			}73		}7475		if err := w.Close(); err != nil {76			t.Fatalf("Unable to write archive: %s", err)77		}7879		// TODO: We may want to check if the archive roundtrips.80	})81}

Code quality findings 4

Ensure errors are handled or logged
warning correctness unhandled-error
if err != nil {
Ensure errors are handled or logged
warning correctness unhandled-error
if err != nil {
Can cause issues on Windows consider filepath.Join instead
info correctness path-join-windows
b, err := os.ReadFile(filepath.Join("testdata", de.Name()))
Multiple appends without pre-allocation; use make() with capacity when size is known
info performance append-without-prealloc
files = append(files, file{header: &f.FileHeader, content: content})

Get this view in your editor

Same data, no extra tab — call code_get_file + code_get_findings over MCP from Claude/Cursor/Copilot.