【问题标题】:How to monkeypatch sqlite database for tests purposes?如何为测试目的对 sqlite 数据库进行猴子补丁?
【发布时间】:2017-10-24 10:35:01
【问题描述】:

在 ORM.py 文件中:

from peewee import *
db = SqliteDatabase('database.db')

class Device(Model):
    uid = CharField(unique=True, max_length=17)

    class Meta:
        database = db

现在在 test.py 中,我想用 test.db 猴子补丁原始数据库 database.db

from _pytest.monkeypatch import MonkeyPatch

@pytest.fixture(scope="session")
def monkeysession(request):
    mp = MonkeyPatch()
    yield mp
    mp.undo()


@pytest.fixture(scope='session', autouse=True)
def create_db(monkeysession, request):
    monkeysession.setattr(ORM, 'db', SqliteDatabase('test.db'))

但我的错误(peewee.OperationalError: table "device" already exists)提示monkeypatch失败

【问题讨论】:

    标签: python-3.x mocking pytest peewee


    【解决方案1】:

    http://docs.peewee-orm.com/en/latest/peewee/database.html#testing-peewee-applications

    # tests.py
    import unittest
    from my_app.models import EventLog, Relationship, Tweet, User
    
    MODELS = [User, Tweet, EventLog, Relationship]
    
    # use an in-memory SQLite for tests.
    test_db = SqliteDatabase(':memory:')
    
    class BaseTestCase(unittest.TestCase):
        def setUp(self):
            # Bind model classes to test db. Since we have a complete list of
            # all models, we do not need to recursively bind dependencies.
            test_db.bind(MODELS, bind_refs=False, bind_backrefs=False)
    
            test_db.connect()
            test_db.create_tables(MODELS)
    
        def tearDown(self):
            # Not strictly necessary since SQLite in-memory databases only live
            # for the duration of the connection, and in the next step we close
            # the connection...but a good practice all the same.
            test_db.drop_tables(MODELS)
    
            # Close connection to db.
            test_db.close()
    
            # If we wanted, we could re-bind the models to their original
            # database here. But for tests this is probably not necessary.
    

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-08-25
    • 2018-01-08
    • 2023-03-03
    • 2013-12-28
    • 2011-10-06
    相关资源
    最近更新 更多