faker

package module
v3.0.0 Latest Latest
Warning

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

Go to latest
Published: Mar 8, 2019 License: MIT Imports: 13 Imported by: 336

README

Docs

faker

Struct Data Fake Generator

Faker will generate you a fake data based on your Struct.

Build Status codecov Go Report Card License GoDoc

Index

Support

You can file an Issue. See documentation in Godoc

Getting Started

Download
go get -u github.com/bxcodec/faker

Example


DEMO


Example to use Faker

Benchmark


Bench To Generate Fake Data

Without Tag
BenchmarkFakerDataNOTTagged-4             500000              3049 ns/op             488 B/op         20 allocs/op
Using Tag
 BenchmarkFakerDataTagged-4                100000             17470 ns/op             380 B/op         26 allocs/op
MUST KNOW

The Struct Field must PUBLIC.
Support Only For :

  • int int8 int16 int32 int64
  • []int []int8 []int16 []int32 []int64
  • bool []bool
  • string []string
  • float32 float64 []float32 []float64
  • Nested Struct Field
  • time.Time []time.Time

Limitation


Unfortunately this library has some limitation

  • It does not support private fields. Make sure your structs fields you intend to generate fake data for are public, it would otherwise trigger a panic. You can however omit fields using a tag skip faker:"-" on your private fields.
  • It does not support the interface{} data type. How could we generate anything without knowing its data type?
  • It does not support the map[interface{}]interface{}, map[any_type]interface{}, map[interface{}]any_type data types. Once again, we cannot generate values for an unknown data type.
  • Custom types are not fully supported. However some custom types are already supported: we are still investigating how to do this the correct way. For now, if you use faker, it's safer not to use any custom types in order to avoid panics.

Contribution


To contrib to this project, you can open a PR or an issue.

Documentation

Index

Constants

View Source
const (
	BaseDateFormat   = "2006-01-02"
	TimeFormat       = "15:04:05"
	MonthFormat      = "January"
	YearFormat       = "2006"
	DayFormat        = "Monday"
	DayOfMonthFormat = "_2"
	TimePeriodFormat = "PM"
)

These example values must use the reference time "Mon Jan 2 15:04:05 MST 2006" as described at https://gobyexample.com/time-formatting-parsing

View Source
const (
	ID                    = "uuid_digit"
	HyphenatedID          = "uuid_hyphenated"
	EmailTag              = "email"
	MacAddressTag         = "mac_address"
	DomainNameTag         = "domain_name"
	UserNameTag           = "username"
	URLTag                = "url"
	IPV4Tag               = "ipv4"
	IPV6Tag               = "ipv6"
	PASSWORD              = "password"
	LATITUDE              = "lat"
	LONGITUDE             = "long"
	CreditCardNumber      = "cc_number"
	CreditCardType        = "cc_type"
	PhoneNumber           = "phone_number"
	TollFreeNumber        = "toll_free_number"
	E164PhoneNumberTag    = "e_164_phone_number"
	TitleMaleTag          = "title_male"
	TitleFemaleTag        = "title_female"
	FirstNameTag          = "first_name"
	FirstNameMaleTag      = "first_name_male"
	FirstNameFemaleTag    = "first_name_female"
	LastNameTag           = "last_name"
	NAME                  = "name"
	UnixTimeTag           = "unix_time"
	DATE                  = "date"
	TIME                  = "time"
	MonthNameTag          = "month_name"
	YEAR                  = "year"
	DayOfWeekTag          = "day_of_week"
	DayOfMonthTag         = "day_of_month"
	TIMESTAMP             = "timestamp"
	CENTURY               = "century"
	TIMEZONE              = "timezone"
	TimePeriodTag         = "time_period"
	WORD                  = "word"
	SENTENCE              = "sentence"
	PARAGRAPH             = "paragraph"
	CurrencyTag           = "currency"
	AmountTag             = "amount"
	AmountWithCurrencyTag = "amount_with_currency"
	SKIP                  = "-"
	Length                = "len"
	BoundaryStart         = "boundary_start"
	BoundaryEnd           = "boundary_end"
	Equals                = "="
)

Supported tags

Variables

View Source
var (
	ErrUnsupportedKindPtr  = "Unsupported kind: %s Change Without using * (pointer) in Field of %s"
	ErrUnsupportedKind     = "Unsupported kind: %s"
	ErrValueNotPtr         = "Not a pointer value"
	ErrTagNotSupported     = "Tag unsupported"
	ErrTagAlreadyExists    = "Tag exists"
	ErrMoreArguments       = "Passed more arguments than is possible : (%d)"
	ErrNotSupportedPointer = "Use sample:=new(%s)\n faker.FakeData(sample) instead"
	ErrSmallerThanZero     = "Size:%d is smaller than zero."

	ErrStartValueBiggerThanEnd = "Start value can not be bigger than end value."
	ErrWrongFormattedTag       = "Tag \"%s\" is not written properly"
	ErrUnknownType             = "Unknown Type"
	ErrNotSupportedTypeForTag  = "Type is not supported by tag."
)

