Random fake data generator written in go

Overview

alt text

Gofakeit Go Report Card Go codecov.io GoDoc license

Random data generator written in go

Buy Me A Coffee

Features

Installation

go get github.com/brianvoe/gofakeit/v6

Simple Usage

import "github.com/brianvoe/gofakeit/v6"

gofakeit.Seed(0)

gofakeit.Name()             // Markus Moen
gofakeit.Email()            // [email protected]
gofakeit.Phone()            // (570)245-7485
gofakeit.BS()               // front-end
gofakeit.BeerName()         // Duvel
gofakeit.Color()            // MediumOrchid
gofakeit.Company()          // Moen, Pagac and Wuckert
gofakeit.CreditCardNumber() // 4287271570245748
gofakeit.HackerPhrase()     // Connecting the array won't do anything, we need to generate the haptic COM driver!
gofakeit.JobTitle()         // Director
gofakeit.CurrencyShort()    // USD
// See full list below

Concurrent Struct

If you need to have independent randomization for the purposes of concurrency

import "github.com/brianvoe/gofakeit/v6"

faker := New(0) // or NewCrypto() to use crypto/rand

faker.Name()             // Markus Moen
faker.Email()            // [email protected]
faker.Phone()            // (570)245-7485
faker.BS()               // front-end
faker.BeerName()         // Duvel
faker.Color()            // MediumOrchid
faker.Company()          // Moen, Pagac and Wuckert
faker.CreditCardNumber() // 4287271570245748
faker.HackerPhrase()     // Connecting the array won't do anything, we need to generate the haptic COM driver!
faker.JobTitle()         // Director
faker.CurrencyShort()    // USD
// See full list below

Global Rand Set

If you would like to use the simple function call but need to use something like crypto/rand you can override the default global with the type you want

import "github.com/brianvoe/gofakeit/v6"

faker := NewCrypto()
SetGlobalFaker(faker)

Struct

import "github.com/brianvoe/gofakeit/v6"

// Create structs with random injected data
type Foo struct {
	Bar      string
	Int      int
	Pointer  *int
	Name     string  `fake:"{firstname}"`         // Any available function all lowercase
	Sentence string  `fake:"{sentence:3}"`        // Can call with parameters
	RandStr  string  `fake:"{randomstring:[hello,world]}"`
	Number   string  `fake:"{number:1,10}"`       // Comma separated for multiple values
	Regex    string  `fake:"{regex:[abcdef]{5}}"` // Generate string from regex
	Skip     *string `fake:"skip"`                // Set to "skip" to not generate data for
}

type FooBar struct {
	Bars    []string `fake:"{name}"`              // Array of random size (1-10) with fake function applied
	Foos    []Foo    `fakesize:"3"`               // Array of size specified with faked struct
	FooBars []Foo    `fake:"{name}" fakesize:"3"` // Array of size 3 with fake function applied
}

// Pass your struct as a pointer
var f Foo
gofakeit.Struct(&f)
fmt.Println(f.Bar)      // hrukpttuezptneuvunh
fmt.Println(f.Int)      // -7825289004089916589
fmt.Println(*f.Pointer) // -343806609094473732
fmt.Println(f.Name)     // fred
fmt.Println(f.Sentence) // Record river mind.
fmt.Println(f.RandStr)  // world
fmt.Println(f.Number)   // 4
fmt.Println(f.Regex)    // cbdfc
fmt.Println(f.Skip)     // <nil>

var fb FooBar
gofakeit.Struct(&fb)
fmt.Println(fb.Bars)      // [Charlie Senger]
fmt.Println(fb.Foos)      // [{blmfxy -2585154718894894116 0xc000317bc0 Emmy Attitude demand addition. hello 3 <nil>} {cplbf -1722374676852125164 0xc000317cb0 Viva Addition option link. hello 7 <nil>}]

Custom Functions

// Simple
AddFuncLookup("friendname", Info{
	Category:    "custom",
	Description: "Random friend name",
	Example:     "bill",
	Output:      "string",
	Generate: func(r *rand.Rand, m *MapParams, info *Info) (interface{}, error) {
		return RandomString([]string{"bill", "bob", "sally"}), nil
	},
})

// With Params
AddFuncLookup("jumbleword", Info{
	Category:    "jumbleword",
	Description: "Take a word and jumple it up",
	Example:     "loredlowlh",
	Output:      "string",
	Params: []Param{
		{Field: "word", Type: "int", Description: "Word you want to jumble"},
	},
	Generate: func(r *rand.Rand, m *MapParams, info *Info) (interface{}, error) {
		word, err := info.GetString(m, "word")
		if err != nil {
			return nil, err
		}

		split := strings.Split(word, "")
		ShuffleStrings(split)
		return strings.Join(split, ""), nil
	},
})

