<commit_before># -*- coding: utf-8 -*-
'''
    tests.utils.test_main
    ~~~~~~~~~~~~~~~~~~~~~

    :copyright: (c) 2014 <NAME> & contributors
    :license: MIT, see LICENSE for more details.
'''

import click

from click.testing import CliRunner
import pytest
import requests

import vdirsyncer.utils as utils
import vdirsyncer.doubleclick as doubleclick
from vdirsyncer.utils.vobject import split_collection

from .. import blow_up, normalize_item, SIMPLE_TEMPLATE, BARE_EVENT_TEMPLATE


class EmptyNetrc(object):
    def __init__(self, file=None):
        self._file = file
    def authenticators(self, hostname):
        return None

class EmptyKeyring(object):
    def get_password(self, *a, **kw):
        return None


@pytest.fixture(autouse=True)
def empty_password_storages(monkeypatch):
    monkeypatch.setattr('netrc.netrc', EmptyNetrc)
    monkeypatch.setattr(utils, 'keyring', EmptyKeyring())


def test_parse_options():
    o = {
        'foo': 'yes',
        'hah': 'true',
        'bar': '',
        'baz': 'whatever',
        'bam': '123',
        'asd': 'off'
    }

    a = dict(utils.parse_options(o.items()))

    expected = {
        'foo': True,
        'hah': True,
        'bar': '',
        'baz': 'whatever',
        'bam': 123,
        'asd': False
    }

    assert a == expected

    for key in a:
        # Yes, we want a very strong typecheck here, because we actually have
        # to differentiate between bool and int, and in Python 2, bool is a
        # subclass of int.
        assert type(a[key]) is type(expected[key])  # flake8: noqa


def test_get_password_from_netrc(monkeypatch):
    username = 'foouser'
    password = '<PASSWORD>'
    resource = 'http://example.com/path/to/whatever/'
    hostname = 'example.com'

    calls = []

    class Netrc(object):
        def authenticators(self, hostname):
            calls.append(hostname)
            return username, 'bogus', password

    monkeypatch.setattr('netrc.netrc', Netrc)
    monkeypatch.setattr('getpass.getpass', blow_up)

    _password = utils.get_password(username, resource)
    assert _password == password
    assert calls == [hostname]


def test_get_password_from_system_keyring(monkeypatch):
    username = 'foouser'
    password = '<PASSWORD>'
    resource = 'http://example.com/path/to/whatever/'
    hostname = 'example.com'

    class KeyringMock(object):
        def get_password(self, resource, _username):
            assert _username == username
            assert resource == utils.password_key_prefix + hostname
            return password

    monkeypatch.setattr(utils, 'keyring', KeyringMock())

    monkeypatch.setattr('getpass.getpass', blow_up)

    _password = utils.get_password(username, resource)
    assert _password == password


def test_get_password_from_prompt():
    getpass_calls = []

    user = 'my_user'
    resource = 'http://example.com'

    @click.command()
    def fake_app():
        x = utils.get_password(user, resource)
        click.echo('Password is {}'.format(x))

    runner = CliRunner()
    result = runner.invoke(fake_app, input='my_password\n\n')
    assert not result.exception
    assert result.output.splitlines() == [
        'Server password for {} at host {}: '.format(user, 'example.com'),
        'Password is <PASSWORD>'
    ]


def test_set_keyring_password(monkeypatch):
    class KeyringMock(object):
        def get_password(self, resource, username):
            assert resource == utils.password_key_prefix + 'example.com'
            assert username == 'foouser'
            return None

        def set_password(self, resource, username, password):
            assert resource == utils.password_key_prefix + 'example.com'
            assert username == 'foouser'
            assert password == '<PASSWORD>'

    monkeypatch.setattr(utils, 'keyring', KeyringMock())

    @doubleclick.click.command()
    @doubleclick.click.pass_context
    def fake_app(ctx):
        ctx.obj = {}
        x = utils.get_password('foouser', 'http://example.com/a/b')
        click.echo('password is ' + x)

    runner = CliRunner()
    result = runner.invoke(fake_app, input='hunter2\ny\n')
    assert not result.exception
    assert result.output == (
        'Server password for foouser at host example.com: \n'
        'Save this password in the keyring? [y/N]: y\n'
        'password is <PASSWORD>'
    )


