PotionUI Docs v0.3.0

Testing your plugin against a scratch database

Your plugin's tests must never touch the application's database. scratch_database makes a throwaway one in a file of the test's temporary folder, and use_database makes it the application's database for the length of a with block: db, and every repository behind this API (SettingRepository, PluginRepository, plugin_settings, ...), read and write it, and the database in place before comes back when the block ends, even when the test fails inside it.

python
import pytest


@pytest.fixture
def plugin_db(tmp_path):
    from src.plugin_api import scratch_database, use_database

    from backend.tables import create_tables

    with use_database(scratch_database(tmp_path / "test.sqlite")) as database:
        create_tables()
        yield database
  • The core schema. A scratch database carries the tables of every core migration, so a table of your plugin can reference users(id) and a core repository finds its own tables. The migrations run once per test process, into a folder of the system's temporary directory; each scratch database is a copy of their result. Pass core_schema=False for an empty database, for a test that checks exactly which tables your plugin creates.
  • Your own tables. Create them inside the block by calling the function your plugin.lifecycle.boot handler calls (see Initializing your plugin). It reads db when it runs, so it writes to the scratch database exactly as it writes to the application's at boot. Code that binds db once, at the top of a module, keeps the database that was in place then: import it inside the function that uses it.
  • A new file only. scratch_database creates its file before it returns and refuses a path that already exists, so a test can never overwrite a database it did not make, and two tests given the same path cannot end up sharing one. It also refuses the application's own database file, storage/db.sqlite or the file POTIONUI_DB_PATH names, even when that file does not exist yet.
  • One block at a time. use_database swaps the database for the whole process. Blocks nest, each one putting back the database it replaced, but two blocks opened at the same time on different threads would put back the wrong one. Parallel runs are safe: each pytest-xdist worker is a process of its own, with its own temporary folders and its own copy of the migrations.
  • Only in tests. Importing src.plugin_api does not load these two names; they load the first time a test asks for them. Never open use_database in running plugin code: every request the application serves while the block is open would read and write the scratch database.
  • Nothing else. Do not patch the module db comes from or build its class yourself: both are internal and change without notice. These two names are the supported way to swap the database.