Help us shape the future of Go! Take the 2026 Go Developer Survey

factory

package
v0.4.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Oct 8, 2026 License: Apache-2.0 Imports: 4 Imported by: 0

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 New

func New[T any](def func(n int) T) *Factory[T]

New returns a factory that makes values with def.

func (*Factory[T]) Create

func (f *Factory[T]) Create(ctx context.Context) (T, error)

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

func (f *Factory[T]) CreateMany(ctx context.Context, n int) ([]T, error)

CreateMany makes and inserts n values, one db.Create each (so every value gets its key on every database).

func (*Factory[T]) Make

func (f *Factory[T]) Make() T

Make returns a new value, not saved.

func (*Factory[T]) MakeMany

func (f *Factory[T]) MakeMany(n int) []T

MakeMany returns n new values, not saved.

func (*Factory[T]) With

func (f *Factory[T]) With(fns ...func(*T)) *Factory[T]

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}

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL