github.com/yunabe/lgo@v0.0.0-20190709125917-42c42d410fdf/converter/format_test.go (about) 1 package converter 2 3 import ( 4 "fmt" 5 "testing" 6 ) 7 8 func TestFormat(t *testing.T) { 9 tests := []struct { 10 name string 11 src string 12 err string 13 want string 14 // If true, use a golden file instead of watn. 15 useGolden bool 16 }{{ 17 name: "error", 18 src: "\"", 19 err: "1:1: string literal not terminated", 20 }, { 21 name: "oneline", 22 src: "x:=10", 23 want: "x := 10", 24 }, { 25 name: "twolines", 26 src: "x := 10\ny:=x*x", 27 want: "x := 10\ny := x * x", 28 }, { 29 name: "leading_trailing_emptylines", 30 src: ` 31 32 var x int 33 34 `, 35 want: "var x int", 36 }, { 37 name: "fixindent", 38 src: `func f(x int) { 39 if(x > 0) { 40 return x 41 } 42 return 0 43 } 44 `, 45 want: `func f(x int) { 46 if x > 0 { 47 return x 48 } 49 return 0 50 }`, 51 }, { 52 name: "sort_imports", 53 src: `import ( 54 "sort" 55 56 "fmt" 57 "github.com/lgo" 58 "bytes" 59 ) 60 }`, 61 want: `import ( 62 "sort" 63 64 "bytes" 65 "fmt" 66 "github.com/lgo" 67 )`, 68 }, { 69 name: "comment_only1", 70 src: "// comment", 71 want: "// comment", 72 }, { 73 name: "comment_only2", 74 src: "/* comnent */", 75 want: "/* comnent */", 76 }, { 77 name: "golden", 78 useGolden: true, 79 src: `// first line comment 80 81 // f is a func 82 func f() { 83 84 // f body 85 } 86 // g is a func 87 func g(){} 88 89 // h is a func 90 func h() {/*do nothing*/} 91 92 // i is an int 93 var i int 94 95 type s struct{ 96 n float32 97 xy int 98 abc string 99 100 // comment1 101 z bool // comment2 102 } 103 `, 104 }, 105 } 106 for _, tc := range tests { 107 t.Run(tc.name, func(t *testing.T) { 108 got, err := Format(tc.src) 109 if err == nil && tc.err != "" { 110 t.Fatalf("got no error; want %q", tc.err) 111 } 112 if err != nil && err.Error() != tc.err { 113 t.Fatalf("got %q; want %q", err, tc.err) 114 } 115 if tc.useGolden { 116 checkGolden(t, got, fmt.Sprintf("testdata/format_%s.golden", tc.name)) 117 return 118 } 119 if got != tc.want { 120 t.Fatalf("got %q; want %q", got, tc.want) 121 } 122 }) 123 } 124 }