faker

package module
v3.8.1 Latest Latest
Warning

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

Go to latest
Published: Dec 8, 2022 License: MIT Imports: 14 Imported by: 297

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 Go.Dev

Index

Support

You can file an Issue. See documentation in Godoc or in Go.Dev

Getting Started

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

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 be PUBLIC.
Support Only For :

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

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.
  • Some extra custom types can be supported IF AND ONLY IF extended with AddProvider() please see example
  • The oneof tag currently only supports string, the int types, and both float32 & float64. Further support is coming soon (i.e. hex numbers, etc). See example for usage.

Contribution


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

Documentation

Overview

Example (CustomFaker)

You can also add your own generator function to your own defined tags.

package main

import (
	"fmt"
	"reflect"

	"github.com/bxcodec/faker/v3"
)

// Gondoruwo ...
type Gondoruwo struct {
	Name       string
	Locatadata int
}

// custom type that aliases over slice of byte
type CustomUUID []byte

// Sample ...
type Sample struct {
	ID        int64      `faker:"customIdFaker"`
	Gondoruwo Gondoruwo  `faker:"gondoruwo"`
	Danger    string     `faker:"danger"`
	UUID      CustomUUID `faker:"customUUID"`
}

// CustomGenerator ...
func CustomGenerator() {
	_ = faker.AddProvider("customIdFaker", func(v reflect.Value) (interface{}, error) {
		return int64(43), nil
	})
	_ = faker.AddProvider("danger", 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
	})

	_ = faker.AddProvider("customUUID", func(v reflect.Value) (interface{}, error) {
		s := CustomUUID{
			0, 8, 7, 2, 3,
		}
		return s, nil
	})
}

// You can also add your own generator function to your own defined tags.
func main() {
	CustomGenerator()
	var sample Sample
	_ = faker.FakeData(&sample)
	fmt.Printf("%+v", sample)
}
Output:

{ID:43 Gondoruwo:{Name:Power Locatadata:324} Danger:danger-ranger UUID:[0 8 7 2 3]}
Example (SingleFakeData)

Single fake function can be used for retrieving particular values.

// Address
faker.Latitude()  // => 81.12195
faker.Longitude() // => -84.38158

// Datetime
faker.UnixTime()   // => 1197930901
faker.Date()       // => 1982-02-27
faker.TimeString() // => 03:10:25
faker.MonthName()  // => February
faker.YearString() // => 1994
faker.DayOfWeek()  // => Sunday
faker.DayOfMonth() // => 20
faker.Timestamp()  // => 1973-06-21 14:50:46
faker.Century()    // => IV
faker.Timezone()   // => Asia/Jakarta
faker.Timeperiod() // => PM

// Internet
faker.Email()      // => mJBJtbv@OSAaT.com
faker.MacAddress() // => cd:65:e1:d4:76:c6
faker.DomainName() // => FWZcaRE.org
faker.URL()        // => https://www.oEuqqAY.org/QgqfOhd
faker.Username()   // => lVxELHS
faker.IPv4()       // => 99.23.42.63
faker.IPv6()       // => 975c:fb2c:2133:fbdd:beda:282e:1e0a:ec7d
faker.Password()   // => dfJdyHGuVkHBgnHLQQgpINApynzexnRpgIKBpiIjpTP

// Words and Sentences
faker.Word()      // => nesciunt
faker.Sentence()  // => Consequatur perferendis voluptatem accusantium.
faker.Paragraph() // => Aut consequatur sit perferendis accusantium voluptatem. Accusantium perferendis consequatur voluptatem sit aut. Aut sit accusantium consequatur voluptatem perferendis. Perferendis voluptatem aut accusantium consequatur sit.

// Payment
faker.CCType()             // => American Express
faker.CCNumber()           // => 373641309057568
faker.Currency()           // => USD
faker.AmountWithCurrency() // => USD 49257.100

// Person
faker.TitleMale()       // => Mr.
faker.TitleFemale()     // => Mrs.
faker.FirstName()       // => Whitney
faker.FirstNameMale()   // => Kenny
faker.FirstNameFemale() // => Jana
faker.LastName()        // => Rohan
faker.Name()            // => Mrs. Casandra Kiehn

