我的一项芹菜任务遇到了一些奇怪的行为.
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.
现在,如果我使用了test_name ….块中的所有功能,则可以简化事情并将其移入其自己的函数中,那么一切正常:
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=), 'summary': {'total': 1, 'passed': 1}, 'exitcode': 0}"
我的其他使用相同pytest.main()和.create()的变体的其他任务没有发生此行为.
另一个观察结果是,如果我先运行此任务,并且抛出数据库访问错误,则所有其他任务将因相同的错误而失败.
我的工作原理是,有关for循环或if的问题导致.create()异常,但我绝对不知道为什么.