gpt4 book ai didi

python - 将自定义测试套件运行器与 pytest-django 一起使用

转载 作者:太空狗 更新时间:2023-10-29 21:57:01 26 4
gpt4 key购买 nike

我想将我的 Django(版本 1.6x)应用程序切换为使用 pytest-django 进行测试。因此我通过 pip 安装了最新的 pytest-django 并获得了这些版本:

pytest==2.6.4
pytest-django==2.7.0

对于常规的 django 测试,我正在使用自定义测试套件运行器扩展 DjangoTestSuiteRunner,我在 settings.py 中配置了它:

设置.py:

TEST_RUNNER = "dcmanager.tests.runner.ManagedModelTestRunner"

运行者.py:

import unittest

from django.conf import settings
from django.db.models import get_app, get_apps
from django.test.simple import DjangoTestSuiteRunner, build_test, build_suite, runner


class ManagedModelTestRunner(DjangoTestSuiteRunner):
"""
Test runner that automatically makes all unmanaged models in
project managed for the duration of the test run and patches VStorage model,
so that one doesn't need to execute the SQL manually to create them.
"""
IGNORE_TESTS = ['django', 'rest_framework', 'rest_framework_swagger']

def build_suite(self, test_labels, extra_tests=None, **kwargs):
suite = unittest.TestSuite()

if test_labels:
for label in test_labels:
if '.' in label:
suite.addTest(build_test(label))
else:
app = get_app(label)
suite.addTest(build_suite(app))
else:
ignore_list = []
for app in get_apps():
app_name_parts = app.__name__.split('.')
for index, _ in enumerate(app_name_parts):
app_part_name = '.'.join(app_name_parts[0:index])
if app_part_name and app_part_name in self.IGNORE_TESTS:
ignore_list.append(app.__name__)
break
if app.__name__ not in ignore_list:
suite.addTest(build_suite(app))

if extra_tests:
for test in extra_tests:
suite.addTest(test)

return runner.reorder_suite(suite, (unittest.TestCase,))

def setup_test_environment(self, *args, **kwargs):
if settings.STAGE == 'TEST':
from django.db.models.loading import get_models
self.unmanaged_models = [m for m in get_models()
if not m._meta.managed]
for m in self.unmanaged_models:
m._meta.managed = True

super(ManagedModelTestRunner, self).setup_test_environment(*args,
**kwargs)

def teardown_test_environment(self, *args, **kwargs):
super(ManagedModelTestRunner, self).teardown_test_environment(*args,
**kwargs)
# reset unmanaged models
for m in self.unmanaged_models:
m._meta.managed = False

如何告诉 pytest-django 使用我的自定义测试套件运行程序?

最佳答案

py.test 根本不使用单元测试运行器

恐怕你将不得不在 py.test 中重做自定义集合

关于python - 将自定义测试套件运行器与 pytest-django 一起使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27280778/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com