Giter Club home page Giter Club logo

faker's Introduction

Important Notes

This repository has been archived, and moved to the new repository here https://github.com/go-faker/faker Further development and fixing will be happening in the new repository.


Docs

Struct Data Fake Generator

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

Build Status codecov Go Report Card License Go.Dev

Index

Support

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

Getting Started

Download

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

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.

faker's People

Contributors

agoalofalife avatar andrew-werdna avatar bxcodec avatar cconcannon avatar daniel134256 avatar davidlarsketch avatar eval-exec avatar geshtng avatar icety avatar ilackarms avatar jostillmanns avatar maco avatar martinbergpetersen avatar mgrachev avatar momotaro98 avatar mrvanboy avatar nashikb avatar olimpias avatar perryao avatar pioz avatar qjcg avatar rdelval avatar rgaskill avatar rodnover55 avatar shivam010 avatar soranoba avatar steveoc64 avatar system-glitch avatar wolf-joe avatar xaionaro 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

faker's Issues

Is localization supported?

I don't understand if languages (localization, l18n) is supported.

E.g.: can I generate fake french first names?

Faking a struct with unexported fields panics

reflect: reflect.Value.Set using value obtained using unexported field
    /home/hein/go/src/runtime/panic.go:502

    Full Stack Trace
        /home/hein/go/src/runtime/panic.go:502 +0x229
    reflect.flag.mustBeAssignable(0x1b9)
        /home/hein/go/src/reflect/value.go:231 +0x1f3
    reflect.Value.Set(0xc6da40, 0xc420db6370, 0x1b9, 0xc6da40, 0x13167d8, 0x99)
        /home/hein/go/src/reflect/value.go:1367 +0x2f
    github.com/bxcodec/faker.getValue(0xe42f40, 0xd3e080, 0xd3e080, 0xc420db62c0, 0x16, 0xa0, 0xa8)
        /home/hein/gocode/src/github.com/bxcodec/faker/faker.go:172 +0x127d
    github.com/bxcodec/faker.FakeData(0xc8b760, 0xc420db62c0, 0x0, 0xc4201e5500)
        /home/hein/gocode/src/github.com/bxcodec/faker/faker.go:134 +0x1bc

Changing getValue by checking CanSet() should fix the problem.

                                if v.Field(i).CanSet() {
					if tag == "" {
						val, err := getValue(v.Field(i).Type())
						if err != nil {
							return reflect.Value{}, err
						}
						val = val.Convert(v.Field(i).Type())
						v.Field(i).Set(val)
					} else {
						err := setDataWithTag(v.Field(i).Addr(), tag)
						if err != nil {
							return reflect.Value{}, err
						}
					}
				}

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.

fatal error: concurrent map writes

I have a goroutine in a for loop that runs faker.FakeData, here a sample code:

package main

import (
	"reflect"
	"github.com/bxcodec/faker"
)

type User struct {
	Username string `faker:"first_name"`
	Email    string `faker:"email,unique"`
}

func main() {
	user := User{}
	modelType := reflect.TypeOf(user)
	for i := 0; i < 1000; i++ {
		go func() {
			for j := 0; j < 1000; j++ {
				modelCopy := reflect.New(modelType).Interface() // copy model
				faker.FakeData(modelCopy)
			}
		}()
	}
}

I get the follow error:

$ go run bin/faker.go 
fatal error: concurrent map read and map write

goroutine 19 [running]:
runtime.throw(0x1122ca3, 0x21)
	/usr/local/Cellar/go/1.14.1/libexec/src/runtime/panic.go:1114 +0x72 fp=0xc000221760 sp=0xc000221730 pc=0x1030a22
runtime.mapaccess1_faststr(0x10f41a0, 0xc00009a600, 0x10e3609, 0x5, 0x10eb480)
	/usr/local/Cellar/go/1.14.1/libexec/src/runtime/map_faststr.go:21 +0x43c fp=0xc0002217d0 sp=0xc000221760 pc=0x10120fc
github.com/bxcodec/faker.getValue(0x10fb380, 0xc00020e580, 0x199, 0x10fb301, 0x10fb380, 0xc00020e580, 0xc00020e500)
	/Users/pioz/Code/go/src/github.com/bxcodec/faker/faker.go:422 +0x1e2e fp=0xc000221b30 sp=0xc0002217d0 pc=0x10cbade
