forked from bluele/factory-go
/
subfactory_slice.go
46 lines (39 loc) · 1023 Bytes
/
subfactory_slice.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
package main
import (
"fmt"
"github.com/everytv/factory-go/factory"
)
type Post struct {
ID int
Content string
}
type User struct {
ID int
Name string
Posts []*Post
}
var PostFactory = factory.NewFactory(
&Post{},
).SeqInt("ID", func(n int) (interface{}, error) {
return n, nil
}).Attr("Content", func(args factory.Args) (interface{}, error) {
post := args.Instance().(*Post)
return fmt.Sprintf("post-%d", post.ID), nil
})
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
}).SubSliceFactory("Posts", PostFactory, func() int { return 3 })
func main() {
for i := 0; i < 3; i++ {
user := UserFactory.MustCreate().(*User)
fmt.Println("ID:", user.ID, " Name:", user.Name)
for _, post := range user.Posts {
fmt.Printf("\tPost.ID: %v Post.Content: %v\n", post.ID, post.Content)
}
}
}