-
Notifications
You must be signed in to change notification settings - Fork 1
/
example_check_test.go
64 lines (53 loc) · 1.58 KB
/
example_check_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
package validation_test
import (
"context"
"errors"
"fmt"
"github.com/muonsoft/validation"
"github.com/muonsoft/validation/validator"
)
type Outlet struct {
Type string
MainCommodity OutletCommodity
}
type OutletCommodity interface {
Name() string
Supports(outletType string) bool
}
type DigitalMovie struct {
name string
}
func (m DigitalMovie) Name() string {
return m.name
}
func (m DigitalMovie) Supports(outletType string) bool {
return outletType == "digital"
}
var ErrUnsupportedCommodity = errors.New("unsupported commodity")
func ExampleCheckProperty() {
outlet := Outlet{
Type: "offline",
MainCommodity: DigitalMovie{name: "Digital movie"},
}
err := validator.Validate(
context.Background(),
validation.
CheckProperty("mainCommodity", outlet.MainCommodity.Supports(outlet.Type)).
WithError(ErrUnsupportedCommodity).
WithMessage(
`Commodity "{{ value }}" cannot be sold at outlet.`,
validation.TemplateParameter{Key: "{{ value }}", Value: outlet.MainCommodity.Name()},
),
)
if violations, ok := validation.UnwrapViolationList(err); ok {
for violation := violations.First(); violation != nil; violation = violation.Next() {
fmt.Println("violation underlying error:", violation.Unwrap())
fmt.Println(violation)
}
}
fmt.Println("errors.Is(err, ErrUnsupportedCommodity) =", errors.Is(err, ErrUnsupportedCommodity))
// Output:
// violation underlying error: unsupported commodity
// violation at "mainCommodity": "Commodity "Digital movie" cannot be sold at outlet."
// errors.Is(err, ErrUnsupportedCommodity) = true
}