github.com/bxcodec/faker.getValue(0x10e58e0, 0xc00020e540, 0xc000221f48, 0x107ab78, 0x10fb380, 0xb7a0, 0x10e58e0)
	/Users/pioz/Code/go/src/github.com/bxcodec/faker/faker.go:356 +0x174a fp=0xc000221e90 sp=0xc000221b30 pc=0x10cb3fa
github.com/bxcodec/faker.FakeData(0x10e58e0, 0xc00020e540, 0x16, 0xc00020e501)
	/Users/pioz/Code/go/src/github.com/bxcodec/faker/faker.go:281 +0x1c6 fp=0xc000221f88 sp=0xc000221e90 pc=0x10c9896
main.main.func1(0x1145580, 0x10fb380)
	/Users/pioz/Code/go/src/github.com/pioz/ct/bin/faker.go:23 +0x81 fp=0xc000221fd0 sp=0xc000221f88 pc=0x10da051
runtime.goexit()
	/usr/local/Cellar/go/1.14.1/libexec/src/runtime/asm_amd64.s:1373 +0x1 fp=0xc000221fd8 sp=0xc000221fd0 pc=0x105d6a1
created by main.main
	/Users/pioz/Code/go/src/github.com/pioz/ct/bin/faker.go:20 +0xaf

goroutine 1 [runnable]:
runtime.gopark(0x0, 0x0, 0xc000001008, 0x1)
	/usr/local/Cellar/go/1.14.1/libexec/src/runtime/proc.go:287 +0x130
runtime.main()
	/usr/local/Cellar/go/1.14.1/libexec/src/runtime/proc.go:222 +0x28c
runtime.goexit()
	/usr/local/Cellar/go/1.14.1/libexec/src/runtime/asm_amd64.s:1373 +0x1

goroutine 20 [runnable]:
github.com/bxcodec/faker/support/slice.ContainsValue(0xc000226000, 0xaf, 0x100, 0x10eb480, 0xc00010d5b0, 0xc00010d5b0)
	/Users/pioz/Code/go/src/github.com/bxcodec/faker/support/slice/helpers.go:21 +0x82
github.com/bxcodec/faker.getValue(0x10fb380, 0xc000115240, 0x199, 0x10fb301, 0x10fb380, 0xc000115240, 0xc0001151c0)
	/Users/pioz/Code/go/src/github.com/bxcodec/faker/faker.go:422 +0x1e6b
github.com/bxcodec/faker.getValue(0x10e58e0, 0xc000115200, 0xc000195f48, 0x107ab78, 0x10fb380, 0xb7a0, 0x10e58e0)
	/Users/pioz/Code/go/src/github.com/bxcodec/faker/faker.go:356 +0x174a
github.com/bxcodec/faker.FakeData(0x10e58e0, 0xc000115200, 0x16, 0xc000115201)
	/Users/pioz/Code/go/src/github.com/bxcodec/faker/faker.go:281 +0x1c6
main.main.func1(0x1145580, 0x10fb380)
	/Users/pioz/Code/go/src/github.com/pioz/ct/bin/faker.go:23 +0x81
created by main.main
	/Users/pioz/Code/go/src/github.com/pioz/ct/bin/faker.go:20 +0xaf
...

If I remove the go keyword all works fine.
If I remove the unique option in the Email field tag all works fine.

Cannot select the fake type when using pointers

Hey there, I am having trouble applying the faker:"Something" tag to struct fields that are pointers.

Here is the struct:

type UserInput struct {
	FirstName         *string                 `json:"first_name,omitempty" faker:"first_name_male"`
	LastName          *string                 `json:"last_name,omitempty" faker:"first_name_male"`
	FullName          *string                 `json:"full_name,omitempty" faker:"first_name_male"`
	Email             *string                 `json:"email,omitempty" faker:"email"`
}

Stack:

panic: reflect.Set: value of type string is not assignable to type *string

goroutine 1 [running]:
reflect.Value.assignTo(0x15f1b80, 0xc0001f6a60, 0x98, 0x16e569f, 0xb, 0x15e0520, 0x0, 0xc0001f6a60, 0x0, 0x0)
        /usr/local/Cellar/go/1.11.1/libexec/src/reflect/value.go:2269 +0x44c
reflect.Value.Set(0x15e0520, 0xc000210640, 0x196, 0x15f1b80, 0xc0001f6a60, 0x98)
        /usr/local/Cellar/go/1.11.1/libexec/src/reflect/value.go:1403 +0xa7
