Git Product home page Git Product logo

faker's Introduction

Faker is a Go library that generates fake data for you. Whether you need to bootstrap your database, create good-looking XML documents, fill-in your persistence to stress test it, or anonymize data taken from a production service, Faker is for you.

Faker is heavily inspired by PHP"s Faker

Faker requires Go >= 1.11 and < 1.20 for 1.X and Go >= 1.20 for 2.X

PkgGoDev Test codecov Go Report Card Codacy Badge CodeFactor Release Gitpod ready-to-code Hits

Test it directly from your browser

Start at https://play.golang.org/p/JpTagDGBaHK

Installation

Add this to your Go file

import "github.com/jaswdr/faker/v2"

And run go get or dep ensure to get the package.

Basic Usage

Use faker.New() to create and initialize a faker generator, which can generate data by accessing properties named after the type of data you want.

import "github.com/jaswdr/faker/v2"

func main() {
    fake := faker.New()

    fake.Person().Name()
    // Lucy Cechtelar

    fake.Address().Address()
    // 426 Jordy Lodge

    fake.Lorem().Text(100)
    // Dolores sit sint laboriosam dolorem culpa et autem. Beatae nam sunt fugit
    // et sit et mollitia sed.
    // Fuga deserunt tempora facere magni omnis. Omnis quia temporibus laudantium
    // sit minima sint.
}

Even if this example shows a method access, each call to fake.Name() yields a different (random) result.

p := fake.Person()

for i:=0; i < 10; i++ {
  fmt.Println(p.Name())
}
  // Adaline Reichel
  // Dr. Santa Prosacco DVM
  // Noemy Vandervort V
  // Lexi O"Conner
  // Gracie Weber
  // Roscoe Johns
  // Emmett Lebsack
  // Keegan Thiel
  // Wellington Koelpin II
  // Ms. Karley Kiehn V

You can also generate a profile image.

image := p.Image()

fmt.Println(image.Name())
// /tmp/profil-picture-img-1064677774.jfif

fmt.Printf("%+v", image)
// &{file:0xc0002e4300}

Generate fake data using Structs

type ExampleStruct struct {
	SimpleStringField string
	SimpleNumber int
	SimpleBool bool
	SomeFormatedString string `fake:"??? ###"`
	SomeStringArray [5]string `fake:"????"`
}

example := ExampleStruct{}
f.Struct().Fill(&example)
fmt.Printf("%+v", example)
//{SimpleStringField:87576a01c2a547b2bbf9b7c736d1db40 SimpleNumber:9223372036854775807 SimpleBool:false SomeFormatedString:cxo 321 SomeStringArray:[effr swxp ldnj obcs nvlg]}

Generate random placeholder images using LoremFlickr

// get a *os.File pointing to a file that is a random image
image := f.LoremFlickr().Image(100, 100, []string{}, "", false)

fmt.Println(image.Name())
// /tmp/loremflickr-img-4101493944.jpg

Generate profile images using ThisPersonDoesNotExist

profileImage := f.ProfileImage().Image()

fmt.Println(profileImage.Name())
// /tmp/profil-picture-img-4022222298.jfif

See more formatters in docs

Development

Create a fork and get the code.

$ go get github.com/jaswdr/faker/v2

Do your changes, add tests, run the tests.

$ go test
PASS
ok      github.com/jaswdr/faker/v2 2.966s

Push to your fork and send a new pull request from your fork to this repository.

Versioning

Faker is maintained under the Semantic Versioning guidelines. Starting at 2.X, we only support maintained versions of Go. Which according to Go's Release Policy means that we only support the two newer major versions.

License

Faker is released under the MIT Licence. See the bundled LICENSE file for details.

Maintainer

Created and maitained by Jonathan Schweder (@jaswdr) and many others

faker's People

Contributors

4k1k0 avatar ab22 avatar adrubesh avatar aleksey-rezvov avatar antfroger avatar arshamalh avatar bagusays avatar bhatipradeep avatar bweston92 avatar caioeverest avatar codacy-badger avatar cszatmary avatar deepsource-autofix[bot] avatar greendjango avatar hemantjoshi11 avatar imgbot[bot] avatar jaswdr avatar kharmaodo avatar kingmidas74 avatar maerf0x0 avatar matsuyoshi30 avatar mirobertod avatar mrtbag avatar norbinsh avatar pankaj-kumar34 avatar sean- avatar shedokan avatar tony2001 avatar wannabe2d avatar xlanor 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

