data.New   A
last analyzed

Complexity

Conditions 3

Size

Total Lines 42
Code Lines 30

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 12

Importance

Changes 0
Metric Value
cc 3
eloc 30
nop 1
dl 0
loc 42
ccs 0
cts 11
cp 0
crap 12
rs 9.16
c 0
b 0
f 0
1
package data
2
3
import (
4
	"context"
5
	"math/rand"
6
	"time"
7
8
	"github.com/getkin/kin-openapi/openapi3"
9
)
10
11
type MediaGenerator interface {
12
	GenerateData(ctx context.Context, mediaType *openapi3.MediaType) (Data, error)
13
}
14
15
func New(options Options) MediaGenerator {
16
	randomSource := rand.NewSource(time.Now().UnixNano())
17
	random := rand.New(randomSource)
18
19
	lengthGenerator := &randomArrayLengthGenerator{random: random}
20
	keyGenerator := &camelCaseKeyGenerator{random: random}
21
22
	combinedGenerator := &combinedSchemaGenerator{
23
		merger: &combinedSchemaMerger{random: random},
24
	}
25
26
	generatorsByType := map[string]schemaGenerator{
27
		"string":  newStringGenerator(random),
28
		"boolean": &booleanGenerator{random: random},
29
		"integer": &integerGenerator{
30
			random:         random,
31
			defaultMinimum: options.DefaultMinInt,
32
			defaultMaximum: options.DefaultMaxInt,
33
		},
34
		"number": &numberGenerator{
35
			random:         random,
36
			defaultMinimum: options.DefaultMinFloat,
37
			defaultMaximum: options.DefaultMaxFloat,
38
		},
39
		"array":  newArrayGenerator(lengthGenerator),
40
		"object": newObjectGenerator(lengthGenerator, keyGenerator),
41
		"oneOf":  &oneOfGenerator{random: random},
42
		"allOf":  combinedGenerator,
43
		"anyOf":  combinedGenerator,
44
	}
45
46
	schemaGenerator := createCoordinatingSchemaGenerator(options, generatorsByType, random)
47
48
	for i := range generatorsByType {
49
		if generator, ok := generatorsByType[i].(recursiveGenerator); ok {
50
			generator.SetSchemaGenerator(schemaGenerator)
51
		}
52
	}
53
54
	return &coordinatingMediaGenerator{
55
		useExamples:     options.UseExamples,
56
		schemaGenerator: schemaGenerator,
57
	}
58
}
59
60
func createCoordinatingSchemaGenerator(options Options, generatorsByType map[string]schemaGenerator, random *rand.Rand) schemaGenerator {
61
	var schemaGenerator schemaGenerator
62
63
	schemaGenerator = &coordinatingSchemaGenerator{
64
		generatorsByType: generatorsByType,
65
	}
66
67
	if options.SuppressErrors {
68
		schemaGenerator = &errorSuppressor{schemaGenerator: schemaGenerator}
69
	}
70
71
	if options.UseExamples != No {
72
		schemaGenerator = &exampleSchemaGenerator{
73
			useExamples:     options.UseExamples,
74
			schemaGenerator: schemaGenerator,
75
		}
76
	}
77
78
	if options.NullProbability > 0 {
79
		schemaGenerator = &nullGenerator{
80
			nullProbability: options.NullProbability,
81
			random:          random,
82
			schemaGenerator: schemaGenerator,
83
		}
84
	}
85
86
	schemaGenerator = &recursionBreaker{schemaGenerator: schemaGenerator}
87
88
	return schemaGenerator
89
}
90