// Phone
faker.Phonenumber()         // -> 201-886-0269
faker.TollFreePhoneNumber() // => (777) 831-964572
faker.E164PhoneNumber()     // => +724891571063

//  UUID
faker.UUIDHyphenated() // => 8f8e4463-9560-4a38-9b0c-ef24481e4e27
faker.UUIDDigit()      // => 90ea6479fd0e4940af741f0a87596b73

// Unique values
faker.SetGenerateUniqueValues(true) // Enable unique data generation on single fake data functions
faker.Word()
// ...
faker.SetGenerateUniqueValues(false) // Disable unique data generation on single fake data functions
faker.ResetUnique()                  // Forget all generated unique values
Output:

Example (WithTags)
package main

import (
	"fmt"

	"github.com/bxcodec/faker/v3"
)

// SomeStructWithTags ...
type SomeStructWithTags struct {
	Latitude           float32 `faker:"lat"`
	Longitude          float32 `faker:"long"`
	CreditCardNumber   string  `faker:"cc_number"`
	CreditCardType     string  `faker:"cc_type"`
	Email              string  `faker:"email"`
	DomainName         string  `faker:"domain_name"`
	IPV4               string  `faker:"ipv4"`
	IPV6               string  `faker:"ipv6"`
	Password           string  `faker:"password"`
	Jwt                string  `faker:"jwt"`
	PhoneNumber        string  `faker:"phone_number"`
	MacAddress         string  `faker:"mac_address"`
	URL                string  `faker:"url"`
	UserName           string  `faker:"username"`
	TollFreeNumber     string  `faker:"toll_free_number"`
	E164PhoneNumber    string  `faker:"e_164_phone_number"`
	TitleMale          string  `faker:"title_male"`
	TitleFemale        string  `faker:"title_female"`
	FirstName          string  `faker:"first_name"`
	FirstNameMale      string  `faker:"first_name_male"`
	FirstNameFemale    string  `faker:"first_name_female"`
	LastName           string  `faker:"last_name"`
	Name               string  `faker:"name"`
	UnixTime           int64   `faker:"unix_time"`
	Date               string  `faker:"date"`
	Time               string  `faker:"time"`
	MonthName          string  `faker:"month_name"`
	Year               string  `faker:"year"`
	DayOfWeek          string  `faker:"day_of_week"`
	DayOfMonth         string  `faker:"day_of_month"`
	Timestamp          string  `faker:"timestamp"`
	Century            string  `faker:"century"`
	TimeZone           string  `faker:"timezone"`
	TimePeriod         string  `faker:"time_period"`
	Word               string  `faker:"word"`
	Sentence           string  `faker:"sentence"`
	Paragraph          string  `faker:"paragraph"`
	Currency           string  `faker:"currency"`
	Amount             float64 `faker:"amount"`
	AmountWithCurrency string  `faker:"amount_with_currency"`
	UUIDHypenated      string  `faker:"uuid_hyphenated"`
	UUID               string  `faker:"uuid_digit"`
	Skip               string  `faker:"-"`
	PaymentMethod      string  `faker:"oneof: cc, paypal, check, money order"` // oneof will randomly pick one of the comma-separated values supplied in the tag
	AccountID          int     `faker:"oneof: 15, 27, 61"`                     // use commas to separate the values for now. Future support for other separator characters may be added
	Price32            float32 `faker:"oneof: 4.95, 9.99, 31997.97"`
	Price64            float64 `faker:"oneof: 47463.9463525, 993747.95662529, 11131997.978767990"`
	NumS64             int64   `faker:"oneof: 1, 2"`
	NumS32             int32   `faker:"oneof: -3, 4"`
	NumS16             int16   `faker:"oneof: -5, 6"`
	NumS8              int8    `faker:"oneof: 7, -8"`
	NumU64             uint64  `faker:"oneof: 9, 10"`
	NumU32             uint32  `faker:"oneof: 11, 12"`
	NumU16             uint16  `faker:"oneof: 13, 14"`
	NumU8              uint8   `faker:"oneof: 15, 16"`
	NumU               uint    `faker:"oneof: 17, 18"`
}

