jaswdr / faker

:rocket: Ultimate fake data generator for Go with zero dependencies
https://pkg.go.dev/github.com/jaswdr/faker
MIT License
570 stars 59 forks source link

Running two tests one after another gives the same data seed #183

Open lehadnk opened 2 weeks ago

lehadnk commented 2 weeks ago

Hello! I'm using faker to generate some random data for my unit tests, and it appears that when tests are run too fast on my CPU I'm getting the same data seed in two different tests, resulting in faker generating the same emails for two different users in two different tests:

func TestCreateUserInDb(t *testing.T) {
    userDao := persistence.NewUserDao()
    fake := faker.New()

    user := dto.NewUser(fake.Person().Name(), fake.Internet().Email(), fake.Internet().Password(), "Pony")
    userDao.CreateUser(user)
}

func TestSelectUserById(t *testing.T) {
    userDao := persistence.NewUserDao()
    fake := faker.New()
    // The test above runs at the same exact epoch, causing faker to initialize with the same seed, therefore the first email given is the same
    fake.Internet().Email()

    user := dto.NewUser(fake.Person().Name(), fake.Internet().Email(), fake.Internet().Password(), "Pony")
    userDao.CreateUser(user)
    readUser := userDao.GetUserById(user.Id)
    if !reflect.DeepEqual(user, readUser) {
        t.Errorf("User and readUser are not equal")
    }
}
2024/11/09 04:33:07 Creating user: berge.loyal@hotmail.com
2024/11/09 04:33:07 Creating user: berge.loyal@hotmail.com
2024/11/09 04:33:07 Could not create user: pq: duplicate key value violates unique constraint "users_email_key"

I guess what we need is some feature to control the data seed identifier or at least some random identifier in it.

mathieu-lemay commented 1 week ago

The default seed is the current timestamp, precise to the current second, so that's why you are getting the same results there.

An easy workaround is to have a global faker instance that you re-use for all tests.

I guess what we need is some feature to control the data seed identifier or at least some random identifier in it.

It is already possible with faker.NewWithSeed()