python连接不上数据库_Python-流控制和失败:不允许数据库访问,请...

在尝试使用.defrun_single_test()函数运行pytest测试并插入数据到数据库时遇到错误:'Database access not allowed...'. 问题在于for循环或if条件导致数据库创建异常。然而,当测试代码移入单独的.run_single_test_path()函数中,一切正常。错误似乎只在首次运行任务时触发,并影响后续任务。问题可能与上下文管理或测试选择有关。
摘要由CSDN通过智能技术生成

我的一项芹菜任务遇到了一些奇怪的行为.

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()异常,但我绝对不知道为什么.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值