Generic Error Messages for tags

ErrUnsupportedKindPtr: Error when get fake from ptr
ErrUnsupportedKind: Error on passing unsupported kind
ErrValueNotPtr: Error when value is not pointer
ErrTagNotSupported: Error when tag is not supported
ErrTagAlreadyExists: Error when tag exists and call AddProvider
ErrMoreArguments: Error on passing more arguments
ErrNotSupportedPointer: Error when passing unsupported pointer

Functions

func AddProvider

func AddProvider(tag string, provider TaggedFunction) error

AddProvider extend faker with tag to generate fake data with specified custom algoritm Example:

type Gondoruwo struct {
	Name       string
	Locatadata int
}

type Sample struct {
	ID                 int64     `faker:"customIdFaker"`
	Gondoruwo          Gondoruwo `faker:"gondoruwo"`
	Danger             string    `faker:"danger"`
}

func CustomGenerator() {
	// explicit
	faker.AddProvider("customIdFaker", func(v reflect.Value) (interface{}, error) {
	 	return int64(43), nil
	})
	// functional
	faker.AddProvider("danger", func() faker.TaggedFunction {
		return func(v reflect.Value) (interface{}, error) {
			return "danger-ranger", nil
		}
	}())
	faker.AddProvider("gondoruwo", func(v reflect.Value) (interface{}, error) {
		obj := Gondoruwo{
			Name:       "Power",
			Locatadata: 324,
		}
		return obj, nil
	})
}

func main() {
	CustomGenerator()
	var sample Sample
	faker.FakeData(&sample)
	fmt.Printf("%+v", sample)
}

Will print

{ID:43 Gondoruwo:{Name:Power Locatadata:324} Danger:danger-ranger}

Notes: when using a custom provider make sure to return the same type as the field

func AmountWithCurrency

func AmountWithCurrency() string

AmountWithCurrency get fake AmountWithCurrency USD 49257.100

func CCNumber

func CCNumber() string

CCNumber get a credit card number randomly in string (VISA, MasterCard, etc)

func CCType

func CCType() string

CCType get a credit card type randomly in string (VISA, MasterCard, etc)

func Century

func Century() string

Century get century randomly in string

func Currency

func Currency() string

Currency get fake Currency (IDR, USD)

func Date

func Date() string

Date get fake date in string randomly

func DayOfMonth

func DayOfMonth() string

DayOfMonth get month randomly in string format

func DayOfWeek

func DayOfWeek() string

DayOfWeek get day of week randomly in string format

func DomainName

func DomainName() string

DomainName get email domain name in string

func E164PhoneNumber

func E164PhoneNumber() string

E164PhoneNumber get fake E164PhoneNumber

func Email

func Email() string

Email get email randomly in string

func FakeData

func FakeData(a interface{}) error

FakeData is the main function. Will generate a fake data based on your struct. You can use this for automation testing, or anything that need automated data. You don't need to Create your own data for your testing.

func FirstName

func FirstName() string

FirstName get fake firstname

func FirstNameFemale

func FirstNameFemale() string

FirstNameFemale get fake firstname for female

func FirstNameMale

func FirstNameMale() string

FirstNameMale get fake firstname for male

func IPv4

func IPv4() string

IPv4 get IPv4 randomly in string

func IPv6

func IPv6() string

IPv6 get IPv6 randomly in string

func LastName

func LastName() string

LastName get fake lastname

func Latitude

func Latitude() float64

Latitude get fake latitude randomly

func Longitude

func Longitude() float64

Longitude get fake longitude randomly

func MacAddress

func MacAddress() string

MacAddress get mac address randomly in string

func MonthName

func MonthName() string

MonthName get month name randomly in string format

func Name

func Name() string

Name get fake name

func Paragraph

func Paragraph() string

Paragraph get a paragraph randomly in string

func Password

func Password() string

Password get password randomly in string

func Phonenumber

func Phonenumber() string

Phonenumber get fake phone number

func RandomInt

func RandomInt(parameters ...int) (p []int, err error)

RandomInt Get three parameters , only first mandatory and the rest are optional

If only set one parameter :  This means the minimum number of digits and the total number
If only set two parameters : First this is min digit and second max digit and the total number the difference between them
If only three parameters: the third argument set Max count Digit