func main() {

	a := SomeStructWithTags{}
	err := faker.FakeData(&a)
	if err != nil {
		fmt.Println(err)
	}
	fmt.Printf("%+v", a)
	/*
		Result:
		{
			Latitude: 81.12195
			Longitude: -84.38158
			CreditCardType: American Express
			CreditCardNumber: 373641309057568
			Email: mJBJtbv@OSAaT.ru
			DomainName: FWZcaRE.ru,
			IPV4: 99.23.42.63
			IPV6: 975c:fb2c:2133:fbdd:beda:282e:1e0a:ec7d
			Password: dfJdyHGuVkHBgnHLQQgpINApynzexnRpgIKBpiIjpTPOmNyMFb
			Jwt: HDMNSOKhEIYkPIuHcVjfCtHlKkaqLGrUEqjKVkgR.HDMNSOKhEIYkPIuHcVjfCtHlKkaqLGrUEqjKVkgR.HDMNSOKhEIYkPIuHcVjfCtHlKkaqLGrUEqjKVkgR
			PhoneNumber: 792-153-4861
			MacAddress: cd:65:e1:d4:76:c6
			URL: https://www.oEuqqAY.org/QgqfOhd
			UserName: lVxELHS
			TollFreeNumber: (777) 831-964572
			E164PhoneNumber: +724891571063
			TitleMale: Mr.
			TitleFemale: Queen
			FirstName: Whitney
			FirstNameMale: Kenny
			FirstNameFemale: Jana
			LastName: Rohan
			Name: Miss Casandra Kiehn
			UnixTime: 1197930901
			Date: 1982-02-27
			Time: 03:10:25
			MonthName: February
			Year: 1996
			DayOfWeek: Sunday
			DayOfMonth: 20
			Timestamp: 1973-06-21 14:50:46
			Century: IV
			TimeZone: Canada/Eastern
			TimePeriod: AM
			Word: nesciunt
			Sentence: Consequatur perferendis aut sit voluptatem accusantium.
			Paragraph: Aut consequatur sit perferendis accusantium voluptatem. Accusantium perferendis consequatur voluptatem sit aut. Aut sit accusantium consequatur voluptatem perferendis. Perferendis voluptatem aut accusantium consequatur sit.
			Currency: IRR,
			Amount: 88.990000,
			AmountWithCurrency: XBB 49257.100000,
			UUIDHypenated: 8f8e4463-9560-4a38-9b0c-ef24481e4e27,
			UUID: 90ea6479fd0e4940af741f0a87596b73,
			PaymentMethod: paypal,
			AccountID: 61,
			Price32: 4.95,
			Price64: 993747.95662529
			NumS64:	1
			NumS32:	-3
			NumS16:	5
			NumS8:	-8
			NumU64:	9
			NumU32:	11
			NumU16:	13
			NumU8:	15
			NumU:	17
			Skip:
		}
	*/

}
Output:

Example (WithTagsAndUnique)
package main

import (
	"fmt"

	"github.com/bxcodec/faker/v3"
)

// SomeStructWithUnique ...
type SomeStructWithUnique struct {
	Word string `faker:"word,unique"`
}

func main() {
	for i := 0; i < 5; i++ { // Generate 5 structs having a unique word
		a := SomeStructWithUnique{}
		err := faker.FakeData(&a)
		if err != nil {
			fmt.Println(err)
		}
		fmt.Printf("%+v", a)
	}
	faker.ResetUnique() // Forget all generated unique values. Allows to start generating another unrelated dataset.

	// Result:
	//	{Word:nobis}{Word:recusandae}{Word:praesentium}{Word:doloremque}{Word:non}
}
Output:

Example (WithTagsLang)

You can set length for your random strings also set boundary for your integers.

// SomeStruct ...
type SomeStruct struct {
	StringENG string `faker:"lang=eng"`
	StringCHI string `faker:"lang=chi"`
	StringRUS string `faker:"lang=rus"`
	StringJPN string `faker:"lang=jpn"`
	StringKOR string `faker:"lang=kor"`
	StringEMJ string `faker:"lang=emj"`
}

