github.com/blend/go-sdk@v1.20240719.1/profanity/generics_test.go (about) 1 /* 2 3 Copyright (c) 2024 - Present. Blend Labs, Inc. All rights reserved 4 Use of this source code is governed by a MIT license that can be found in the LICENSE file. 5 6 */ 7 8 package profanity 9 10 import ( 11 "testing" 12 13 "github.com/blend/go-sdk/assert" 14 ) 15 16 func TestNoGenericDecls(t *testing.T) { 17 for _, tc := range []struct { 18 Name string 19 Enabled bool 20 Filename string 21 Contents string 22 ErrLine int 23 }{ 24 { 25 Name: "no generics", 26 Enabled: true, 27 Filename: "main.go", 28 Contents: `package main 29 30 func SumInts(m map[string]int) int { 31 var s int 32 for _, v := range m { 33 s += v 34 } 35 return s 36 } 37 `, 38 ErrLine: 0, 39 }, 40 { 41 Name: "generic function", 42 Enabled: true, 43 Filename: "main.go", 44 Contents: `package main 45 46 func SumIntsOrFloats[K comparable, V int64 | float64](m map[K]V) V { 47 var s V 48 for _, v := range m { 49 s += v 50 } 51 return s 52 } 53 `, 54 ErrLine: 3, 55 }, 56 { 57 Name: "generic function when disabled", 58 Enabled: false, 59 Filename: "main.go", 60 Contents: `package main 61 62 func SumIntsOrFloats[K comparable, V int64 | float64](m map[K]V) V { 63 var s V 64 for _, v := range m { 65 s += v 66 } 67 return s 68 } 69 `, 70 ErrLine: 0, 71 }, 72 { 73 Name: "generic type", 74 Enabled: true, 75 Filename: "main.go", 76 Contents: `package main 77 78 type ( 79 Foo[T any] struct { 80 Bar T 81 } 82 ) 83 `, 84 ErrLine: 4, 85 }, 86 { 87 Name: "generic type when disabled", 88 Enabled: false, 89 Filename: "main.go", 90 Contents: `package main 91 92 type ( 93 Foo[T any] struct { 94 Bar T 95 } 96 ) 97 `, 98 ErrLine: 0, 99 }, 100 { 101 Name: "interface union", 102 Enabled: true, 103 Filename: "main.go", 104 Contents: `package main 105 106 type ( 107 Num interface { 108 int | float64 109 } 110 ) 111 `, 112 ErrLine: 5, 113 }, 114 { 115 Name: "underlying type in interface", 116 Enabled: true, 117 Filename: "main.go", 118 Contents: `package main 119 120 type ( 121 Int interface { 122 ~int 123 } 124 ) 125 `, 126 ErrLine: 5, 127 }, 128 { 129 Name: "bitwise ops ok outside of interface", 130 Enabled: true, 131 Filename: "main.go", 132 Contents: `package main 133 134 func Foo() { 135 _ = 0 | 1 136 } 137 `, 138 ErrLine: 0, 139 }, 140 { 141 Name: "not go source file", 142 Enabled: true, 143 Filename: "README.txt", 144 Contents: `README`, 145 ErrLine: 0, 146 }, 147 } { 148 t.Run(tc.Name, func(t *testing.T) { 149 assert := assert.New(t) 150 151 rule := NoGenericDecls{ 152 Enabled: tc.Enabled, 153 } 154 155 res := rule.Check(tc.Filename, []byte(tc.Contents)) 156 if tc.ErrLine > 0 { 157 assert.Nil(res.Err) 158 assert.False(res.OK) 159 assert.Equal(tc.Filename, res.File) 160 assert.Equal(tc.ErrLine, res.Line) 161 } else { 162 assert.Nil(res.Err) 163 assert.True(res.OK) 164 } 165 }) 166 } 167 }