func RandomUnixTime

func RandomUnixTime() int64

RandomUnixTime is a helper function returning random Unix time

func Sentence

func Sentence() string

Sentence get a sentence randomly in string

func SetAddress

func SetAddress(net Addresser)

SetAddress sets custom Address

func SetDataFaker

func SetDataFaker(d DataFaker)

SetDataFaker sets Custom data in lorem

func SetDateTimer

func SetDateTimer(d DateTimer)

SetDateTimer sets custom date time

func SetDowser

func SetDowser(d Dowser)

SetDowser sets custom Dowsers of Person names

func SetNetwork

func SetNetwork(net Networker)

SetNetwork sets custom Network

func SetNilIfLenIsZero

func SetNilIfLenIsZero(setNil bool)

SetNilIfLenIsZero allows to set nil for the slice and maps, if size is 0.

func SetPayment

func SetPayment(p Render)

SetPayment set custom Network

func SetPhoner

func SetPhoner(p Phoner)

SetPhoner sets custom Phoner

func SetPrice

func SetPrice(p Money)

SetPrice sets custom Money

func SetRandomMapAndSliceSize

func SetRandomMapAndSliceSize(size int) error

SetRandomMapAndSliceSize sets the size for maps and slices for random generation.

func SetRandomNumberBoundaries

func SetRandomNumberBoundaries(start, end int) error

SetRandomNumberBoundaries sets boundary for random number generation

func SetRandomStringLength

func SetRandomStringLength(size int) error

SetRandomStringLength sets a length for random string generation

func TimeString

func TimeString() string

TimeString get time randomly in string format

func Timeperiod

func Timeperiod() string

Timeperiod get timeperiod randomly in string (AM/PM)

func Timestamp

func Timestamp() string

Timestamp get timestamp randomly in string format: 2006-01-02 15:04:05

func Timezone

func Timezone() string

Timezone get timezone randomly in string

func TitleFemale

func TitleFemale() string

TitleFemale get a title female randomly in string ("Mrs.", "Ms.", "Miss", "Dr.", "Prof.", "Lady", "Queen", "Princess")

func TitleMale

func TitleMale() string

TitleMale get a title male randomly in string ("Mr.", "Dr.", "Prof.", "Lord", "King", "Prince")

func TollFreePhoneNumber

func TollFreePhoneNumber() string

TollFreePhoneNumber get fake TollFreePhoneNumber

func URL

func URL() string

URL get Url randomly in string

func UUIDDigit

func UUIDDigit() string

UUIDDigit get fake Digit UUID

func UUIDHyphenated

func UUIDHyphenated() string

UUIDHyphenated get fake Hyphenated UUID

func UnixTime

func UnixTime() int64

UnixTime get unix time randomly

func Username

func Username() string

Username get username randomly in string

func Word

func Word() string

Word get a word randomly in string

func YearString

func YearString() string

YearString get year randomly in string format

Types

type Address

type Address struct{}

Address struct

func (Address) Latitude

func (i Address) Latitude(v reflect.Value) (interface{}, error)

Latitude sets latitude of the address

func (Address) Longitude

func (i Address) Longitude(v reflect.Value) (interface{}, error)

Longitude sets longitude of the address

type Addresser

type Addresser interface {
	Latitude(v reflect.Value) (interface{}, error)
	Longitude(v reflect.Value) (interface{}, error)
}

Addresser is logical layer for Address

func GetAddress

func GetAddress() Addresser

GetAddress returns a new Addresser interface of Address

type DataFaker

type DataFaker interface {
	Word(v reflect.Value) (interface{}, error)
	Sentence(v reflect.Value) (interface{}, error)
	Paragraph(v reflect.Value) (interface{}, error)
}

DataFaker generates randomized Words, Sentences and Paragraphs

func GetLorem

func GetLorem() DataFaker

GetLorem returns a new DataFaker interface of Lorem struct

type DateTime

type DateTime struct {
}

DateTime struct

func (DateTime) Century

func (d DateTime) Century(v reflect.Value) (interface{}, error)

Century returns a random century

func (DateTime) Date

func (d DateTime) Date(v reflect.Value) (interface{}, error)

Date formats DateTime using example BaseDateFormat const

func (DateTime) DayOfMonth

func (d DateTime) DayOfMonth(v reflect.Value) (interface{}, error)

DayOfMonth formats DateTime using example DayOfMonth const

func (DateTime) DayOfWeek

func (d DateTime) DayOfWeek(v reflect.Value) (interface{}, error)

DayOfWeek formats DateTime using example Day const

func (DateTime) MonthName

