1
|
|
|
package data |
2
|
|
|
|
3
|
|
|
import ( |
4
|
|
|
"context" |
5
|
|
|
"fmt" |
6
|
|
|
"github.com/lucasjones/reggen" |
7
|
|
|
|
8
|
|
|
"github.com/getkin/kin-openapi/openapi3" |
9
|
|
|
"github.com/pkg/errors" |
10
|
|
|
) |
11
|
|
|
|
12
|
|
|
type stringGenerator struct { |
13
|
|
|
random randomGenerator |
14
|
|
|
textGenerator schemaGenerator |
15
|
|
|
formatGenerators map[string]stringGeneratorFunction |
16
|
|
|
} |
17
|
|
|
|
18
|
|
|
func newStringGenerator(random randomGenerator) schemaGenerator { |
19
|
|
|
generator := &rangedTextGenerator{ |
20
|
|
|
random: random, |
21
|
|
|
} |
22
|
|
|
|
23
|
|
|
return &stringGenerator{ |
24
|
|
|
random: random, |
25
|
|
|
textGenerator: &textGenerator{generator: generator}, |
26
|
|
|
formatGenerators: defaultFormattedStringGenerators(generator), |
27
|
|
|
} |
28
|
|
|
} |
29
|
|
|
|
30
|
|
|
func (generator *stringGenerator) GenerateDataBySchema(ctx context.Context, schema *openapi3.Schema) (Data, error) { |
31
|
1 |
|
var value Data |
32
|
1 |
|
var err error |
33
|
|
|
|
34
|
1 |
|
maxLength := 0 |
35
|
1 |
|
if schema.MaxLength != nil { |
36
|
|
|
maxLength = int(*schema.MaxLength) |
37
|
|
|
} |
38
|
|
|
|
39
|
1 |
|
if len(schema.Enum) > 0 { |
40
|
1 |
|
value = generator.getRandomEnumValue(schema.Enum) |
41
|
1 |
|
} else if schema.Pattern != "" { |
42
|
1 |
|
value, err = generator.generateValueByPattern(schema.Pattern, maxLength) |
43
|
1 |
|
} else if formatGenerator, isSupported := generator.formatGenerators[schema.Format]; isSupported { |
44
|
1 |
|
value = formatGenerator(int(schema.MinLength), maxLength) |
45
|
|
|
} else { |
46
|
1 |
|
value, err = generator.textGenerator.GenerateDataBySchema(ctx, schema) |
47
|
|
|
} |
48
|
|
|
|
49
|
1 |
|
return value, err |
50
|
|
|
} |
51
|
|
|
|
52
|
|
|
func (generator *stringGenerator) getRandomEnumValue(enum []interface{}) string { |
53
|
1 |
|
return fmt.Sprint(enum[generator.random.Intn(len(enum))]) |
54
|
|
|
} |
55
|
|
|
|
56
|
|
|
func (generator *stringGenerator) generateValueByPattern(pattern string, maxLength int) (string, error) { |
57
|
1 |
|
g, err := reggen.NewGenerator(pattern) |
58
|
1 |
|
if err != nil { |
59
|
|
|
return "", errors.WithStack(&ErrGenerationFailed{ |
60
|
|
|
GeneratorID: "stringGenerator", |
61
|
|
|
Message: fmt.Sprintf("cannot generate string value by pattern '%s'", pattern), |
62
|
|
|
Previous: err, |
63
|
|
|
}) |
64
|
|
|
} |
65
|
1 |
|
if maxLength <= 0 { |
66
|
1 |
|
maxLength = defaultMaxLength |
67
|
|
|
} |
68
|
1 |
|
value := g.Generate(maxLength) |
69
|
1 |
|
return value, nil |
70
|
|
|
} |
71
|
|
|
|