新闻中心
新闻中心与新手教程
新闻中心与新手教程
发布时间:2024-10-11 12:51:05
首先,我们需要安装 pytest 和 pytest-django:
pip install pytest pytest-django
在项目根目录创建 pytest.ini
文件:
[pytest]
django_settings_module = your_project.settings
python_files = tests.py test_*.py *_tests.py
确保将 your_project
替换为您的实际 django 项目名称。
在每个 django 应用中创建一个 tests
目录,并在其中创建 __init__.py
文件:
your_app/
tests/
__init__.py
test_models.py
test_views.py
在 test_models.py
中编写模型测试:
import pytest
from your_app.models import yourmodel
@pytest.mark.django_db
def test_your_model():
model = yourmodel.objects.create(name="test")
assert model.name == "test"
在 test_views.py
中编写视图测试:
import pytest
from django.urls import reverse
@pytest.mark.django_db
def test_your_view(client):
url = reverse('your-view-name')
response = client.get(url)
assert response.status_code == 200
创建 conftest.py
文件来定义 fixtures:
import pytest
from your_app.models import yourmodel
@pytest.fixture
def sample_model(db):
return yourmodel.objects.create(name="sample")
在测试中使用 fixture:
def test_your_model_with_fixture(sample_model):
assert sample_model.name == "sample"
在命令行中运行:
pytest
安装 pytest-cov:
pip install pytest-cov
运行带覆盖率报告的测试:
pytest --cov=your_app
在 .gitlab-ci.yml
或 .github/workflows/main.yml
中添加测试步骤:
test:
script:
- pip install -r requirements.txt
- pytest --cov=your_app
@pytest.mark.django_db
装饰器pytest.ini
中的 django_settings_module
conftest.py
文件位于正确的目录conftest.py
中添加 pytest.mark.django_db(transaction=true)
django.test.override_settings
来修改测试时的设置--reuse-db
选项重用数据库pytest-xdist
进行并行测试-s
选项运行 pytest记住,可以使用 pytest -v
来获取更详细的测试输出,这对调试非常有帮助。此外,pytest --pdb
可以在测试失败时进入 python 调试器。
这个指南涵盖了在 django 项目中集成和使用 pytest 的主要步骤,包括安装、配置、编写测试用例、使用 fixtures、运行测试、配置测试覆盖率,以及集成到 ci/cd 流程中。我还添加了一些常见问题的故障排查方法。
感谢提供:05互联