# -*- coding: utf-8 -*-
# -----------------------------------------------------------------------------
# Copyright 2016 Continuum Analytics, Inc.
#
# May be copied and distributed freely only as part of an Anaconda or
# Miniconda installation.
# -----------------------------------------------------------------------------
import io

import pytest

from anaconda_enterprise.cli.config import (ConfigManager, platform_defaults, system_wide,
                                            user_local, conda_env, ConfigurationError,
                                            SCHEMA_LATEST, SCHEMA_1)


def test_remove_conda_env_templates_without_conda_prefix(monkeypatch):
    monkeypatch.delenv('CONDA_PREFIX')
    mgr = ConfigManager('cli', SCHEMA_LATEST)
    assert mgr.config_path_templates == platform_defaults + system_wide + user_local


def test_make_sure_conda_env_templates_are_added_with_conda_prefix(monkeypatch):
    monkeypatch.setenv('CONDA_PREFIX', 'test')  # just to make sure it's set
    mgr = ConfigManager('cli', SCHEMA_LATEST)
    assert mgr.config_path_templates == platform_defaults + system_wide + conda_env + user_local
    assert mgr.variables[mgr.ENV_DIR] == 'test/etc'


def test_upgrade_1():
    # Test with an explicit version, so that the test doesn't have to change on the next upgrade
    mgr = ConfigManager('cli', SCHEMA_1)

    mgr.load_yaml_string('''
verify_ssl: true
sites:
  example:
    verify_ssl: foobar.pem
    ''', 'test.yml')

    assert mgr['ssl_verify'] is True
    assert mgr['sites.example.ssl_verify'] == 'foobar.pem'

    with pytest.raises(KeyError):
        mgr['verify_ssl']

    fd = io.StringIO()
    mgr.dump(file_=fd)

    # the upgraded config should have a version
    assert "version: '1'" in fd.getvalue()


def test_upgrade_1_validate():
    mgr = ConfigManager('cli', SCHEMA_LATEST)

    with pytest.raises(ConfigurationError):
        mgr.load_yaml_string('''
bad_config: true
    ''', 'test.yml')
