Documentation
¶
Overview ¶
Package factory makes model values for tests and seeders:
var Posts = factory.New(func(n int) models.Post {
return models.Post{Title: fmt.Sprintf("Post %d", n), Body: "Lorem ipsum."}
})
post, err := Posts.Create(ctx) // one row
drafts, err := Posts.With(func(p *models.Post) {
p.PublishedAt = nil
}).CreateMany(ctx, 3) // three rows
unsaved := Posts.Make() // a value, not saved
The definition gets a sequence number, unique per factory and increasing from 1, for values that must differ (emails, slugs). Factories are immutable: With returns a new factory, so a base factory can be shared. A Factory is safe for concurrent use.
Index ¶
Examples ¶
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
This section is empty.
Types ¶
type Factory ¶
type Factory[T any] struct { // contains filtered or unexported fields }
Factory makes values of model T.
func (*Factory[T]) Create ¶
Create makes a value and inserts it with db.Create (so hooks run and the key and timestamps are set) using the database in ctx.
func (*Factory[T]) CreateMany ¶
CreateMany makes and inserts n values, one db.Create each (so every value gets its key on every database).
func (*Factory[T]) With ¶
With returns a factory that also applies fns, in order, to every value it makes: a state ("unpublished") or specific values for one test.
Example ¶
// SPDX-License-Identifier: Apache-2.0
package main
import (
"fmt"
"anetos.dev/anetos/db/factory"
)
type User struct {
Name string
Email string
Admin bool
}
func main() {
users := factory.New(func(n int) User {
return User{Name: fmt.Sprintf("User %d", n), Email: fmt.Sprintf("user%d@example.com", n)}
})
admins := users.With(func(u *User) { u.Admin = true }) // a new factory; users is unchanged
fmt.Printf("%+v\n", users.Make())
fmt.Printf("%+v\n", admins.Make())
}
Output: {Name:User 1 Email:user1@example.com Admin:false} {Name:User 2 Email:user2@example.com Admin:true}