import datetime from typing import Callable import pytest from apollo_main_db.base import Base from app import app from auth import util as auth_util from main_db.base import db from main_db.base import session as Session from redis_db import redis_client @pytest.yield_fixture def create_db_tables(): """Create models tables""" Base.metadata.create_all(bind=db.engine) yield Base.metadata.drop_all(bind=db.engine) @pytest.yield_fixture def db_session(create_db_tables): """Returns an sqlalchemy session, and after the test tears down.""" connection = db.engine.connect() transaction = connection.begin() session = Session() yield session session.close() transaction.rollback() connection.close() @pytest.fixture(scope="session") def app_fixture(): app.config["TESTING"] = True app_context = app.test_request_context() app_context.push() yield app @pytest.fixture def client(app_fixture): yield app_fixture.test_client() @pytest.fixture def patch_auth_key(monkeypatch): """ Patching authorize function for tests """ monkeypatch.setattr("auth.util.authorize", lambda: None) @pytest.fixture def patch_auth_user(monkeypatch, patch_auth_key) -> Callable: """ Patching authenticate_user function for tests """ def patch_user_id(user_id): monkeypatch.setattr("auth.util.get_user", lambda: auth_util.User(user_id)) return patch_user_id @pytest.fixture def user_id(): yield "6784fa8b-d468-4237-a181-1b9ce2759567" @pytest.fixture(autouse=True) def redis_flush(): """Flush all before each test""" redis_client.flushall() @pytest.fixture def patch_datetime_now(monkeypatch): """Patching datetime now for tests.""" fake_datetime = datetime.datetime(2020, 2, 10, 10, 0, 0) class PatchedDatetime(datetime.datetime): @classmethod def now(cls): return fake_datetime monkeypatch.setattr("push_notifications.views.datetime", PatchedDatetime)