-
Notifications
You must be signed in to change notification settings - Fork 108
/
options.go
64 lines (51 loc) · 1.31 KB
/
options.go
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
// SPDX-License-Identifier: MIT
package mock
import (
"strconv"
"github.com/caixw/apidoc/v7/internal/ast"
)
// GenOptions 生成随机数据的函数
type GenOptions struct {
// 返回一个随机的数值
//
// 可以是浮点和整数类型。
Number func(p *ast.Param) interface{}
// 返回一个随机长度的字符串
String func(p *ast.Param) string
// 返回一个随机的布尔值
Bool func() bool
// 返回一个随机的数值
//
// 该数值被用于声明 slice 长度,所以必须为正整数。
SliceSize func() int
// 返回一个介于 [0, max] 之间的数值
//
// 该数值被用于从数组中获取其中的某个元素。
Index func(max int) int
}
func isEnum(p *ast.Param) bool {
return len(p.Enums) > 0
}
func (g *GenOptions) generateBool() bool {
return g.Bool()
}
func (g *GenOptions) generateNumber(p *ast.Param) interface{} {
if isEnum(p) {
index := g.Index(len(p.Enums))
v, err := strconv.ParseInt(p.Enums[index].Value.V(), 10, 32)
if err != nil { // 这属于文档定义错误,直接 panic
panic(err)
}
return v
}
return g.Number(p)
}
func (g *GenOptions) generateString(p *ast.Param) string {
if isEnum(p) {
return p.Enums[g.Index(len(p.Enums))].Value.V()
}
return g.String(p)
}
func (g *GenOptions) generateSliceSize() int {
return g.SliceSize()
}