a := SomeStruct{}
_ = faker.SetRandomStringLength(5)
_ = faker.FakeData(&a)
fmt.Printf("%+v", a)
// Result:
/*
	   {
		   StringENG:VVcaPS
		   StringCHI: 随机字符串
		   StringRUS:ваЩфз
		   StringJPN:びゃほぱヒてふ
		   StringKOR:텻밚쨋큊몉
		   StringEMJ:🐅😄🕢🍪🐡
	   }
*/
Output:

Example (WithTagsLengthAndBoundary)

You can set length for your random strings also set boundary for your integers.

// SomeStruct ...
type SomeStruct struct {
	Inta  int   `faker:"boundary_start=5, boundary_end=10"`
	Int8  int8  `faker:"boundary_start=100, boundary_end=1000"`
	Int16 int16 `faker:"boundary_start=123, boundary_end=1123"`
	Int32 int32 `faker:"boundary_start=-10, boundary_end=8123"`
	Int64 int64 `faker:"boundary_start=31, boundary_end=88"`

	UInta  uint   `faker:"boundary_start=35, boundary_end=152"`
	UInt8  uint8  `faker:"boundary_start=5, boundary_end=1425"`
	UInt16 uint16 `faker:"boundary_start=245, boundary_end=2125"`
	UInt32 uint32 `faker:"boundary_start=0, boundary_end=40"`
	UInt64 uint64 `faker:"boundary_start=14, boundary_end=50"`

	Float32 float32 `faker:"boundary_start=12.65, boundary_end=184.05"`
	Float64 float64 `faker:"boundary_start=1.256, boundary_end=3.4"`

	ASString []string          `faker:"len=50"`
	SString  string            `faker:"len=25"`
	MSString map[string]string `faker:"len=30"`
	MIint    map[int]int       `faker:"boundary_start=5, boundary_end=10"`
}

_ = faker.SetRandomMapAndSliceSize(20) // Random generated map or array size wont exceed 20...
a := SomeStruct{}
_ = faker.FakeData(&a)
fmt.Printf("%+v", a)
// Result:
/*
   {
       Inta:7
       Int8:-102
       Int16:556
       Int32:113
       Int64:70
       UInta:78
       UInt8:54
       UInt16:1797
       UInt32:8
       UInt64:34
       Float32:60.999058
       Float64:2.590148738554016
       ASString:[
           geHYIpEoQhQdijFooVEAOyvtTwJOofbQPJdbHvEEdjueZaKIgI
           WVJBBtmrrVccyIydAiLSkMwWbFzFMEotEXsyUXqcmBTVORlkJK
           xYiRTRSZRuGDcMWYoPALVMZgIXoTQtmdGXQfbISKJiavLspuBV
           qsoiYlyRbXLDAMoIdQhgMriODYWCTEYepmjaldWLLjkulDGuQN
           GQXUlqNkVjPKodMebPIeoZZlxfhbQJOjHSRjUTrcgBFPeDZIxn
           MEeRkkLceDsqKLEJFEjJxHtYrYxQMxYcuRHEDGYSPbELDQLSsj
           tWUIACjQWeiUhbboGuuEQIhUJCRSBzVImpYwOlFbsjCRmxboZW
           ZDaAUZEgFKbMJoKIMpymTreeZGWLXNCfVzaEyWNdbkaZOcsfst
           uwlsZBMlEknIBsALpXRaplZWVtXTKzsWglRVBpmfsQfqraiEYA
           AXszbzsOzYPYeXHXRwoPmoPoBxopdFFvWMBTPCxESTepRpjlnB
           kTuOPHlUrSzUQRmZMYplWbyoBbWzQYCiydyzurOduhjuyiGrCE
           FZbeLMbelIeCMnixknIARZRbwALObGXADQqianJbkiEAqqpdnK
           TiQrZbnkvxEciyKXlliUDOGVdpMoAsHSalFbLcYyXxNFLAhqjy
           KlbjbloxkWKSqvUfJQPpFLoddWgeABfYUoaAnylKmEHwxgNsnO
           ]
       SString:VVcaPSFrOPYlEkpVyTRbSZneB
       MSString:map[
           ueFBFTTmqDwrXDoXAYTRhQRmLXhudA:AhQewvZfrlytbAROzGjpXUmNQzIoGl
           fZwrCsFfZwqMsDJXOUYIacflFIeyFU:VMufFCRRHTtuFthOrRAMbzbKVJHnvJ
           rHDQTyZqZVSPLwTtZfNSwKWrgmRghL:lRSXNHkhUyjDuBgoAfrQwOcHYilqRB
           BvCpQJMHzKXKbOoAnTXkLCNxKshwWr:tiNFrXAXUtdywkyygWBrEVrmAcAepD
           uWWKgHKTkUgAZiopAIUmgVWrkrceVy:GuuDNTUiaBtOKwWrMoZDiyaOPxywnq
           HohMjOdMDkAqimKPTgdjUorydpKkly:whAjmraukcZczskqycoJELlMJTghca
           umEgMBGUvBptdKImKsoWXMGJJoRbgT:tPpgHgLEyHmDOocOiSgTbXQHVduLxP
           SRQLHjBXCXKvbLIktdKeLwMnIFOmbi:IJBpLyTcraOxOUtwSKTisjElpulkTL
           dbnDeJZLqMXQGjbTSNxPSlfDHGCghU:JWrymovFwNWbIQBxPpQmlgJsgpXcui
           roraKNGnBXnrJlsxTnFgxHyZeTXdAC:XIcLWqUAQAbfkRrgfjrTVxZCvRJXyl
           TrvxqVVjXAboYDPvUglSJQrltPjzLx:nBhWdfNPybnNnCyQlSshWKOnwUMQzL
           dTHhWJWMwfVvKpIKTFCaoBJgKmnfbD:ixjNHsvSkRkFiNLpgUzIKPsheqhCeY
           lWyBrtfcGWiNbSTJZJXwOPvVngZZMk:kvlYeGgwguVtiafGKjHWsYWewbaXte
           bigsYNfVcNMGtnzgaqEjeRRlIcUdbR:hYOnJupEOvblTTEYzZYPuTVmvTmiit
           ]
       MIint:map[7:7 5:7 8:8 9:5 6:5]
   }
*/
Output:

