Debian Codegraph @

format/fuzz_test.go

raw symbols SCIP
1 // Copyright (c) 2021, Daniel Martí <[email protected]>
2 // See LICENSE for licensing information
3
4 package format
5
6 import (
7 "errors"
8 "fmt"
9 "go/scanner"
10 "path/filepath"
11 "strings"
12 "testing"
13
14 qt "github.com/frankban/quicktest"
15 "golang.org/x/tools/txtar"
16 )
17
18 func FuzzFormat(f *testing.F) {
19 // Initialize the corpus with the Go files from our test scripts.
20 paths, err := filepath.Glob(filepath.Join("..", "testdata", "script", "*.txtar"))
21 qt.Assert(f, err, qt.IsNil)
22 qt.Assert(f, paths, qt.Not(qt.HasLen), 0)
23 for _, path := range paths {
24 archive, err := txtar.ParseFile(path)
25 qt.Assert(f, err, qt.IsNil)
26 for _, file := range archive.Files {
27 f.Logf("adding %s from %s", file.Name, path)
28 if strings.HasSuffix(file.Name, ".go") || strings.Contains(file.Name, ".go.") {
29 f.Add(string(file.Data), int8(18), false) // -lang=1.18
30 f.Add(string(file.Data), int8(1), false) // -lang=1.1
31 f.Add(string(file.Data), int8(18), true) // -lang=1.18 -extra
32 }
33 }
34 }
35
36 f.Fuzz(func(t *testing.T, src string,
37 majorVersion int8, // Empty version if negative, 1.N otherwise.
38 extraRules bool,
39 ) {
40 // TODO: also fuzz Options.ModulePath
41 opts := Options{ExtraRules: extraRules}
42 if majorVersion >= 0 {
43 opts.LangVersion = fmt.Sprintf("1.%d", majorVersion)
44 }
45
46 orig := []byte(src)
47 formatted, err := Source(orig, opts)
48 if errors.As(err, &scanner.ErrorList{}) {
49 return // invalid syntax from parsing
50 }
51 qt.Assert(t, err, qt.IsNil)
52 _ = formatted
53
54 // TODO: verify that the result is idempotent
55
56 // TODO: verify that, if the input was valid Go 1.N syntax,
57 // so is the output (how? go/parser lacks an option)
58
59 // TODO: check calling format.Node directly as well
60
61 qt.Assert(t, string(orig), qt.Equals, src,
62 qt.Commentf("input source bytes were modified"))
63 })
64 }