-
Notifications
You must be signed in to change notification settings - Fork 8
Expand file tree
/
Copy pathdiff_test.go
More file actions
108 lines (88 loc) · 2.48 KB
/
diff_test.go
File metadata and controls
108 lines (88 loc) · 2.48 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
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
package deep_test
import (
"github.com/brunoga/deep/v5"
"github.com/brunoga/deep/v5/internal/testmodels"
"testing"
)
func TestBuilder(t *testing.T) {
type Config struct {
Theme string `json:"theme"`
}
c1 := Config{Theme: "dark"}
patch := deep.Edit(&c1).
With(deep.Set(deep.Field(func(c *Config) *string { return &c.Theme }), "light")).
Build()
if err := deep.Apply(&c1, patch); err != nil {
t.Fatalf("deep.Apply failed: %v", err)
}
if c1.Theme != "light" {
t.Errorf("got %s, want light", c1.Theme)
}
}
func TestComplexBuilder(t *testing.T) {
u1 := testmodels.User{
ID: 1,
Name: "Alice",
Roles: []string{"user"},
Score: map[string]int{"a": 10},
}
namePath := deep.Field(func(u *testmodels.User) *string { return &u.Name })
agePath := deep.Field(func(u *testmodels.User) *int { return &u.Info.Age })
rolesPath := deep.Field(func(u *testmodels.User) *[]string { return &u.Roles })
scorePath := deep.Field(func(u *testmodels.User) *map[string]int { return &u.Score })
patch := deep.Edit(&u1).
With(
deep.Set(namePath, "Alice Smith"),
deep.Set(agePath, 35),
deep.Add(deep.At(rolesPath, 1), "admin"),
deep.Set(deep.MapKey(scorePath, "b"), 20),
deep.Remove(deep.MapKey(scorePath, "a")),
).
Build()
u2 := u1
if err := deep.Apply(&u2, patch); err != nil {
t.Fatalf("deep.Apply failed: %v", err)
}
if u2.Name != "Alice Smith" {
t.Errorf("Name failed: %s", u2.Name)
}
if u2.Info.Age != 35 {
t.Errorf("Age failed: %d", u2.Info.Age)
}
if len(u2.Roles) != 2 || u2.Roles[1] != "admin" {
t.Errorf("Roles failed: %v", u2.Roles)
}
if u2.Score["b"] != 20 {
t.Errorf("Score failed: %v", u2.Score)
}
if _, ok := u2.Score["a"]; ok {
t.Errorf("Score 'a' should have been removed")
}
}
func TestLog(t *testing.T) {
u := testmodels.User{ID: 1, Name: "Alice"}
namePath := deep.Field(func(u *testmodels.User) *string { return &u.Name })
p := deep.Edit(&u).
Log("Starting update").
With(deep.Set(namePath, "Bob")).
Log("Finished update").
Build()
deep.Apply(&u, p)
}
func TestBuilderAdvanced(t *testing.T) {
u := &testmodels.User{}
idPath := deep.Field(func(u *testmodels.User) *int { return &u.ID })
namePath := deep.Field(func(u *testmodels.User) *string { return &u.Name })
p := deep.Edit(u).
Guard(deep.Eq(idPath, 1)).
With(
deep.Set(idPath, 2).Unless(deep.Eq(idPath, 1)),
).
Build()
_ = deep.Gt(idPath, 0)
_ = deep.Lt(idPath, 10)
_ = deep.Exists(namePath)
if p.Guard == nil || p.Guard.Op != "==" {
t.Error("Guard failed")
}
}