Example (WithTagsSliceLength)

You can set the size for your random slices.

// SomeStruct ...
type SomeStruct struct {
	EmptyList       []string `faker:"slice_len=0"`
	FixedStringList []string `faker:"slice_len=2"`
	FixedIntList    []int64  `faker:"slice_len=4"`
	RandomIntList   []int64
}

_ = faker.SetRandomMapAndSliceSize(20) // If no slice_len is set, this sets the max of the random size
a := SomeStruct{}
_ = faker.FakeData(&a)
fmt.Printf("%+v", a)
// Result:
/*
	   {
	       EmptyList:[]
	       FixedStringList:[
		           geHYIpEoQhQdijFooVEAOyvtTwJOofbQPJdbHvEEdjueZaKIgI
		           WVJBBtmrrVccyIydAiLSkMwWbFzFMEotEXsyUXqcmBTVORlkJK
		   ]
		   FixedIntList:[10,25,60,15]
	       RandomIntList:[5,16,134,6235,123,53,123] //Random len() with a max of 20
	   }
*/
Output:

Example (WithoutTag)

You also can use faker to generate your structs data randomly without any tag. And it will fill the data based on its data-type.

package main

import (
	"fmt"

	"github.com/bxcodec/faker/v3"
)

// SomeStruct ...
type SomeStruct struct {
	Int      int
	Int8     int8
	Int16    int16
	Int32    int32
	Int64    int64
	String   string
	Bool     bool
	SString  []string
	SInt     []int
	SInt8    []int8
	SInt16   []int16
	SInt32   []int32
	SInt64   []int64
	SFloat32 []float32
	SFloat64 []float64
	SBool    []bool
	Struct   AStruct
}

// AStruct ...
type AStruct struct {
	Number        int64
	Height        int64
	AnotherStruct BStruct
}

// BStruct ...
type BStruct struct {
	Image string
}

