Go (Golang) Fake Data Generator for Struct

Overview

Docs

faker

Struct Data Fake Generator

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

Build Status codecov Go Report Card License GoDoc Go.Dev

Index

Support

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

Getting Started

Download

go get -u github.com/bxcodec/faker/v3

Example


DEMO


Example to use Faker

Benchmark


Bench To Generate Fake Data

Without Tag

BenchmarkFakerDataNOTTagged-4             500000              3049 ns/op             488 B/op         20 allocs/op

Using Tag

 BenchmarkFakerDataTagged-4                100000             17470 ns/op             380 B/op         26 allocs/op

MUST KNOW


The Struct Field must be PUBLIC.
Support Only For :

  • int, int8, int16, int32 & int64
  • []int, []int8, []int16, []int32 & []int64
  • bool & []bool
  • string & []string
  • float32, float64, []float32 &[]float64
  • time.Time & []time.Time
  • Nested Struct Field

Limitation


Unfortunately this library has some limitation

  • It does not support private fields. Make sure your structs fields you intend to generate fake data for are public, it would otherwise trigger a panic. You can however omit fields using a tag skip faker:"-" on your private fields.
  • It does not support the interface{} data type. How could we generate anything without knowing its data type?
  • It does not support the map[interface{}]interface{}, map[any_type]interface{} & map[interface{}]any_type data types. Once again, we cannot generate values for an unknown data type.
  • Custom types are not fully supported. However some custom types are already supported: we are still investigating how to do this the correct way. For now, if you use faker, it's safer not to use any custom types in order to avoid panics.
  • Some extra custom types can be supported IF AND ONLY IF extended with AddProvider() please see example
  • The oneof tag currently only supports string, the int types, and both float32 & float64. Further support is coming soon (i.e. hex numbers, etc). See example for usage.

Contribution


To contrib to this project, you can open a PR or an issue.

