From ce4a9a084b9e8923d33c37102741548d25238453 Mon Sep 17 00:00:00 2001 From: Vadim Melnik Date: Sun, 15 Oct 2023 12:45:00 +0300 Subject: [PATCH] Made pytest to be self-sufficient, e.g. test SQLite3 DB is created/initialized/deleted automatically in temporary location. --- .github/workflows/pytest.yml | 6 ------ repromon_app/tests/conftest.py | 20 +++++++++++++++++++- 2 files changed, 19 insertions(+), 7 deletions(-) diff --git a/.github/workflows/pytest.yml b/.github/workflows/pytest.yml index 4c7ef41..7fa22a0 100644 --- a/.github/workflows/pytest.yml +++ b/.github/workflows/pytest.yml @@ -54,12 +54,6 @@ jobs: poetry build shell: bash - - name: Setup test DB - run: | - > db/db_dev.sqlite3 - poetry run setup_db - shell: bash - - name: Run pytest run: | poetry run pytest --cov=. --cov-report=xml diff --git a/repromon_app/tests/conftest.py b/repromon_app/tests/conftest.py index 5ab6ef7..f32a009 100644 --- a/repromon_app/tests/conftest.py +++ b/repromon_app/tests/conftest.py @@ -1,5 +1,7 @@ +import os import logging import threading +import tempfile import pytest from fastapi import FastAPI @@ -10,6 +12,7 @@ from repromon_app.db import db_init from repromon_app.service import SecSysService from repromon_app.srv import create_fastapi_app +from repromon_tools import setup_db logger = logging.getLogger(__name__) # @@ -30,15 +33,30 @@ @pytest.fixture(scope="session", autouse=True) def init_config(): logger.debug("init_config()") + # + temp = tempfile.NamedTemporaryFile(prefix='repromon_db_test_sqlite3_', delete=False) + db_path = temp.name + logger.info(f"create temporary file: {db_path}") + db_url = f"sqlite:///{db_path}" + os.environ['DB_URL'] = db_url + logger.info(f"override DB_URL env with this value: {db_url}") + # app_config_init() yield + # + if os.path.isfile(db_path): + os.remove(db_path) + print(f"Deleted temporary DB file: {db_path}") @pytest.fixture(scope="session", autouse=True) def init_db(): logger.debug("init_db()") logger.debug("Initialize DB...") - db_init(app_config().db.dict(), threading.get_ident) + # db_init(app_config().db.dict(), threading.get_ident) + logger.debug("Execute setup_db first") + setup_db.main() + logger.debug("Done, setup_db") svc: SecSysService = SecSysService() global _apikey_tester1, _apikey_tester2, _apikey_tester3