17.[DRF] Pytest: How to test your django project

로직

  • managers.py 에서 일반/ 슈퍼 유저들을 분리해서 생성하는 로직을 넣음
  • factories.py 에서 유저 안에 들어갈 변수들을 지정
  • conftest.py 에서 테스트에 들어갈 유저를 fixture로 생성
  • test_models.py 에서 assert로 테스트가 넘어가는지 확인

pip install pytest-factoryboy

파일 구조

users/tests/
     __init__.py
     factories.py
     test_models.py
     conftest.py
pytest.ini
setup.cfg

factories.py

import factory
from factory.django import DjangoModelFactory
from django.contrib.auth import get_user_model
from faker import Faker
fake = Faker('ko_KR')



class UserFactory(factory.django.DjangoModelFactory):
    class Meta:
        model = get_user_model()

    username = factory.Sequence(lambda n:f'lennon{n}')
    is_staff = 'True'
    email = factory.Sequence(lambda n:f'lennon{n}@thebeatles.com')

conftest.py

import pytest
from pytest_factoryboy import register
from .factories import BoardFactory, UserFactory

register(UserFactory) #user_factory
register(BoardFactory)

@pytest.fixture
def new_user1(user_factory):
    user = user_factory.create()
    return user

test_models.py

import pytest


@pytest.mark.django_db
def test_new_user(new_user1):
    print(new_user1.username)
    assert True

pytest.ini

[pytest]
DJANGO_SETTINGS_MODULE = 프로젝트명.settings.local
python_files = tests.py test_*.py *_tests.py
addopts = -p no:warnings --strict-markers --no-migrations --reuse-db

requirements/local.txt

pytest-django=4.5.2
pytest-factoryboy=2.1.0
Faker=11.3.0
pytest-cov==3.0.0

파이테스트 커버리지:

  • python unit test 를 pytest 로 이용할 때 내가 만든 스크립트에 대해서 test code 들이 모두 다 커버하고 있는지 확인할 필요가 있다.

setup.cfg

  • 테스트 커버리지 설정
  • 소스는 manage.py 가 위치한 current directory
[coverage:run]
source = .
omit =
    *apps.py
    *settings.py
    *urls.py,
    *wsgi.py,
    *asgi.py,
    manage.py,
    conftest.py,
    *base.py,
    *local.py,
    *production.py,
    *__init__.py,
    */migrations/*,
    *tests/*,
    */env/*,
    */venv/*,
[coverage:report]
show_missing = True

테스트 실행 (HTML 버전이 나음)

pytest -p no:warnings --cov=. -v
pytest -p no:warnings --cov=. --cov-report html
  • htmlcov 폴더가 자동생성됨
  • index.html 파일
  • Live Server 익스텐션을 사용하고 있어야함
  • 마우스 우클릭 후 Open with Live Server 클릭
  • 127.0.0.1:5500/htmlcov/index.html 에서 자동으로 열림

이렇게 하면 기본 설정이 끝남

git

chore: configure pytest and coverage

Did you find this article valuable?

Support Christy Choi by becoming a sponsor. Any amount is appreciated!