# pytest django
###### tags: `python` `django` `backend` `learn` `project`
docs:https://pytest-django.readthedocs.io/en/latest/
```
pip install pytest-django
```
pytest -rP
### fixture 固定裝置
usage:
fixtures are used to feed data to the tests such as database connection, urls to test and input data
fixture run before/after each test function to which the fixture is applied
### pattern for writing test
- arrange 準備
- act 行動
- asset 結果(true/false)
conftest.py
->test file that runs at first
->fixture function
```
import pytest
from django.contrib.auth.models import User
@pytest.fixture()
def user_1(db):
return User.objects.create_user('test_user')
@pytest.fixture()
def new_user_factory(db):
def create_user_factory(
username: str,
password: str=None,
first_name: str = "first_name",
last_name: str = "last_name",
email: str = "test@test.com",
is_staff: str = False,
is_superuser: str = False,
is_active: str = True,
):
user = User.objects.create_user(
username = username,
password = password,
first_name = first_name,
last_name = last_name,
email = email,
is_staff = is_staff,
is_superuser = is_superuser,
is_active = is_active,
)
return user
return create_user_factory
@pytest.fixture
def new_user(db, new_user_factory):
return new_user_factory("test_user", "password", "firstname")
```
### Factory Boy
https://pytest-factoryboy.readthedocs.io/en/latest/
q faced:
when application growth the fixtures become to much to manage
usage:
* Fixture replacement tool
* Factories are define in a nice, clean and readable manner
* Easy-to-use factories for complex objects
* Class base approach
* subfactory
* ForeignKey, reverse ForeignKey, Many to Many
install:
```
pip install pytest-factoryboy
pip install Faker
```