Issues
  • feat: Add ability to ignore interface{} population with SetIgnoreInterface()

    feat: Add ability to ignore interface{} population with SetIgnoreInterface()

    This PR adds a flag that tells faker to ignore the population of interface{} types.

    This is useful when populating complex structures for Marshal testing, where you don't have the control or ability to use a non-interface{}. This makes testing complex structure marshaling a LOT simpler, since otherwise you would have to faker every element in the structure above and beside an interface{}.

    The default behavior is to not ignore interface{}, so no behavior changes should be seen.

    A test has been added.

    Thanks!

    opened by nashikb 12
  • fix slice tag bug AND add chinese name

    fix slice tag bug AND add chinese name

    fix bug

    AdCode[]string `json:"ad_code" xorm:"ad_code" faker:"len=slice_len=5,len=10"` 
    

    return:

    {AdCode:[rMZLe XgkhW IZHBZ qEaWa nwrKJ]}
    

    but

    AdCode[]string `json:"ad_code" xorm:"ad_code" faker:"len=10,slice_len=5"`
    

    return:

    {AdCode:[RotjXUZmnq MTbKBCQhJC PedUsSqIwv xTnlUgWajY PBENmHwGfc]}
    

    features

    • add chinese_first_name
    • add chinese_last_name
    • add chinese_name
    opened by qiangmzsx 11
  • oneof float support

    oneof float support

    • add support for float32
    • ensure support for both float32 and float64
    • lint fixes
    • add tests for float64 & add test for nil pointer""

    fix #82

    opened by andrew-werdna 8
  • Go mod cannot find module

    Go mod cannot find module

    Since the 2.01 update, go modules cannot find the module

    unknown import path "github.com/bxcodec/faker": cannot find module providing package github.com/bxcodec/faker

    It did work with version v2.0.0

    opened by psiservices-scohen 7
  • Usernames with non-alphabetical characters

    Usernames with non-alphabetical characters

    Since v3.4.0 (specifically, feature "new lang tag"), the generated fake usernames may include non-alphabetical characters : "[", "", "]", "^", "_" and "`" : those characters are in the ASCII table between lowercase and uppercase letters.

    Before v3.4.0, it was based on the string letterBytes, which contained "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ".

    opened by tiramiseb 6
  • feat: Implement oneof tag

    feat: Implement oneof tag

    • This adds support for a faker:"oneof: val1 :val2 :val3"
    • Currently only string and int is suppported
    • I would be happy to add support for more types at a later time
    • This looks like it might fix (or at least partially fix) https://github.com/bxcodec/faker/issues/82
    opened by andrew-werdna 6
  • Unique modifier

    Unique modifier

    I have a use-case where I need to generate some structs and one of the fields needs to be unique. As the library doesn't have a unique modifier, I implemented UniqueFaker wrapper which retries the generation if the value has already been generated before.

    This feature could be integrated officially into the library and I think it could be a very useful one. That way, uniqueness wouldn't require a wrapper and wouldn't require to instantiate multiple fakers for a single dataset.

    opened by System-Glitch 6
  • feat(faker): length Support

    feat(faker): length Support

    String len, number boundaries and array and map size have become configurable. In reference task, it was asked as a tag but I think, adding two new unnecessary field will be pointless for length setting instead making configuration will be more convenient. So It has become configurable with this PR...

    fix #49

    opened by olimpias 6
  • Concurrent data generation (thread safety)

    Concurrent data generation (thread safety)

    I'm using faker to generate data for a simulation that has multiple goroutines. It seems faker is currently unable to work with more than a single thread due to the fact that it uses rand.NewSource
    here .

    The docs say:

    NewSource returns a new pseudo-random Source seeded with the given value. Unlike the default Source used by top-level functions, this source is not safe for concurrent use by multiple goroutines.
    

    https://golang.org/pkg/math/rand/

    It would be great to make it so we're able to use faker across multiple threads.

    bug 
    opened by ridv 6
  • feat(faker): unique data generation

    feat(faker): unique data generation

    Refer to issue #76

    • Added a unique tag to generate unique data.
      • Call ResetUnique() after generating a dataset to forget all already generated values
    • Added tests for the new feature
    • Added unique support for Lorem generator as a proposal for the single fake data functions. My implementation is redundant. Any feedback would be appreciated before implementing it to the other single fake data functions.
      • Call SetGenerateUniqueValues(true) to enable unique data generation on single fake data functions
      • Call SetGenerateUniqueValues(false) to disable it
      • Call ResetUnique() to forget all already generated values

    This change shouldn't break backwards compatibility.

    TODO:

    • [x] Update documentation
    • [x] Implement unique handling in all single fake data functions
    opened by System-Glitch 5
  • Thread safety by using the default source for the RNG

    Thread safety by using the default source for the RNG

    • Using custom sources results in the RNG becoming non-thread safe. Using the default source guarantees that multiple threads are able to generate data using faker safely as per the Go docs (https://golang.org/pkg/math/rand/).
    bug 
    opened by ridv 5
  • Make possible to ignore some fields or provide custom generators

    Make possible to ignore some fields or provide custom generators

    For the cases when you cant use struct tags (eg struct is from 3d-party) it would be nice to have an option to ignore some fields by it's name or provide a custom generator.

    type SomeType struct {
      Field1 error
      Field2 context.Context
      Field3 string
    }
    

    a.

    var v SomeType
    faker.Fake(&v, faker.IgnoreFields("Field1", "Field2"))
    

    b.

    var v SomeType
    faker.Fake(&v,
       faker.FieldGenerator("Field1", func() (interface{}, error) {
          return context.TODO(), nil
       }),
       faker.FieldGenerator("Field2", func() (interface{}, error){
          return errors.New("test"), nil
       },
    )
    

    c.

    faker.SetGeneratorForType("context.Context", func() (interface{}, error) {
      return context.TODO(), nil
    })
    faker.SetGeneratorForType("error", func() (interface{}, error) {
      return errors.New("test"), nil
    })
    

    b and c are more flexible as they allow custom generators

    opened by unkeep 0
  • `slice_len` only works for `string`

    `slice_len` only works for `string`

    Right now, slice_len does not actually work for a slice of integers/bytes, despite what the example has: https://github.com/bxcodec/faker/blob/master/example_with_tags_slicelength_test.go

    If you add a slice of integers to the test: https://github.com/bxcodec/faker/blob/master/faker_test.go#L650

    It will fail with "Invalid Tags" here: https://github.com/bxcodec/faker/blob/master/faker.go#L921

    The reason you don't see similar with Strings is because the similar check in extractStringFromTag, we always have lang set: https://github.com/bxcodec/faker/blob/master/faker.go#L858

    I wasn't sure how best to approach this, whether we should just have a check accepting slice_len as an additional tag in extractNumberFromTag or some other cleaner way, but dem's de facts.

    opened by trynity 0
  • Is bitcoin address supported?

    Is bitcoin address supported?

    Bitcoin address would take up 26-35, see here for the information from Bitcoin wiki

    A Bitcoin invoice address, or simply invoice, is an identifier of 26-35 alphanumeric characters, beginning with the number 1, 3 or bc1 that represents a possible destination for a bitcoin payment. Invoices can be generated at no cost by any user of Bitcoin. It is also possible to get a Bitcoin invoice address using an account at an exchange or online wallet service.

    There are currently three invoice address formats in use:

    P2PKH which begin with the number 1, eg: 1BvBMSEYstWetqTFn5Au4m4GFg7xJaNVN2. P2SH type starting with the number 3, eg: 3J98t1WpEZ73CNmQviecrnyiWrnqRhWNLy. Bech32 type starting with bc1, eg: bc1qar0srrr7xfkvy5l643lydnw9re59gtzzwf5mdq.


    Ethereum address would take up 42 characters long for the prefixed address, see here for the information from Ethereum documentation glossary

    An Ethereum address represents an account. For EOA, the address is derived as the last 20 bytes of the public key controlling the account, e.g., cd2a3d9f938e13cd947ec05abc7fe734df8dd826. This is a hexadecimal format (base 16 notation), which is often indicated explicitly by appending 0x to the address. Web3.js and console functions accept addresses with or without this prefix but for transparency we encourage their use. Since each byte of the address is represented by 2 hex characters, a prefixed address is 42 characters long. Several apps and APIs are also meant to implement the new checksum-enabled address scheme introduced in the Mist Ethereum wallet as of version 0.5.0.

    opened by fzn0x 0
  • Tag unsupported: boundary_start=31,boundary_end=88

    Tag unsupported: boundary_start=31,boundary_end=88

    PostalCode *uint64  `protobuf:"varint,3,opt,name=postalCode,proto3,oneof" json:"postalCode,omitempty" binding:"omitempty,min=1000,max=99999" faker:"boundary_start=1000, boundary_end=99999"`
    

    https://github.com/bxcodec/faker/blob/master/example_with_tags_lenbounds_test.go

    opened by loeffel-io 2
Releases(v3.8.0)
  • v3.8.0(Mar 10, 2022)

    What's Changed

    • feat: add min max size for random slice map And allowing one element for Oneof by @autumn31 in https://github.com/bxcodec/faker/pull/130
    • Support for Korean Hangul by @geshtng in https://github.com/bxcodec/faker/pull/154
    • fix slice tag bug AND add chinese name by @qiangmzsx in https://github.com/bxcodec/faker/pull/141
    • Support for Emoticons by @geshtng in https://github.com/bxcodec/faker/pull/155
    • Float boundaries by @Xaspy in https://github.com/bxcodec/faker/pull/156

    New Contributors

    • @autumn31 made their first contribution in https://github.com/bxcodec/faker/pull/130
    • @geshtng made their first contribution in https://github.com/bxcodec/faker/pull/154
    • @qiangmzsx made their first contribution in https://github.com/bxcodec/faker/pull/141
    • @Xaspy made their first contribution in https://github.com/bxcodec/faker/pull/156

    Full Changelog: https://github.com/bxcodec/faker/compare/v3.7.0...v3.8.0

    Source code(tar.gz)
    Source code(zip)
  • v3.7.0(Dec 29, 2021)

    What's Changed

    • feat: added random source customization by @fredbi in https://github.com/bxcodec/faker/pull/137
    • feat: Support for Japanese hiragana and katakana by @tomtwinkle in https://github.com/bxcodec/faker/pull/145
    • chore: check slice.Contains in for range block by @eval-exec in https://github.com/bxcodec/faker/pull/151
    • feat: randomInt support third argument by @maco in https://github.com/bxcodec/faker/pull/150

    New Contributors

    • @fredbi made their first contribution in https://github.com/bxcodec/faker/pull/137
    • @tomtwinkle made their first contribution in https://github.com/bxcodec/faker/pull/145 and thanks to @geshtng for reviewing the PR
    • @eval-exec made their first contribution in https://github.com/bxcodec/faker/pull/151
    • @maco made their first contribution in https://github.com/bxcodec/faker/pull/150

    Full Changelog: https://github.com/bxcodec/faker/compare/v3.6.0...v3.7.0

    Source code(tar.gz)
    Source code(zip)
  • v3.6.0(Feb 5, 2021)

    Features

    • feat: added fake jwt-token support (#113) by @musinit
    • feat: Add RemoveProvider public method (#115) by @pioz
    • feat: Add ability to ignore interface{} population with SetIgnoreInterface() (#123) by @nashikb

    Chores

    • chore: removes Adolf from male names (#128) by @DavidLarsKetch
    Source code(tar.gz)
    Source code(zip)
  • v3.5.0(Jun 17, 2020)

    Features

    • feat: Implement oneof tag (#103) by @andrew-werdna
    • feat: oneof float support (#106) by @andrew-werdna
    • feat: Adds Slice length tag (#109) by @Icety

    Fixes

    • fix: excluded characters in random string generator (#111) by @musinit
    Source code(tar.gz)
    Source code(zip)
  • v3.4.0(Jun 7, 2020)

    Features

    • feat: added gender tag (#104) by @musinit
      • test: add gender unit test (#105)by @bxcodec
    • feat: new lang tag, chinese + russian lang generators (#97) by @musinit
      • docs: added lang tag example in readme (#100) by @musinit
    • feat: upgrade linter version to use the latest stable version (#98) by @bxcodec

    Fixes

    • fix: Allow AddProvider to still work with some custom types (#102) by @andrew-werdna
    • bugfix(faker): don't panic on typed array (#99) by @xaionaro
    • fix: 0 not valid for random size #96 by @mattquest
    Source code(tar.gz)
    Source code(zip)
  • v3.3.1(Apr 18, 2020)

  • v3.3.0(Feb 25, 2020)

    Features

    • feat(error): extend error messages for bad tag's name (#80) by @steveoc64

    Chores

    • chore(linters): resolve linter and typos (#78)
    • README.md: fix a typo & formatting (#79) by @ifnotak
    • chore(go): update go version for testing in travis (#85)
    • chore: update examples (#88) by @momotaro98
    • chores(docs): Move example from markdown to tests (#89) by @mrVanboy
    Source code(tar.gz)
    Source code(zip)
  • v3.2.0(Nov 15, 2019)

    Features

    • feat(faker): unique data generation (#77) by @System-Glitch
    • feat(custom-faker): add map support to custom fakers (#70) by @jostillmanns

    Chores

    • chore(typos): fix typos #73 by @mgrachev
    Source code(tar.gz)
    Source code(zip)
  • v3.1.0(May 7, 2019)

    Features

    • feat(faker): add support for keeping struct property values (#64)

    Fixes

    • fix(skip-tag): skip tag does not really skip the value but reset it. (#67)
    Source code(tar.gz)
    Source code(zip)
  • v3.0.0(Mar 8, 2019)

    This version already fully support for Go Module.

    Features

    • feat(faker): open the faker core function to be able accessed from external project (#63)
    • feat(faker): length Support (#60)
    • feat(credit-card): add card type of jcb and diners club (#61)
    • Optionally insert nils instead of empty slices and maps (#59)
    • feat: New faker/v3 go module (#56) [⚠️Breaking Changes]

    Chore

    • chore: apply linter for better quality code (#55)
    • chore: remove duplicate creditCard definitions. (#53)
    • chore: Correct and rephrase the README (#50)
    • chore: add docs to godoc (#48)

    Fixes

    • fix: typos ("tool_free" -> "toll_free") (#52) [⚠️Breaking Changes]

    Docs

    • Update WithStructTag.md (2b41ee29bd6d10b10e5ffc2abe125dc5ac490b94)
    • Update CustomFaker.md (287a86e2051f497a3f63980e067b45b53a2a558c)
    • Update WithoutTag.md (00d1ce7affedbd85101c68daba4dbed2fb1d6cfe)
    • Update SingleFakeData.md(8eb7c000510ece7f792e23c6986b43b8a6cd2a9a)
    Source code(tar.gz)
    Source code(zip)
  • v2.0.1(Jan 22, 2019)

    Fix:

    • fix: resolve pointer on tagged field (#47)

    Notes

    From this version to previous versions: There is a typo that I forgot to fix but fixed on #52.

    Keep using this tag for generate Tool Free Number.

    tool_free_number
    
    Source code(tar.gz)
    Source code(zip)
  • v2.0.0(Jan 13, 2019)

    Breaking Changes

    Breaking changes for (extend) custom provider.

    • fix: custom provider generator #43

    Feature

    • feat: UUID Generator (#40)

    Fix

    • fix: fake data generation for custom scalar type pointers (#41)

    Chore

    • chore: add Skip a field to example docs (#38)
    Source code(tar.gz)
    Source code(zip)
  • v1.5.0(Sep 24, 2018)

    Feature

    • feat: adds support for FirstName of either male or female gender (#28)
    • feat: Add skipping field tag (#32)
    • feat: Add extending faker by custom providers (#33)
    • feat: Added price (amount and currency) | Code commented and styled (#37)

    Fix

    • fix: panic on named types (#26)
    • fix: DayOfWeek now returns random day (#24)
    • fix: panic on unexported field in struct (#31)
    • fix: random string not random when loop (#35)
    Source code(tar.gz)
    Source code(zip)
  • v1.4.3(May 4, 2018)

  • v1.4.1(Mar 23, 2018)

  • v1.4.0(Mar 23, 2018)

  • v1.3.0(Nov 4, 2017)

  • v1.2.2(Jul 12, 2017)

  • v1.2.1(Jul 11, 2017)

  • v1.1.1(Jun 25, 2017)

  • v1.1.0(Jun 22, 2017)

  • v1.0.0(Jun 22, 2017)

    Support Only For :

    • int int8 int16 int32 int64 and the slice
    • bool and the slice
    • string and the slice
    • float32 float64 and the slice
    • Nested Struct Field for Non POINTER
    Source code(tar.gz)
    Source code(zip)
Owner
Iman Tumorang
Software Engineer | Writer | Open Source Enthusiast | Startup Enthusiast
Iman Tumorang
A library for generating fake data such as names, addresses, and phone numbers.

faker Faker is a library for generating fake data such as names, addresses, and phone numbers. It is a (mostly) API-compatible port of Ruby Faker gem

Dmitri Goutnik 296 Jun 26, 2022
This is a simple test application that sends fake video data from one pion instance to another

Pion test app for BWE This is a simple test application that sends fake video data from one pion instance to another. It is a modified version of the

Mathis Engelbart 2 Jun 8, 2022
Behaviour Driven Development tests generator for Golang

gherkingen It's a Behaviour Driven Development (BDD) tests generator for Golang. It accept a *.feature Cucumber/Gherkin file and generates a test boil

Maxim Krivchun 46 Jun 25, 2022
HTTP load generator, ApacheBench (ab) replacement, formerly known as rakyll/boom

hey is a tiny program that sends some load to a web application. hey was originally called boom and was influenced from Tarek Ziade's tool at tarekzia

Jaana Dogan 13.8k Jun 24, 2022
A presentable test report generator for go packages

go-tprof Overview Prerequisites 1. Go version >= 1.12 2. Node.js version >= 8.0.0 (for building the UI) 3. Yarn 4. GOPATH and local bin setup (`expor

Gokul T P 34 Feb 7, 2022
A workload generator for MySQL compatible databases

Diligent is a tool we created at Flipkart for generating workloads for our SQL databases that enables us to answer specific questions about the performance of a database.

Flipkart Incubator 14 May 18, 2022
Completely type-safe compile-time mock generator for Go

Mockc Mockc is a completely type-safe compile-time mock generator for Go. You can use it just by writing the mock generators with mockc.Implement() or

Geon Kim 29 May 23, 2021
Load generator for measuring overhead generated by EDRs and other logging tools on Linux

Simple load generator for stress-testing EDR software The purpose of this tool is to measure CPU overhead incurred by having active or passive securit

Hilko Bengen 6 Jun 14, 2022
Cloud Spanner load generator to load test your application and pre-warm the database before launch

GCSB GCSB Quickstart Create a test table Load data into table Run a load test Operations Load Single table load Multiple table load Loading into inter

Cloud Spanner Ecosystem 20 May 2, 2022
bencode is a golang package for bencoding and bdecoding data from and from to equivalents.

Bencode bencode is a golang package for bencoding and bdecoding data from and from to equivalents. Bencode (pronounced like Ben-code) is the encoding

Arun Murugan 2 Jan 8, 2022
A yaml data-driven testing format together with golang testing library

Specimen Yaml-based data-driven testing Specimen is a yaml data format for data-driven testing. This enforces separation between feature being tested

Design it, Run it 0 Jan 31, 2022
A simple tool to fill random data into a file to overwrite the free space on a disk

random-fill random-fill is a simple tool to fill random data into a file to over

null 1 Dec 30, 2021
A go server which will respond with data to mock a server!

Mocker A go program which will respond with data to mock a server; mainly useful while developing a frontend application, whose backend is not running

BE 0 Jan 29, 2022
Fortio load testing library, command line tool, advanced echo server and web UI in go (golang). Allows to specify a set query-per-second load and record latency histograms and other useful stats.

Fortio Fortio (Φορτίο) started as, and is, Istio's load testing tool and now graduated to be its own project. Fortio is also used by, among others, Me

Fortio (Φορτίο) 2.6k Jun 24, 2022
Golang HTTP client testing framework

flute Golang HTTP client testing framework Presentation https://speakerdeck.com/szksh/flute-golang-http-client-testing-framework Overview flute is the

Shunsuke Suzuki 17 Apr 19, 2022
Extremely flexible golang deep comparison, extends the go testing package and tests HTTP APIs

go-testdeep Extremely flexible golang deep comparison, extends the go testing package. Latest news Synopsis Description Installation Functions Availab

Maxime Soulé 303 Jun 19, 2022
Cucumber for golang

Godog The API is likely to change a few times before we reach 1.0.0 Please read the full README, you may find it very useful. And do not forget to pee

Cucumber 1.7k Jun 28, 2022
Testing API Handler written in Golang.

Gofight API Handler Testing for Golang Web framework. Support Framework Http Handler Golang package http provides HTTP client and server implementatio

Bo-Yi Wu 402 Jun 19, 2022
Sql mock driver for golang to test database interactions

Sql driver mock for Golang sqlmock is a mock library implementing sql/driver. Which has one and only purpose - to simulate any sql driver behavior in

DATA-DOG 4.5k Jun 25, 2022