faker's Issues

Adding a car license plate

Is your feature request related to a problem? Please describe.
It would be useful to have a license plate generator

Describe the solution you'd like
I would like to implement a license plate generator that could return a random code, region series, and car number.

[BUG] E164Number generates invalid E164 phone number

Describe the bug
E164Number sometimes generates invalid E164 phone number.

Expected behavior
E164Number should return a phone number that doesn't start with 0.

Additional context
E164Number works by generating random 11 digit number with + as a prefix but 0 as a first digit is an invalid country code. Fairly popular way of checking validity of E164 numbers is to do a regex match like:

^\+[1-9]\d{1,14}$ 

For which this function fails 1 out of 10 times.

[FEATURE] Variable name generator

Is your feature request related to a problem? Please describe.

It would be nice to have a function/method to generate a valid variable name in most programming languages: [_a-zA-Z][_a-zA-Z0-9]*.

Describe the solution you'd like

Any method to generate that value.

Describe alternatives you've considered

Find something like that in documentation (it wasn't easy, by the way).
Do it my own code.

[FEATURE] Have 100% of test coverage

Is your feature request related to a problem? Please describe.
This is an improvement on our current test coverage.

Describe the solution you'd like
Recently we have added the test coverage report, considering that this project is focused in generate fake data for tests, is good to have 100% of test coverage.

Describe alternatives you've considered
For normal projects, it's common knowledge that 100% don't guarantee quality, but in this case this project is focused on tests, so is important to us to have at minimum a good test coverage.

Additional context
The confirmation that we reach this goal is having 100% in coveralls

Important! Use the full-tests-coverage branch as target of pull requests.

[FEATURE] New generators, Wave 1

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

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
  • [x ] 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 // winking face
  • EmojiCategory() string // Smileys & Emotion
  • EmojiAlias() string // smiley
  • EmojiTag() string // happy

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

[FEATURE] Add more generators

Create more generators

Prerequisite

  1. Must not require any third-party dependency
  2. Must have tests and tests must be passing go test command
  3. Must apply gofmt -s -w *.go before committing to format the code

[FEATURE] Generator should be wrapped by a Interface to allow mocking

Is your feature request related to a problem? Please describe.
Currently, the generator utilises random.randInt.

This becomes a problem further down the line, for example, when randoming a number between 0-2 to decide a choice of what to return in functions with a wider scope.

Describe the solution you'd like
Instead of directly utilising rand, we can use an interface that exposes the methods that we want to use from rand. This allows for the replacement of rand with a mock during unit tests,

[FEATURE] Generate a string of a certain length

Is your feature request related to a problem? Please describe.
Currently looking for a simple mechanism to fake strings of a certain length across multiple projects.

Describe the solution you'd like
Add a calling function in a for loop using f.RandomLetter and generating it l times to generate a string of length l

[BUG] person first and last names should not contain double-quotes

Describe the bug
The list of first and last names that can be generated for a person (and subsequently, all other data types that use these) contain several that include double-quotes. Ex. (https://github.com/jaswdr/faker/blob/master/person.go#L102). A double-quote is generally not a valid character to be included in a person's name. Names such as the ones in this list would instead typically use a single-quote or apostrophe.

To Reproduce

seed := int64(5272036870)
f := faker.NewWithSeed(rand.NewSource(seed))

// Generate first name first to advance the seed
f.faker.Person().FirstName()

// Generated last name that contains a double-quote (O"Keefe)
fakerLastName := f.faker.Person().LastName()

Expected behavior
I would expect data generated from faker to only contain characters that are valid for that type of data. Because I would not expect double-quotes to be included in a person's name, I would replace those with single-quotes.

Additional context
For developer environments in my org, we have seed data generated by the faker package fed into a service that also executes a set of validation rules against it. Because we have validation that restricts names, addresses, etc. to only valid characters, occasionally that data will fail validation due to the aforementioned double-quotes. This has been worked around by swapping double for single quotes when generating data where necessary.

Pull request opened to make this change: #152

[BUG] Struct().Fill() is not correctly handling nested structures

Describe the bug
goroutine stack exceeds 1000000000-byte limit

To Reproduce

type A struct {
children []*A
}
tmp := A{}
f.Struct().Fill(&tmp)

Expected behavior
A clear and concise description of what you expected to happen.

Screenshots
image

Desktop (please complete the following information):

  • OS: macOS 12.2.1
  • go version output: go version go1.17.3 darwin/amd64

[FEATURE] Add a currency generator

Is your feature request related to a problem? Please describe.
To test applications, that are somehow connected with the financial field, would be helpful to have a currency generator.

Describe the solution you'd like
Iโ€™d like to implement a currency generator, that could return a random currency name and code.

Describe alternatives you've considered
Also, Iโ€™m thinking about adding currency symbols, but Iโ€™m not sure whatever it is really so useful in server-side development. What do you think?

Fix transient issues in tests

[FEATURE] Add a fake random gender data generator

Is your feature request related to a problem? Please describe.
While testing we might need gender in the test input.

Describe the solution you'd like
Add a random gender(Ex. male, female, etc. ) generator.

Generate Iban

Inspired by https://github.com/fzaninotto/Faker/blob/5ffe7db6c80f441f150fc88008d64e64af66634b/src/Faker/Provider/Payment.php#L71

package fakeriban

import (
	Faker "github.com/jaswdr/faker"
)

func format(t rune, size int) string {
	s := ""
	o := ""
	if t == 'n' {
		o = "#"
	} else if t == 'a' {
		o = "?"
	} else if t == 'c' {
		o = "*"
	}

	for i := 0; i < size; i++ {
		s += o
	}
	return s
}

/**
 * @var array list of IBAN formats, source: @link https://www.swift.com/standards/data-standards/iban
 */
var iban = []string{
	"AD" + format('n', 4) + format('n', 4) + format('c', 12),
	"AE" + format('n', 3) + format('n', 16),
	"AL" + format('n', 8) + format('c', 16),
	"AT" + format('n', 5) + format('n', 11),
	"AZ" + format('a', 4) + format('c', 20),
	"BA" + format('n', 3) + format('n', 3) + format('n', 8) + format('n', 2),
	"BE" + format('n', 3) + format('n', 7) + format('n', 2),
	"BG" + format('a', 4) + format('n', 4) + format('n', 2) + format('c', 8),
	"BH" + format('a', 4) + format('c', 14),
	"BR" + format('n', 8) + format('n', 5) + format('n', 10) + format('a', 1) + format('c', 1),
	"CH" + format('n', 5) + format('c', 12),
	"CR" + format('n', 4) + format('n', 14),
	"CY" + format('n', 3) + format('n', 5) + format('c', 16),
	"CZ" + format('n', 4) + format('n', 6) + format('n', 10),
	"DE" + format('n', 8) + format('n', 10),
	"DK" + format('n', 4) + format('n', 9) + format('n', 1),
	"DO" + format('c', 4) + format('n', 20),
	"EE" + format('n', 2) + format('n', 2) + format('n', 11) + format('n', 1),
	"ES" + format('n', 4) + format('n', 4) + format('n', 1) + format('n', 1) + format('n', 10),
	"FI" + format('n', 6) + format('n', 7) + format('n', 1),
	"FR" + format('n', 5) + format('n', 5) + format('c', 11) + format('n', 2),
	"GB" + format('a', 4) + format('n', 6) + format('n', 8),
	"GE" + format('a', 2) + format('n', 16),
	"GI" + format('a', 4) + format('c', 15),
	"GR" + format('n', 3) + format('n', 4) + format('c', 16),
	"GT" + format('c', 4) + format('c', 20),
	"HR" + format('n', 7) + format('n', 10),
	"HU" + format('n', 3) + format('n', 4) + format('n', 1) + format('n', 15) + format('n', 1),
	"IE" + format('a', 4) + format('n', 6) + format('n', 8),
	"IL" + format('n', 3) + format('n', 3) + format('n', 13),
	"IS" + format('n', 4) + format('n', 2) + format('n', 6) + format('n', 10),
	"IT" + format('a', 1) + format('n', 5) + format('n', 5) + format('c', 12),
	"KW" + format('a', 4) + format('n', 22),
	"KZ" + format('n', 3) + format('c', 13),
	"LB" + format('n', 4) + format('c', 20),
	"LI" + format('n', 5) + format('c', 12),
	"LT" + format('n', 5) + format('n', 11),
	"LU" + format('n', 3) + format('c', 13),
	"LV" + format('a', 4) + format('c', 13),
	"MC" + format('n', 5) + format('n', 5) + format('c', 11) + format('n', 2),
	"MD" + format('c', 2) + format('c', 18),
	"ME" + format('n', 3) + format('n', 13) + format('n', 2),
	"MK" + format('n', 3) + format('c', 10) + format('n', 2),
	"MR" + format('n', 5) + format('n', 5) + format('n', 11) + format('n', 2),
	"MT" + format('a', 4) + format('n', 5) + format('c', 18),
	"MU" + format('a', 4) + format('n', 2) + format('n', 2) + format('n', 12) + format('n', 3) + format('a', 3),
	"NL" + format('a', 4) + format('n', 10),
	"NO" + format('n', 4) + format('n', 6) + format('n', 1),
	"PK" + format('a', 4) + format('c', 16),
	"PL" + format('n', 8) + format('n', 16),
	"PS" + format('a', 4) + format('c', 21),
	"PT" + format('n', 4) + format('n', 4) + format('n', 11) + format('n', 2),
	"RO" + format('a', 4) + format('c', 16),
	"RS" + format('n', 3) + format('n', 13) + format('n', 2),
	"SA" + format('n', 2) + format('c', 18),
	"SE" + format('n', 3) + format('n', 16) + format('n', 1),
	"SI" + format('n', 5) + format('n', 8) + format('n', 2),
	"SK" + format('n', 4) + format('n', 6) + format('n', 10),
	"SM" + format('a', 1) + format('n', 5) + format('n', 5) + format('c', 12),
	"TN" + format('n', 2) + format('n', 3) + format('n', 13) + format('n', 2),
	"TR" + format('n', 5) + format('n', 1) + format('c', 16),
	"VG" + format('a', 4) + format('n', 16),
}

func Iban(f Faker.Faker) string {
	out := f.RandomStringElement(iban)
	out = f.Lexify(out)
	out = f.Numerify(out)
	out = f.Asciify(out)
	return out
}

[BUG] v2.1.0 IntBetween still panic()'s...

Describe the bug
This looks like a continuation of #164

To Reproduce
This may still need to be entirely fixed. I can reproduce this about once every 50-100 runs or so. Using https://github.com/sean-/bench-go-histograms as the reproducer:

$ go test -test.bench=PromDuration -benchmem -count 200
goos: darwin
goarch: arm64
pkg: github.com/sean-/bench-go-histograms
Benchmark_PromDuration-10    	 5184980	       229.5 ns/op	       0 B/op	       0 allocs/op
Benchmark_PromDuration-10    	 5846218	       217.5 ns/op	       0 B/op	       0 allocs/op
[snip]
Benchmark_PromDuration-10    	 5678696	       234.6 ns/op	       0 B/op	       0 allocs/op
Benchmark_PromDuration-10    	 5885458	       226.5 ns/op	       0 B/op	       0 allocs/op
Benchmark_PromDuration-10    	 5580679	       225.2 ns/op	       0 B/op	       0 allocs/op
Benchmark_PromDuration-10    	panic: runtime error: index out of range [-1]

goroutine 635 [running]:
math/rand.(*rngSource).Uint64(...)
	/opt/homebrew/Cellar/go/1.22.0/libexec/src/math/rand/rng.go:249
math/rand.(*rngSource).Int63(0x9?)
	/opt/homebrew/Cellar/go/1.22.0/libexec/src/math/rand/rng.go:234 +0x8c
math/rand.(*Rand).Int63(...)
	/opt/homebrew/Cellar/go/1.22.0/libexec/src/math/rand/rand.go:96
math/rand.(*Rand).Int63n(0x140000a8c30, 0x2540be400)
	/opt/homebrew/Cellar/go/1.22.0/libexec/src/math/rand/rand.go:128 +0x68
math/rand.(*Rand).Intn(0xb?, 0x14000130000?)
	/opt/homebrew/Cellar/go/1.22.0/libexec/src/math/rand/rand.go:185 +0x44
github.com/jaswdr/faker/v2.Faker.IntBetween({{0x102946538?, 0x140000a8c30?}}, 0x1?, 0x2540be400?)
	/Users/seanc/go/pkg/mod/github.com/jaswdr/faker/[email protected]/faker.go:182 +0xb0
github.com/sean-/bench-go-histograms.randDuration(...)
	/Users/seanc/go/src/github.com/sean-/bench-go-histograms/bench_test.go:22
github.com/sean-/bench-go-histograms.Benchmark_PromDuration.func1(0x1400007e000)
	/Users/seanc/go/src/github.com/sean-/bench-go-histograms/bench_test.go:151 +0x64
testing.(*B).RunParallel.func1()
	/opt/homebrew/Cellar/go/1.22.0/libexec/src/testing/benchmark.go:797 +0xbc
created by testing.(*B).RunParallel in goroutine 610
	/opt/homebrew/Cellar/go/1.22.0/libexec/src/testing/benchmark.go:790 +0x104
exit status 2
FAIL	github.com/sean-/bench-go-histograms	15.354s

JFYI. The rate of this happening is now quite small, but it's not zero, either. I don't know if you want to open a new issue, or

Stringifier

Scenario: Sometimes you need to format a String with fake values and calling fmt.Sprintf each time is boring, so this feature will introduce a way that you can handdle this like this example:

import "jaswdr/faker"

func main() {
    f := faker.New()
    f.Stringify(`{ "name": "{{ Person.Name }}" }`)
    // { "name": "John Doe"}
}

The pattern {{Entity.Method}} will be used

[BUG] Flaking tests around time.

Some of the tests are flaky and failing randomly - mainly related to TestUNIXTime and the like. I've noticed 3 of them randomly failing so far and am opening this issue to investigate at a later stage. This should not be related to any changes in the crypto feature that I was writing as these are in completely different files and non-overlapping.

Edit: Managed to get the verbose output.

=== RUN   TestRFC1123
    time_test.go:74: 
        Expected: (int) 29 
        Got:      (int) 31
--- FAIL: TestRFC1123 (0.00s)

=== RUN   TestUnixDate
    time_test.go:43: 
        Expected: (int) 28 
        Got:      (int) 30
--- FAIL: TestUnixDate (0.00s)

=== RUN   TestRFC822
    time_test.go:55: 
        Expected: (int) 19 
        Got:      (int) 21
--- FAIL: TestRFC822 (0.00s)

[BUG] Bitcoin addresses generated are not valid (incorrect checksum)

Describe the bug

Bitcoin keys use base58 check (see https://en.bitcoin.it/wiki/Base58Check_encoding, for example: https://gobittest.appspot.com/Address). Addresses generated by this package are not valid Bitcoin addresses since their checksums are invalid.

The generator just generates random base58 text. I implemented a function that can fix checksums of a randomly generated address, it just requires base58 encode/decode. You can copy this small implementation into the Faker lib to not need to go get it: https://github.com/akamensky/base58/blob/master/base58.go. Or implement it yourself.

If base58 is in this package, I can make a PR that runs all bitcoin generated addressed through a checksum fix function and make sure they are valid.

To Reproduce

https://go.dev/play/p/No5BYCcsUk4

package main

import (
	"crypto/sha256"
	"fmt"

	"github.com/btcsuite/btcutil/base58"
	"github.com/jaswdr/faker"
)

func main() {
	fake := faker.New()
	address := fake.Crypto().BitcoinAddress()
	fmt.Println("Before:", address)
	_, _, err := base58.CheckDecode(address)
	if err != nil {
		fmt.Println("Failed:", err)
	} else {
		fmt.Println("Success!")
	}

	// Fix the address
	address = FixChecksum(address)
	fmt.Println("After:", address)
	_, _, err = base58.CheckDecode(address)
	if err != nil {
		fmt.Println("Failed:", err)
	} else {
		fmt.Println("Success!")
	}
}

func FixChecksum(addr string) string {
	decoded := base58.Decode(addr)

	// Remove the last 4 bytes
	decoded = decoded[:len(decoded)-4]

	// Find the checksum
	checksum := sha256.Sum256(decoded)
	checksum = sha256.Sum256(checksum[:])

	// Add back the 4 byte checksum
	decoded = append(decoded, checksum[:4]...)
	return base58.Encode(decoded)
}

Expected behavior

The address should pass the CheckDecode

[FEATURE] Add a mechanism to generate a fake data json

Is your feature request related to a problem? Please describe.
Currently we have several generators available in Faker. But what if we have a mechanism which takes a format as input and returns a data with same format completely generated by the generators of faker. The format will contain multiple data fields and nested complexity. This can be useful for generating multiple test scenarios in one go.

Describe the solution you'd like
You recursive search and build of data using faker generators.

[BUG] Different coverage percents every time the test run

Describe the bug
If you run the test with the coverprofile flag it return different results every time.

To Reproduce

$ for i in {1..10}; do go test -coverprofile=coverage.out .; done

E.g.

$ for i in {1..10}; do go test -coverprofile=coverage.out .; done
ok  	faker	6.565s	coverage: 95.6% of statements
ok  	faker	5.586s	coverage: 94.9% of statements
ok  	faker	6.202s	coverage: 95.6% of statements
ok  	faker	5.363s	coverage: 96.2% of statements
ok  	faker	5.253s	coverage: 96.4% of statements
ok  	faker	5.439s	coverage: 95.9% of statements
ok  	faker	5.360s	coverage: 96.3% of statements
ok  	faker	5.089s	coverage: 96.2% of statements
ok  	faker	6.661s	coverage: 95.1% of statements
ok  	faker	9.051s	coverage: 96.2% of statements

Expected behavior
It should return the same value every time.

Desktop (please complete the following information):

  • OS: MacOS Monterrey 12.4
  • go version output: go version go1.11 darwin/amd64

Generate a word from English dictionary instead of lorem list of words

Is your feature request related to a problem? Please describe.
I need to generate real words from a dictionary to use inside a security project. The problem with the hard-coded list in `Lorem().Text()`` that it can be easy identified as fake data

I can understand that faker's point is to generate fake data, though it will be useful to also give an option to generate more realistic fake data when it comes to strings.

Describe the solution you'd like
fake.Lorem().Word(min-length?) -> "apple"

Describe alternatives you've considered
Completely random slice of letters or a ransom elements of lorem texts array is not suitable for my use case.

Check out this: https://raw.githubusercontent.com/tjarratt/babble/master/babble_windows.go

We don't need to grab the whole words from the dictionary as it will increase significantly the package size, for example words under 4 letters can be dropped.

[HACKTOBERFEST-2021] Create more generators

Is your feature request related to a problem? Please describe.
Create more generators to generate more fake data.

Describe the solution you'd like
Each new generator should follow the existing patterns, have tests and have a purpose.

Describe alternatives you've considered
Some inspiration https://github.com/search?q=%23faker

Additional context
Happy 2021 Hacktoberfest ๐ŸŽ‰

[BUG] IntBetween not giving correct output

Describe the bug
While trying to fix the test coverage for ticket #28, I found out that the IntBetween function does not return values correctly for some cases.

Example: https://github.com/jaswdr/faker/blob/master/person.go#L136-L142

To Reproduce

Go playground sample snippet.

f := faker.New()

for i := 0; i < 10; i++ {
	fmt.Println(f.IntBetween(0, 1))
}

The output will always be 0. The current IntBetween function does not handle the range [0, 1] correctly.

Expected behavior
I would expect that IntBetween(0, 1) would return 0s and 1s randomly.

Also, I would like to get clarification if the function should return numbers between 0-1 in this case. I do have a fix for this already but I am seeing some other tests fail because of the way IntBetween is being used. For example on address.go:

func (f Faker) RandomStringElement(s []string) string {
	i := f.IntBetween(0, len(s))
	return s[i]
}

A number between 0 and len(s) would cause random index out of range errors because it would sometimes return len(s).

Screenshots
N/A.

Desktop (please complete the following information):

  • OS: any
  • go version output: go version go1.15.2 linux/amd64

Additional context
Add any other context about the problem here.

[BUG] v2.0.3 returns incorrect values for Int and UInt methods

Describe the bug
Changes made to v2.0.3 seem to have broken the Int and Uint methods. The sample code in the Go Playground will generate the output below (10 random numbers for each method). Only Uint() appears to be working correctly.

Int64: [-9223372036854775808 -9223372036854775808 -9223372036854775808 -9223372036854775808 -9223372036854775808 -9223372036854775808 -9223372036854775808 -9223372036854775808 -9223372036854775808 -9223372036854775808]
Int32: [0 0 0 0 0 0 0 0 0 0]
Int16: [0 0 0 0 0 0 0 0 0 0]
Int8: [0 0 0 0 0 0 0 0 0 0]
Int: [-9223372036854775808 -9223372036854775808 -9223372036854775808 -9223372036854775808 -9223372036854775808 -9223372036854775808 -9223372036854775808 -9223372036854775808 -9223372036854775808 -9223372036854775808]

UInt64: [9223372036854775808 9223372036854775808 9223372036854775808 9223372036854775808 9223372036854775808 9223372036854775808 9223372036854775808 9223372036854775808 9223372036854775808 9223372036854775808]
UInt32: [0 0 0 0 0 0 0 0 0 0]
UInt16: [0 0 0 0 0 0 0 0 0 0]
UInt8: [0 0 0 0 0 0 0 0 0 0]
UInt: [7656741239857252927 5594207809226113391 6008768823903029407 2021276371439549788 338472662231586328 7331582930402992456 1862095825495157913 6678231846753265959 9208902309648365007 549713215453345498]

They appear to be working more correctly with v2.0.2 (although Int64 and Int do not appear to be producing any negative values with v2.0.2):

Int64: [4457966027044790232 3068793850071510156 4241597960427124847 7097929654138723183 53203214098893531 4549093053679149128 4180637979454261572 7573092381611586563 9173485451690427125 3851087538435533936]
Int32: [-455826018 -1258706307 -1044868518 851197946 -1216443716 515121644 1535424041 -1623242824 -434048819 -921841709]
Int16: [-4581 17178 24303 15499 16902 12949 9880 14951 11319 -6594]
Int8: [-122 100 72 -102 -22 15 -88 -5 110 120]
Int: [7533801517110527743 6978115144997277611 6286691177520792259 4024021042162847838 5061842129050809232 4191043012286955853 3602606074011605235 6839266255701396663 4091504718573783711 4638797404464528346]

UInt64: [41055368818041555 8938590738929278265 1192535113924107347 1668087444309155861 4833168004950273266 790332503801125400 3813344926054000253 1394808423049600791 7440181255669925228 7712871825341992071]
UInt32: [3719961827 1904474432 1215507601 2700000476 1190456603 2950735355 3292251569 3440930050 1848275514 1027039561]
UInt16: [61836 3570 34601 53919 3204 10354 64422 49933 10516 41437]
UInt8: [197 130 112 80 117 215 25 130 68 70]
UInt: [122291367368253944 9184109984619104570 6913572135790214506 4359817097239585374 7179945772768069149 228053568771661241 180971267124051659 832342306344858062 2357607085026279658 1566666409152456504]

To Reproduce
See https://goplay.tools/snippet/6eRhDKSKzfW

Expected behavior
A clear and concise description of what you expected to happen.

Desktop (please complete the following information):

  • OS: Mac OS 14.1.1 (Sonoma)
  • go version output: go version go1.21.6 darwin/arm64

Add shuffle slice utility

Is your feature request related to a problem? Please describe.
I'm trying to fake a randomized array of unique enums

Describe the solution you'd like
To include shuffleSlice as Faker.ShuffleSlice

func ShuffleSlice[T any](slice []T) []T {
	rand.Shuffle(len(slice), func(i, j int) {
		slice[i], slice[j] = slice[j], slice[i]
	})

	return slice
}

go playground example
https://play.golang.com/p/1rQ2O-0aNOx

[BUG] UUID generation is not random

Describe the bug
When I generate UUID's rapidly (for a test for example) the UUIDs are not random and unique.

To Reproduce

func (m *Scan) Factory() {
	fake := faker.New()
	fake.Struct().Fill(&m)
}
for i := 0; i < 5; i++ {
	object := models.Object{}
	object.Factory()
	fmt.Println(object)
}

Expected behavior
Generate a random and unique UUID each time.

Desktop (please complete the following information):

  • OS: macOS
  • go version output: go version go1.20.1 darwin/arm64

Additional context
My suggestion is to generate UUID's using a library like "github.com/google/uuid"

[FEATURE] Users can generate bank account id Uding their country code or without it

Is your feature request related to a problem? Please describe.
Users could specify the country code as an input parameter or option when generating a bank account ID. For example, they might provide a country code like "US" for the United States or leave it blank for a default or random country.

Describe the solution you'd like
Yes, different countries may have specific rules and formats for bank account IDs. It would be essential to have a mechanism that considers these rules when generating bank account IDs for a specific country. Additionally, you may need a default format for cases where the country code is not provided.

Describe alternatives you've considered
None alternatives as of now

Additional context
The purpose of generating bank account IDs can vary. It could be for testing, simulation, generating sample data, or any other scenario where having realistic-looking bank account IDs is necessary.The purpose of generating bank account IDs can vary. It could be for testing, simulation, generating sample data, or any other scenario where having realistic-looking bank account IDs is necessary.

[FEATURE] Generate unique value to struct's fields.

type User struct {
        Id             int               // unique value in this struct, like: 1.
        Age          int               // unique value in this struct, other value except 1, like: 2.
        Name      string           // unique value in this struct, like: "Jack".
        Phone      string          // unique value in this struct, other vlaue except "Jack".
}  

[FEATURE] Improve performance using strings builders instead of a string

Is your feature request related to a problem? Please describe.
No.

Describe the solution you'd like
Some functions use a string inside a for look to create a value to be returned. This is not very performant. A better approach is use a string builder.

Describe alternatives you've considered
None.

Additional context
None.

[BUG] Some fake emails fails email validation regex

Describe the bug
When using faker.Internet().Email(), some generated fake emails fails email regex patterns.
Some names like "O\"Connell", "O\"Conner", "O\"Hara", "O\"Keefe", "O\"Kon" found in here trips up a regex pattern for validating email addresses.

Regex: /^[\w-\.]+@([\w-]+\.)+[\w-]{2,4}$/g

To Reproduce

In the off chance that you can get the library to pick one of these names and generate a fake email, you can run it against this regex validator: https://regexr.com/3e48o

Expected behavior
That faker.Internet().Email() returns a semantically valid email address format.

Screenshots
Screen Shot 2022-01-26 at 7 58 19 PM

Desktop (please complete the following information):

  • OS: MacOS Monterey
  • go version output: go version go1.17.6 darwin/amd64

[BUG] v2 Go Module

Describe the bug
v2 of this package cannot be found

This is because the module name in go.mod in the v2.0.0 tag should be

module github.com/jaswdr/faker/v2

[FEATURE] Add methods for uints

Is your feature request related to a problem? Please describe.
It is convenient to have same methods for uint - uint64 that we have for int type. For example:
UIntBetween(min, max uint64) uint64 - UInt64Between(min, max uint64) uint64.

Describe the solution you'd like
We can take the IntBetween(min, max int) int as basement and make UIntXXBetween(min, max uintXX) uintXX.

[FEATURE] Improve documentation

Is your feature request related to a problem? Please describe.

The current documentation is basically the one README file and the automatically generated in https://pkg.go.dev/github.com/jaswdr/faker. We can improve our README to include more examples of how to use faker and each generator.

Describe the solution you'd like
I would to recommend improving the existing README file, adding examples of all generators.

Describe alternatives you've considered
To generate the list of examples we can use the go/ast package to load and analyze the current and future code.

Additional context
No other context needed

[BUG] Uint() is panicking

Hi! First and foremost, I'd like to thank You an amazing work :) I've been on PHP's side for a long time, where I was using Faker a lot. After switching to Go world, this faker is definitely the easiest and most convenient to use. I haven't seen any issue reported regarding Uint(), so here is what I found out.

Describe the bug
Calling Faker.Uint() panics.

To Reproduce

import (
	"fmt"
	"testing"

	"github.com/jaswdr/faker"
)

func TestUint(t *testing.T) {
	fakerInstance := faker.New()

	t.Run("It is panicking", func(t *testing.T) {
		//userId := uint(fakerInstance.Int()) // Temporary workaround
		userId := fakerInstance.UInt()

		fmt.Println(userId)
	})
}

Expected behavior
UInt() returns a random uint value.

Screenshots
obraz

obraz

obraz

Desktop (please complete the following information):

  • OS: macOS 12.2
  • go version output: go version go1.17.6 darwin/amd64

Additional context
I was able to debug, that UInt() calls IntBetween(0, maxValueOf_int_type), and IntBetween() is later calling f.Generator.Intn(diff+1). The diff+1 is the problem here since it overflows int type max value and, in the end, when rand.Intn() receives negative value, it panics.

I'm also attaching a few screenshots from debugging chain.

Godoc

Document all methods in a way that godoc can generate awesome documentation.

[FEATURE] Generate a fake email and Generate a fake SSN

Is your feature request related to a problem? Please describe.
generation of fake emails and social security numbers

Describe the solution you'd like
fake = Faker()

Generate a fake SSN (Note: This is for educational/testing purposes only)

fake_ssn = fake.ssn()

Generate a fake email

fake_email = fake.email()

Describe alternatives you've considered
I have considered only this feature

Additional context
Please exercise caution when generating fake SSNs, and avoid using them in any production or real-world scenario. Always respect privacy and legal regulations when working with sensitive data.

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.