golang.org/x/tools/gopls@v0.15.3/internal/test/integration/misc/extract_test.go (about) 1 // Copyright 2022 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 package misc 5 6 import ( 7 "testing" 8 9 "golang.org/x/tools/gopls/internal/test/compare" 10 . "golang.org/x/tools/gopls/internal/test/integration" 11 12 "golang.org/x/tools/gopls/internal/protocol" 13 ) 14 15 func TestExtractFunction(t *testing.T) { 16 const files = ` 17 -- go.mod -- 18 module mod.com 19 20 go 1.12 21 -- main.go -- 22 package main 23 24 func Foo() int { 25 a := 5 26 return a 27 } 28 ` 29 Run(t, files, func(t *testing.T, env *Env) { 30 env.OpenFile("main.go") 31 loc := env.RegexpSearch("main.go", `a := 5\n.*return a`) 32 actions, err := env.Editor.CodeAction(env.Ctx, loc, nil) 33 if err != nil { 34 t.Fatal(err) 35 } 36 37 // Find the extract function code action. 38 var extractFunc *protocol.CodeAction 39 for _, action := range actions { 40 if action.Kind == protocol.RefactorExtract && action.Title == "Extract function" { 41 extractFunc = &action 42 break 43 } 44 } 45 if extractFunc == nil { 46 t.Fatal("could not find extract function action") 47 } 48 49 env.ApplyCodeAction(*extractFunc) 50 want := `package main 51 52 func Foo() int { 53 return newFunction() 54 } 55 56 func newFunction() int { 57 a := 5 58 return a 59 } 60 ` 61 if got := env.BufferText("main.go"); got != want { 62 t.Fatalf("TestFillStruct failed:\n%s", compare.Text(want, got)) 63 } 64 }) 65 }