faker

package module
v4.0.0-beta.3 Latest Latest
Warning

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

Go to latest
Published: Oct 14, 2022 License: MIT Imports: 19 Imported by: 38

README

Important Notes

This repository has been archived, and moved to the new repository here https://github.com/go-faker/faker Further development and fixing will be happening in the new repository.


Docs

faker

Struct Data Fake Generator

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

Build Status codecov Go Report Card License Go.Dev

Index

Support

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

Getting Started

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

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/v4"
)

// 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
fmt.Println(faker.Latitude())  // => 81.12195
fmt.Println(faker.Longitude()) // => -84.38158

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

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

// Words and Sentences
fmt.Println(faker.Word())      // => nesciunt
fmt.Println(faker.Sentence())  // => Consequatur perferendis voluptatem accusantium.
fmt.Println(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
fmt.Println(faker.CCType())             // => American Express
fmt.Println(faker.CCNumber())           // => 373641309057568
fmt.Println(faker.Currency())           // => USD
fmt.Println(faker.AmountWithCurrency()) // => USD 49257.100

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

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

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

fmt.Println(faker.Word())

faker.ResetUnique() // Forget all generated unique values
Output:

Example (WithTags)
package main

import (
	"fmt"

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

// 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"`
	PtrNumU            *uint   `faker:"oneof: 19, 20"`
}

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
			PtrNumU: 19
			Skip:
		}
	*/

}
Output:

Example (WithTagsAndUnique)
package main

import (
	"fmt"

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

// 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)
package main

import (
	"fmt"

	"github.com/bxcodec/faker/v4"
	"github.com/bxcodec/faker/v4/pkg/options"
)

// You can set length for your random strings also set boundary for your integers.
// SomeStructForLanguage ...
type SomeStructForLanguage 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"`
}

func main() {
	a := SomeStructForLanguage{}
	_ = faker.FakeData(&a, options.WithRandomStringLength(5))
	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.

package main

import (
	"fmt"

	"github.com/bxcodec/faker/v4"
	"github.com/bxcodec/faker/v4/pkg/options"
)

// SomeStructWithLengthAndBoundary ...
type SomeStructWithLengthAndBoundary 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"`
}

// You can set length for your random strings also set boundary for your integers.
func main() {
	a := SomeStructWithLengthAndBoundary{}
	_ = faker.FakeData(&a, options.WithRandomMapAndSliceMaxSize(20)) // Random generated map or array size wont exceed 20...
	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.

a := SomeStructWithSliceLength{}
_ = faker.FakeData(&a, options.WithRandomMapAndSliceMaxSize(20)) // If no slice_len is set, this sets the max of the random size
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/v4"
)

// 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 (
	SetGenerateUniqueValues     = options.SetGenerateUniqueValues
	SetIgnoreInterface          = options.SetIgnoreInterface
	SetRandomStringLength       = options.SetRandomStringLength
	SetStringLang               = options.SetStringLang
	SetRandomMapAndSliceSize    = options.SetRandomMapAndSliceSize
	SetRandomMapAndSliceMaxSize = options.SetRandomMapAndSliceMaxSize
	SetRandomMapAndSliceMinSize = options.SetRandomMapAndSliceMinSize
	SetRandomNumberBoundaries   = options.SetRandomNumberBoundaries
)

PriorityTags define the priority order of the tag

Functions

func AddProvider

