"""
Unit tests for app configuration.

:copyright: Copyright 2013-2017, Dorian Pula <dorian.pula@amber-penguin-software.ca>
:license: AGPL v3+
"""

import contextlib
import copy
import os

import pytest

import rookeries
from rookeries import config


@pytest.fixture
def flask_test_app():
    return rookeries.make_rookeries_app(quiet_log=True).test_client().application


def test_configuration_will_use_default_configuration_class(flask_test_app):
    config.configure_app(flask_test_app)
    expected_config = config.DefaultConfig()

    for key, value in expected_config.__dict__.items():
        assert key in flask_test_app.config
        assert value == flask_test_app.config[key]


def test_configuration_will_use_envs_with_appropriate_prefix(flask_test_app):
    test_config_key = 'CONFIG_KEY'
    test_config_value = 'ROOKERIES_CONFIG_VALUE'

    with set_config_in_environ(test_config_key, test_config_value):
        config.configure_app(flask_test_app)
        assert test_config_key in flask_test_app.config
        assert test_config_value == flask_test_app.config[test_config_key]


def test_configuration_will_skip_envs_with_wrong_prefix(flask_test_app):
    test_config_key = 'CONFIG_KEY'
    test_config_value = 'BAD_CONFIG_VALUE'

    with set_config_in_environ(test_config_key, test_config_value, prefix='RANDOM_'):
        config.configure_app(flask_test_app)
        assert test_config_key not in flask_test_app.config


def test_configuration_from_environment_variable_will_override_default(flask_test_app):
    test_config_key = 'JWT_SECRET_KEY'
    test_config_value = 'test_environ'

    with set_config_in_environ(test_config_key, test_config_value):
        config.configure_app(flask_test_app)
        assert test_config_key in flask_test_app.config
        assert config.DefaultConfig.JWT_SECRET_KEY != flask_test_app.config[test_config_key]
        assert test_config_value == flask_test_app.config[test_config_key]


@contextlib.contextmanager
def set_config_in_environ(environ_variable, environ_value, prefix=config.ROOKERIES_ENV_CONFIG_PREFIX):
    """Context manager to change an environment variable."""

    environ_name = ''.join((prefix, environ_variable))
    original_environ_value = copy.deepcopy(os.environ.get(environ_name))

    os.environ[environ_name] = environ_value
    yield
    os.environ.pop(environ_name)
    if original_environ_value:
        os.environ[environ_name] = original_environ_value
