-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathenum.go
More file actions
61 lines (49 loc) · 1.45 KB
/
Copy pathenum.go
File metadata and controls
61 lines (49 loc) · 1.45 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
package chaff
import (
"fmt"
"github.com/ryanolee/go-chaff/internal/util"
"github.com/thoas/go-funk"
)
type (
enumGenerator struct {
Values []interface{}
}
)
// Parses the "enum" keyword of a schema
// Example:
//
// {
// "enum": ["foo", "bar"]
// }
func parseEnum(node schemaNode, metadata *parserMetadata) (Generator, error) {
if node.Enum == nil || len(*node.Enum) == 0 {
return nullGenerator{}, fmt.Errorf("enum must be a non-empty array")
}
selfSchema, err := metadata.SchemaManager.ParseSchemaNode(metadata, node, "enum")
if err != nil {
return nullGenerator{}, fmt.Errorf("failed to compile schema for enum item validation: %w", err)
}
validEnumValues, ok := funk.Filter(*node.Enum, func(value interface{}) bool {
err := selfSchema.Validate(value)
return err == nil
}).([]interface{})
if !ok || len(validEnumValues) == 0 {
return nullGenerator{}, fmt.Errorf("illogical schema, no enum values match the other schema constraints of the passed node: %v", util.MarshalJsonToString(node.Enum))
}
if len(validEnumValues) == 1 {
return constGenerator{
Value: validEnumValues[0],
}, nil
}
return enumGenerator{
Values: validEnumValues,
}, nil
}
func (g enumGenerator) Generate(opts *GeneratorOptions) interface{} {
opts.overallComplexity++
return opts.Rand.Choice(g.Values)
}
func (g enumGenerator) String() string {
numberOfItemsInEnum := len(g.Values)
return fmt.Sprintf("EnumGenerator[items: %d]", numberOfItemsInEnum)
}