# Copyright 2014-2016 Morgan Delahaye-Prat. All Rights Reserved.
#
# Licensed under the Simplified BSD License (the "License");
# you may not use this file except in compliance with the License.
"""Test Hypr configuration."""


import os
import pytest


# config keys used for the tests
TEST_KEY = 'foo'
SECRET_KEY = 'devkey'


@pytest.fixture
def app(app):
    """A pre-initialized configuration."""
    app.config['FOO_BAR_0'] = 'baz'
    app.config['FOO_BAR_1'] = 'baz'
    app.config['FOO_0'] = 'bar'
    app.config['FOO_1'] = 'bar'

    return app


def test_config_from_class(app):
    """Load config from a python object."""
    class PythonObject:
        TEST_KEY = 'foo'

    app.config.from_object(PythonObject)
    assert app.config['TEST_KEY'] == 'foo'


class TestFromFile:
    """Test loading configuration from file."""

    def test_working(self, app):
        """Load config from file."""
        assert 'TEST_KEY' not in app.config
        app.config.from_pyfile(__file__.rsplit('.', 1)[0] + '.py')
        assert app.config['TEST_KEY'] == 'foo'

    def test_config_missing(self, app):
        """Missing configuration file raises error."""
        with pytest.raises(IOError):
            app.config.from_pyfile('missing.cfg')

    def test_config_missing_silent(self, app):
        """Missing configuration file fails silently."""
        app.config.from_pyfile('missing.cfg', silent=True)


class TestFromEnvironment:
    """Test loading configuration from environment."""

    def test_working(self, app):
        """Load config from env."""
        os.environ = {'TEST_ENV': __file__.rsplit('.', 1)[0] + '.py'}
        app.config.from_envvar('TEST_ENV')
        assert app.config['TEST_KEY'] == 'foo'

    def test_config_missing(self, app):
        """File does not exist."""
        os.environ = {'TEST_ENV': 'missing.cfg'}
        with pytest.raises(IOError):
            app.config.from_envvar('TEST_ENV')

    def test_config_missing_silent(self, app):
        """File does not exist (silent)."""
        os.environ = {'TEST_ENV': 'missing.cfg'}
        app.config.from_envvar('TEST_ENV', silent=True)

    def test_missing_env(self, app):
        """Missing environment variable."""
        with pytest.raises(RuntimeError):
            app.config.from_envvar('MISSING_ENV')

    def test_missing_env_silent(self, app):
        """Missing environment variable (silent)."""
        app.config.from_envvar('MISSING_ENV', silent=True)


class TestConfigNamespace:
    """Test the namespace feature of the configuration."""

    def test_namespace(self, app):
        """Low discrimination namespace."""
        rv = app.config.get_namespace('FOO')
        assert rv == {'BAR_0': 'baz', 'BAR_1': 'baz', '0': 'bar', '1': 'bar'}

    def test_alt_namespace(self, app):
        """High discrimination namespace."""
        rv = app.config.get_namespace('FOO_BAR')
        assert rv == {'0': 'baz', '1': 'baz'}
