data.*integerGenerator.getMinMax   B
last analyzed

Complexity

Conditions 7

Size

Total Lines 22
Code Lines 14

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 12
CRAP Score 7.0222

Importance

Changes 0
Metric Value
cc 7
eloc 14
nop 1
dl 0
loc 22
ccs 12
cts 13
cp 0.9231
crap 7.0222
rs 8
c 0
b 0
f 0
1
package data
2
3
import (
4
	"context"
5
	"math"
6
7
	"github.com/getkin/kin-openapi/openapi3"
8
	"github.com/pkg/errors"
9
)
10
11
type integerGenerator struct {
12
	random         randomGenerator
13
	defaultMinimum int64
14
	defaultMaximum int64
15
}
16
17
func (generator *integerGenerator) GenerateDataBySchema(ctx context.Context, schema *openapi3.Schema) (Data, error) {
18 1
	minimum, maximum := generator.getMinMax(schema)
19
20 1
	if maximum < minimum {
21 1
		return 0, errors.WithStack(&ErrGenerationFailed{
22
			GeneratorID: "integerGenerator",
23
			Message:     "maximum cannot be less than minimum",
24
		})
25
	}
26 1
	if maximum == minimum {
27 1
		return minimum, nil
28
	}
29
30 1
	value := generator.generateValueInRange(minimum, maximum)
31
32 1
	if schema.MultipleOf != nil {
33 1
		value -= value % int64(*schema.MultipleOf)
34
	}
35
36 1
	return value, nil
37
}
38
39
func (generator *integerGenerator) getMinMax(schema *openapi3.Schema) (int64, int64) {
40 1
	minimum := generator.defaultMinimum
41 1
	maximum := generator.defaultMaximum
42 1
	if schema.Format == "int32" && generator.defaultMaximum > math.MaxInt32 {
43
		maximum = math.MaxInt32
44
	}
45
46 1
	if schema.Min != nil {
47 1
		minimum = int64(*schema.Min)
48
	}
49 1
	if schema.Max != nil {
50 1
		maximum = int64(*schema.Max)
51
	}
52
53 1
	if schema.ExclusiveMin {
54 1
		minimum++
55
	}
56 1
	if schema.ExclusiveMax {
57 1
		maximum--
58
	}
59
60 1
	return minimum, maximum
61
}
62
63
func (generator *integerGenerator) generateValueInRange(minimum int64, maximum int64) int64 {
64 1
	delta := maximum - minimum
65 1
	if delta < math.MaxInt64 {
66 1
		delta++
67
	}
68
69 1
	return generator.random.Int63n(delta) + minimum
70
}
71