使用 peewee ORM 进行代码单元测试的自定义 sqlite 数据库 [英] Custom sqlite database for unit tests for code using peewee ORM

查看:58
本文介绍了使用 peewee ORM 进行代码单元测试的自定义 sqlite 数据库的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用 peewee python ORM 实现多对多场景,我想要一些单元测试.Peewee 教程很棒,但它假设数据库是在模块级别定义的,然后所有模型都在使用它.我的情况有所不同:我没有包含显式运行的测试的源代码文件(从 Python 的角度来看是一个模块),我使用的是从该文件中收集测试并运行它们的鼻子.

I am trying to implement a many-to-many scenario using peewee python ORM and I'd like some unit tests. Peewee tutorial is great but it assumes that database is defined at module level then all models are using it. My situation is different: I don't have a source code file (a module from python's point of view) with tests which I run explicitly, I am using nose which collects tests from that file and runs them.

如何仅将自定义数据库用于在测试中实例化的模型(由鼻子运行)?我的目标是将内存数据库仅用于测试,以加快测试过程.

How do I use a custom database only for models instantiated in tests (which are being run by nose)? My goal is to use an in-memory database for tests only, to speedup the testing process.

推荐答案

我今天刚刚推送了一个提交,使这更容易.

I just pushed a commit today that makes this easier.

修复采用上下文管理器的形式,它允许您覆盖模型的数据库:

The fix is in the form of a context manager which allows you to override the database of a model:

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 documentation and have a look at the example testcases:

这篇关于使用 peewee ORM 进行代码单元测试的自定义 sqlite 数据库的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