func (d DateTime) MonthName(v reflect.Value) (interface{}, error)

MonthName formats DateTime using example Month const

func (DateTime) Time

func (d DateTime) Time(v reflect.Value) (interface{}, error)

Time formats DateTime using example Time const

func (DateTime) TimePeriod

func (d DateTime) TimePeriod(v reflect.Value) (interface{}, error)

TimePeriod formats DateTime using example TimePeriod const

func (DateTime) TimeZone

func (d DateTime) TimeZone(v reflect.Value) (interface{}, error)

TimeZone returns a random timezone

func (DateTime) Timestamp

func (d DateTime) Timestamp(v reflect.Value) (interface{}, error)

Timestamp formats DateTime using example Timestamp const

func (DateTime) UnixTime

func (d DateTime) UnixTime(v reflect.Value) (interface{}, error)

UnixTime get unix time

func (DateTime) Year

func (d DateTime) Year(v reflect.Value) (interface{}, error)

Year formats DateTime using example Year const

type DateTimer

type DateTimer interface {
	UnixTime(v reflect.Value) (interface{}, error)
	Date(v reflect.Value) (interface{}, error)
	Time(v reflect.Value) (interface{}, error)
	MonthName(v reflect.Value) (interface{}, error)
	Year(v reflect.Value) (interface{}, error)
	DayOfWeek(v reflect.Value) (interface{}, error)
	DayOfMonth(v reflect.Value) (interface{}, error)
	Timestamp(v reflect.Value) (interface{}, error)
	Century(v reflect.Value) (interface{}, error)
	TimeZone(v reflect.Value) (interface{}, error)
	TimePeriod(v reflect.Value) (interface{}, error)
}

A DateTimer contains random Time generators, returning time string in certain particular format

func GetDateTimer

func GetDateTimer() DateTimer

GetDateTimer returns a new DateTimer interface of DateTime

type Dowser

type Dowser interface {
	TitleMale(v reflect.Value) (interface{}, error)
	TitleFeMale(v reflect.Value) (interface{}, error)
	FirstName(v reflect.Value) (interface{}, error)
	FirstNameMale(v reflect.Value) (interface{}, error)
	FirstNameFemale(v reflect.Value) (interface{}, error)
	LastName(v reflect.Value) (interface{}, error)
	Name(v reflect.Value) (interface{}, error)
}

Dowser provides interfaces to generate random logical Names with their initials

func GetPerson

func GetPerson() Dowser

GetPerson returns a new Dowser interface of Person struct

type Identifier

type Identifier interface {
	Digit(v reflect.Value) (interface{}, error)
	Hyphenated(v reflect.Value) (interface{}, error)
}

Identifier ...

func GetIdentifier

func GetIdentifier() Identifier

GetIdentifier returns a new Identifier

type Internet

type Internet struct{}

Internet struct

func (Internet) DomainName

func (internet Internet) DomainName(v reflect.Value) (interface{}, error)

DomainName generates random domain name

func (Internet) Email

func (internet Internet) Email(v reflect.Value) (interface{}, error)

Email generates random email id

func (Internet) IPv4

func (internet Internet) IPv4(v reflect.Value) (interface{}, error)

IPv4 generates random IPv4 address

func (Internet) IPv6

func (internet Internet) IPv6(v reflect.Value) (interface{}, error)

IPv6 generates random IPv6 address

func (Internet) MacAddress

func (internet Internet) MacAddress(v reflect.Value) (interface{}, error)

MacAddress generates random MacAddress

func (Internet) Password

func (internet Internet) Password(v reflect.Value) (interface{}, error)

Password returns a hashed password

func (Internet) URL

func (internet Internet) URL(v reflect.Value) (interface{}, error)

URL generates random URL standardised in urlFormats const

func (Internet) UserName

func (internet Internet) UserName(v reflect.Value) (interface{}, error)

UserName generates random username

type Lorem

type Lorem struct {
}

Lorem struct

func (Lorem) Paragraph

func (l Lorem) Paragraph(v reflect.Value) (interface{}, error)

Paragraph returns a series of sentences as a paragraph using the wordList const

func (Lorem) Sentence

func (l Lorem) Sentence(v reflect.Value) (interface{}, error)

Sentence returns a sentence using the wordList const

func (Lorem) Word

func (l Lorem) Word(v reflect.Value) (interface{}, error)

Word returns a word from the wordList const

type Money

type Money interface {
	Currency(v reflect.Value) (interface{}, error)
	Amount(v reflect.Value) (interface{}, error)
	AmountWithCurrency(v reflect.Value) (interface{}, error)
}

Money provides an interface to generate a custom price with or without a random currency code

