Git Product home page Git Product logo

gofakeit's Introduction

Gofakeit

Gofakeit Go Report Card Test GoDoc license

Random data generator written in go

ko-fi

Buy Me A Coffee

Features

Contributors

Thank you to all our Gofakeit contributors!

Installation

go get github.com/brianvoe/gofakeit/v7

Simple Usage

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

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/v7"

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/v2 PCG which is a pseudo random number generator and is thread locked.

If you want to see other potential sources you can see the sub package Source for more information.

import (
	"github.com/brianvoe/gofakeit/v7"
	"github.com/brianvoe/gofakeit/v7/source"
	"math/rand/v2"
)

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

// NewFaker takes in a source and whether or not it should be thread safe
faker := gofakeit.NewFaker(source rand.Source, threadSafe bool)

// PCG Pseudo
faker := gofakeit.NewFaker(rand.NewPCG(11, 11), true)

// ChaCha8
faker := gofakeit.NewFaker(rand.NewChaCha8([32]byte{0, 1, 2, 3, 4, 5}), true)


// Additional from Gofakeit sub package source

// JSF(Jenkins Small Fast)
faker := gofakeit.NewFaker(source.NewJSF(11), true)

// SFC(Simple Fast Counter)
faker := gofakeit.NewFaker(source.NewSFC(11), true)

// Crypto - Uses crypto/rand
faker := gofakeit.NewFaker(source.NewCrypto(), true)

// Dumb - simple incrementing number
faker := gofakeit.NewFaker(source.NewDumb(11), true)

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/v7"

gofakeit.GlobalFaker = gofakeit.New(0)

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/v7"

// 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"`
	ArrayRange    []string       `fakesize:"2,6"`
	Bar           Bar
	Skip          *string        `fake:"skip"`                // Set to "skip" to not generate data for
	SkipAlt       *string        `fake:"-"`                   // Set to "-" 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
err := 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(fStr)  				// 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 Embedded Fields

Fakeable types

It is possible to extend a struct by implementing the Fakeable interface in order to control the generation.

For example, this is useful when it is not possible to modify the struct that you want to fake by adding struct tags to a field but you still need to be able to control the generation process.

// Custom string that you want to generate your own data for
type Friend string

func (c *Friend) Fake(f *gofakeit.Faker) (any, error) {
	// Can call any other faker methods
	return f.RandomString([]string{"billy", "fred", "susan"}), nil
}

// Custom time that you want to generate your own data for
type Age time.Time

func (c *Age) Fake(f *gofakeit.Faker) (any, error) {
	return f.DateRange(time.Now().AddDate(-100, 0, 0), time.Now().AddDate(-18, 0, 0)), nil
}

// This is the struct that we cannot modify to add struct tags
type User struct {
	Name Friend
	Age *Age
}

var u User
gofakeit.Struct(&u)
fmt.Printf("%s", f.Name) // billy
fmt.Printf("%s", f.Age) // 1990-12-07 04:14:25.685339029 +0000 UTC

Custom Functions

In a lot of situations 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", gofakeit.Info{
	Category:    "custom",
	Description: "Random friend name",
	Example:     "bill",
	Output:      "string",
	Generate: func(f *Faker, m *gofakeit.MapParams, info *gofakeit.Info) (any, error) {
		return f.RandomString([]string{"bill", "bob", "sally"}), nil
	},
})

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

		split := strings.Split(word, "")
		f.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

Templates

Generate custom outputs using golang's template engine https://pkg.go.dev/text/template.

We have added all the available functions to the template engine as well as some additional ones that are useful for template building.

Additional Available Functions

- ToUpper(s string) string   			// Make string upper case
- ToLower(s string) string   			// Make string lower case
- ToString(s any)            			// Convert to string
- ToDate(s string) time.Time 			// Convert string to date
- SpliceAny(args ...any) []any 			// Build a slice of anys, used with Weighted
- SpliceString(args ...string) []string // Build a slice of strings, used with Teams and RandomString
- SpliceUInt(args ...uint) []uint 		// Build a slice of uint, used with Dice and RandomUint
- SpliceInt(args ...int) []int 			// Build a slice of int, used with RandomInt
Unavailable Gofakeit functions
// Any functions that dont have a return value
- AnythingThatReturnsVoid(): void

// Not available to use in templates
- Template(co *TemplateOptions) ([]byte, error)
- RandomMapKey(mapI any) any

Example Usages

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