// You also can use faker to generate your structs data randomly without any tag.
// And it will fill the data based on its data-type.
func main() {
	a := SomeStruct{}
	err := faker.FakeData(&a)
	if err != nil {
		fmt.Println(err)
	}
	fmt.Printf("%+v", a)
	/*
		Result:
		{
		    Int:5231564546548329
		    Int8:52
		    Int16:8
		    Int32:2046951236
		    Int64:1486554863682234423
		    String:ELIQhSfhHmWxyzRPOTNblEQsp
		    Bool:false
		    SString:[bzYwplRGUAXPwatnpVMWSYjep zmeuJVGHHgmIsuyWmLJnDmbTI FqtejCwoDyMBWatoykIzorCJZ]
		    SInt:[11661230973193 626062851427 12674621422454 5566279673347]
		    SInt8:[12 2 58 22 11 66 5 88]
		    SInt16:[29295225 8411281 69902706328]
		    SInt32:[60525685140 2733640366211 278043484637 5167734561481]
		    SInt64:[81684520429188374184 9917955420365482658170 996818723778286568 163646873275501565]
		    SFloat32:[0.556428 0.7692596 0.6779895 0.29171365 0.95445055]
		    SFloat64:[0.44829454895586585 0.5495675898536803 0.6584538253883265]
		    SBool:[true false true false true true false]
		    Struct:{
		        Number:1
		        Height:26
		        AnotherStruct:{
		            Image:RmmaaHkAkrWHldVbBNuQSKlRb
		        }
		    }
		}
	*/
}
Output:

Index

Examples

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"
	JWT                   = "jwt"
	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"
	ChineseFirstNameTag   = "chinese_first_name"
	ChineseLastNameTag    = "chinese_last_name"
	ChineseNameTag        = "chinese_name"
	GENDER                = "gender"
	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"
	SliceLength           = "slice_len"
	Language              = "lang"
	BoundaryStart         = "boundary_start"
	BoundaryEnd           = "boundary_end"
	Equals                = "="

	ONEOF = "oneof"
)

Supported tags

Variables

View Source
var (
	// LangENG is for english language
	LangENG = langRuneBoundary{65, 122, []rune{91, 92, 93, 94, 95, 96}}
	// LangCHI is for chinese language
	LangCHI = langRuneBoundary{19968, 40869, nil}
	// LangRUS is for russian language
	LangRUS = langRuneBoundary{1025, 1105, nil}
	// LangJPN is for japanese Hiragana Katakana language
	LangJPN = langRuneBoundary{12353, 12534, []rune{12436, 12437, 12438, 12439, 12440, 12441, 12442, 12443, 12444, 12445, 12446, 12447, 12448}}
	// LangKOR is for korean Hangul language
	LangKOR = langRuneBoundary{44032, 55203, nil}
	// EmotEMJ is for emoticons
	EmotEMJ = langRuneBoundary{126976, 129535, nil}
)

Language rune boundaries here

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: %s"
	ErrTagAlreadyExists    = "Tag exists"
	ErrTagDoesNotExist     = "Tag does not exist"
	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."
	ErrSmallerThanOne      = "Size:%d is smaller than one."
	ErrUniqueFailure       = "Failed to generate a unique value for field \"%s\""

	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."
	ErrUnsupportedTagArguments = "Tag arguments are not compatible with field type."
	ErrDuplicateSeparator      = "Duplicate separator for tag arguments."
	ErrNotEnoughTagArguments   = "Not enough arguments for tag."
	ErrUnsupportedNumberType   = "Unsupported Number type."
)

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
ErrTagDoesNotExist: Error when tag does not exist and call RemoveProvider
ErrMoreArguments: Error on passing more arguments
ErrNotSupportedPointer: Error when passing unsupported pointer

PriorityTags define the priority order of the tag

Functions

func AddProvider

func AddProvider(tag string, provider TaggedFunction) error

AddProvider extend faker with tag to generate fake data with specified custom algorithm 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 ChineseFirstName added in v3.8.0

func ChineseFirstName() string

ChineseFirstName get chinese first name

func ChineseLastName added in v3.8.0

func ChineseLastName() string

ChineseLastName get chinese lsst name

func ChineseName added in v3.8.0

func ChineseName() string

ChineseName get chinese lsst name

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 Gender added in v3.4.0

func Gender() string

Gender get fake gender

func IPv4

func IPv4() string

IPv4 get IPv4 randomly in string

