Debian Codegraph @

report.go

raw
1 // Licensed under the MIT license, see LICENSE file for details.
2
3 package qt
4
5 import (
6 "bytes"
7 "fmt"
8 "go/ast"
9 "go/parser"
10 "go/printer"
11 "go/token"
12 "io"
13 "reflect"
14 "runtime"
15 "strings"
16 "testing"
17 )
18
19 // reportParams holds parameters for reporting a test error.
20 type reportParams struct {
21 // args holds all the arguments passed to the checker.
22 args []Arg
23 // comments optionally holds comments passed when performing the check.
24 comments []Comment
25 // notes holds notes added while doing the check.
26 notes []note
27 }
28
29 // Unquoted indicates that the string must not be pretty printed in the failure
30 // output. This is useful when a checker calls note and does not want the
31 // provided value to be quoted.
32 type Unquoted string
33
34 // SuppressedIfLong indicates that the value must be suppressed if verbose
35 // testing is off and the pretty printed version of the value is long. This is
36 // useful when a checker calls note and does not want the provided value to be
37 // printed in non-verbose test runs if the value is too long.
38 type SuppressedIfLong struct {
39 // Value holds the original annotated value.
40 Value any
41 }
42
43 // longValueLines holds the number of lines after which a value is long.
44 const longValueLines = 10
45
46 // report generates a failure report for the given error, optionally including
47 // in the output the checker arguments, comment and notes included in the
48 // provided report parameters.
49 func report(err error, p reportParams) string {
50 var buf bytes.Buffer
51 buf.WriteByte('\n')
52 writeError(&buf, err, p)
53 writeStack(&buf)
54 return buf.String()
55 }
56
57 // writeError writes a pretty formatted output of the given error using the
58 // provided report parameters.
59 func writeError(w io.Writer, err error, p reportParams) {
60 ptrs := make(map[string]any)
61 values := make(map[string]string)
62
63 printPair := func(key string, value any) {
64 fmt.Fprintln(w, key+":")
65 var v string
66
67 if u, ok := value.(Unquoted); ok {
68 // Output the raw string without quotes.
69 v = string(u)
70 } else if s, ok := value.(SuppressedIfLong); ok {
71 // Check whether the output is too long and must be suppressed.
72 v = Format(s.Value)
73 if !testingVerbose() {
74 if n := strings.Count(v, "\n"); n > longValueLines {
75 fmt.Fprint(w, prefixf(prefix, "<suppressed due to length (%d lines), use -v for full output>", n))
76 return
77 }
78 }
79 } else {
80 // Check whether the output has been already seen.
81 v = Format(value)
82 isPtr := reflect.ValueOf(value).Kind() == reflect.Pointer
83 if k := values[v]; k != "" {
84 if previousValue, ok := ptrs[k]; ok && isPtr && previousValue != value {
85 fmt.Fprint(w, prefixf(prefix, "<same as %q but different pointer value>", k))
86 return
87 }
88 fmt.Fprint(w, prefixf(prefix, "<same as %q>", k))
89 return
90 }
91 if isPtr {
92 ptrs[key] = value
93 }
94 }
95
96 values[v] = key
97 fmt.Fprint(w, prefixf(prefix, "%s", v))
98 }
99
100 // Write the checker error.
101 if err != ErrSilent {
102 printPair("error", Unquoted(err.Error()))
103 }
104
105 // Write comments if provided.
106 for _, c := range p.comments {
107 if comment := c.String(); comment != "" {
108 printPair("comment", Unquoted(comment))
109 }
110 }
111
112 // Write notes if present.
113 for _, n := range p.notes {
114 printPair(n.key, n.value)
115 }
116 if IsBadCheck(err) || err == ErrSilent {
117 // For errors in the checker invocation or for silent errors, do not
118 // show output from args.
119 return
120 }
121 // Write provided args.
122 for _, arg := range p.args {
123 printPair(arg.Name, arg.Value)
124 }
125 }
126
127 // testingVerbose is defined as a variable for testing.
128 var testingVerbose = func() bool {
129 return testing.Verbose()
130 }
131
132 // writeStack writes the traceback information for the current failure into the
133 // provided writer.
134 func writeStack(w io.Writer) {
135 fmt.Fprintln(w, "stack:")
136 pc := make([]uintptr, 8)
137 sg := &stmtGetter{
138 fset: token.NewFileSet(),
139 files: make(map[string]*ast.File, 8),
140 config: &printer.Config{
141 Mode: printer.UseSpaces,
142 Tabwidth: 4,
143 },
144 }
145 runtime.Callers(5, pc)
146 frames := runtime.CallersFrames(pc)
147 thisPackage := reflect.TypeOf(Unquoted("")).PkgPath() + "."
148 for {
149 frame, more := frames.Next()
150 if strings.HasPrefix(frame.Function, "testing.") {
151 // Stop before getting back to stdlib test runner calls.
152 break
153 }
154 if fname := strings.TrimPrefix(frame.Function, thisPackage); fname != frame.Function {
155 if ast.IsExported(fname) {
156 // Continue without printing frames for quicktest exported API.
157 continue
158 }
159 // Stop when entering quicktest internal calls.
160 // This is useful for instance when using qtsuite.
161 break
162 }
163 fmt.Fprint(w, prefixf(prefix, "%s:%d", frame.File, frame.Line))
164 if strings.HasSuffix(frame.File, ".go") {
165 stmt, err := sg.Get(frame.File, frame.Line)
166 if err != nil {
167 fmt.Fprint(w, prefixf(prefix+prefix, "<%s>", err))
168 } else {
169 fmt.Fprint(w, prefixf(prefix+prefix, "%s", stmt))
170 }
171 }
172 if !more {
173 // There are no more callers.
174 break
175 }
176 }
177 }
178
179 type stmtGetter struct {
180 fset *token.FileSet
181 files map[string]*ast.File
182 config *printer.Config
183 }
184
185 // Get returns the lines of code of the statement at the given file and line.
186 func (sg *stmtGetter) Get(file string, line int) (string, error) {
187 f := sg.files[file]
188 if f == nil {
189 var err error
190 f, err = parser.ParseFile(sg.fset, file, nil, parser.ParseComments)
191 if err != nil {
192 return "", fmt.Errorf("cannot parse source file: %s", err)
193 }
194 sg.files[file] = f
195 }
196 var stmt string
197 ast.Inspect(f, func(n ast.Node) bool {
198 if n == nil || stmt != "" {
199 return false
200 }
201 pos := sg.fset.Position(n.Pos()).Line
202 end := sg.fset.Position(n.End()).Line
203 // Go < v1.9 reports the line where the statements ends, not the line
204 // where it begins.
205 if line == pos || line == end {
206 var buf bytes.Buffer
207 // TODO: include possible comment after the statement.
208 sg.config.Fprint(&buf, sg.fset, &printer.CommentedNode{
209 Node: n,
210 Comments: f.Comments,
211 })
212 stmt = buf.String()
213 return false
214 }
215 return pos < line && line <= end
216 })
217 return stmt, nil
218 }
219
220 // prefixf formats the given string with the given args. It also inserts the
221 // final newline if needed and indentation with the given prefix.
222 func prefixf(prefix, format string, args ...any) string {
223 var buf []byte
224 s := strings.TrimSuffix(fmt.Sprintf(format, args...), "\n")
225 for _, line := range strings.Split(s, "\n") {
226 buf = append(buf, prefix...)
227 buf = append(buf, line...)
228 buf = append(buf, '\n')
229 }
230 return string(buf)
231 }
232
233 // note holds a key/value annotation.
234 type note struct {
235 key string
236 value any
237 }
238
239 // prefix is the string used to indent blocks of output.
240 const prefix = " "