Ejemplo n.º 1
0
package main

import (
	"fmt"
	"github.com/Pallinder/go-randomdata"
	"github.com/bluele/factory-go/factory"
)

type User struct {
	ID          int
	Name        string
	CloseFriend *User
}

var UserFactory = factory.NewFactory(
	&User{},
)

func init() {
	UserFactory.SeqInt("ID", func(n int) (interface{}, error) {
		return n, nil
	}).Attr("Name", func(args factory.Args) (interface{}, error) {
		return randomdata.FullName(randomdata.RandomGender), nil
	}).SubRecursiveFactory("CloseFriend", UserFactory, func() int { return 2 }) // recursive depth is always 2
}

func main() {
	user := UserFactory.MustCreate().(*User)
	fmt.Println("ID:", user.ID, " Name:", user.Name,
		" CloseFriend.ID:", user.CloseFriend.ID, " CloseFriend.Name:", user.CloseFriend.Name)
	// `user.CloseFriend.CloseFriend.CloseFriend ` depth is 3, so this value is always nil.
Ejemplo n.º 2
0
package main

import (
	"fmt"
	"github.com/bluele/factory-go/factory"
)

type User struct {
	ID       int
	Name     string
	Location string
}

// 'Location: "Tokyo"' is default value.
var UserFactory = factory.NewFactory(
	&User{Location: "Tokyo"},
).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
})

func main() {
	for i := 0; i < 3; i++ {
		user := UserFactory.MustCreate().(*User)
		fmt.Println("ID:", user.ID, " Name:", user.Name, " Location:", user.Location)
	}
}
)

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{},
Ejemplo n.º 4
0
	"github.com/bluele/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 })