def test_get_password_from_cache(monkeypatch):
    user = 'my_user'
    resource = 'http://example.com'

    @doubleclick.click.command()
    @doubleclick.click.pass_context
    def fake_app(ctx):
        ctx.obj = {}
        x = utils.get_password(user, resource)
        click.echo('Password is {}'.format(x))
        monkeypatch.setattr(doubleclick.click, 'prompt', blow_up)

        assert (user, 'example.com') in ctx.obj['passwords']
        x = utils.get_password(user, resource)
        click.echo('Password is {}'.format(x))

    runner = CliRunner()
    result = runner.invoke(fake_app, input='my_password\n')
    assert not result.exception
    assert result.output.splitlines() == [
        'Server password for {} at host {}: '.format(user, 'example.com'),
        'Save this password in the keyring? [y/N]: ',<commit_msg>Fix failing testcase<commit_after># -*- coding: utf-8 -*-
'''
    tests.utils.test_main
    ~~~~~~~~~~~~~~~~~~~~~

    :copyright: (c) 2014 <NAME> & contributors
    :license: MIT, see LICENSE for more details.
'''

import click

from click.testing import CliRunner
import pytest
import requests

import vdirsyncer.utils as utils
import vdirsyncer.doubleclick as doubleclick
from vdirsyncer.utils.vobject import split_collection

from .. import blow_up, normalize_item, SIMPLE_TEMPLATE, BARE_EVENT_TEMPLATE


class EmptyNetrc(object):
    def __init__(self, file=None):
        self._file = file
    def authenticators(self, hostname):
        return None

class EmptyKeyring(object):
    def get_password(self, *a, **kw):
        return None


@pytest.fixture(autouse=True)
def empty_password_storages(monkeypatch):
    monkeypatch.setattr('netrc.netrc', EmptyNetrc)
    monkeypatch.setattr(utils, 'keyring', EmptyKeyring())


def test_parse_options():
    o = {
        'foo': 'yes',
        'hah': 'true',
        'bar': '',
        'baz': 'whatever',
        'bam': '123',
        'asd': 'off'
    }

    a = dict(utils.parse_options(o.items()))

    expected = {
        'foo': True,
        'hah': True,
        'bar': '',
        'baz': 'whatever',
        'bam': 123,
        'asd': False
    }

    assert a == expected

    for key in a:
        # Yes, we want a very strong typecheck here, because we actually have
        # to differentiate between bool and int, and in Python 2, bool is a
        # subclass of int.
        assert type(a[key]) is type(expected[key])  # flake8: noqa


def test_get_password_from_netrc(monkeypatch):
    username = 'foouser'
    password = '<PASSWORD>'
    resource = 'http://example.com/path/to/whatever/'
    hostname = 'example.com'

    calls = []

    class Netrc(object):
        def authenticators(self, hostname):
            calls.append(hostname)
            return username, 'bogus', password

    monkeypatch.setattr('netrc.netrc', Netrc)
    monkeypatch.setattr('getpass.getpass', blow_up)

    _password = utils.get_password(username, resource)
    assert _password == password
    assert calls == [hostname]


def test_get_password_from_system_keyring(monkeypatch):
    username = 'foouser'
    password = '<PASSWORD>'
    resource = 'http://example.com/path/to/whatever/'
    hostname = 'example.com'

    class KeyringMock(object):
        def get_password(self, resource, _username):
            assert _username == username
            assert resource == utils.password_key_prefix + hostname
            return password

    monkeypatch.setattr(utils, 'keyring', KeyringMock())

    monkeypatch.setattr('getpass.getpass', blow_up)

    _password = utils.get_password(username, resource)
    assert _password == password


def test_get_password_from_prompt():
    getpass_calls = []

    user = 'my_user'
    resource = 'http://example.com'

    @click.command()
    def fake_app():
        x = utils.get_password(user, resource)
        click.echo('Password is {}'.format(x))

    runner = CliRunner()
    result = runner.invoke(fake_app, input='my_password\n\n')
    assert not result.exception
    assert result.output.splitlines() == [
        'Server password for {} at host {}: '.format(user, 'example.com'),
        'Password is <PASSWORD>'
    ]


def test_set_keyring_password(monkeypatch):
    class KeyringMock(object):
        def get_password(self, resource, username):
            assert resource == utils.password_key_prefix + 'example.com'
            assert username == 'foouser'
            return None

        def set_password(self, resource, username, password):
            assert resource == utils.password_key_prefix + 'example.com'
            assert username == 'foouser'
            assert password == '<PASSWORD>'

    monkeypatch.setattr(utils, 'keyring', KeyringMock())

    @doubleclick.click.command()
    @doubleclick.click.pass_context
    def fake_app(ctx):
        ctx.obj = {}
        x = utils.get_password('<PASSWORD>', 'http://example.com/a/b')
        click.echo('password is ' + x)

    runner = CliRunner()
    result = runner.invoke(fake_app, input='hunter2\ny\n')
    assert not result.exception
    assert result.output == (
        'Server password for foouser at host example.com: \n'
        'Save this password in the keyring? [y/N]: y\n'
        'password is <PASSWORD>'
    )


def test_get_password_from_cache(monkeypatch):
    user = 'my_user'
    resource = 'http://example.com'

    @doubleclick.click.command()
    @doubleclick.click.pass_context
    def fake_app(ctx):
        ctx.obj = {}
        x = utils.get_password(user, resource)
        click.echo('Password is {}'.format(x))
        monkeypatch.setattr(doubleclick.click, 'prompt', blow_up)

        assert (user, 'example.com') in ctx.obj['passwords']
        x = utils.get_password(user, resource)
        click.echo('Password is {}'.format(x))

    runner = CliRunner()
    result = runner.invoke(fake_app, input='my_password\n')
    assert not result.exception
    assert result.output.splitlines() == [
        'Server password for {} at host {}: '.format(user, 'example.com'),
        'Save this password in the keyring? [y/N]: ',
{'fraction_non_alphanumeric': 0.12838226827864133, 'fraction_numerical': 0.0026866244482824796, 'mean_word_length': 2.8618006669136715, 'pattern_counts': {'":': 0, '<': 16, '<?xml version=': 0, '>': 16, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '4790378', 'n_tokens_mistral': 3293, 'n_tokens_neox': 3177, 'n_words': 756}