/
refer_to_parent_factory.go
50 lines (44 loc) · 1.19 KB
/
refer_to_parent_factory.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
package main
import (
"fmt"
"github.com/bluele/factory-go/factory"
)
type User struct {
ID int
Name string
Group *Group
}
type Group struct {
ID int
Name string
Users []*User
}
var UserFactory = factory.NewFactory(
&User{},
).SeqInt("ID", func(n int) (interface{}, error) {
return n, nil
}).Attr("Name", func(args factory.Args) (interface{}, error) {
user := args.Instance().(*User)
return fmt.Sprintf("user-%d", user.ID), nil
}).Attr("Group", func(args factory.Args) (interface{}, error) {
if parent := args.Parent(); parent != nil {
// if args have parent, use it.
return parent.Instance(), nil
}
return nil, nil
})
var GroupFactory = factory.NewFactory(
&Group{},
).SeqInt("ID", func(n int) (interface{}, error) {
return 2 - n%2, nil
}).Attr("Name", func(args factory.Args) (interface{}, error) {
group := args.Instance().(*Group)
return fmt.Sprintf("group-%d", group.ID), nil
}).SubSliceFactory("Users", UserFactory, func() int { return 3 })
func main() {
group := GroupFactory.MustCreate().(*Group)
fmt.Println("Group.ID:", group.ID)
for _, user := range group.Users {
fmt.Println("\tUser.ID:", user.ID, " User.Name:", user.Name, " User.Group.ID:", user.Group.ID)
}
}