github.com/terraform-linters/tflint@v0.51.2-0.20240520175844-3750771571b6/integrationtest/langserver/text_document_did_change_test.go (about) 1 package main 2 3 import ( 4 "bytes" 5 "encoding/json" 6 "fmt" 7 "os" 8 "testing" 9 10 "github.com/google/go-cmp/cmp" 11 lsp "github.com/sourcegraph/go-lsp" 12 ) 13 14 func Test_textDocumentDidChange(t *testing.T) { 15 withinFixtureDir(t, "workdir", func(dir string) { 16 src, err := os.ReadFile(dir + "/main.tf") 17 if err != nil { 18 t.Fatal(err) 19 } 20 uri := pathToURI(dir + "/main.tf") 21 22 stdin, stdout, plugin := startServer(t, dir+"/.tflint.hcl") 23 defer plugin.Clean() 24 25 req, err := json.Marshal(jsonrpcMessage{ 26 ID: 0, 27 Method: "textDocument/didChange", 28 Params: lsp.DidChangeTextDocumentParams{ 29 TextDocument: lsp.VersionedTextDocumentIdentifier{ 30 TextDocumentIdentifier: lsp.TextDocumentIdentifier{ 31 URI: uri, 32 }, 33 Version: 2, 34 }, 35 ContentChanges: []lsp.TextDocumentContentChangeEvent{ 36 { 37 Text: ` 38 resource "aws_instance" "foo" { 39 ami = "ami-12345678" 40 }`, 41 }, 42 }, 43 }, 44 JSONRPC: "2.0", 45 }) 46 if err != nil { 47 t.Fatal(err) 48 } 49 50 go func() { 51 fmt.Fprint(stdin, initializeRequest()) 52 fmt.Fprint(stdin, didOpenRequest(uri, string(src), t)) 53 fmt.Fprint(stdin, toJSONRPC2(string(req))) 54 fmt.Fprint(stdin, shutdownRequest()) 55 fmt.Fprint(stdin, exitRequest()) 56 }() 57 58 buf := new(bytes.Buffer) 59 if _, err := buf.ReadFrom(stdout); err != nil { 60 t.Fatal(err) 61 } 62 63 expected := initializeResponse() + didOpenResponse(uri, t) + noDiagnosticsResponse(uri, t) + emptyResponse() 64 if !cmp.Equal(expected, buf.String()) { 65 t.Fatalf("Diff: %s", cmp.Diff(expected, buf.String())) 66 } 67 68 // Assert no changes for actual files 69 changedSrc, err := os.ReadFile(dir + "/main.tf") 70 if err != nil { 71 t.Fatal(err) 72 } 73 if string(src) != string(changedSrc) { 74 t.Fatal("textDocument/didChange event is rewriting the actual files") 75 } 76 }) 77 } 78 79 func noDiagnosticsResponse(uri lsp.DocumentURI, t *testing.T) string { 80 didChangeResponse, err := json.Marshal(jsonrpcMessage{ 81 Method: "textDocument/publishDiagnostics", 82 Params: lsp.PublishDiagnosticsParams{ 83 URI: uri, 84 Diagnostics: []lsp.Diagnostic{}, 85 }, 86 JSONRPC: "2.0", 87 }) 88 if err != nil { 89 t.Fatal(err) 90 } 91 92 return toJSONRPC2(string(didChangeResponse)) 93 }