func IPv6

func IPv6() string

IPv6 get IPv6 randomly in string

func Jwt added in v3.6.0

func Jwt() string

Jwt get jwt-like 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 NewSafeSource added in v3.7.0

func NewSafeSource(in mathrand.Source) mathrand.Source

NewSafeSource wraps an unsafe rand.Source with a mutex to guard the random source against concurrent access.

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 (minimum_int, maximum_int, count)

If only set one parameter :  An integer greater than minimum_int will be returned
If only set two parameters : All integers between minimum_int and maximum_int will be returned, in a random order.
If three parameters: `count` integers between minimum_int and maximum_int will be returned.

func RandomUnixTime

func RandomUnixTime() int64

RandomUnixTime is a helper function returning random Unix time

func RemoveProvider added in v3.6.0

func RemoveProvider(tag string) error

RemoveProvider removes existing customization added with AddProvider

func ResetUnique added in v3.2.0

func ResetUnique()

ResetUnique is used to forget generated unique values. Call this when you're done generating a dataset.

func Sentence

func Sentence() string

Sentence get a sentence randomly in string

func SetAddress

func SetAddress(net Addresser)

SetAddress sets custom Address

func SetCryptoSource added in v3.7.0

func SetCryptoSource(in io.Reader)

SetCryptoSource sets a new reader for functions using a cryptographically-safe random generator (e.g. UUID).

The default is the global source provided by crypto/rand.

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 SetGenerateUniqueValues added in v3.2.0

func SetGenerateUniqueValues(unique bool)

SetGenerateUniqueValues allows to set the single fake data generator functions to generate unique data.

func SetIgnoreInterface added in v3.6.0

func SetIgnoreInterface(ignore bool)

SetIgnoreInterface allows to set a flag to ignore found interface{}s.

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 SetRandomMapAndSliceMaxSize added in v3.8.0

func SetRandomMapAndSliceMaxSize(size int) error

SetRandomMapAndSliceMaxSize sets the max size for maps and slices for random generation.

func SetRandomMapAndSliceMinSize added in v3.8.0

func SetRandomMapAndSliceMinSize(size int) error

SetRandomMapAndSliceMinSize sets the min size for maps and slices for random generation.

func SetRandomMapAndSliceSize

func SetRandomMapAndSliceSize(size int) error

SetRandomMapAndSliceSize sets the size for maps and slices for random generation. deprecates, currently left for old version usage

func SetRandomNumberBoundaries

func SetRandomNumberBoundaries(start, end int) error

SetRandomNumberBoundaries sets boundary for random number generation

func SetRandomSource added in v3.7.0

func SetRandomSource(in mathrand.Source)

SetRandomSource sets a new random source at the package level.

To use a concurrent-safe source, you may wrap it with NewSafeSource, e.g. SetRandomSource(NewSafeSource(mysource)).

The default is the global, concurrent-safe source provided by math/rand.

func SetRandomStringLength

func SetRandomStringLength(size int) error

SetRandomStringLength sets a length for random string generation

func SetStringLang added in v3.4.0

func SetStringLang(l langRuneBoundary)

SetStringLang sets language of random string generation (LangENG, LangCHI, LangRUS, LangJPN, LangKOR, EmotEMJ)

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)
	Gender(v reflect.Value) (interface{}, error)
	ChineseFirstName(v reflect.Value) (interface{}, error)
	ChineseLastName(v reflect.Value) (interface{}, error)
	ChineseName(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) Jwt added in v3.6.0

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

Jwt returns a jwt-like random string in xxxx.yyyy.zzzz style

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 standardized 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)
	Jwt(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) ChineseFirstName added in v3.8.0

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

ChineseFirstName returns a random chinese first name

func (Person) ChineseLastName added in v3.8.0

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

ChineseLastName returns a random chinese last name

func (Person) ChineseName added in v3.8.0

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

ChineseName returns a random nhinese name

func (Person) FirstName

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

FirstName returns first names

func (Person) FirstNameFemale

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

FirstNameFemale returns first names for females

func (Person) FirstNameMale

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

FirstNameMale returns first names for males

func (Person) Gender added in v3.4.0

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

Gender returns a random gender

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