我正在尝试使用 peewee python ORM 实现多对多场景,并且我想要一些单元测试。 Peewee 教程很棒,但它假设数据库是在模块级别定义的,然后所有模型都使用它。我的情况有所不同:我没有带有显式运行的测试的源代码文件(从Python的角度来看是一个模块),我使用nose从该文件收集测试并运行它们。
如何仅将自定义数据库用于测试中实例化的模型(正在通过鼻子运行)?我的目标是仅使用内存数据库进行测试,以加快测试过程。
我今天刚刚推送了一个承诺,让这件事变得更容易。
该修复采用上下文管理器的形式,它允许您覆盖模型的数据库:
from unittest import TestCase
from playhouse.test_utils import test_database
from peewee import *
from my_app.models import User, Tweet
test_db = SqliteDatabase(':memory:')
class TestUsersTweets(TestCase):
def create_test_data(self):
# ... create a bunch of users and tweets
for i in range(10):
User.create(username='user-%d' % i)
def test_timeline(self):
with test_database(test_db, (User, Tweet)):
# This data will be created in `test_db`
self.create_test_data()
# Perform assertions on test data inside ctx manager.
self.assertEqual(Tweet.timeline('user-0') [...])
# once we exit the context manager, we're back to using the normal database
See the 文档 http://docs.peewee-orm.com/en/latest/peewee/playhouse.html#test-utils并查看示例测试用例:
- 上下文管理器 https://github.com/coleifer/peewee/blob/master/playhouse/test_utils.py
- 测试用例展示了如何使用 https://github.com/coleifer/peewee/blob/master/tests/test_utils.py
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)