bitbucket.org/teammemento/demo-api/vendor/github.com/bxcodec/faker.setDataWithTag(0xc0000b6640, 0xc000210640, 0x16, 0x15f253e, 0xf, 0x16, 0x196)
        /Users/zkynet/go/src/bitbucket.org/teammemento/demo-api/vendor/github.com/bxcodec/faker/faker.go:311 +0x282
bitbucket.org/teammemento/demo-api/vendor/github.com/bxcodec/faker.getValue(0x17a2c20, 0x16ba440, 0x16ba440, 0x5, 0xc0002184f0, 0xc0000f7d18, 0x100dc0f)
        /Users/zkynet/go/src/bitbucket.org/teammemento/demo-api/vendor/github.com/bxcodec/faker/faker.go:209 +0x168b
bitbucket.org/teammemento/demo-api/vendor/github.com/bxcodec/faker.FakeData(0x161af20, 0xc0002105a0, 0x1d02880, 0x15d3c60)
        /Users/zkynet/go/src/bitbucket.org/teammemento/demo-api/vendor/github.com/bxcodec/faker/faker.go:152 +0x1f5

Now, if I remove the faker:"first_name_male" .. everything works fine.

It probably has something to do with this change:
d5d9f35

Peace and love <3

[TODO] Move to Go Module

Todo

Roadmap for go module faker/v3:

