import configparser

import pytest
from betamax import Betamax

from credmgr import CredentialManager, config
from credmgr.exceptions import InitializationError
from tests.utils import gen_cassette_name


def _initialize_config_override(self):
    self.server = self._fetch("server")
    self.endpoint = self._fetch("endpoint")
    self.api_token = None
    self.username = self._fetch("username")
    self.password = self._fetch("password")


def test_credmgr_init(recorder, credential_manager):
    assert credential_manager.current_user.username == "spaz"


def test_credmgr_init_bad_params(credential_manager):
    with pytest.raises(InitializationError):
        _ = CredentialManager(
            api_token="token", username="username", password="password"
        )


def test_credmgr_init_bad_section_name(credential_manager):
    with pytest.raises(configparser.NoSectionError):
        _ = CredentialManager("invalid")


def test_credmgr_no_params():
    old = config.Config._initialize_config
    config.Config._initialize_config = _initialize_config_override
    with pytest.raises(InitializationError):
        _ = CredentialManager()
    config.Config._initialize_config = old


def test_credmgr_camel_case():
    credmgr = CredentialManager(api_token="token")
    assert credmgr.config.api_token == "token"

    with pytest.deprecated_call():
        credmgr = CredentialManager(api_token="token", apiToken="old token")
        assert credmgr.config.api_token == "token"


def test_credmgr_init_username_password():
    old = config.Config._initialize_config
    config.Config._initialize_config = _initialize_config_override
    credmgr = CredentialManager(username="username", password="password")
    with Betamax(credmgr._requestor._session).use_cassette(gen_cassette_name()):
        assert credmgr.current_user.username == "username"
    config.Config._initialize_config = old
