All Projects → brianvoe → Gofakeit

brianvoe / Gofakeit

Licence: mit
Random fake data generator written in go

Programming Languages

go
31211 projects - #10 most used programming language

Projects that are alternatives of or similar to Gofakeit

Bogus
📇 A simple and sane fake data generator for C#, F#, and VB.NET. Based on and ported from the famed faker.js.
Stars: ✭ 5,083 (+131.78%)
Mutual labels:  fake, data, seed, generator
Mimesis
Mimesis is a high-performance fake data generator for Python, which provides data for a variety of purposes in a variety of languages.
Stars: ✭ 3,439 (+56.82%)
Mutual labels:  fake, data, generator
Jaymock
Minimal fake JSON test data generator.
Stars: ✭ 28 (-98.72%)
Mutual labels:  fake, data, generator
Faker
Faker is a pure Elixir library for generating fake data.
Stars: ✭ 673 (-69.31%)
Mutual labels:  data, seed, generator
falso
All the Fake Data for All Your Real Needs 🙂
Stars: ✭ 877 (-60.01%)
Mutual labels:  data, random, fake
Agots
Anomaly Generator on Time Series
Stars: ✭ 24 (-98.91%)
Mutual labels:  data, generator
Samples Viewer Generator
🎉 A CLI utility tool to generate web app of data visualization samples for presentation purpose
Stars: ✭ 13 (-99.41%)
Mutual labels:  data, generator
Randomdatagenerator
This is a configurable generator to create random data like Lorum Ipsum Text, Words, Text Patterns, First/Last Names, MAC-Addresses, IP-Addresses, Guids and DateTime.
Stars: ✭ 45 (-97.95%)
Mutual labels:  random, generator
Fakerator
Random fake data generator with localization for Javascript in Node.js and browser
Stars: ✭ 91 (-95.85%)
Mutual labels:  fake, generator
Generator Http Fake Backend
Yeoman generator for building a fake backend by providing the content of JSON files or JavaScript objects through configurable routes.
Stars: ✭ 49 (-97.77%)
Mutual labels:  fake, data
Generator Jekyll Starter Kit
🚀 Jekyll Progressive Web App Generator.
Stars: ✭ 139 (-93.66%)
Mutual labels:  seed, generator
Randomix
🎲 An open source app to choose randomly between numbers, answers, options and so on.
Stars: ✭ 24 (-98.91%)
Mutual labels:  random, generator
Rando Php
RandoPhp is a open source library that implements random generators (Integer, Char, Byte, Sequences, Boolean) and take random sample from arrays
Stars: ✭ 107 (-95.12%)
Mutual labels:  random, generator
Generator Ngx Rocket
🚀 Extensible Angular 11+ enterprise-grade project generator
Stars: ✭ 1,329 (-39.4%)
Mutual labels:  seed, generator
Fakedata
Haskell Library for producing quality fake data
Stars: ✭ 118 (-94.62%)
Mutual labels:  fake, random
Spicy Proton
Generate a random English adjective-noun word pair in Ruby
Stars: ✭ 76 (-96.53%)
Mutual labels:  random, generator
Baba Core
Mini-language for creating random text generators.
Stars: ✭ 127 (-94.21%)
Mutual labels:  random, generator
Roguesharp
A .NET Standard class library providing map generation, path-finding, and field-of-view utilities frequently used in roguelikes or 2D tile based games. Inspired by libtcod
Stars: ✭ 316 (-85.59%)
Mutual labels:  random, generator
Keygen Php
A fluent PHP random key generator.
Stars: ✭ 93 (-95.76%)
Mutual labels:  random, generator
Micro Jaymock
Tiny API mocking microservice for generating fake JSON data.
Stars: ✭ 123 (-94.39%)
Mutual labels:  fake, data

alt text

Gofakeit Go Report Card Test 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.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 of functions

Seed

If you are using the default global usage and dont care about seeding no need to set anything. Gofakeit will seed it with a cryptographically secure number.

If you need a reproducible outcome you can set it via the Seed function call. Every example in this repo sets it for testing purposes.

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

gofakeit.Seed(0) // If 0 will use crypto/rand to generate a number

// or

gofakeit.Seed(8675309) // Set it to whatever number you want

Random Sources

