如何将monkeypatch sqlite数据库用于测试目的?

时间:2017-10-24 10:35:01

标签: python-3.x mocking pytest peewee

在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中我希望monkeypatch原始数据库database.dbtest.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:表“设备”已经存在)表明monkeypatch失败

1 个答案:

答案 0 :(得分:0)

您可能想查看2.x http://docs.peewee-orm.com/en/latest/peewee/api.html#Using

中的$ sed '/^leaf-foo.*bar/ s/-/_/' file dont-touch-these-hyphens leaf_foo.*bar replace-these-hyphens leaf_foobar dont-replace-these-hyphens 帮助器

或3.0a中的Using(尚未记录,抱歉)。

还有bind()扩展名,分别位于2.x和3.0a:http://docs.peewee-orm.com/en/latest/peewee/playhouse.html#test_database