import pathlib import pytest import random import shutil import string from sqlalchemy import create_engine from sqlalchemy.orm import sessionmaker from app.sql.models import Base from app.routers.stats import top_movers # TODO - this is almost a copy-paste of `isolated_database` from `tests/sql/test_crud` - # consider unifying and extracting. @pytest.mark.parametrize("isolated_database", [["populated_db.db"]], indirect=True) def test_initialization(isolated_database): response = top_movers(db=isolated_database) biggest_positive = response["positive"][0] assert biggest_positive["deck_id"] == 74 assert biggest_positive["name"] == "Goose Mother" assert float(biggest_positive["diff"]) == 6.758 biggest_negative = response["negative"][0] assert biggest_negative["deck_id"] == 45 assert biggest_negative["name"] == "Ashad" assert float(biggest_negative["diff"]) == -6.542 # This fixture expects a parameter representing the filename within `test-data/sqlite-database-snapshots` that should be # used to initialize the database. # See http://stackoverflow.com/a/33879151 @pytest.fixture(scope="function") def isolated_database(request, cleanups): database_dir = "database" db_dir_path = pathlib.Path(database_dir) if not db_dir_path.exists(): db_dir_path.mkdir() db_dir_path.chmod(0o777) isolated_db_name = f"isolated_database_{''.join([random.choice(string.ascii_lowercase) for _ in range(5)])}.db" isolated_db_path = db_dir_path.joinpath(isolated_db_name) seedPath = pathlib.Path("test-data").joinpath( "sqlite-database-snapshots", request.param[0] ) if not seedPath.exists(): raise Exception( f"Cannot initialize a database from {seedPath} - does not exist" ) shutil.copy(str(seedPath), isolated_db_path.absolute()) engine = create_engine(f"sqlite:///{isolated_db_path.absolute()}") SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine) Base.metadata.create_all(bind=engine) def success_cleanup(): isolated_db_path.unlink() def failure_cleanup(): print( f"Isolated database {isolated_db_path.absolute()}, used in test `{request.node.name}` at path `{request.node.path.absolute()}`, has been preserved for debugging" ) cleanups.add_success(success_cleanup) cleanups.add_failure(failure_cleanup) yield SessionLocal() # yield isolated_db_path