|
| 1 | +// Copyright 2025 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 misc |
| 6 | + |
| 7 | +// This file defines tests of the source.test ("Run tests and |
| 8 | +// benchmarks") code action. |
| 9 | + |
| 10 | +import ( |
| 11 | + "os" |
| 12 | + "path/filepath" |
| 13 | + "testing" |
| 14 | + |
| 15 | + "golang.org/x/tools/gopls/internal/protocol" |
| 16 | + "golang.org/x/tools/gopls/internal/settings" |
| 17 | + . "golang.org/x/tools/gopls/internal/test/integration" |
| 18 | +) |
| 19 | + |
| 20 | +func TestRunTestsAndBenchmarks(t *testing.T) { |
| 21 | + file := filepath.Join(t.TempDir(), "out") |
| 22 | + os.Setenv("TESTFILE", file) |
| 23 | + |
| 24 | + const src = ` |
| 25 | +-- go.mod -- |
| 26 | +module example.com |
| 27 | +go 1.19 |
| 28 | +
|
| 29 | +-- a/a.go -- |
| 30 | +package a |
| 31 | +
|
| 32 | +-- a/a_test.go -- |
| 33 | +package a |
| 34 | +
|
| 35 | +import ( |
| 36 | + "os" |
| 37 | + "testing" |
| 38 | +) |
| 39 | +
|
| 40 | +func Test(t *testing.T) { |
| 41 | + os.WriteFile(os.Getenv("TESTFILE"), []byte("ok"), 0644) |
| 42 | +} |
| 43 | +
|
| 44 | +` |
| 45 | + Run(t, src, func(t *testing.T, env *Env) { |
| 46 | + env.OpenFile("a/a_test.go") |
| 47 | + loc := env.RegexpSearch("a/a_test.go", "WriteFile") |
| 48 | + |
| 49 | + // Request code actions. (settings.GoTest is special: |
| 50 | + // it is returned only when explicitly requested.) |
| 51 | + actions, err := env.Editor.Server.CodeAction(env.Ctx, &protocol.CodeActionParams{ |
| 52 | + TextDocument: protocol.TextDocumentIdentifier{URI: loc.URI}, |
| 53 | + Range: loc.Range, |
| 54 | + Context: protocol.CodeActionContext{ |
| 55 | + Only: []protocol.CodeActionKind{settings.GoTest}, |
| 56 | + }, |
| 57 | + }) |
| 58 | + if err != nil { |
| 59 | + t.Fatal(err) |
| 60 | + } |
| 61 | + if len(actions) != 1 { |
| 62 | + t.Fatalf("CodeAction returned %#v, want one source.test action", actions) |
| 63 | + } |
| 64 | + if actions[0].Command == nil { |
| 65 | + t.Fatalf("CodeActions()[0] has no Command") |
| 66 | + } |
| 67 | + |
| 68 | + // Execute test. |
| 69 | + // (ExecuteCommand fails if the test fails.) |
| 70 | + t.Logf("Running %s...", actions[0].Title) |
| 71 | + env.ExecuteCommand(&protocol.ExecuteCommandParams{ |
| 72 | + Command: actions[0].Command.Command, |
| 73 | + Arguments: actions[0].Command.Arguments, |
| 74 | + }, nil) |
| 75 | + |
| 76 | + // Check test had expected side effect. |
| 77 | + data, err := os.ReadFile(file) |
| 78 | + if string(data) != "ok" { |
| 79 | + t.Fatalf("Test did not write expected content of %s; ReadFile returned (%q, %v)", file, data, err) |
| 80 | + } |
| 81 | + }) |
| 82 | +} |
0 commit comments