type Foo struct {
	FriendName string `fake:"{friendname}"`
	JumbleWord string `fake:"{jumbleword:helloworld}"`
}

var f Foo
Struct(&f)
fmt.Printf("%s", f.FriendName) // bill
fmt.Printf("%s", f.JumbleWord) // loredlowlh

Functions

All functions also exist as methods on the Faker struct

File

JSON(jo *JSONOptions) []byte
XML(xo *XMLOptions) []byte
Extension() string
MimeType() string

Person

Person() *PersonInfo
Name() string
NamePrefix() string
NameSuffix() string
FirstName() string
LastName() string
Gender() string
SSN() string
Contact() *ContactInfo
Email() string
Phone() string
PhoneFormatted() string
Teams(people []string, teams []string) map[string][]string

Generate

Struct(v interface{})
Map() map[string]interface{}
Generate(value string) string
Regex(value string) string

Auth

Username() string
Password(lower bool, upper bool, numeric bool, special bool, space bool, num int) string

Address

Address() *AddressInfo
City() string
Country() string
CountryAbr() string
State() string
StateAbr() string
Street() string
StreetName() string
StreetNumber() string
StreetPrefix() string
StreetSuffix() string
Zip() string
Latitude() float64
LatitudeInRange(min, max float64) (float64, error)
Longitude() float64
LongitudeInRange(min, max float64) (float64, error)

Game

Gamertag() string

Beer

BeerAlcohol() string
BeerBlg() string
BeerHop() string
BeerIbu() string
BeerMalt() string
BeerName() string
BeerStyle() string
BeerYeast() string

Cars

Vehicle() *VehicleInfo
CarMaker() string
CarModel() string
VehicleType() string
FuelType() string
TransmissionGearType() string

Words

Noun() string
Verb() string
Adverb() string
Preposition() string
Adjective() string
Word() string
Sentence(wordCount int) string
Paragraph(paragraphCount int, sentenceCount int, wordCount int, separator string) string
LoremIpsumWord() string
LoremIpsumSentence(wordCount int) string
LoremIpsumParagraph(paragraphCount int, sentenceCount int, wordCount int, separator string) string
Question() string
Quote() string
Phrase() string

Foods

Fruit() string
Vegetable() string
Breakfast() string
Lunch() string
Dinner() string
Snack() string
Dessert() string

Misc

Bool() bool
UUID() string

Colors

Color() string
HexColor() string
RGBColor() []int
SafeColor() string

Internet

URL() string
ImageURL(width int, height int) string
DomainName() string
DomainSuffix() string
IPv4Address() string
IPv6Address() string
StatusCode() string
SimpleStatusCode() int
LogLevel(logType string) string
HTTPMethod() string
UserAgent() string
ChromeUserAgent() string
FirefoxUserAgent() string
OperaUserAgent() string
SafariUserAgent() string

Date/Time

Date() time.Time
DateRange(start, end time.Time) time.Time
NanoSecond() int
Second() int
Minute() int
Hour() int
Month() string
Day() int
WeekDay() string
Year() int
TimeZone() string
TimeZoneAbv() string
TimeZoneFull() string
TimeZoneOffset() float32
TimeZoneRegion() string

Payment

Price(min, max float64) float64
CreditCard() *CreditCardInfo
CreditCardCvv() string
CreditCardExp() string
CreditCardNumber(*CreditCardOptions) string
CreditCardType() string
Currency() *CurrencyInfo
CurrencyLong() string
CurrencyShort() string
AchRouting() string
AchAccount() string
BitcoinAddress() string
BitcoinPrivateKey() string

Company

BS() string
BuzzWord() string
Company() string
CompanySuffix() string
Job() *JobInfo
JobDescriptor() string
JobLevel() string
JobTitle() string

Hacker

HackerAbbreviation() string
HackerAdjective() string
HackerIngverb() string
HackerNoun() string
HackerPhrase() string
HackerVerb() string

Hipster

HipsterWord() string
HipsterSentence(wordCount int) string
HipsterParagraph(paragraphCount int, sentenceCount int, wordCount int, separator string) string

App

AppName() string
AppVersion() string
AppAuthor() string

Animal

PetName() string
Animal() string
AnimalType() string
FarmAnimal() string
Cat() string
Dog() string

