Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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

Open
lehadnk opened this issue Nov 9, 2024 · 1 comment
Open

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

lehadnk opened this issue Nov 9, 2024 · 1 comment
Labels
bug Something isn't working

Comments

@lehadnk
Copy link

lehadnk commented Nov 9, 2024

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: [email protected]
2024/11/09 04:33:07 Creating user: [email protected]
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.

@lehadnk lehadnk added the bug Something isn't working label Nov 9, 2024
@mathieu-lemay
Copy link
Contributor

mathieu-lemay commented Nov 13, 2024

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()

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
bug Something isn't working
Projects
None yet
Development

No branches or pull requests

2 participants