-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathfactory_constrained_test.go
81 lines (64 loc) · 2.05 KB
/
factory_constrained_test.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
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
// Copyright 2021 Harold Campbell. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package salem_test
import (
"go-salem"
"testing"
"github.com/stretchr/testify/assert"
)
type testConstraint struct {
didCallIsValid bool
actualField interface{}
}
// So that testConstraint conforms to salem.FieldConstraint
func (t *testConstraint) IsValid(field interface{}) bool {
t.didCallIsValid = true
t.actualField = field
return true
}
func Test_FactoryConstrainedEnsure(t *testing.T) {
test_constrained_ensure(t)
test_string_constrained_ensure(t)
test_constraint_clash_with_ensure(t)
}
func test_constrained_ensure(t *testing.T) {
type human struct {
Name string // Field we are checking
}
tc := &testConstraint{}
assert.False(t, tc.didCallIsValid)
assert.Empty(t, tc.actualField)
f := salem.Mock(human{})
f.EnsureConstraint("Name", tc)
f.Execute()
assert.True(t, tc.didCallIsValid, "should call IsValid(...) on constraint handler")
assert.NotEmpty(t, tc.actualField, "should pass field to constraint")
}
func test_constraint_clash_with_ensure(t *testing.T) {
minBound := 4
maxBound := 20
type human struct {
Name string
}
f := salem.Mock(human{})
f.Ensure("Name", "xxxxx xxxxx xxxxx xxxxx xxxxx yyyy") // This is clashes with the maxBound and should cause a panic
f.EnsureConstraint("Name", salem.ConstrainStringLength(minBound, maxBound))
assert.Panics(t, func() {
f.Execute()
}, "should panic when an Ensure(...) clashes with an EnsureContraint(...)")
}
func test_string_constrained_ensure(t *testing.T) {
type human struct {
Name string // We want this to be 4 - 20 charaters
Age int
}
minBound := 4
maxBound := 20
f := salem.Mock(human{})
f.EnsureConstraint("Name", salem.ConstrainStringLength(minBound, maxBound))
results := f.Execute()
actualMock := results[0].(human)
assert.True(t, len(actualMock.Name) >= minBound, "should constraint field to lower-bound")
assert.True(t, len(actualMock.Name) <= maxBound, "should constraint field to upper-bound")
}