func main() {
	// Accessing the Lines variable from within the template.
	template := `
	Subject: {{RandomString (SliceString "Greetings" "Hello" "Hi")}}

	Dear {{LastName}},

	{{RandomString (SliceString "Greetings!" "Hello there!" "Hi, how are you?")}}

	{{Paragraph 1 5 10 "\n\n"}}

	{{RandomString (SliceString "Warm regards" "Best wishes" "Sincerely")}}
	{{$person:=Person}}
	{{$person.FirstName}} {{$person.LastName}}
	{{$person.Email}}
	{{$person.Phone}}
	`

	value, err := gofakeit.Template(template, &TemplateOptions{Data: 5})

	if err != nil {
		fmt.Println(err)
	}

	fmt.Println(string(value))
}

Output:

Subject: Hello

Dear Krajcik,

Greetings!

Quia voluptatem voluptatem voluptatem. Quia voluptatem voluptatem voluptatem. Quia voluptatem voluptatem voluptatem.

Warm regards
Kaitlyn Krajcik
kaitlynkrajcik@krajcik
570-245-7485

Functions

All functions also exist as methods on the Faker struct

File

Passing nil to CSV, JSON or XML will auto generate data using default values.

CSV(co *CSVOptions) ([]byte, error)
JSON(jo *JSONOptions) ([]byte, error)
XML(xo *XMLOptions) ([]byte, error)
FileExtension() string
FileMimeType() string

Template

Passing nil will auto generate data using default values.

Template(co *TemplateOptions) (string, error)
Markdown(co *MarkdownOptions) (string, error)
EmailText(co *EmailOptions) (string, error)
FixedWidth(co *FixedWidthOptions) (string, error)

Product

Product() *ProductInfo
ProductName() string
ProductDescription() string
ProductCategory() string
ProductFeature() string
ProductMaterial() string

Person

Person() *PersonInfo
Name() string
NamePrefix() string
NameSuffix() string
FirstName() string
MiddleName() string
LastName() string
Gender() string
SSN() string
Hobby() string
Contact() *ContactInfo
Email() string
Phone() string
PhoneFormatted() string
Teams(peopleArray []string, teamsArray []string) map[string][]string

Generate

Struct(v any)
Slice(v any)
Map() map[string]any
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
Dice(numDice uint, sides []uint) []uint

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

// Nouns
Noun() string
NounCommon() string
NounConcrete() string
NounAbstract() string
NounCollectivePeople() string
NounCollectiveAnimal() string
NounCollectiveThing() string
NounCountable() string
NounUncountable() string

// Verbs
Verb() string
VerbAction() string
VerbLinking() string
VerbHelping() string

// Adverbs
Adverb() string
AdverbManner() string
AdverbDegree() string
AdverbPlace() string
AdverbTimeDefinite() string
AdverbTimeIndefinite() string
AdverbFrequencyDefinite() string
AdverbFrequencyIndefinite() string

// Propositions
Preposition() string
PrepositionSimple() string
PrepositionDouble() string
PrepositionCompound() string

// Adjectives
Adjective() string
AdjectiveDescriptive() string
AdjectiveQuantitative() string
AdjectiveProper() string
AdjectiveDemonstrative() string
AdjectivePossessive() string
AdjectiveInterrogative() string
AdjectiveIndefinite() string

// Pronouns
Pronoun() string
PronounPersonal() string
PronounObject() string
PronounPossessive() string
PronounReflective() string
PronounDemonstrative() string
PronounInterrogative() string
PronounRelative() string

// Connectives
Connective() string
ConnectiveTime() string
ConnectiveComparative() string
ConnectiveComplaint() string
ConnectiveListing() string
ConnectiveCasual() string
ConnectiveExamplify() string

// Words
Word() string

// Sentences
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
Weighted(options []any, weights []float32) (any, error)
FlipACoin() string
RandomMapKey(mapI any) any
ShuffleAnySlice(v any)

Colors

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

Images

Image(width int, height int) *img.RGBA
ImageJpeg(width int, height int) []byte
ImagePng(width int, height int) []byte

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

HTML

InputName() string
Svg(options *SVGOptions) string

Date/Time

Date() time.Time
PastDate() time.Time
FutureDate() 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

Finance

Cusip() string
Isin() string

Company

BS() string
Blurb() string
BuzzWord() string
Company() string
CompanySuffix() string
Job() *JobInfo
JobDescriptor() string
JobLevel() string
JobTitle() string
Slogan() 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
Bird() 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
Int() int
IntN(n int) int
Int8() int8
Int16() int16
Int32() int32
Int64() int64
Uint() uint
UintN(n uint) uint
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
HexUint(bitsize int) 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

