Search code examples
peewee

What can replace the test_database () function from playhouse.test_utils?


I want to use custom sqlite database for unit tests for code. The answer to the question uses test_database from playhouse.test_utils.

However, this is currently not available there.

What can I replace it with?


Solution

  • You can use the Database.bind() or Database.bind_ctx() methods, which are documented:

    http://docs.peewee-orm.com/en/latest/peewee/api.html#Database.bind_ctx

    The documentation covers this exact scenario:

    MODELS = (User, Account, Note)
    
    # Bind the given models to the db for the duration of wrapped block.
    def use_test_database(fn):
        @wraps(fn)
        def inner(self):
            with test_db.bind_ctx(MODELS):
                test_db.create_tables(MODELS)
                try:
                    fn(self)
                finally:
                    test_db.drop_tables(MODELS)
        return inner
    
    
    class TestSomething(TestCase):
        @use_test_database
        def test_something(self):
            # ... models are bound to test database ...
            pass