Gofakeit has a few rand sources, by default it uses math.Rand and uses mutex locking to allow for safe goroutines.

If you want to use a more performant source please use NewUnlocked. Be aware that it is not goroutine safe.

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

// Uses math/rand(Pseudo) with mutex locking
faker := gofakeit.New(0)

// Uses math/rand(Pseudo) with NO mutext locking
// More performant but not goroutine safe.
faker := gofakeit.NewUnlocked(0)

// Uses crypto/rand(cryptographically secure) with mutext locking
faker := gofakeit.NewCrypto()

// Pass in your own random source
faker := gofakeit.NewCustom()

Global Rand Set

If you would like to use the simple function calls but need to use something like crypto/rand you can override the default global with the random source that you want.

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

faker := gofakeit.NewCrypto()
gofakeit.SetGlobalFaker(faker)

Struct

Gofakeit can generate random data for struct fields. For the most part it covers all the basic type as well as some non basic like time.Time.

Struct fields can also use tags to more specifically generate data for that field type.

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

// Create structs with random injected data
type Foo struct {
	Str      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
	Map      map[string]int `fakesize:"2"`
	Array    []string       `fakesize:"2"`
	Bar 	 Bar
	Skip     *string        `fake:"skip"`                // Set to "skip" to not generate data for
	Created  time.Time								     // Can take in a fake tag as well as a format tag
	CreatedFormat  time.Time `fake:"{year}-{month}-{day}" format:"2006-01-02"`
}

type Bar struct {
	Name    string
	Number  int
	Float   float32
}

// Pass your struct as a pointer
var f Foo
gofakeit.Struct(&f)

fmt.Println(f.Str)      		// 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.Map)    			// map[PxLIo:52 lxwnqhqc:846]
fmt.Println(f.Array)    		// cbdfc
fmt.Printf("%+v", f.Bar)    	// {Name:QFpZ Number:-2882647639396178786 Float:1.7636692e+37}
fmt.Println(f.Skip)     		// <nil>
fmt.Println(f.Created.String()) // 1908-12-07 04:14:25.685339029 +0000 UTC

// Supported formats
// int, int8, int16, int32, int64,
// uint, uint8, uint16, uint32, uint64,
// float32, float64,
// bool, string,
// array, pointers, map
// time.Time // If setting time you can also set a format tag
// Nested Struct Fields and Embeded Fields

Custom Functions

In a lot of sitations you may need to use your own random function usage for your specific needs.

If you would like to extend the usage of struct tags, generate function, available usages in the gofakeit server or gofakeit command sub packages. You can do so via the AddFuncLookup. Each function has their own lookup, if you need more reference examples you can look at each files lookups.

// Simple
gofakeit.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
gofakeit.AddFuncLookup("jumbleword", Info{
	Category:    "jumbleword",
	Description: "Take a word and jumple it up",
	Example:     "loredlowlh",
	Output:      "string",
	Params: []Param{
		{Field: "word", Type: "string", 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
gofakeit.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, error)
XML(xo *XMLOptions) ([]byte, error)
FileExtension() string
FileMimeType() 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(peopleArray []string, teamsArray []string) map[string][]string

Generate

Struct(v interface{})
Slice(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

Car

Car() *CarInfo
CarMaker() string
CarModel() string
CarType() string
CarFuelType() string
CarTransmissionType() 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
FlipACoin() string
ShuffleAnySlice(v interface{})

Colors

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

Internet

URL() string
DomainName() string
DomainSuffix() string
IPv4Address() string
IPv6Address() string
MacAddress() string
HTTPStatusCode() string
HTTPStatusCodeSimple() int
LogLevel(logType string) string
HTTPMethod() string
HTTPVersion() 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() int
MonthString() 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

Language

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

Number

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
HexUint8() string
HexUint16() string
HexUint32() string
HexUint64() string
HexUint128() string
HexUint256() string

String

Digit() string
DigitN(n uint) string
Letter() string
LetterN(n uint) string
Lexify(str string) string
Numerify(str string) string
ShuffleStrings(a []string)
RandomString(a []string) string
Note that the project description data, including the texts, logos, images, and/or trademarks, for each open source project belongs to its rightful owner. If you wish to add or remove any projects, please contact us at [email protected].