Documentation
¶
Overview ¶
Package factory builds models with fake data for tests and seeders:
var Users = factory.New(func(f *factory.Faker) models.User {
return models.User{Name: f.Name(), Email: f.Email()}
})
admins, err := Users.Count(3).State(func(u *models.User) { u.Role = "admin" }).Create(ctx, db)
Factories are values: State, Count, Seed and AfterCreate return copies, so a base factory can be shared.
Index ¶
- func Pick[T any](f *Faker, items ...T) T
- type Factory
- func (f Factory[T]) AfterCreate(fn func(ctx context.Context, ex database.Executor, m *T) error) Factory[T]
- func (f Factory[T]) Count(n int) Factory[T]
- func (f Factory[T]) Create(ctx context.Context, ex database.Executor) ([]T, error)
- func (f Factory[T]) CreateOne(ctx context.Context, ex database.Executor) (T, error)
- func (f Factory[T]) Make() []T
- func (f Factory[T]) MakeOne() T
- func (f Factory[T]) Seed(seed uint64) Factory[T]
- func (f Factory[T]) State(fn func(*T)) Factory[T]
- type Faker
- func (f *Faker) Bool() bool
- func (f *Faker) Email() string
- func (f *Faker) FirstName() string
- func (f *Faker) Float(lo, hi float64) float64
- func (f *Faker) Int(lo, hi int) int
- func (f *Faker) LastName() string
- func (f *Faker) Name() string
- func (f *Faker) Paragraph() string
- func (f *Faker) Sentence() string
- func (f *Faker) Seq() int
- func (f *Faker) Slug() string
- func (f *Faker) Time(from, to time.Time) time.Time
- func (f *Faker) URL() string
- func (f *Faker) UUID() string
- func (f *Faker) Username() string
- func (f *Faker) Word() string
- func (f *Faker) Words(n int) string
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
Types ¶
type Factory ¶
type Factory[T any] struct { // contains filtered or unexported fields }
Factory builds T values.
func (Factory[T]) AfterCreate ¶
func (f Factory[T]) AfterCreate(fn func(ctx context.Context, ex database.Executor, m *T) error) Factory[T]
AfterCreate runs fn for every created model, inside Create; use it to create related models:
Users.AfterCreate(func(ctx context.Context, ex database.Executor, u *User) error {
_, err := Posts.Count(2).State(func(p *Post) { p.UserID = u.ID }).Create(ctx, ex)
return err
})
func (Factory[T]) Create ¶
Create builds and inserts Count models (in a transaction when ex is a *database.DB), then runs AfterCreate hooks.
func (Factory[T]) Make ¶
func (f Factory[T]) Make() []T
Make builds Count models without saving them.
func (Factory[T]) MakeOne ¶
func (f Factory[T]) MakeOne() T
MakeOne builds one model without saving it.
type Faker ¶
type Faker struct {
// contains filtered or unexported fields
}
Faker generates fake data. It is deterministic for a given seed; it is not cryptographically secure and must never produce secrets.
func (*Faker) Email ¶
Email returns an address on a reserved example domain, unique within one Make and unlikely to collide across Makes.