forked from go-telegram-bot-api/telegram-bot-api
-
Notifications
You must be signed in to change notification settings - Fork 50
Expand file tree
/
Copy pathapi_parity_test.go
More file actions
358 lines (306 loc) · 8.65 KB
/
api_parity_test.go
File metadata and controls
358 lines (306 loc) · 8.65 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
//go:build api_parity
package tgbotapi
import (
"encoding/json"
"fmt"
"go/ast"
"go/parser"
"go/token"
"os"
"path/filepath"
"reflect"
"sort"
"strconv"
"strings"
"testing"
)
type parityDoc struct {
Methods map[string]json.RawMessage `json:"methods"`
Types map[string]parityType `json:"types"`
}
type parityType struct {
Fields []parityField `json:"fields"`
}
type parityField struct {
Name string `json:"name"`
}
type parityTypeDecl struct {
Expr ast.Expr
}
func TestAPIParityMethods(t *testing.T) {
doc := loadParityDoc(t)
index := loadPackageIndex(t)
implementedMethods := index.methodNames
for _, name := range []string{"getMe", "getWebhookInfo"} {
implementedMethods[name] = struct{}{}
}
missingMethods := make([]string, 0)
for name := range doc.Methods {
if _, ok := implementedMethods[name]; !ok {
missingMethods = append(missingMethods, name)
}
}
extraMethods := make([]string, 0)
for name := range implementedMethods {
if _, ok := doc.Methods[name]; !ok {
extraMethods = append(extraMethods, name)
}
}
sort.Strings(missingMethods)
sort.Strings(extraMethods)
if len(missingMethods) > 0 || len(extraMethods) > 0 {
t.Fatalf("method parity failed, missing=%v extra=%v", missingMethods, extraMethods)
}
}
func TestAPIParityTypesAndFields(t *testing.T) {
doc := loadParityDoc(t)
index := loadPackageIndex(t)
allowedMissingTypeNames := map[string]string{
"ChatBoostSourcePremium": "type name conflicts with exported constant",
"ChatBoostSourceGiftCode": "type name conflicts with exported constant",
"ChatBoostSourceGiveaway": "type name conflicts with exported constant",
"MessageOriginUser": "type name conflicts with exported constant",
"MessageOriginHiddenUser": "type name conflicts with exported constant",
"MessageOriginChat": "type name conflicts with exported constant",
"MessageOriginChannel": "type name conflicts with exported constant",
"ReactionTypeEmoji": "type name conflicts with exported constant",
"ReactionTypeCustomEmoji": "type name conflicts with exported constant",
"ReactionTypePaid": "type name conflicts with exported constant",
}
missingTypes := make([]string, 0)
missingFields := make(map[string][]string)
for typeName, apiType := range doc.Types {
if _, ok := index.types[typeName]; !ok {
if _, allowed := allowedMissingTypeNames[typeName]; allowed {
continue
}
missingTypes = append(missingTypes, typeName)
continue
}
if len(apiType.Fields) == 0 {
continue
}
fields, ok := index.collectJSONFields(typeName)
if !ok {
missingFields[typeName] = []string{"<non-struct>"}
continue
}
for _, field := range apiType.Fields {
if _, exists := fields[field.Name]; !exists {
missingFields[typeName] = append(missingFields[typeName], field.Name)
}
}
}
unusedAllowed := make([]string, 0)
for typeName := range allowedMissingTypeNames {
if _, ok := index.types[typeName]; ok {
unusedAllowed = append(unusedAllowed, typeName)
}
}
sort.Strings(missingTypes)
sort.Strings(unusedAllowed)
missingFieldTypes := make([]string, 0, len(missingFields))
for typeName, fields := range missingFields {
sort.Strings(fields)
missingFieldTypes = append(missingFieldTypes, typeName)
}
sort.Strings(missingFieldTypes)
if len(missingTypes) > 0 || len(missingFieldTypes) > 0 || len(unusedAllowed) > 0 {
builder := strings.Builder{}
if len(missingTypes) > 0 {
builder.WriteString(fmt.Sprintf("missing types: %v\n", missingTypes))
}
if len(missingFieldTypes) > 0 {
builder.WriteString("types with missing fields:\n")
for _, typeName := range missingFieldTypes {
builder.WriteString(fmt.Sprintf("- %s: %v\n", typeName, missingFields[typeName]))
}
}
if len(unusedAllowed) > 0 {
builder.WriteString(fmt.Sprintf("allowed missing types no longer needed: %v\n", unusedAllowed))
}
t.Fatalf("type parity failed\n%s", builder.String())
}
}
type packageIndex struct {
types map[string]parityTypeDecl
methodNames map[string]struct{}
}
func loadPackageIndex(t *testing.T) *packageIndex {
t.Helper()
entries, err := os.ReadDir(".")
if err != nil {
t.Fatalf("read dir: %v", err)
}
goFiles := make([]string, 0)
for _, entry := range entries {
name := entry.Name()
if entry.IsDir() {
continue
}
if !strings.HasSuffix(name, ".go") || strings.HasSuffix(name, "_test.go") {
continue
}
goFiles = append(goFiles, name)
}
sort.Strings(goFiles)
fset := token.NewFileSet()
index := &packageIndex{
types: make(map[string]parityTypeDecl),
methodNames: make(map[string]struct{}),
}
for _, file := range goFiles {
parsed, err := parser.ParseFile(fset, file, nil, parser.ParseComments)
if err != nil {
t.Fatalf("parse %s: %v", file, err)
}
for _, decl := range parsed.Decls {
switch current := decl.(type) {
case *ast.GenDecl:
if current.Tok != token.TYPE {
continue
}
for _, spec := range current.Specs {
typeSpec := spec.(*ast.TypeSpec)
index.types[typeSpec.Name.Name] = parityTypeDecl{Expr: typeSpec.Type}
}
case *ast.FuncDecl:
if current.Recv == nil || current.Name == nil || current.Name.Name != "method" {
continue
}
if current.Body == nil || len(current.Body.List) == 0 {
continue
}
for _, statement := range current.Body.List {
returnStatement, ok := statement.(*ast.ReturnStmt)
if !ok || len(returnStatement.Results) != 1 {
continue
}
literal, ok := returnStatement.Results[0].(*ast.BasicLit)
if !ok || literal.Kind != token.STRING {
continue
}
methodName, err := strconv.Unquote(literal.Value)
if err != nil {
t.Fatalf("unquote method literal in %s: %v", file, err)
}
index.methodNames[methodName] = struct{}{}
break
}
}
}
}
return index
}
func loadParityDoc(t *testing.T) parityDoc {
t.Helper()
content, err := os.ReadFile(filepath.Join(".", "api.json"))
if err != nil {
if os.IsNotExist(err) {
t.Skip("api.json not found, skipping api parity tests")
return parityDoc{}
}
t.Fatalf("read api.json: %v", err)
}
trimmed := strings.TrimSpace(string(content))
if trimmed == "" {
t.Fatalf("api.json is empty")
}
if trimmed[0] == '<' {
preview := trimmed
if newline := strings.IndexByte(preview, '\n'); newline >= 0 {
preview = preview[:newline]
}
if len(preview) > 120 {
preview = preview[:120] + "..."
}
t.Fatalf("api.json contains HTML instead of JSON; fetch the raw file, not the GitHub blob page (starts with %q)", preview)
}
var doc parityDoc
if err := json.Unmarshal(content, &doc); err != nil {
t.Fatalf("unmarshal api.json: %v", err)
}
return doc
}
func (index *packageIndex) collectJSONFields(typeName string) (map[string]struct{}, bool) {
return index.collectJSONFieldsByExpr(&ast.Ident{Name: typeName}, map[string]bool{})
}
func (index *packageIndex) collectJSONFieldsByExpr(expr ast.Expr, path map[string]bool) (map[string]struct{}, bool) {
switch current := expr.(type) {
case *ast.ParenExpr:
return index.collectJSONFieldsByExpr(current.X, path)
case *ast.StarExpr:
return index.collectJSONFieldsByExpr(current.X, path)
case *ast.Ident:
if path[current.Name] {
return nil, false
}
path[current.Name] = true
defer delete(path, current.Name)
decl, ok := index.types[current.Name]
if !ok {
return nil, false
}
switch typed := decl.Expr.(type) {
case *ast.StructType:
fields := make(map[string]struct{})
for _, field := range typed.Fields.List {
tagName, hasTag := parseJSONTag(field.Tag)
if len(field.Names) > 0 {
for _, fieldName := range field.Names {
jsonName := fallbackJSONFieldName(tagName, hasTag, fieldName.Name)
if jsonName != "" {
fields[jsonName] = struct{}{}
}
}
continue
}
if hasTag {
if tagName != "" {
fields[tagName] = struct{}{}
}
continue
}
embeddedFields, ok := index.collectJSONFieldsByExpr(field.Type, path)
if !ok {
continue
}
for name := range embeddedFields {
fields[name] = struct{}{}
}
}
return fields, true
default:
return index.collectJSONFieldsByExpr(decl.Expr, path)
}
default:
return nil, false
}
}
func parseJSONTag(tag *ast.BasicLit) (string, bool) {
if tag == nil {
return "", false
}
value, err := strconv.Unquote(tag.Value)
if err != nil {
return "", false
}
parsed := reflect.StructTag(value).Get("json")
if parsed == "" {
return "", false
}
name := strings.Split(parsed, ",")[0]
if name == "-" {
return "", true
}
return name, true
}
func fallbackJSONFieldName(tagName string, hasTag bool, fieldName string) string {
if hasTag {
if tagName == "" {
return fieldName
}
return tagName
}
return fieldName
}