func AddProvider(tag string, provider interfaces.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(opts ...options.OptionFunc) string

AmountWithCurrency get fake AmountWithCurrency USD 49257.100

func CCNumber

func CCNumber(opts ...options.OptionFunc) string

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

func CCType

func CCType(opts ...options.OptionFunc) string

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

func Century

func Century(opts ...options.OptionFunc) string

Century get century randomly in string

func ChineseFirstName

func ChineseFirstName(opts ...options.OptionFunc) string

ChineseFirstName get chinese first name

func ChineseLastName

func ChineseLastName(opts ...options.OptionFunc) string

ChineseLastName get chinese lsst name

func ChineseName

func ChineseName(opts ...options.OptionFunc) string

ChineseName get chinese lsst name

func Currency

func Currency(opts ...options.OptionFunc) string

Currency get fake Currency (IDR, USD)

func Date

func Date(opts ...options.OptionFunc) string

Date get fake date in string randomly

func DayOfMonth

func DayOfMonth(opts ...options.OptionFunc) string

DayOfMonth get month randomly in string format

func DayOfWeek

func DayOfWeek(opts ...options.OptionFunc) string

DayOfWeek get day of week randomly in string format

func DomainName

func DomainName(opts ...options.OptionFunc) string

DomainName get email domain name in string

func E164PhoneNumber

func E164PhoneNumber(opts ...options.OptionFunc) string

E164PhoneNumber get fake E164PhoneNumber

func Email

func Email(opts ...options.OptionFunc) string

Email get email randomly in string

func FakeData

func FakeData(a interface{}, opt ...options.OptionFunc) 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(opts ...options.OptionFunc) string

FirstName get fake firstname

func FirstNameFemale

func FirstNameFemale(opts ...options.OptionFunc) string

FirstNameFemale get fake firstname for female

func FirstNameMale

func FirstNameMale(opts ...options.OptionFunc) string

FirstNameMale get fake firstname for male

func Gender

func Gender(opts ...options.OptionFunc) string

Gender get fake gender

func IPv4

func IPv4(opts ...options.OptionFunc) string

IPv4 get IPv4 randomly in string

func IPv6

func IPv6(opts ...options.OptionFunc) string

IPv6 get IPv6 randomly in string

func Jwt

func Jwt(opts ...options.OptionFunc) string

Jwt get jwt-like string

func LastName

func LastName(opts ...options.OptionFunc) string

LastName get fake lastname

func Latitude

func Latitude(opts ...options.OptionFunc) float64

Latitude get fake latitude randomly

func Longitude

func Longitude(opts ...options.OptionFunc) float64

Longitude get fake longitude randomly

func MacAddress

func MacAddress(opts ...options.OptionFunc) string

MacAddress get mac address randomly in string

func MonthName

func MonthName(opts ...options.OptionFunc) string

MonthName get month name randomly in string format

func Name

func Name(opts ...options.OptionFunc) string

Name get fake name

func NewSafeSource

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(opts ...options.OptionFunc) string

Paragraph get a paragraph randomly in string

func Password

func Password(opts ...options.OptionFunc) string

Password get password randomly in string

func Phonenumber

func Phonenumber(opts ...options.OptionFunc) 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

func RemoveProvider(tag string) error

RemoveProvider removes existing customization added with AddProvider

func ResetUnique

func ResetUnique()

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

func Sentence

func Sentence(opts ...options.OptionFunc) string

Sentence get a sentence randomly in string

func SetCryptoSource

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 SetRandomSource

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 TimeString

func TimeString(opts ...options.OptionFunc) string

TimeString get time randomly in string format

func Timeperiod

func Timeperiod(opts ...options.OptionFunc) string

Timeperiod get timeperiod randomly in string (AM/PM)

func Timestamp

func Timestamp(opts ...options.OptionFunc) string

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

func Timezone

func Timezone(opts ...options.OptionFunc) string

Timezone get timezone randomly in string

func TitleFemale

func TitleFemale(opts ...options.OptionFunc) string

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

func TitleMale

func TitleMale(opts ...options.OptionFunc) string

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

func TollFreePhoneNumber

func TollFreePhoneNumber(opts ...options.OptionFunc) string

TollFreePhoneNumber get fake TollFreePhoneNumber

func URL

func URL(opts ...options.OptionFunc) string

URL get Url randomly in string

func UUIDDigit

func UUIDDigit(opts ...options.OptionFunc) string

UUIDDigit get fake Digit UUID

func UUIDHyphenated

func UUIDHyphenated(opts ...options.OptionFunc) string

UUIDHyphenated get fake Hyphenated UUID

func UnixTime

func UnixTime(opts ...options.OptionFunc) int64

UnixTime get unix time randomly

func Username

func Username(opts ...options.OptionFunc) string

Username get username randomly in string

func Word

func Word(opts ...options.OptionFunc) string

Word get a word randomly in string

func YearString

func YearString(opts ...options.OptionFunc) 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 {
	// contains filtered or unexported fields
}

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

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(opts ...options.OptionFunc) 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

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

ChineseFirstName returns a random chinese first name

func (Person) ChineseLastName

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

ChineseLastName returns a random chinese last name

func (Person) ChineseName

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

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 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
pkg

Jump to

Keyboard shortcuts

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