import unittest
import unittest.mock as mock

from connectome.builder import DistributedFileStorer


class MockModel:
    name = "mock_name"


class TestSQLITEPersistence(unittest.TestCase):
    def setUp(self):
        self.persistence = DistributedFileStorer(":memory:")
        self.persistence._connect()
        self.persistence._connect = mock.MagicMock()
        self.persistence._close = mock.MagicMock()

    def tearDown(self):
        self.persistence._connection.close()

    def test_set_retrieve_once(self):
        self.persistence.store(MockModel(), {"data": 123})
        result = self.persistence.fetch_all()
        self.assertEqual("mock_name", result[0]['name'])
        self.assertEqual(1, result[0]['id'])
        self.assertEqual({"data": 123}, result[0]['value'])

    def test_set_retrieve_twice(self):
        self.persistence.store(MockModel(), {"data": 123})
        self.persistence.store(MockModel(), {"data": 123})
        result = self.persistence.fetch_all()

        # first result
        self.assertEqual("mock_name", result[0]['name'])
        self.assertEqual(1, result[0]['id'])
        self.assertEqual({"data": 123}, result[0]['value'])

        # second result
        self.assertEqual("mock_name", result[1]['name'])
        self.assertEqual(2, result[1]['id'])
        self.assertEqual({"data": 123}, result[1]['value'])

    def test_date(self):
        self.persistence.store(MockModel(), {"data": 123})
        result = self.persistence.fetch_all()
        self.assertGreaterEqual(len(result[0]['date']), 4)  # a year has 4 digits


if __name__ == "__main__":
    unittest.main()