Chore

  • Introduce new go module as new version: v/3. (#56)
  • Apply linter for better quality. PR: (#55)

Breaking changes

  • Fix typos that caused a breaking change. (#52 )

Features

  • Optionally insert nils instead of empty slices and maps (#58, #59)
  • Export a generator functions so that can accessed publicly (#45 #63)
  • Support length (#49, #60)

Really appreciate if anyone can help to submit any PR regarding to these issues.

Tag unsupported error on oneof usage

Issue:
Unable to use the oneof tag

Steps to reproduce.

  1. Create a struct that looks like this.

import(
  "fmt"
)
type Engagement struct {
	IsEntity   bool   `default:"True"`
	EventType  string `faker:"oneof: a, b"`
}

Try printing it


func GenerateEngmt() {
	data := Engagement{}
	err := faker.FakeData(&data)
	if err != nil {
		fmt.Printf("ERR %v\n", err)
	}
	fmt.Printf("%v", data)
}

Output

ERR Tag unsupported: oneof: a, b

Go env

GO111MODULE=""
GOARCH="amd64"
GOBIN=""
GOCACHE="/Users/wolf/Library/Caches/go-build"
GOENV="/Users/wolf/Library/Application Support/go/env"
GOEXE=""
GOFLAGS=""
GOHOSTARCH="amd64"
GOHOSTOS="darwin"
GOINSECURE=""
GONOPROXY=""
GONOSUMDB=""
GOOS="darwin"
GOPATH="/Users/wolf/go"
GOPRIVATE=""
GOPROXY="https://proxy.golang.org,direct"
GOROOT="/Users/wolf/Tools/go"
GOSUMDB="sum.golang.org"
GOTMPDIR=""
GOTOOLDIR="/Users/wolf/Tools/go/pkg/tool/darwin_amd64"
GCCGO="gccgo"
AR="ar"
CC="clang"
CXX="clang++"
CGO_ENABLED="1"
GOMOD="/Users/wolf/Work/utils/load-ebus-go/ebuspub/go.mod"
CGO_CFLAGS="-g -O2"
CGO_CPPFLAGS=""
CGO_CXXFLAGS="-g -O2"
CGO_FFLAGS="-g -O2"
CGO_LDFLAGS="-g -O2"
PKG_CONFIG="pkg-config"
GOGCCFLAGS="-fPIC -m64 -pthread -fno-caret-diagnostics -Qunused-arguments -fmessage-length=0 -fdebug-prefix-map=/var/folders/cq/35z51m017zs1zv8n_jcnc5x9kwcqwm/T/go-build970742704=/tmp/go-build -gno-record-gcc-switches -fno-common"

Allow ability to use `json` tag to get lower case names

Structs in Go have to have upper case names in order to be public but in json you can get around this by passing the tag: `json: name_lower`

Is there a way to do something similar with faker so that field names don't have to always be upper case?

dep ensure error

Trying to add your lib to project using dep, but can't:
`
dep ensure -v --update github.com/bxcodec/faker

(4) try github.com/bxcodec/[email protected]
(4) ✗ "github.com/bxcodec/faker" imports "github.com/bxcodec/faker/v3/support/slice", which contains malformed code: no package exists at "github.com/bxcodec/faker/v3/support/slice"
`

Support for less than tags with numbers and length of strings

For context, I'm storing non standard uint and int lengths (for example uint2 and int12 as uint8 and int16). This data is being Deserialized from and Serialized to binary. if I use faker to make the struct, it may make a much larger value than will actually be Serialized to binary. So when I Deserialize that binary it does not equal the object that faker generated. Same issue with the length of strings.

My suggestion would be to implement a tag which lets you specify bounds for numbers, and lengths for strings.

using in loop results in duplicate values

I'm generating data in a loop, but since randomElementFromSliceString seeds on every invocation, the generated values aren't random. I'd think seeding in init would be good enough, and removing the seed from randomElementFromSliceString would allow random data to be generated in a loop.

Panic if struct field is a named type

the following code will panic:

type Foo string

type MyStruct struct {
	Foo Foo
}

func test() {
	s := MyStruct{}
	faker.FakeData(s)
}

with the error reflect.Set: value of type int32 is not assignable to type <pkgname>.Foo

My suggestion is to add a type conversion in faker.go. I've tested it manually and (at least for my use case) this fixes the issue.

Not working with interface type?

I am using faker/v3 module. I understand that faker doesn't work with interface{}, however in the following code

package main

import (
	"fmt"
	"github.com/bxcodec/faker/v3"
)

type Request struct {
	Headers    map[string][]string
	Body       []byte
	StatusCode int
	Status     string
	Err        error
}

func main() {
	r := &Request{}
	err := faker.FakeData(r)
	fmt.Println(err)
}

I am getting interface{} not allowed error. I don't have any interface{} type element in the struct. The only interface is error, all others are collection type.

nested pointer support

It'd be really useful to have support for nested pointer structs and a probability for each pointer field whether or not it gets filled.

This would make it really easy to fuzz GRPC endpoints since you would be able to generate random messages.

Bool values or OneOf

Like so many other faker libraries, is it possible to generate fake bool values and OneOf.

I think that bool is easy to understand, but with OneOf, I was searching for something like this

faker:"oneof="foo","bar","x","y"

thanks

FakeData on interface that is a slice

Is possible with faker do something like this:

func BulkCreate(db *gorm.DB, records interface{}) {
	switch reflect.TypeOf(records).Kind() {
	case reflect.Slice:
		slice := reflect.ValueOf(records)
		for i := 0; i < slice.Len(); i++ {
			faker.FakeData(slice.Index(i).Interface())
			fmt.Println(slice.Index(i).Interface())
		}
		db.Create(slice.Interface())
	}
}

I've tried, but this function does not modify the slice.Index(i).Interface() with fake data.

Here a playground.

Any idea to achieve this behavior?

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

How to ignore field?

How I can ignore to generate fake data for any field?
Here is my code

package main

import (
	"fmt"

	"github.com/bxcodec/faker"
)

type User struct {
	ID    uint64
	Name  string `faker:"name"`
	Email string `faker:"email"`
}

func main() {
	user := User{}
	err := faker.FakeData(&user)
	if err != nil {
		fmt.Println(err)
	}

	fmt.Println(user)
}

The result is

{29 Prof. Telly Howe [email protected]}

The faker generate random ID. Can I Ignore so the id not generated?

Optionally insert nils instead of empty slices and maps

When populating slice fields, faker may decide to use an empty slice as a slice value ([]sometype {}). Some other libraries, however, feature an optimization, whereupon empty slices are always replaced with nils to keep the amount of memory garbage down.

When unit testing various serialization scenarios we often have a situation whereupon an object has to be compared to an equivalent object:

  1. Populate a reference struct with fake data
  2. Serialize it to a byte array
  3. Deserialize it to another struct
  4. Compare the newly obtained struct to a reference one

However, if serialization library treats empty slices as nils the comparison would not succeed, because empty slice object and nil do not compare as equal using reflect.DeepEqual.

Given the above, I believe that an easy to implement option to emit nils instead of zero length slices will be quite handy, because serialization testing is actually quite common in network oriented programs.

The above equally applies to maps.

Generate only for non-default fields

I like this for populating test data - but often I want to be in control of a couple of the structs property values, and then fake whatever's left (and not skipped). Is this possible? I guess what I'm asking for is a 'ifDefaultValueForTypeThenGenerate' kind of functionality

Also, it would be cool if there was a way for us to feed you a func name that you invoke to populate the field. Product-specific fake data that you cannot provide could be added thus.

Compatible with interface{}

If meet some fields which not supported such as interface{}, Can we just ignore the err.
For example

struct Test{
A  int
B string
C interface{}
}

I only want A, B filed, just give me C with a nil value

Custom tag: Tag Unsupported

Example struct field:

Status   string `faker:"Status"`

From the example code provided on the repo:

_ = faker.AddProvider("Status", func(v reflect.Value) (interface{}, error) {
	rand.Seed(time.Now().Unix())
	statuses := []string{
		"APPROVAL",
		"DENIAL",
	}
	n := rand.Int() % len(statuses)

	return statuses[n], nil
})

Result:

    go_test.go:45: Tag unsupported

Faker generating empty slices

With enough tries Faker generates at least a couple of empty sizes. I believe using the default settings this is unintentional, right?

Repro:

	for i := 0; i < 1000; i++ {
		var randomSlice []string
		faker.FakeData(&randomSlice)
		if len(randomSlice) == 0 {
			fmt.Println("OH NO!")
		}
	}

Or: https://play.golang.org/p/IHpHR6x8IAM

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".

Skip does not really skip a struct

I have the following use case:

type MyStruct struct {
	Title          string          `faker:"word,keep"`
	MyOtherStruct []MyOtherStruct `faker:"-"`
}

When I fake the data, I would expect that the initial data of MyOtherStruct would be persistent. But in fact, it is being reset by faker.

Faking a UUID panics

I had a complex struct generating a panic from faker and I isolated it to the uuid field causing the issue.
Here's the minimal code to show the error:

package main

import (
	"github.com/bxcodec/faker"
	"github.com/gofrs/uuid"
	"fmt"
)

func main() {
	var u uuid.UUID
	faker.FakeData(&u)
	fmt.Println(u)
}

And the error trace is:

panic: reflect.MakeSlice of non-slice type

goroutine 1 [running]:
reflect.MakeSlice(0x11367c0, 0x1104fe0, 0x58, 0x58, 0xc420065cc8, 0xc420065cd8, 0x1010068)
	/usr/local/Cellar/go/1.10.3/libexec/src/reflect/value.go:2092 +0x1ce
github.com/bxcodec/faker.getValue(0x11367c0, 0x1104fe0, 0x1104fe0, 0xc4200aa250, 0x16, 0x0, 0x10)
	/Users/msorens/code/go/src/github.com/bxcodec/faker/faker.go:218 +0x7a9
github.com/bxcodec/faker.FakeData(0x110c840, 0xc4200aa250, 0xc42008a058, 0x0)
	/Users/msorens/code/go/src/github.com/bxcodec/faker/faker.go:145 +0x1bc
main.main()
	/Users/msorens/code/go/src/github.com/me/fake/tryfake.go:11 +0x4b
exit status 2

Define arguments for custom tags

Would it be possible to define arguments for custom tags?

For example:

type Employee struct {
  Name string `faker:"name"`
  TerminationDateSet *time.Time `faker:"termination_date, freq=10"`
}

That would avoid creating tags such as "10_percent_chance_termination_date", "20_percent_chance_termination_date", "30_percent_chance_termination_date" for different scenarios

support the array of custom type

I want to get this sample code supported.

func TestArrayOfCustomType(t *testing.T) {
        type MyInt int
        type Sample struct {
                Value  []MyInt
        }

        val := Sample{}

        err := FakeData(&val)
        if err != nil {
                t.Errorf("%v", err)
        }
}
 $ go test -v ./... -run TestArrayOfCustomType
=== RUN   TestArrayOfCustomType
--- FAIL: TestArrayOfCustomType (0.00s)
panic: reflect.Set: value of type int is not assignable to type faker.MyInt [recovered]
	panic: reflect.Set: value of type int is not assignable to type faker.MyInt

goroutine 34 [running]:
testing.tRunner.func1(0xc00011c100)
	/Users/user/.goenv/versions/1.12beta1/src/testing/testing.go:827 +0x387
panic(0x1151620, 0xc000090780)
	/Users/user/.goenv/versions/1.12beta1/src/runtime/panic.go:522 +0x1b7
reflect.Value.assignTo(0x1150be0, 0xc0000982a0, 0x82, 0x1193bf5, 0xb, 0x1150ba0, 0x0, 0x58, 0xc000124000, 0x17)
	/Users/user/.goenv/versions/1.12beta1/src/reflect/value.go:2338 +0x425
reflect.Value.Set(0x1150ba0, 0xc000124000, 0x182, 0x1150be0, 0xc0000982a0, 0x82)
	/Users/user/.goenv/versions/1.12beta1/src/reflect/value.go:1472 +0xa7
github.com/bxcodec/faker/v3.getValue(0x114e220, 0xc0000a6720, 0x197, 0x1, 0x114e220, 0xc0000a6720, 0x197)
	/Users/user/git/faker/faker.go:411 +0xd92
github.com/bxcodec/faker/v3.getValue(0x1163780, 0xc0000a66e0, 0x199, 0x1163701, 0x1163780, 0xc0000a66e0, 0x135b5f0)
	/Users/user/git/faker/faker.go:375 +0x1eef
github.com/bxcodec/faker/v3.getValue(0x1148840, 0xc0000a66a0, 0x0, 0xc000098288, 0x1, 0xc0000386f8, 0x100bdf4)
	/Users/user/git/faker/faker.go:335 +0x16a1
github.com/bxcodec/faker/v3.FakeData(0x1148840, 0xc0000a66a0, 0x1049128, 0x28dc6f6812e)
	/Users/user/git/faker/faker.go:260 +0x1c5
github.com/bxcodec/faker/v3.TestArrayOfCustomType(0xc00011c100)
	/Users/user/git/faker/faker_test.go:934 +0x4b
testing.tRunner(0xc00011c100, 0x119fb30)
	/Users/user/.goenv/versions/1.12beta1/src/testing/testing.go:862 +0xbf
created by testing.(*T).Run
	/Users/user/.goenv/versions/1.12beta1/src/testing/testing.go:913 +0x356
FAIL	github.com/bxcodec/faker/v3	0.013s
?   	github.com/bxcodec/faker/v3/support/slice	[no test files]

Support inter-field dependencies

Consider the following struct

type Entry struct {
    Bananas []int
    BananasCount int
}

The field BananasCount must be consistent with len(Entry.Bananas)

How can one create this kind of fake instance of Entry using faker?

Toll free number

Toll is spelled as tool in a few places,

faker/faker.go

Line 36 in c672223

TOLL_FREE_NUMBER = "tool_free_number"
and the examples.

Also I'm not sure that 777 is a toll free number. Not sure how it works globally.

Consideration about keep tag

I love faker and I use it a lot on my tests. Something like this:

type User struct {
	Id        uint64 `faker:"-"`
	Email     string 
	Username  string
	FirstName string 
	LastName  string
}

user := User{Username: "John"}
faker.FakeData(&user) // I want all fake data except for `Username` because it was set manually

In practice, I want the faker:"keep" tag always. I don't know if also other users have this need. But for me, the keep tag should be the default behavior. This is also the default behavior for gems like FactoryBot for Ruby. So what I propose is to remove the keep tag and add a new one with the opposite effect, something like replace. Or a global configuration (faker.EnableKeepDefaultBehaviour())

What do you think guys?

package v3 not found

package dependency not found in phone.go.
"github.com/bxcodec/faker/v3/support/slice" => "github.com/bxcodec/faker/support/slice"

Cannotn find package

package github.com/bxcodec/faker/v3/support/slice: cannot find package "github.com/bxcodec/faker/v3/support/slice" in any of:
/usr/local/go/src/github.com/bxcodec/faker/v3/support/slice (from $GOROOT)
/home/andres/go/src/github.com/bxcodec/faker/v3/support/slice (from $GOPATH)

AddProvider for custom tag doesn't work with some custom types

Example struct field and type:

import "github.com/google/uuid"
...
type Product struct {
  ProductID uuid.UUID `faker:"google_uuid"`
}
...
_ = faker.AddProvider("google_uuid", func(v reflect.Value) (interface{}, error) {
  return uuid.New(), nil // to instantiate a new, random instance
})

Result:

panic: reflect.MakeSlice of non-slice type [recovered]
    panic: reflect.MakeSlice of non-slice type

What appears to be the problem:

If you look, google's UUID is defined as type UUID [16]byte.
It would appear that in setDataWithTag() the reflect.Indirect(v) is returning array, but if you were to do v.Kind() you would get uuid.UUID. In the switch statement you would arrive at the reflect.Slice, reflect.Array, call userDefinedArray(), and then arrive at the following line, where the panic occurs

array := reflect.MakeSlice(v.Type(), len, len)

So even despite adding the custom tag with AddProvider() and including the ability to create a new, random UUID, it never checks if there is a custom tag before going into userDefinedArray()

Proposal

Allow a user-defined tag (added with AddProvider()), to take precedence, and if the user provides that ability, check it first before defaulting to userDefinedArray().

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.

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.