Celebrity

CelebrityActor() string
CelebrityBusiness() string
CelebritySport() string

Minecraft

MinecraftOre() string
MinecraftWood() string
MinecraftArmorTier() string
MinecraftArmorPart() string
MinecraftWeapon() string
MinecraftTool() string
MinecraftDye() string
MinecraftFood() string
MinecraftAnimal() string
MinecraftVillagerJob() string
MinecraftVillagerStation() string
MinecraftVillagerLevel() string
MinecraftMobPassive() string
MinecraftMobNeutral() string
MinecraftMobHostile() string
MinecraftMobBoss() string
MinecraftBiome() string
MinecraftWeather() string

Book

Book() *BookInfo
BookTitle() string
BookAuthor() string
BookGenre() string

Movie

Movie() *MovieInfo
MovieName() string
MovieGenre() string

Error

Error() error
ErrorDatabase() error
ErrorGRPC() error
ErrorHTTP() error
ErrorHTTPClient() error
ErrorHTTPServer() error
ErrorInput() error
ErrorRuntime() error

School

School() string

gofakeit's People

Contributors

adambabik avatar alex-wzm avatar andrewcretin avatar bgadrian avatar borosr avatar brianvoe avatar bvoelker avatar cagriekin avatar calvernaz avatar daisy1754 avatar dminkovski avatar hbagdi avatar hound672 avatar kishaningithub avatar mgilbir avatar mingrammer avatar moul avatar mrpye avatar n3xem avatar petergeorgas avatar rcoy-v avatar se-omar avatar smt923 avatar sp628193 avatar stefanb avatar viridianforge avatar woodb avatar wulfharth7 avatar xiegeo avatar zacscoding avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

gofakeit's Issues

Feature: ๐Ÿ”€ Ensure different

I'd like to generate data, but also ensure that the data differs from one call to another within a specific scope. As an example:

d1 := data{name: gofakeit.Name() }
d2 := data{name: gofakeit.Name() }

I want to guarantee that d1.name and d2.name are not the same. But I don't really care what the values are.

Add timezones to gofakeit

Hey great job on this package. You are the best and super sexy might i just add.

That being said add timezones you crazy son of a bitch!

Add food

Fruits, vegetables, meats, breads, sweats, etc...

Struct method almost doesn't do anything

It seems that the Struct method does not fill out the structure fields at all, except for those that have a person.first and person.last. I expected that with this method I could fill the structure using the names of the functions available in the package.

Example

package model_test

import (
	"testing"
	"time"

	"github.com/brianvoe/gofakeit/v4"
	"github.com/stretchr/testify/assert"
)

type User struct {
	Name                string `fake:"{name}"`
	PersonName          string `fake:"{person.name}"`
	PersonFirstLastName string `fake:"{person.first} {person.last}"`
	Email               string `fake:"{email}"`
	ContactEmail        string `fake:"{contact.email}"`
	PersonContactEmail  string `fake:"{person.contact.email}"`
}

func TestFake(t *testing.T) {
	u := new(User)

	gofakeit.Seed(time.Now().UnixNano())
	gofakeit.Struct(u)

	assert.NotEmpty(t, u.Name)                // fail
	assert.NotEmpty(t, u.PersonName)          // fail
	assert.NotEmpty(t, u.PersonFirstLastName) // success
	assert.NotEmpty(t, u.Email)               // fail
	assert.NotEmpty(t, u.ContactEmail)        // fail
	assert.NotEmpty(t, u.PersonContactEmail)  // fail
}

SSN Formatting

You have the SSN formatted as ###-###-####, but it should be ###-##-####. Please disregard if this is not for the US.

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"

HackerIngverb missing in FuncLookups

I noticed that HackerIngverb is missing in the FuncLookups.

The file hacker.go defines 6 functions for generating fake data, but only 5 are added during addHackerLookup.

I can provide a pull request. I just wanted to check if this is missing intentionally.

Bug: Digit(), randDigit(), replaceWithNumbers does not return 9

I refactored this function a while ago and I had a feeling something is wrong. The old code was in replaceWithNumbers and I moved it to randDigit, and now all its callers are affected.

The issue is that rand.Intn(9) returns in the interval [0, 9)

When the patch is applied 19 Examples will fail
Got : 6536459948995369
want:6587271570245748

Generate from multi inner brackets

Be able to make something like this work {{randomstring:firstname,lastname}} that would randomly give you either {firstname} or {lastname} then when it loops again would generate either a random firstname or lastname