func GetPrice

func GetPrice() Money

GetPrice returns a new Money interface of Price struct

type Networker

type Networker interface {
	Email(v reflect.Value) (interface{}, error)
	MacAddress(v reflect.Value) (interface{}, error)
	DomainName(v reflect.Value) (interface{}, error)
	URL(v reflect.Value) (interface{}, error)
	UserName(v reflect.Value) (interface{}, error)
	IPv4(v reflect.Value) (interface{}, error)
	IPv6(v reflect.Value) (interface{}, error)
	Password(v reflect.Value) (interface{}, error)
}

Networker is logical layer for Internet

func GetNetworker

func GetNetworker() Networker

GetNetworker returns a new Networker interface of Internet

type Payment

type Payment struct{}

Payment struct

func (Payment) CreditCardNumber

func (p Payment) CreditCardNumber(v reflect.Value) (interface{}, error)

CreditCardNumber generated credit card number according to the card number rules

func (Payment) CreditCardType

func (p Payment) CreditCardType(v reflect.Value) (interface{}, error)

CreditCardType returns one of the following credit values: VISA, MasterCard, American Express, Discover, JCB and Diners Club

type Person

type Person struct {
}

Person struct

func (Person) FirstName

func (p Person) FirstName(v reflect.Value) (interface{}, error)

FirstName retuns first names

func (Person) FirstNameFemale

func (p Person) FirstNameFemale(v reflect.Value) (interface{}, error)

FirstNameFemale retuns first names for females

func (Person) FirstNameMale

func (p Person) FirstNameMale(v reflect.Value) (interface{}, error)

FirstNameMale retuns first names for males

func (Person) LastName

func (p Person) LastName(v reflect.Value) (interface{}, error)

LastName returns last name

func (Person) Name

func (p Person) Name(v reflect.Value) (interface{}, error)

Name returns a random name

func (Person) TitleFeMale

func (p Person) TitleFeMale(v reflect.Value) (interface{}, error)

TitleFeMale generates random titles for females

func (Person) TitleMale

func (p Person) TitleMale(v reflect.Value) (interface{}, error)

TitleMale generates random titles for males

type Phone

type Phone struct {
}

Phone struct

func (Phone) E164PhoneNumber

func (p Phone) E164PhoneNumber(v reflect.Value) (interface{}, error)

E164PhoneNumber generates phone numbers of type: "+27113456789"

func (Phone) PhoneNumber

func (p Phone) PhoneNumber(v reflect.Value) (interface{}, error)

PhoneNumber generates phone numbers of type: "201-886-0269"

func (Phone) TollFreePhoneNumber

func (p Phone) TollFreePhoneNumber(v reflect.Value) (interface{}, error)

TollFreePhoneNumber generates phone numbers of type: "(888) 937-7238"

type Phoner

type Phoner interface {
	PhoneNumber(v reflect.Value) (interface{}, error)
	TollFreePhoneNumber(v reflect.Value) (interface{}, error)
	E164PhoneNumber(v reflect.Value) (interface{}, error)
}

Phoner serves overall tele-phonic contact generator

func GetPhoner

func GetPhoner() Phoner

GetPhoner serves as a constructor for Phoner interface

type Price

type Price struct {
}

Price struct

func (Price) Amount

func (p Price) Amount(v reflect.Value) (interface{}, error)

Amount returns a random floating price amount with a random precision of [1,2] up to (10**8 - 1)

func (Price) AmountWithCurrency

func (p Price) AmountWithCurrency(v reflect.Value) (interface{}, error)

AmountWithCurrency combines both price and currency together

func (Price) Currency

func (p Price) Currency(v reflect.Value) (interface{}, error)

Currency returns a random currency from currencies

type Render

type Render interface {
	CreditCardType(v reflect.Value) (interface{}, error)
	CreditCardNumber(v reflect.Value) (interface{}, error)
}

Render contains Whole Random Credit Card Generators with their types

func GetPayment

func GetPayment() Render

GetPayment returns a new Render interface of Payment struct

type TaggedFunction

type TaggedFunction func(v reflect.Value) (interface{}, error)

TaggedFunction used as the standard layout function for tag providers in struct. This type also can be used for custom provider.

type UUID

type UUID struct{}

UUID struct

func (UUID) Digit

func (u UUID) Digit(v reflect.Value) (interface{}, error)

Digit returns a 32 bytes UUID

func (UUID) Hyphenated

func (u UUID) Hyphenated(v reflect.Value) (interface{}, error)

Hyphenated returns a 36 byte hyphenated UUID

Directories

Path Synopsis
support

Jump to

Keyboard shortcuts

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