I created UserFactory
class in factories.py
as shown below. I use pytest-django and pytest-factoryboy in Django:
# "factories.py"
import factory
from django.contrib.auth.models import User
class UserFactory(factory.django.DjangoModelFactory):
class Meta:
model = User
username = "John"
Then, I registered UserFactory
class in conftest.py
as shown below:
# "conftest.py"
import pytest
from pytest_factoryboy import register
from tests.factories import UserFactory
register(UserFactory)
Then, I created test_user()
which prints username
with user_factory
and user_factory.build() and user_factory.create() in test_ex1.py
as shown below:
# "test_ex1.py"
import pytest
from django.contrib.auth.models import User
def test_user(db, user_factory):
print(user_factory.username) # Here
print(user_factory.build().username) # Here
print(user_factory.create().username) # Here
assert True
Then, I got 3 John
's as shown below:
$ pytest -q -rP
. [100%]
=============== PASSES ================
____________ test_new_user ____________
-------- Captured stdout call ---------
John
John
John
1 passed in 0.55s
My questions:
- What is the difference between
user_factory
,user_factory.build()
anduser_factory.create()
in Factory Boy? - When should I use
user_factory
,user_factory.build()
anduser_factory.create()
in Factory Boy?