factory

package module
v0.1.0 Latest Latest
Warning

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

Go to latest
Published: Dec 3, 2017 License: Apache-2.0 Imports: 8 Imported by: 0

README

Factory: Factory for Go Tests

Factory is a fixtures replacement. With its readable APIs, you can define factories and use factories to create saved, unsaved and stubbed instances by build multiple strategies.

Factory's APIs are inspired by factory_bot in Ruby.

See how easily to use factory:

import (
	. "github.com/nauyey/factory"
	"github.com/nauyey/factory/def"
)

type User struct {
    ID        int64     `factory:"id,primary"`
	Name      string    `factory:"name"`
	Gender    string    `factory:"gender"`
    Email     string    `factory:"email"`
}

// Define a factory for User struct
userFactory := def.NewFactory(User{}, "db_table_users",
	def.SequenceField("ID", 1, func(n int64) interface{} {
		return n
	}),
	def.DynamicField("Name", func(user interface{}) (interface{}, error) {
		return fmt.Sprintf("User Name %d", user.(*User).ID), nil
	}),
	def.Trait("boy",
		def.Field("Gender", "male"),
	),
)

user := &User{}
Build(userFactory).To(user)
// user.ID   -> 1
// user.Name -> "User Name 1"

user2 := &User{}
Create(userFactory, WithTraits("boy")).To(user2) // saved to database
// user2.ID      -> 2
// user2.Name   -> "User Name 2"
// user2.Gender -> "male"

Feature Support

  • Fields
  • Dynamic Fields
  • Dependent Fields
  • Sequence Fields
  • Multilevel Fields
  • Associations
  • Traits
  • Callbacks
  • Multiple Build Strategies

Installation

 Simple install the package to your $GOPATH with the go tool from shell:

$ go get -u github.com/nauyey/factory

Documentation

See GETTING_STARTED for information on defining and using factories.

How to Contribute

  1. Check for open issues or open a fresh issue to start a discussion around a feature idea or a bug.
  2. Fork the repository on GitHub to start making your changes to the master branch (or branch off of it).
  3. Write a test which shows that the bug was fixed or that the feature works as expected.
  4. Send a pull request and bug the maintainer until it gets merged and published. :) Make sure to add yourself to AUTHORS.

Documentation

Index

Constants

This section is empty.

Variables

View Source
var DebugMode = false

DebugMode is a flag controlling whether debug information is outputted to the os.Stdout

Functions

func Build

func Build(f *Factory, opts ...factoryOption) *buildTo

Build creates an instance from a factory model but won't store it into database.

model := &Model{}

err := Build(FactoryModel,

WithTrait("Chinese"),
WithField("Name", "new name"),
WithField("ID", 123),

).To(model)

func BuildSlice

func BuildSlice(f *Factory, count int, opts ...factoryOption) *buildSliceTo

BuildSlice creates a slice instance from a factory model but won't store them into database.

modelSlice := []*Model{}

err := Build(FactoryModel,

WithTrait("Chinese"),
WithField("Name", "new name"),

).To(&modelSlice)

func Create

func Create(f *Factory, opts ...factoryOption) *createTo

Create creates an instance from a factory model and stores it into database.

model := &Model{}

err := Create(FactoryModel,

WithTrait("Chinese"),
WithField("Name", "new name"),
WithField("ID", 123),

).To(model)

func CreateSlice

func CreateSlice(f *Factory, count int, opts ...factoryOption) *createSliceTo

CreateSlice creates a slice of instance from a factory model and stores them into database.

modelSlice := []*Model{}

err := CreateSlice(FactoryModel,

WithTrait("Chinese"),
WithField("Name", "new name"),

).To(&modelSlice)

func Delete

func Delete(f *Factory, instance interface{}) error

Delete deletes an instance of a factory model from database. Example: err := Delete(FactoryModel, Model{})

func SetDB

func SetDB(db *sql.DB)

SetDB sets database connection for factory

func WithField

func WithField(name string, value interface{}) factoryOption

WithField sets the value of a specific field. This way has the highest priority to set the field value.

func WithTraits

func WithTraits(traits ...string) factoryOption

WithTraits defines which traits the new instance will use. It can take multiple traits. These traits will be execute one by one. So the later one may override the before ones. For example: The trait "trait1" set Field1 as "value1", and at the same time, trait "trait2" set Field1 as "value2". The WithTraits("trait1", "trait2") will finally set Field1 as "value2".

Types

type AssociationFieldValue

type AssociationFieldValue struct {
	ReferenceField            string
	AssociationReferenceField string
	OriginalFactory           *Factory
	Factory                   *Factory
}

AssociationFieldValue represents a struct which contains data to generate value of a association field.

type Callback

type Callback func(model interface{}) error

Callback defines the callback function type

type DynamicFieldValue

type DynamicFieldValue func(model interface{}) (interface{}, error)

DynamicFieldValue defines the value generator type of a field. It's return result will be set as the value of the field dynamicly.

type Factory

type Factory struct {
	ModelType              reflect.Type
	Table                  string
	FiledValues            map[string]interface{}
	SequenceFiledValues    map[string]*sequenceValue
	DynamicFieldValues     map[string]DynamicFieldValue
	AssociationFieldValues map[string]*AssociationFieldValue
	Traits                 map[string]*Factory
	AfterBuildCallbacks    []Callback
	BeforeCreateCallbacks  []Callback
	AfterCreateCallbacks   []Callback

	CanHaveAssociations bool
	CanHaveTraits       bool
	CanHaveCallbacks    bool
}

Factory represents a factory defined by some model struct

func (*Factory) AddSequenceFiledValue

func (f *Factory) AddSequenceFiledValue(name string, first int64, value SequenceFieldValue)

AddSequenceFiledValue adds sequence field value to factory by field name

type SequenceFieldValue

type SequenceFieldValue func(n int64) (interface{}, error)

SequenceFieldValue defines the value generator type of sequence field. It's return result will be set as the value of the sequence field dynamicly.

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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