如何在独立Django包中用pytest和GitHub Actions测试模型(无manage.py)
独立Django包的pytest测试实现方案
核心思路
由于是独立包没有manage.py,直接通过Django核心API初始化数据库,结合pytest-django配置与自定义夹具完成测试环境搭建,完全脱离对管理命令的依赖。
步骤1:配置pytest与Django测试环境
- 在项目根目录创建
pytest.ini,指定测试配置:
[pytest] DJANGO_SETTINGS_MODULE = tests.settings python_files = tests/**/*.py
- 创建
tests/settings.py,配置内存SQLite与必要的Django环境:
import sys import os # 将包目录加入Python路径,确保能导入你的模型 sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), '..'))) DEBUG = True SECRET_KEY = 'test-only-secret-key' INSTALLED_APPS = [ 'django.contrib.contenttypes', 'django.contrib.auth', # 替换成你的独立包APP名称 'your_package', ] DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': ':memory:', } }
步骤2:用夹具自动创建表与维护隔离
创建tests/conftest.py,定义全局夹具处理数据库初始化与清理:
import pytest from django.db import connection from django.apps import apps @pytest.fixture(scope='session') def django_db_setup(): # 直接通过schema编辑器创建模型对应的表,替代migrate命令 with connection.schema_editor() as editor: for model in apps.get_app_config('your_package').get_models(): editor.create_model(model) # 如需初始化基础数据,可在这里调用loaddata或手动创建 # from django.core.management import call_command # call_command('loaddata', 'tests/fixtures/test_data.json') @pytest.fixture(autouse=True) def clean_test_data(django_db_setup): # 每个测试完成后清空表数据,保证测试隔离 yield with connection.cursor() as cursor: for model in apps.get_app_config('your_package').get_models(): cursor.execute(f"DELETE FROM {model._meta.db_table};")
步骤3:编写测试用例示例
创建tests/test_models.py,编写模型测试:
from your_package.models import YourModel from mixer.backend.django import mixer def test_model_basic_creation(): obj = mixer.blend(YourModel, name="测试项") assert obj.pk is not None assert obj.name == "测试项" def test_custom_model_method(): obj = YourModel.objects.create(name="测试数据") result = obj.your_custom_method() assert result == 预期结果
步骤4:GitHub Actions CI配置
创建.github/workflows/test.yml,配置自动化测试流水线:
name: 运行测试 on: [push, pull_request] jobs: test: runs-on: ubuntu-latest steps: - uses: actions/checkout@v4 - name: 设置Python环境 uses: actions/setup-python@v5 with: python-version: '3.11' - name: 安装依赖 run: | python -m pip install --upgrade pip pip install pytest pytest-django django mixer pip install -e . - name: 执行测试 run: pytest
关键注意事项
- 避免依赖迁移文件:独立包的迁移文件可能未被测试环境加载,直接用
schema_editor创建表更可靠 - 强制测试隔离:通过
autouse夹具自动清空数据,避免测试间互相干扰 - 内存SQLite优势:每次会话都是全新数据库,测试速度快且无需额外数据库服务
内容的提问来源于stack exchange,提问作者Alex
相关产品推荐
相关产品推荐

