Ibo*_*lit 5 python testing django
我需要用不同的参数测试一个函数,最合适的方法似乎是使用with self.subTest(...)上下文管理器。
但是,该函数向数据库写入了一些内容,并最终处于不一致的状态。我可以删除我写的东西,但如果我能完全重新创建整个数据库会更干净。有没有办法做到这一点?
不确定如何在 self.subTest() 中重新创建数据库,但我目前正在使用另一种技术,您可能会感兴趣。您可以使用固定装置创建数据库的“快照”,该快照基本上将被复制到仅用于测试目的的第二个数据库中。我目前使用这种方法来测试我正在工作的一个大项目的代码。
我将发布一些示例代码,让您了解实践中的情况,但您可能需要做一些额外的研究才能根据您的需求定制代码(我添加了链接来指导您)。
这个过程相当简单。您将仅使用使用固定装置所需的数据创建数据库的副本,该副本将存储在.yaml文件中,并且只能由您的测试单元访问。
该过程如下所示:
生成.py
django.setup()
stdout = sys.stdout
conf = [
{
'file': 'myfile.yaml',
'models': [
dict(model='your.model', pks='your, primary, keys'),
dict(model='your.model', pks='your, primary, keys')
]
}
]
for fixture in conf:
print('Processing: %s' % fixture['file'])
with open(fixture['file'], 'w') as f:
sys.stdout = FixtureAnonymiser(f)
for model in fixture['models']:
call_command('dumpdata', model.pop('model'), format='yaml',indent=4, **model)
sys.stdout.flush()
sys.stdout = stdout
Run Code Online (Sandbox Code Playgroud)
测试类.py
from django.test import TestCase
class classTest(TestCase):
fixtures = ('myfile.yaml',)
def setUp(self):
"""setup tests cases"""
# create the object you want to test here, which will use data from the fixtures
def test_function(self):
self.assertEqual(True,True)
# write your test here
Run Code Online (Sandbox Code Playgroud)
您可以在这里阅读更多内容:
如果您因不清楚而有任何疑问,请提出,我很乐意为您提供帮助。