gpt4 book ai didi

python - 流量控制和失败 : Database access not allowed, 使用 "django_db".... 错误

转载 作者:太空宇宙 更新时间:2023-11-03 15:40:51 24 4
gpt4 key购买 nike

我的一项 celery 任务遇到了一些奇怪的行为。

def run_single_test(test_name_or_decorator):
# get dict of test names, test paths
test_dict = get_single_test_names()

# check to see if test is in the dict
if test_name_or_decorator not in test_dict:
return 'The requested test could not be found.'

for test_name, test_path in test_dict.items():
# if test name is valid run associated test
if test_name == test_name_or_decorator:
pytest.main(['-p', 'no:django','--json-report', test_path])
report = return_test_result_json('.report.json')
report_id = str(uuid.uuid4())
test_run_data = TestResults.objects.create(name=report_id, data=report)

return 'this is your test report: {}'.format(get_report(test_run_data.id))

此任务将执行 pytest.main() 命令并运行测试,但是当它使用 .create() 将 .report.json 插入 Db 时,我收到以下错误:

Failed: Database access not allowed, use the "django_db" mark, or the "db" or "transactional_db" fixtures to enable it.

现在,如果我采用 for test_name.... block 中的所有功能来简化事情并将其移动到它自己的函数中,一切正常:

def run_single_test_path():

test_path = 'test_folder/test_file.py::TestClass::specific_test_name'
pytest.main(['-p', 'no:django','--json-report', test_path])
report = return_test_result_json('.report.json')
report_id = str(uuid.uuid4())
test_run_data = TestResults.objects.create(name=report_id, data=report)
return 'this is your test report: {}'.format(get_report(test_run_data.id))

我得到了预期的返回:

"this is your test report: {'created': datetime.datetime(2018, 9, 27, 15, 51, 59, 297991, tzinfo=<UTC>), 'summary': {'total': 1, 'passed': 1}, 'exitcode': 0}"

我使用相同 pytest.main() 和 .create() 的变体的其他任务不会发生此行为。另一个观察结果是,如果我先运行此任务并抛出数据库访问错误,则所有其他任务都将失败并出现相同的错误。

我的工作理论是关于 for 循环或 if 的某些东西导致 .create() 崩溃,但我完全不知道为什么。

最佳答案

通常,pytest.main 不关心测试运行后留下的全局状态,因为它假设进程在测试运行完成后终止并返回退出代码。因此,如果您在 pytest.main 完成后在同一进程中运行代码,则必须谨慎对待范围内的修改。其中之一是由 pytest-django 在 django 测试配置上激活的数据库拦截器;它不会在测试执行完成后停用。要停用,请在代码中明确执行:

import pytest_django

def run_single_test(test_name_or_decorator):
...
pytest.main(['-p', 'no:django','--json-report', test_path])
pytest_django.plugin._blocking_manager.unblock()

# database access unblocked, you can run the query now
test_run_data = TestResults.objects.create(name=report_id, data=report)

或者添加一个运行后的钩子(Hook)来隐式地执行它,例如:

# conftest.py

import pytest_django

def pytest_unconfigure(config):
pytest_django.plugin._blocking_manager.unblock()

关于python - 流量控制和失败 : Database access not allowed, 使用 "django_db".... 错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52555918/

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