Emoji

Emoji() string
EmojiDescription() string
EmojiCategory() string
EmojiAlias() string
EmojiTag() string

Languages

Language() string
LanguageAbbreviation() string
ProgrammingLanguage() string
ProgrammingLanguageBest() string

Numbers

Number(min int, max int) int
Int8() int8
Int16() int16
Int32() int32
Int64() int64
Uint8() uint8
Uint16() uint16
Uint32() uint32
Uint64() uint64
Float32() float32
Float32Range(min, max float32) float32
Float64() float64
Float64Range(min, max float64) float64
ShuffleInts(a []int)
RandomInt(i []int) int

String

Digit() string
DigitN(n int) string
Letter() string
LetterN(n int) string
Lexify(str string) string
Numerify(str string) string
ShuffleStrings(a []string)
RandomString(a []string) string
Issues
  • Concurrency

    Concurrency

    Hello, nice job on the package, it looks neat and has a good documentation.

    I have 2 main issues:

    1. is not concurrent safe, it uses rand.* global version
    2. I need one instance for each thread, and all the functions are public.

    The refactoring will be big and I don't see a way to make it backward compatible, to make all the functions as methods and using a custom private random generator.

    Any ideas?

    opened by bgadrian 22
  • Small tweaks, tests, fixes and optimizations

    Small tweaks, tests, fixes and optimizations

    Added seed to some benchmarks, so they can be compared. Small refactor and optimization (+10%) of ReplaceWith* functions Added Digit() function Fixed RandString panic when input is empty Optimized ShuffleStrings (20%) Fixed getRandValue, intDataCheck and dataCheck panic when input is empty

    opened by bgadrian 15
  • Ability to create Faker instance with local rand

    Ability to create Faker instance with local rand

    This is an example change of what it could like to support a Faker client instance, that does not rely on or seed global rand.

    Similar to https://github.com/brianvoe/gofakeit/issues/78.

    This would give users greater, and potentially simpler, control over how to create fake data and without affecting global state.

    I only made a change to a single function for demonstration purposes to start the conversation. Each function would be slightly different, but the idea to avoid breaking changes and keep maintenance simple would be move existing functionality to private functions, and the new receiver methods could call with their rand instance.

    I could further work on this if the change is welcome, and I'm open to other suggestions on implementation strategy.

    opened by rcoy-v 14
  • go get github.com/brianvoe/gofakeit/v5 giving error

    go get github.com/brianvoe/gofakeit/v5 giving error

    Error: cannot find package "github.com/brianvoe/gofakeit/v5"

    Go get github.com/brianvoe/gofakeit is pulling the code. But throwing error :

    goserver1 % go get github.com/brianvoe/gofakeit

    internal/race

    compile: version "go1.14" does not match go tool version "go1.14.2"

    unicode/utf8

    compile: version "go1.14" does not match go tool version "go1.14.2"

    runtime/internal/sys

    compile: version "go1.14" does not match go tool version "go1.14.2"

    math/bits

    compile: version "go1.14" does not match go tool version "go1.14.2"

    unicode

    compile: version "go1.14" does not match go tool version "go1.14.2"

    encoding

    compile: version "go1.14" does not match go tool version "go1.14.2"

    unicode/utf16

    compile: version "go1.14" does not match go tool version "go1.14.2"

    image/color

    compile: version "go1.14" does not match go tool version "go1.14.2"

    github.com/brianvoe/gofakeit/data

    compile: version "go1.14" does not match go tool version "go1.14.2"

    sync/atomic

    compile: version "go1.14" does not match go tool version "go1.14.2"

    internal/cpu

    compile: version "go1.14" does not match go tool version "go1.14.2"

    runtime/internal/atomic

    compile: version "go1.14" does not match go tool version "go1.14.2"

    opened by simsolTech 13
  • Add gofakeit command

    Add gofakeit command

    The motivation for this was using jsonify which allows to quickly produce JSON using CLI.

    The thing with jsonify is that it does not support generating fake data, and that's good, one tool should do one thing.

    gofakeit is awesome lib but the fact that you can't use it from a CLI is a bummer, hence, I decided to propose this PR. I haven't found and previous attempts to do this.

    The main goals were simplicity and easy to maintenance. The exposed commands are generated using go generate tool. When a new function is added, it's enough to execute go generate ./cmd/gofakeit/... in the project root directory to update the list of available commands.

    The current limitation is that it supports only functions that take no params and return a single value of type string. The codebase can be extended to support this, it's not a blocker.

    opened by adambabik 10
  •  feat: add Struct() to randomize a struct

    feat: add Struct() to randomize a struct

    Lots of details are missing but this should give an idea of what I've in mind.

    I'm going to implement all basic type.

    An important addition that could come in will be range for all data types

    struct Foo{
      Bar int `fake:"{Number|42|50}" // will fill 42 <= Bar <= 50
    }
    
    opened by hbagdi 10
  • Date struct annotation not working

    Date struct annotation not working

    Test struct {
            CreatedAt   time.Time `json:"created_at" fake:"{date}"`
        }
    

    This always ends up with "created_at":"0001-01-01T00:00:00Z"

    Is that a bug?

    opened by gadelkareem 8
  • What is the correct usage for generating a string from a regular expression using a struct tag?

    What is the correct usage for generating a string from a regular expression using a struct tag?

    Hi,

    Started using this library and like the feature for generating strings according to a regular expression! I am trying to use this to create random strings that satisfy a specific format and/or for a specific length.

    I have managed to generate a string from a regular expression using gofakeit.Regex function. However, I cannot seem to managed the same functionality using a struct tag.

    What is the correct usage for generating a string from a regular expression using a struct tag?

    I have created a small example listing below that illustrates my attempt at this. This is also available at the following go playground.

    package main
    
    import (
    	"fmt"
    	"github.com/brianvoe/gofakeit/v6"
    )
    
    type Foo struct {
    	RegExpStr  string  `fake:"{regex:^[0-9]{0,16}$}"`
    }
    
    
    func main() {
    	var f Foo
    	gofakeit.Struct(&f)
    	
    	fmt.Println("Try and generate a random string of digits upto length 16 using regex")
    	fmt.Println()
    	fmt.Println()
    	fmt.Println("RegExpStr Via Tag := ", f.RegExpStr)
    	
    	result := gofakeit.Regex(`^[0-9]{0,16}$`)
    	fmt.Println("RegExp Via Function := ", result)
    }
    
    opened by dcs3spp 8
  • Fakeit client instead of global/package vars/seed

    Fakeit client instead of global/package vars/seed

    I'd like be able to create a "fakeit" client object that could be instantiated

    Example usage:

    // parameter is the seed
    f := gofakeit.New(0)
    f.Name()
    

    It is safe/expected to call gofakeit.Seed(?) many times? What happens?

    opened by ghostsquad 7
  • Compiling to windows 386 fails:  number.go: constant 18446744073709551615 overflows uint

    Compiling to windows 386 fails: number.go: constant 18446744073709551615 overflows uint

    тип release failed after 733.16s error=failed to build for windows_386: exit status 2: # github.com/brianvoe/gofakeit/v6 Error: ../../../go/pkg/mod/github.com/brianvoe/gofakeit/[email protected]/number.go:46:71: constant 18446744073709551615 overflows uint

    opened by dosco 6
  • Random generator race condition

    Random generator race condition

    global random generator is internally being used by gofakeit, which is known to be non-thread safe.

    This produces multiple unexpected errors when using gofakeit on tests running with -race flag.

    WARNING: DATA RACE
    Read at 0x00c00044c000 by goroutine 41:
    --
    321 | math/rand.(*rngSource).Uint64()
    322 | /usr/local/go/src/math/rand/rng.go:239 +0x3e
    323 | math/rand.(*rngSource).Int63()
    324 | /usr/local/go/src/math/rand/rng.go:234 +0x1d9
    325 | math/rand.(*Rand).Int63()
    326 | /usr/local/go/src/math/rand/rand.go:85 +0x85
    327 | math/rand.(*Rand).Int31()
    328 | /usr/local/go/src/math/rand/rand.go:99 +0x9a
    329 | math/rand.(*Rand).Int31n()
    330 | /usr/local/go/src/math/rand/rand.go:134 +0x4f
    331 | math/rand.(*Rand).Intn()
    332 | /usr/local/go/src/math/rand/rand.go:172 +0x59
    333 | github.com/brianvoe/gofakeit/v6.getRandValue()
    334 | /go/pkg/mod/github.com/brianvoe/gofakeit/[email protected]/helpers.go:67 +0x2ee
    335 | github.com/brianvoe/gofakeit/v6.color()
    336 | /go/pkg/mod/github.com/brianvoe/gofakeit/[email protected]/color.go:11 +0x266
    337 | github.com/brianvoe/gofakeit/v6.Color()
    338 | /go/pkg/mod/github.com/brianvoe/gofakeit/[email protected]/color.go:6 +0x1c1
    ....
    
    opened by botchris 6
Owner
Brian Voelker
Senior Full Stack Developer. Love working with golang and building front end applications.
Brian Voelker
generate fake data in go

Faker for Go Usage package main import ( "github.com/manveru/faker" ) func main() { fake, err := faker.New("en") if err != nil { panic(err

Michael Fellinger 163 Jul 6, 2022
Randomdata : a tiny help suite for generating random data

go-randomdata randomdata is a tiny help suite for generating random data such as first names (male or female) last names full names (male or female) c

Kalyan Janumpally 0 Dec 5, 2021
Generate random, pronounceable, sometimes even memorable, "superhero like" codenames - just like Docker does with container names.

Codename an RFC1178 implementation to generate pronounceable, sometimes even memorable, "superheroe like" codenames, consisting of a random combinatio

Luca Sepe 82 Jul 2, 2022
A repository of random code snippets used to develop proof of concepts

Oddments Oddments is a repository of random code snippets used to develop proof of concepts for techniques used with the Windows operating system. POC

Russel Van Tuyl 6 Feb 23, 2022
Helps exercise your memory by giving you random tokens and poems to memorize.

memory-enhancer Helps exercise your memory by giving you random tokens and poems to memorize. Using Every day when you first open your terminal you wi

Miguel Pinheiro 0 Nov 9, 2021
Rfpm - Random Fair Preemption Model For Golang

rfpm RFPM (Random Fair Preemption Model) is absolutely fair to all clients who r

null 1 Jan 7, 2022
Go package and associated command line utility to generate random yet human-readable names and identifiers

namegen | What's this? Go package and associated command line utility to generate random yet human-readable names and identifiers. Somewhat inspired b

Anand Varma 4 Jun 26, 2022
Package reservoir samples values uniformly at random from an unbounded sequence of inputs

Package reservoir samples values uniformly at random from an unbounded sequence of inputs

null 0 Jan 24, 2022
Giraffe - An opinionated static site generator written in Go

Giraffe: An opinionated static site generator I want to start 2022 by writing a

Thien Nguyen 3 May 25, 2022
Exercise for solve problem data processing, performance and something wrong in passing data

Citcall Exercise Exercise for solve problem data processing, performance and something wrong in passing data Pengolahan data data processing - Readme

Muhammad Fazri 0 Nov 25, 2021
Experimental Monika After Story persistent data loader written in Go

Go Persistent Loader This project is an experiment on loading/deserializing Monika After Story persistent (save) file into memory. Currently it contai

Friends of Monika 2 May 10, 2022
A distributed unique ID generator of using Sonyflake and encoded by Base58

Indigo About A distributed unique ID generator of using Sonyflake and encoded by Base58. ID max length is 11 characters by unsigned int64 max value. A

Osamu TONOMORI 95 May 31, 2022
:guardsman: A teeny tiny and somewhat opinionated generator for your next golang project

A Yeoman Golang Generator We are very sorry Gophers, but other names for the generator where taken, so we choose go-lang. But we have gocreate as an a

Axel Springer SE 24 Jun 17, 2022
Unit tests generator for Go programming language

GoUnit GoUnit is a commandline tool that generates tests stubs based on source function or method signature. There are plugins for Vim Emacs Atom Subl

Max Chechel 62 Jul 8, 2022
XSD (XML Schema Definition) parser and Go/C/Java/Rust/TypeScript code generator

xgen Introduction xgen is a library written in pure Go providing a set of functions that allow you to parse XSD (XML schema definition) files. This li

null 173 Jul 22, 2022
GObject-introspection based bindings generator

WARNING! This project is no longer maintained. Probably doesn't even compile. GObject-introspection based bindings generator for Go. Work in progress

null 47 Jan 5, 2022
Typo/error resilient, human-readable token generator

toktok A human-friendly token generator Creates tokens which avoid characters that can be easily misinterpreted, like '1' and 'I' or '8' and 'B', as w

Christian Muehlhaeuser 67 Jul 26, 2022
Fast and secure initramfs generator

Booster - fast and secure initramfs generator Initramfs is a specially crafted small root filesystem that mounted at the early stages of Linux OS boot

Anatol Pomozov 272 Aug 3, 2022
Jennifer is a code generator for Go

Jennifer Jennifer is a code generator for Go. package main import ( "fmt" . "github.com/dave/jennifer/jen" ) func main() { f := NewFile("m

Dave Brophy 2.5k Jul 31, 2022