Random json data

Would be nice for devlog to have a way to randomly generate json data

rename package

Ideally the package should be renamed to gofakeyourself

Miss you dad

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?

Extra Method Suggestions

Hi, great work on gofakeit! If you have time, there are a couple of methods that I used heavily in the Ruby Faker Gem, which ould be awesome to see make it over here:

If these, or any other from stympy/faker made it into gofakeit, I would be very grateful!

Can you add a changelog?

It will be very helpful to know what each release is changing.

Also it seems like there was a breaking change with the format of SSN in a recent release.

Random generate is not seeded.

It's worth mentioning in the docs that the library users must init random with some seed, otherwise the fake data won't be really random.

To put it simply, one should add some init code, e.g.:

rand.Seed(time.Now().UnixNano())

Number() can't generate across range of ints

From https://play.golang.org/p/7n0az_D-uZ9

package main

import (
	"fmt"
	"math"

	"github.com/brianvoe/gofakeit"
)

func main() {
	fmt.Printf("%d", gofakeit.Number(math.MinInt32, math.MaxInt32))
}

results in

panic: invalid argument to Intn

goroutine 1 [running]:
math/rand.(*Rand).Intn(0x43e260, 0x0, 0x0, 0xbab699fc)
	/usr/local/go/src/math/rand/rand.go:169 +0xc0
math/rand.Intn(...)
	/usr/local/go/src/math/rand/rand.go:329
github.com/brianvoe/gofakeit.randIntRange(...)
	/tmp/gopath082295618/pkg/mod/github.com/brianvoe/[email protected]+incompatible/misc.go:104
github.com/brianvoe/gofakeit.Number(0x80000000, 0x7fffffff, 0x7d9, 0x28b2)
	/tmp/gopath082295618/pkg/mod/github.com/brianvoe/[email protected]+incompatible/number.go:10 +0x60
main.main()
	/tmp/sandbox693462447/prog.go:11 +0x40

Program exited: status 2.

Can only get about halfway there (+/- 1) based on how randIntRange() works.

Random Number with step

Have this package something similar?
Like, I want to generate a number from 0 to 100 with step 5, like 0, 5, 10, 15, 20...

defined length numberstring

It would be awesome to have a function to create a defined length string containing only numbers. Something like:

gofakeit.NumericString(5) // returns "83756"

Add example with tags usage

There is just on example with tag usage for structures in README ("skip" only). It will be fine to add more examples.

struct.go missing uint* types

I need to generate an age, and I noticed that struct.go is missing reflect types for all uint types, and it will remain a 0 value.

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?

Space character in url domain

Hello, I tried gofakeit to generate random URLs,
but one of the test failed due to a invalid domain in the URL:

Error: Received unexpected error:
parse http://www.forwardweb services.info/synthesize: invalid character " " in host name

is generating invalid urls an expected behaviour?

Pet Names

Pet Names would be a good new category

Note for required go version on readme

Hi.

I'm using your gofakeit in my cli open source, the flog

Today, I've tried the installing the flog in centos:latest docker, but go get failed with undefined: math.Round error message. Yes, the Round method is available since Go 1.10. I didn't know it.

So, I think it is good idea that notes the required Go version on README to let users know the required Go version to use gofakeit.

How about you?

Custom faker functions

It will be fine to have ability to register custom functions which can be used in in structure tags:

func MyStrangeName() string {
    return "strange name"
}

type MyStruct struct {
    name string `fake:"my_strange_name"`
}

func main() {
    gofakeit.RegisterString("my_strange_name", MyStrangeName)
    // apply
   var s MyStruct
   gofakeit.Struct(&s)   
}

Unable to use it with reflect

This library has an impressive collection of methods.
Unfortunately, having all methods defined at top level without being able to instantiate a generator value forbids the use of reflect to inspect this package (ie templates, generators).
Think of a template filter with name "fakeit" and arguments method, args...
Or a tag on a struct field like fakeit:"email".
The only way to implement something like this right now is to write a huge switch statement and painstakingly map all function names manually.
Any plans of providing such an API?

Installation Issue

Using the below command for installation

go get github.com/brianvoe/gofakeit/v5

gives following error

package github.com/brianvoe/gofakeit/v5: cannot find package "github.com/brianvoe/gofakeit/v5" in any of:
/usr/local/Cellar/go/1.14.2_1/libexec/src/github.com/brianvoe/gofakeit/v5 (from $GOROOT)
/Users/user/go/src/github.com/brianvoe/gofakeit/v5 (from $GOPATH)

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.