Debian Codegraph @

gopls/internal/test/integration/expectation.go

raw symbols SCIP
1 // Copyright 2020 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 integration
6
7 import (
8 "bytes"
9 "fmt"
10 "maps"
11 "regexp"
12 "slices"
13 "strings"
14
15 "github.com/google/go-cmp/cmp"
16 "golang.org/x/tools/gopls/internal/protocol"
17 "golang.org/x/tools/gopls/internal/server"
18 "golang.org/x/tools/gopls/internal/util/constraints"
19 )
20
21 var (
22 // InitialWorkspaceLoad is an expectation that the workspace initial load has
23 // completed. It is verified via workdone reporting.
24 InitialWorkspaceLoad = CompletedWork(server.DiagnosticWorkTitle(server.FromInitialWorkspaceLoad), 1, false)
25 )
26
27 // A Verdict is the result of checking an expectation against the current
28 // editor state.
29 type Verdict int
30
31 // Order matters for the following constants: verdicts are sorted in order of
32 // decisiveness.
33 const (
34 // Met indicates that an expectation is satisfied by the current state.
35 Met Verdict = iota
36 // Unmet indicates that an expectation is not currently met, but could be met
37 // in the future.
38 Unmet
39 // Unmeetable indicates that an expectation cannot be satisfied in the
40 // future.
41 Unmeetable
42 )
43
44 func (v Verdict) String() string {
45 switch v {
46 case Met:
47 return "Met"
48 case Unmet:
49 return "Unmet"
50 case Unmeetable:
51 return "Unmeetable"
52 }
53 return fmt.Sprintf("unrecognized verdict %d", v)
54 }
55
56 // An Expectation is an expected property of the state of the LSP client.
57 // The Check function reports whether the property is met.
58 //
59 // Expectations are combinators. By composing them, tests may express
60 // complex expectations in terms of simpler ones.
61 type Expectation struct {
62 // Check returns the verdict of this expectation for the given state.
63 // If the vertict is not [Met], the second result should return a reason
64 // that the verdict is not (yet) met.
65 Check func(State) (Verdict, string)
66
67 // Description holds a noun-phrase identifying what the expectation checks.
68 //
69 // TODO(rfindley): revisit existing descriptions to ensure they compose nicely.
70 Description string
71 }
72
73 // OnceMet returns an Expectation that, once the precondition is met, asserts
74 // that mustMeet is met.
75 func OnceMet(pre, post Expectation) Expectation {
76 check := func(s State) (Verdict, string) {
77 switch v, why := pre.Check(s); v {
78 case Unmeetable, Unmet:
79 return v, fmt.Sprintf("precondition is %s: %s", v, why)
80 case Met:
81 v, why := post.Check(s)
82 if v != Met {
83 return Unmeetable, fmt.Sprintf("postcondition is not met:\n%s", indent(why))
84 }
85 return Met, ""
86 default:
87 panic(fmt.Sprintf("unknown precondition verdict %s", v))
88 }
89 }
90 desc := fmt.Sprintf("once the following is met:\n%s\nmust have:\n%s",
91 indent(pre.Description), indent(post.Description))
92 return Expectation{
93 Check: check,
94 Description: desc,
95 }
96 }
97
98 // Not inverts the sense of an expectation: a met expectation is unmet, and an
99 // unmet expectation is met.
100 func Not(e Expectation) Expectation {
101 check := func(s State) (Verdict, string) {
102 switch v, _ := e.Check(s); v {
103 case Met:
104 return Unmet, "condition unexpectedly satisfied"
105 case Unmet, Unmeetable:
106 return Met, ""
107 default:
108 panic(fmt.Sprintf("unexpected verdict %v", v))
109 }
110 }
111 return Expectation{
112 Check: check,
113 Description: fmt.Sprintf("not: %s", e.Description),
114 }
115 }
116
117 // AnyOf returns an expectation that is satisfied when any of the given
118 // expectations is met.
119 func AnyOf(anyOf ...Expectation) Expectation {
120 if len(anyOf) == 1 {
121 return anyOf[0] // avoid unnecessary boilerplate
122 }
123 check := func(s State) (Verdict, string) {
124 for _, e := range anyOf {
125 verdict, _ := e.Check(s)
126 if verdict == Met {
127 return Met, ""
128 }
129 }
130 return Unmet, "none of the expectations were met"
131 }
132 description := describeExpectations(anyOf...)
133 return Expectation{
134 Check: check,
135 Description: fmt.Sprintf("any of:\n%s", description),
136 }
137 }
138
139 // AllOf expects that all given expectations are met.
140 func AllOf(allOf ...Expectation) Expectation {
141 if len(allOf) == 1 {
142 return allOf[0] // avoid unnecessary boilerplate
143 }
144 check := func(s State) (Verdict, string) {
145 var (
146 verdict = Met
147 reason string
148 )
149 for _, e := range allOf {
150 v, why := e.Check(s)
151 if v > verdict {
152 verdict = v
153 reason = why
154 }
155 }
156 return verdict, reason
157 }
158 desc := describeExpectations(allOf...)
159 return Expectation{
160 Check: check,
161 Description: fmt.Sprintf("all of:\n%s", indent(desc)),
162 }
163 }
164
165 func describeExpectations(expectations ...Expectation) string {
166 var descriptions []string
167 for _, e := range expectations {
168 descriptions = append(descriptions, e.Description)
169 }
170 return strings.Join(descriptions, "\n")
171 }
172
173 // ReadDiagnostics is an Expectation that stores the current diagnostics for
174 // fileName in into, whenever it is evaluated.
175 //
176 // It can be used in combination with OnceMet or AfterChange to capture the
177 // state of diagnostics when other expectations are satisfied.
178 func ReadDiagnostics(fileName string, into *protocol.PublishDiagnosticsParams) Expectation {
179 check := func(s State) (Verdict, string) {
180 diags, ok := s.diagnostics[fileName]
181 if !ok {
182 return Unmeetable, fmt.Sprintf("no diagnostics for %q", fileName)
183 }
184 *into = *diags
185 return Met, ""
186 }
187 return Expectation{
188 Check: check,
189 Description: fmt.Sprintf("read diagnostics for %q", fileName),
190 }
191 }
192
193 // ReadAllDiagnostics is an expectation that stores all published diagnostics
194 // into the provided map, whenever it is evaluated.
195 //
196 // It can be used in combination with OnceMet or AfterChange to capture the
197 // state of diagnostics when other expectations are satisfied.
198 func ReadAllDiagnostics(into *map[string]*protocol.PublishDiagnosticsParams) Expectation {
199 check := func(s State) (Verdict, string) {
200 allDiags := maps.Clone(s.diagnostics)
201 *into = allDiags
202 return Met, ""
203 }
204 return Expectation{
205 Check: check,
206 Description: "read all diagnostics",
207 }
208 }
209
210 // ShownDocument asserts that the client has received a
211 // ShowDocumentRequest for the given URI.
212 func ShownDocument(uri protocol.URI) Expectation {
213 check := func(s State) (Verdict, string) {
214 for _, params := range s.showDocument {
215 if params.URI == uri {
216 return Met, ""
217 }
218 }
219 return Unmet, fmt.Sprintf("no ShowDocumentRequest received for %s", uri)
220 }
221 return Expectation{
222 Check: check,
223 Description: fmt.Sprintf("received window/showDocument for URI %s", uri),
224 }
225 }
226
227 // ShownDocuments is an expectation that appends each showDocument
228 // request into the provided slice, whenever it is evaluated.
229 //
230 // It can be used in combination with OnceMet or AfterChange to
231 // capture the set of showDocument requests when other expectations
232 // are satisfied.
233 func ShownDocuments(into *[]*protocol.ShowDocumentParams) Expectation {
234 check := func(s State) (Verdict, string) {
235 *into = append(*into, s.showDocument...)
236 return Met, ""
237 }
238 return Expectation{
239 Check: check,
240 Description: "read shown documents",
241 }
242 }
243
244 // NoShownMessage asserts that the editor has not received a ShowMessage.
245 func NoShownMessage(containing string) Expectation {
246 check := func(s State) (Verdict, string) {
247 for _, m := range s.showMessage {
248 if strings.Contains(m.Message, containing) {
249 // Format the message (which may contain newlines) as a block quote.
250 msg := fmt.Sprintf("\"\"\"\n%s\n\"\"\"", strings.TrimSpace(m.Message))
251 return Unmeetable, fmt.Sprintf("observed the following message:\n%s", indent(msg))
252 }
253 }
254 return Met, ""
255 }
256 var desc string
257 if containing != "" {
258 desc = fmt.Sprintf("received no ShowMessage containing %q", containing)
259 } else {
260 desc = "received no ShowMessage requests"
261 }
262 return Expectation{
263 Check: check,
264 Description: desc,
265 }
266 }
267
268 // ShownMessage asserts that the editor has received a ShowMessageRequest
269 // containing the given substring.
270 func ShownMessage(containing string) Expectation {
271 check := func(s State) (Verdict, string) {
272 for _, m := range s.showMessage {
273 if strings.Contains(m.Message, containing) {
274 return Met, ""
275 }
276 }
277 return Unmet, fmt.Sprintf("no ShowMessage containing %q", containing)
278 }
279 return Expectation{
280 Check: check,
281 Description: fmt.Sprintf("received window/showMessage containing %q", containing),
282 }
283 }
284
285 // ShownMessageRequest asserts that the editor has received a
286 // ShowMessageRequest with message matching the given regular expression.
287 func ShownMessageRequest(matchingRegexp string) Expectation {
288 msgRE := regexp.MustCompile(matchingRegexp)
289 check := func(s State) (Verdict, string) {
290 if len(s.showMessageRequest) == 0 {
291 return Unmet, "no ShowMessageRequest have been received"
292 }
293 for _, m := range s.showMessageRequest {
294 if msgRE.MatchString(m.Message) {
295 return Met, ""
296 }
297 }
298 return Unmet, fmt.Sprintf("no ShowMessageRequest (out of %d) match %q", len(s.showMessageRequest), matchingRegexp)
299 }
300 return Expectation{
301 Check: check,
302 Description: fmt.Sprintf("ShowMessageRequest matching %q", matchingRegexp),
303 }
304 }
305
306 // DoneDiagnosingChanges expects that diagnostics are complete from common
307 // change notifications: didOpen, didChange, didSave, didChangeWatchedFiles,
308 // and didClose.
309 //
310 // This can be used when multiple notifications may have been sent, such as
311 // when a didChange is immediately followed by a didSave. It is insufficient to
312 // simply await NoOutstandingWork, because the LSP client has no control over
313 // when the server starts processing a notification. Therefore, we must keep
314 // track of
315 func (e *Env) DoneDiagnosingChanges() Expectation {
316 stats := e.Editor.Stats()
317 statsBySource := map[server.ModificationSource]uint64{
318 server.FromDidOpen: stats.DidOpen,
319 server.FromDidChange: stats.DidChange,
320 server.FromDidSave: stats.DidSave,
321 server.FromDidChangeWatchedFiles: stats.DidChangeWatchedFiles,
322 server.FromDidClose: stats.DidClose,
323 server.FromDidChangeConfiguration: stats.DidChangeConfiguration,
324 }
325
326 var expected []server.ModificationSource
327 for k, v := range statsBySource {
328 if v > 0 {
329 expected = append(expected, k)
330 }
331 }
332
333 // Sort for stability.
334 slices.Sort(expected)
335
336 var all []Expectation
337 for _, source := range expected {
338 all = append(all, CompletedWork(server.DiagnosticWorkTitle(source), statsBySource[source], true))
339 }
340
341 return AllOf(all...)
342 }
343
344 // AfterChange expects that the given expectations will be met after all
345 // state-changing notifications have been processed by the server.
346 // Specifically, it awaits the awaits completion of the process of diagnosis
347 // after the following notifications, before checking the given expectations:
348 // - textDocument/didOpen
349 // - textDocument/didChange
350 // - textDocument/didSave
351 // - textDocument/didClose
352 // - workspace/didChangeWatchedFiles
353 // - workspace/didChangeConfiguration
354 func (e *Env) AfterChange(expectations ...Expectation) {
355 e.TB.Helper()
356 e.OnceMet(
357 e.DoneDiagnosingChanges(),
358 expectations...,
359 )
360 }
361
362 // DoneWithOpen expects all didOpen notifications currently sent by the editor
363 // to be completely processed.
364 func (e *Env) DoneWithOpen() Expectation {
365 opens := e.Editor.Stats().DidOpen
366 return CompletedWork(server.DiagnosticWorkTitle(server.FromDidOpen), opens, true)
367 }
368
369 // StartedChange expects that the server has at least started processing all
370 // didChange notifications sent from the client.
371 func (e *Env) StartedChange() Expectation {
372 changes := e.Editor.Stats().DidChange
373 return StartedWork(server.DiagnosticWorkTitle(server.FromDidChange), changes)
374 }
375
376 // DoneWithChange expects all didChange notifications currently sent by the
377 // editor to be completely processed.
378 func (e *Env) DoneWithChange() Expectation {
379 changes := e.Editor.Stats().DidChange
380 return CompletedWork(server.DiagnosticWorkTitle(server.FromDidChange), changes, true)
381 }
382
383 // DoneWithSave expects all didSave notifications currently sent by the editor
384 // to be completely processed.
385 func (e *Env) DoneWithSave() Expectation {
386 saves := e.Editor.Stats().DidSave
387 return CompletedWork(server.DiagnosticWorkTitle(server.FromDidSave), saves, true)
388 }
389
390 // StartedChangeWatchedFiles expects that the server has at least started
391 // processing all didChangeWatchedFiles notifications sent from the client.
392 func (e *Env) StartedChangeWatchedFiles() Expectation {
393 changes := e.Editor.Stats().DidChangeWatchedFiles
394 return StartedWork(server.DiagnosticWorkTitle(server.FromDidChangeWatchedFiles), changes)
395 }
396
397 // DoneWithChangeWatchedFiles expects all didChangeWatchedFiles notifications
398 // currently sent by the editor to be completely processed.
399 func (e *Env) DoneWithChangeWatchedFiles() Expectation {
400 changes := e.Editor.Stats().DidChangeWatchedFiles
401 return CompletedWork(server.DiagnosticWorkTitle(server.FromDidChangeWatchedFiles), changes, true)
402 }
403
404 // DoneWithClose expects all didClose notifications currently sent by the
405 // editor to be completely processed.
406 func (e *Env) DoneWithClose() Expectation {
407 changes := e.Editor.Stats().DidClose
408 return CompletedWork(server.DiagnosticWorkTitle(server.FromDidClose), changes, true)
409 }
410
411 // StartedWork expect a work item to have been started >= atLeast times.
412 //
413 // See CompletedWork.
414 func StartedWork(title string, atLeast uint64) Expectation {
415 check := func(s State) (Verdict, string) {
416 started := s.startedWork[title]
417 if started >= atLeast {
418 return Met, ""
419 }
420 return Unmet, fmt.Sprintf("started work %d %s", started, pluralize("time", started))
421 }
422 return Expectation{
423 Check: check,
424 Description: fmt.Sprintf("started work %q at least %d %s", title, atLeast, pluralize("time", atLeast)),
425 }
426 }
427
428 // CompletedWork expects a work item to have been completed >= atLeast times.
429 //
430 // Since the Progress API doesn't include any hidden metadata, we must use the
431 // progress notification title to identify the work we expect to be completed.
432 func CompletedWork(title string, count uint64, atLeast bool) Expectation {
433 check := func(s State) (Verdict, string) {
434 completed := s.completedWork[title]
435 if completed == count || atLeast && completed > count {
436 return Met, ""
437 }
438 return Unmet, fmt.Sprintf("completed %d %s", completed, pluralize("time", completed))
439 }
440 desc := fmt.Sprintf("completed work %q %v %s", title, count, pluralize("time", count))
441 if atLeast {
442 desc = fmt.Sprintf("completed work %q at least %d %s", title, count, pluralize("time", count))
443 }
444 return Expectation{
445 Check: check,
446 Description: desc,
447 }
448 }
449
450 // pluralize adds an 's' suffix to name if n > 1.
451 func pluralize[T constraints.Integer](name string, n T) string {
452 if n > 1 {
453 return name + "s"
454 }
455 return name
456 }
457
458 type WorkStatus struct {
459 // Last seen message from either `begin` or `report` progress.
460 Msg string
461 // Message sent with `end` progress message.
462 EndMsg string
463 }
464
465 // CompletedProgressToken expects that workDone progress is complete for the given
466 // progress token. When non-nil WorkStatus is provided, it will be filled
467 // when the expectation is met.
468 //
469 // If the token is not a progress token that the client has seen, this
470 // expectation is Unmeetable.
471 func CompletedProgressToken(token protocol.ProgressToken, into *WorkStatus) Expectation {
472 check := func(s State) (Verdict, string) {
473 work, ok := s.work[token]
474 if !ok {
475 return Unmeetable, "no matching work items"
476 }
477 if work.complete {
478 if into != nil {
479 into.Msg = work.msg
480 into.EndMsg = work.endMsg
481 }
482 return Met, ""
483 }
484 return Unmet, fmt.Sprintf("work is not complete; last message: %q", work.msg)
485 }
486 return Expectation{
487 Check: check,
488 Description: fmt.Sprintf("completed work for token %v", token),
489 }
490 }
491
492 // CompletedProgress expects that there is exactly one workDone progress with
493 // the given title, and is satisfied when that progress completes. If it is
494 // met, the corresponding status is written to the into argument.
495 //
496 // TODO(rfindley): refactor to eliminate the redundancy with CompletedWork.
497 // This expectation is a vestige of older workarounds for asynchronous command
498 // execution.
499 func CompletedProgress(title string, into *WorkStatus) Expectation {
500 check := func(s State) (Verdict, string) {
501 var work *workProgress
502 for _, w := range s.work {
503 if w.title == title {
504 if work != nil {
505 return Unmeetable, "multiple matching work items"
506 }
507 work = w
508 }
509 }
510 if work == nil {
511 return Unmeetable, "no matching work items"
512 }
513 if work.complete {
514 if into != nil {
515 into.Msg = work.msg
516 into.EndMsg = work.endMsg
517 }
518 return Met, ""
519 }
520 return Unmet, fmt.Sprintf("work is not complete; last message: %q", work.msg)
521 }
522 desc := fmt.Sprintf("exactly 1 completed workDoneProgress with title %v", title)
523 return Expectation{
524 Check: check,
525 Description: desc,
526 }
527 }
528
529 // OutstandingWork expects a work item to be outstanding. The given title must
530 // be an exact match, whereas the given msg must only be contained in the work
531 // item's message.
532 func OutstandingWork(title, msg string) Expectation {
533 check := func(s State) (Verdict, string) {
534 for _, work := range s.work {
535 if work.complete {
536 continue
537 }
538 if work.title == title && strings.Contains(work.msg, msg) {
539 return Met, ""
540 }
541 }
542 return Unmet, "no matching work"
543 }
544 return Expectation{
545 Check: check,
546 Description: fmt.Sprintf("outstanding work: %q containing %q", title, msg),
547 }
548 }
549
550 // NoOutstandingWork asserts that there is no work initiated using the LSP
551 // $/progress API that has not completed.
552 //
553 // If non-nil, the ignore func is used to ignore certain work items for the
554 // purpose of this check.
555 //
556 // TODO(rfindley): consider refactoring to treat outstanding work the same way
557 // we treat diagnostics: with an algebra of filters.
558 func NoOutstandingWork(ignore func(title, msg string) bool) Expectation {
559 check := func(s State) (Verdict, string) {
560 for _, w := range s.work {
561 if w.complete {
562 continue
563 }
564 if w.title == "" {
565 // A token that has been created but not yet used.
566 //
567 // TODO(rfindley): this should be separated in the data model: until
568 // the "begin" notification, work should not be in progress.
569 continue
570 }
571 if ignore != nil && ignore(w.title, w.msg) {
572 continue
573 }
574 return Unmet, fmt.Sprintf("found outstanding work %q: %q", w.title, w.msg)
575 }
576 return Met, ""
577 }
578 return Expectation{
579 Check: check,
580 Description: "no outstanding work",
581 }
582 }
583
584 // IgnoreTelemetryPromptWork may be used in conjunction with NoOutStandingWork
585 // to ignore the telemetry prompt.
586 func IgnoreTelemetryPromptWork(title, msg string) bool {
587 return title == server.TelemetryPromptWorkTitle
588 }
589
590 // NoErrorLogs asserts that the client has not received any log messages of
591 // error severity.
592 func NoErrorLogs() Expectation {
593 return NoLogMatching(protocol.Error, "")
594 }
595
596 // LogMatching asserts that the client has received a log message
597 // of type typ matching the regexp re a certain number of times.
598 //
599 // The count argument specifies the expected number of matching logs. If
600 // atLeast is set, this is a lower bound, otherwise there must be exactly count
601 // matching logs.
602 //
603 // Logs are asynchronous to other LSP messages, so this expectation should not
604 // be used with combinators such as OnceMet or AfterChange that assert on
605 // ordering with respect to other operations.
606 func LogMatching(typ protocol.MessageType, re string, count int, atLeast bool) Expectation {
607 rec, err := regexp.Compile(re)
608 if err != nil {
609 panic(err)
610 }
611 check := func(state State) (Verdict, string) {
612 var found int
613 for _, msg := range state.logs {
614 if msg.Type == typ && rec.Match([]byte(msg.Message)) {
615 found++
616 }
617 }
618 // Check for an exact or "at least" match.
619 if found == count || (found >= count && atLeast) {
620 return Met, ""
621 }
622 // If we require an exact count, and have received more than expected, the
623 // expectation can never be met.
624 verdict := Unmet
625 if found > count && !atLeast {
626 verdict = Unmeetable
627 }
628 return verdict, fmt.Sprintf("found %d matching logs", found)
629 }
630 desc := fmt.Sprintf("log message matching %q expected %v times", re, count)
631 if atLeast {
632 desc = fmt.Sprintf("log message matching %q expected at least %v times", re, count)
633 }
634 return Expectation{
635 Check: check,
636 Description: desc,
637 }
638 }
639
640 // NoLogMatching asserts that the client has not received a log message
641 // of type typ matching the regexp re. If re is an empty string, any log
642 // message is considered a match.
643 func NoLogMatching(typ protocol.MessageType, re string) Expectation {
644 var r *regexp.Regexp
645 if re != "" {
646 var err error
647 r, err = regexp.Compile(re)
648 if err != nil {
649 panic(err)
650 }
651 }
652 check := func(state State) (Verdict, string) {
653 for _, msg := range state.logs {
654 if msg.Type != typ {
655 continue
656 }
657 if r == nil || r.Match([]byte(msg.Message)) {
658 return Unmeetable, fmt.Sprintf("found matching log %q", msg.Message)
659 }
660 }
661 return Met, ""
662 }
663 desc := fmt.Sprintf("no %s log messages", typ)
664 if re != "" {
665 desc += fmt.Sprintf(" matching %q", re)
666 }
667 return Expectation{
668 Check: check,
669 Description: desc,
670 }
671 }
672
673 // FileWatchMatching expects that a file registration matches re.
674 func FileWatchMatching(re string) Expectation {
675 return Expectation{
676 Check: checkFileWatch(re, Met, Unmet),
677 Description: fmt.Sprintf("file watch matching %q", re),
678 }
679 }
680
681 // NoFileWatchMatching expects that no file registration matches re.
682 func NoFileWatchMatching(re string) Expectation {
683 return Expectation{
684 Check: checkFileWatch(re, Unmet, Met),
685 Description: fmt.Sprintf("no file watch matching %q", re),
686 }
687 }
688
689 func checkFileWatch(re string, onMatch, onNoMatch Verdict) func(State) (Verdict, string) {
690 rec := regexp.MustCompile(re)
691 return func(s State) (Verdict, string) {
692 r := s.registeredCapabilities["workspace/didChangeWatchedFiles"]
693 watchers := jsonProperty(r.RegisterOptions, "watchers").([]any)
694 for _, watcher := range watchers {
695 pattern := jsonProperty(watcher, "globPattern").(string)
696 if rec.MatchString(pattern) {
697 return onMatch, fmt.Sprintf("matches watcher pattern %q", pattern)
698 }
699 }
700 return onNoMatch, "no matching watchers"
701 }
702 }
703
704 // jsonProperty extracts a value from a path of JSON property names, assuming
705 // the default encoding/json unmarshaling to the empty interface (i.e.: that
706 // JSON objects are unmarshalled as map[string]interface{})
707 //
708 // For example, if obj is unmarshalled from the following json:
709 //
710 // {
711 // "foo": { "bar": 3 }
712 // }
713 //
714 // Then jsonProperty(obj, "foo", "bar") will be 3.
715 func jsonProperty(obj any, path ...string) any {
716 if len(path) == 0 || obj == nil {
717 return obj
718 }
719 m := obj.(map[string]any)
720 return jsonProperty(m[path[0]], path[1:]...)
721 }
722
723 func formatDiagnostic(d protocol.Diagnostic) string {
724 return fmt.Sprintf("%d:%d [%s]: %s\n", d.Range.Start.Line, d.Range.Start.Character, d.Source, d.Message)
725 }
726
727 // Diagnostics asserts that there is at least one diagnostic matching the given
728 // filters.
729 func Diagnostics(filters ...DiagnosticFilter) Expectation {
730 check := func(s State) (Verdict, string) {
731 diags := flattenDiagnostics(s)
732 for _, filter := range filters {
733 var filtered []flatDiagnostic
734 for _, d := range diags {
735 if filter.check(d.name, d.diag) {
736 filtered = append(filtered, d)
737 }
738 }
739 if len(filtered) == 0 {
740 // Reprinting the description of the filters is too verbose.
741 //
742 // We can probably do better here, but for now just format the
743 // diagnostics.
744 var b bytes.Buffer
745 for name, params := range s.diagnostics {
746 fmt.Fprintf(&b, "\t%s (version %d):\n", name, params.Version)
747 for _, d := range params.Diagnostics {
748 fmt.Fprintf(&b, "\t\t%s", formatDiagnostic(d))
749 }
750 }
751 return Unmet, fmt.Sprintf("diagnostics:\n%s", b.String())
752 }
753 diags = filtered
754 }
755 return Met, ""
756 }
757 var descs []string
758 for _, filter := range filters {
759 descs = append(descs, filter.desc)
760 }
761 return Expectation{
762 Check: check,
763 Description: "any diagnostics " + strings.Join(descs, ", "),
764 }
765 }
766
767 // NoDiagnostics asserts that there are no diagnostics matching the given
768 // filters. Notably, if no filters are supplied this assertion checks that
769 // there are no diagnostics at all, for any file.
770 func NoDiagnostics(filters ...DiagnosticFilter) Expectation {
771 check := func(s State) (Verdict, string) {
772 diags := flattenDiagnostics(s)
773 for _, filter := range filters {
774 var filtered []flatDiagnostic
775 for _, d := range diags {
776 if filter.check(d.name, d.diag) {
777 filtered = append(filtered, d)
778 }
779 }
780 diags = filtered
781 }
782 if len(diags) > 0 {
783 d := diags[0]
784 why := fmt.Sprintf("have diagnostic: %s: %v", d.name, formatDiagnostic(d.diag))
785 return Unmet, why
786 }
787 return Met, ""
788 }
789 var descs []string
790 for _, filter := range filters {
791 descs = append(descs, filter.desc)
792 }
793 return Expectation{
794 Check: check,
795 Description: "no diagnostics " + strings.Join(descs, ", "),
796 }
797 }
798
799 type flatDiagnostic struct {
800 name string
801 diag protocol.Diagnostic
802 }
803
804 func flattenDiagnostics(state State) []flatDiagnostic {
805 var result []flatDiagnostic
806 for name, diags := range state.diagnostics {
807 for _, diag := range diags.Diagnostics {
808 result = append(result, flatDiagnostic{name, diag})
809 }
810 }
811 return result
812 }
813
814 // -- Diagnostic filters --
815
816 // A DiagnosticFilter filters the set of diagnostics, for assertion with
817 // Diagnostics or NoDiagnostics.
818 type DiagnosticFilter struct {
819 desc string
820 check func(name string, _ protocol.Diagnostic) bool
821 }
822
823 // ForFile filters to diagnostics matching the sandbox-relative file name.
824 func ForFile(name string) DiagnosticFilter {
825 return DiagnosticFilter{
826 desc: fmt.Sprintf("for file %q", name),
827 check: func(diagName string, _ protocol.Diagnostic) bool {
828 return diagName == name
829 },
830 }
831 }
832
833 // FromSource filters to diagnostics matching the given diagnostics source.
834 func FromSource(source string) DiagnosticFilter {
835 return DiagnosticFilter{
836 desc: fmt.Sprintf("with source %q", source),
837 check: func(_ string, d protocol.Diagnostic) bool {
838 return d.Source == source
839 },
840 }
841 }
842
843 // AtRegexp filters to diagnostics in the file with sandbox-relative path name,
844 // at the first position matching the given regexp pattern.
845 //
846 // TODO(rfindley): pass in the editor to expectations, so that they may depend
847 // on editor state and AtRegexp can be a function rather than a method.
848 func (e *Env) AtRegexp(name, pattern string) DiagnosticFilter {
849 loc := e.RegexpSearch(name, pattern)
850 return DiagnosticFilter{
851 desc: fmt.Sprintf("at the first position (%v) matching %#q in %q", loc.Range.Start, pattern, name),
852 check: func(diagName string, d protocol.Diagnostic) bool {
853 return diagName == name && d.Range.Start == loc.Range.Start
854 },
855 }
856 }
857
858 // AtPosition filters to diagnostics at location name:line:character, for a
859 // sandbox-relative path name.
860 //
861 // Line and character are 0-based, and character measures UTF-16 codes.
862 //
863 // Note: prefer the more readable AtRegexp.
864 func AtPosition(name string, line, character uint32) DiagnosticFilter {
865 pos := protocol.Position{Line: line, Character: character}
866 return DiagnosticFilter{
867 desc: fmt.Sprintf("at %s:%d:%d", name, line, character),
868 check: func(diagName string, d protocol.Diagnostic) bool {
869 return diagName == name && d.Range.Start == pos
870 },
871 }
872 }
873
874 // WithMessage filters to diagnostics whose message contains the given
875 // substring.
876 func WithMessage(substring string) DiagnosticFilter {
877 return DiagnosticFilter{
878 desc: fmt.Sprintf("with message containing %q", substring),
879 check: func(_ string, d protocol.Diagnostic) bool {
880 return strings.Contains(d.Message, substring)
881 },
882 }
883 }
884
885 // WithSeverityTags filters to diagnostics whose severity and tags match
886 // the given expectation.
887 func WithSeverityTags(diagName string, severity protocol.DiagnosticSeverity, tags []protocol.DiagnosticTag) DiagnosticFilter {
888 return DiagnosticFilter{
889 desc: fmt.Sprintf("with diagnostic %q with severity %q and tag %#q", diagName, severity, tags),
890 check: func(_ string, d protocol.Diagnostic) bool {
891 return d.Source == diagName && d.Severity == severity && cmp.Equal(d.Tags, tags)
892 },
893 }
894 }