import datetime import pytest from elasticsearch import Elasticsearch from typing import Callable from apollo_main_db.base import Base from src.app import app from src.cache import redis_client from src.db.base import db from src.db.base import session as Session from src.utils import auth as auth_util @pytest.fixture def create_db_tables(): """Create models tables""" Base.metadata.create_all(bind=db.engine) yield Base.metadata.drop_all(bind=db.engine) @pytest.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.elasticsearch = Elasticsearch() 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("src.utils.auth.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("src.utils.auth.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("src.legacy.push_notifications.views.datetime", PatchedDatetime) @pytest.fixture def patch_date_today(monkeypatch): """Patching datetime now for tests.""" fake_date = datetime.date(2021, 5, 10) class PatchedDate(datetime.date): @classmethod def today(cls): return fake_date monkeypatch.setattr("src.legacy.apollo_api.util.nps_survey.date", PatchedDate)