import pytest
import copy

from blitzdb import Document
import six

@pytest.fixture(scope="function")
def mockup_backend():

    class Backend(object):  

        def __init__(self):
            self.attributes = {'foo': 'bar', 'baz': 123}

        def get(self, DocumentClass, pk):
            return DocumentClass(copy.deepcopy(self.attributes))

    return Backend()

def test_unicode():

    doc = Document({'pk' : 'foo'})
    if six.PY2:
        assert unicode(str(doc)) == unicode(doc)
    else:
        assert doc.__unicode__ == doc.__str__

def test_basic_attributes():

    attributes = {'foo': 'bar', 'baz': 1243, 'd': {1: 3, 4: 5}, 'l': [1, 2, 3, 4]}

    doc = Document(attributes)

    assert doc.foo == 'bar'
    assert doc.baz == 1243
    assert doc.d == {1: 3, 4: 5}
    assert doc.l == [1, 2, 3, 4]
    assert doc.foo == doc['foo']
    assert doc.baz == doc['baz']
    assert doc.d == doc['d']

    assert doc.attributes == attributes

def test_iteration():

    attributes = {'foo': 'bar', 'baz': 1243, 'd': {1: 3, 4: 5}, 'l': [1, 2, 3, 4]}

    doc = Document(attributes)

    for key in doc:
        assert key in attributes

    for key,value in doc.items():
        assert key in attributes
        assert attributes[key] == value

    for value in doc.values():
        assert value in attributes.values()


def test_attribute_deletion():

    attributes = {'foo': 'bar', 'baz': 1243, 'd': {1: 3, 4: 5}, 'l': [1, 2, 3, 4]}

    doc = Document(attributes)

    del doc.foo

    with pytest.raises(AttributeError):
        doc.foo

    with pytest.raises(KeyError):
        doc['foo']

    with pytest.raises(KeyError):
        del doc['foo']