diff --git a/tests/fixtures.py b/tests/fixtures.py new file mode 100644 index 0000000..20ff85a --- /dev/null +++ b/tests/fixtures.py @@ -0,0 +1,38 @@ +import contextlib + +import _pytest +import pytest + +from keyosk import config +from keyosk import database + + +@contextlib.contextmanager +def sqlite_database(tmp_path): + """Database context manager for use with other fixtures that add data""" + + sqlite_path = tmp_path / "test.db" + + conf = config.ConfigSerializer().load( + {"storage": {"backend": "sqlite", "sqlite": {"path": str(sqlite_path)}}} + ) + + database.initialize(conf) + yield + with contextlib.suppress(FileNotFoundError): + sqlite_path.unlink() + + +@pytest.fixture(scope="module") +def demo_database(request, tmp_path_factory): + """Generate a database with test data in it for tests""" + # The built in tmp_path fixture is function scope so even though we want the ``demo_database`` + # fixture to be module scope it would end up behaving as if it were function scope because the + # database file path would change for every invocation. Thus this fixture simply rebuilds the + # tmp_path fixture internally. Relevant source code: + # https://github.com/pytest-dev/pytest/blob/master/src/_pytest/tmpdir.py#L169 + # pylint: disable=protected-access + tmp_path = _pytest.tmpdir._mk_tmp(request, tmp_path_factory) + + with sqlite_database(tmp_path): + yield diff --git a/tests/test_config.py b/tests/test_config.py index 2882ebf..c4fb69b 100644 --- a/tests/test_config.py +++ b/tests/test_config.py @@ -48,10 +48,11 @@ def test_settings(): def test_filepath(tmp_path): tmp_file = Path(tmp_path, "conf.toml") - os.environ[constants.ENV_CONFIG_PATH] = str(tmp_file) with tmp_file.open("w+") as outfile: toml.dump(DEMO_CONFIG, outfile) assert config.load(tmp_file) == config.ConfigSerializer().load(DEMO_CONFIG) + os.environ[constants.ENV_CONFIG_PATH] = str(tmp_file) + assert config.load() == config.ConfigSerializer().load(DEMO_CONFIG) tmp_file.unlink() assert config.load(tmp_file) == config.KeyoskConfig()