"""Conftest. This file gets picked up when running py.test tests: http://pytest.org/latest/writing_plugins.html#conftest """ import os from pathlib import Path import re import sys from unittest.mock import patch from freezegun import freeze_time import moto import pytest PROJECT_ROOT = Path(__file__).parent.parent @pytest.fixture def clear_os_environ(): """Clear all the environment variables.""" clean_environ = dict( FEED_INGESTION_TABLE='dev_feed_ingestion_status' ) with patch.dict(os.environ, clean_environ, clear=True): yield def pytest_sessionstart(session): """Set environment variables to their test values. Also set env variable "Environment" to "test" explicitly. """ from dotenv.main import DotEnv dotenv = DotEnv(PROJECT_ROOT / '.env.shadow') for env, value in dotenv.dict().items(): if env in os.environ: del os.environ[env] os.environ['Environment'] = 'dev' @pytest.fixture def frozen_time(mocker): """Fixture to freeze time to a specific date. It also mocks time.sleep() which adjusts frozen time Returns: tuple: (freeze_time_mock, sleep_mock) """ with freeze_time('2024-11-11') as freeze_time_mock: sleep_mock = mocker.patch( 'time.sleep', side_effect=lambda v: freeze_time_mock.tick(v) ) yield freeze_time_mock, sleep_mock @pytest.fixture def mock_aws(monkeypatch): """Mock AWS services with help of moto package. Additionally, sets the AWS_SESSION_TOKEN env variable. """ monkeypatch.setenv('AWS_SESSION_TOKEN', 'FOOBARTOKEN') # these AWS creds values will be set by moto: # AWS_ACCESS_KEY_ID: FOOBARKEY # AWS_SECRET_ACCESS: FOOBARSECRET with moto.mock_aws(): yield class SubstringMatcher: """Class which allows to check for SQL calls by the list of substrings.""" def __init__(self, containing): """Initialise object. Args: containing (list): A list of substrings to check. """ self.containing = [el.lower() for el in containing] def __eq__(self, sql): """Equal magic method. Check if all the substrings from the passed list are present in SQL. Args: sql (str): SQL statement from a call. """ sql = re.sub('\\s+', ' ', sql.lower()).strip() return all(el in sql for el in self.containing) def __repr__(self): """Represent string magic method to play nice with py.test messages.""" return 'SQL containing: {}'.format(', '.join(self.containing)) @pytest.fixture def sf_config_mock(): """Fixture returning the dict with Snowflake connection params.""" return { 'account': 'test_acc', 'role': 'test_role', 'host': 'test_host', 'warehouse': 'test_wh', 'port': 10, 'user': 'test_user', 'password': 'test_pass', 'private_key': None, 'db': 'test_db', 'ocsp_fail_open': False, 'schema': 'test_schema' } @pytest.fixture def aws_config_mock(): """Return mocked AWS credentials dict.""" return {'access_key': 'test', 'access_secret': 'test', 'access_token': 'test', } def pytest_configure(config): """Set `sys._called_from_test` if running in test env.""" sys._called_from_test = True os.environ['SWITCHBOARD_CONSUMER_KAFKA_TOPIC'] = 'test_kafka_topic' def pytest_unconfigure(config): """Clear test env configuration.""" if hasattr(sys, '_called_from_test'): del sys._called_from_test if hasattr(os.environ, 'SWITCHBOARD_CONSUMER_KAFKA_TOPIC'): del (os.environ['SWITCHBOARD_CONSUMER_KAFKA_TOPIC'])