"""
Test database code for handling the retrieval and storage of journal entries.

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

from pycouchdb import exceptions
import pytest

from rookeries import database


@pytest.fixture
def test_config():
    return {
        database.COUCHDB_SERVER_CONNECTION: 'http://test.server.net:1234/',
        database.COUCHDB_DATABASE: 'test_db',
    }


def test_gets_database_connection_if_database_exists(mocker, test_config):
    mock_server_cls = mocker.patch('pycouchdb.Server', autospec=True)
    mock_server = mock_server_cls.return_value

    actual_db = database.create_or_get_database(test_config)

    mock_server_cls.assert_called_with(test_config[database.COUCHDB_SERVER_CONNECTION])
    mock_server.database.assert_called_with(test_config[database.COUCHDB_DATABASE])
    assert actual_db == mock_server.database.return_value


def test_creates_database_connection_if_database_does_not_exist(mocker, test_config):
    mock_server_cls = mocker.patch('pycouchdb.Server', autospec=True)
    mock_server = mock_server_cls.return_value
    mock_server.database.side_effect = exceptions.NotFound

    actual_db = database.create_or_get_database(test_config)

    mock_server_cls.assert_called_with(test_config[database.COUCHDB_SERVER_CONNECTION])
    mock_server.create.assert_called_with(test_config[database.COUCHDB_DATABASE])
    assert actual_db == mock_server.create.return_value


def test_creates_database_connection_fails_if_database_server_not_found(mocker, test_config):
    mock_server_cls = mocker.patch('pycouchdb.Server', autospec=True)
    mock_server_cls.side_effect = RuntimeError

    with pytest.raises(RuntimeError):
        database.create_or_get_database(test_config)

    mock_server_cls.assert_called_with(test_config[database.COUCHDB_SERVER_CONNECTION])
