From e475fd4971d076bc24f06875d6a4e90b25ef7cd0 Mon Sep 17 00:00:00 2001 From: Ethan Paul Date: Sun, 23 Feb 2020 00:55:00 -0500 Subject: [PATCH] Add database test fixtures Fix test condition in config tests for possible false pass --- tests/fixtures.py | 38 ++++++++++++++++++++++++++++++++++++++ tests/test_config.py | 3 ++- 2 files changed, 40 insertions(+), 1 deletion(-) create mode 100644 tests/fixtures.py 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()