import numpy
import scipy.sparse

from django.test import SimpleTestCase

from matrixstore.serializer import serialize, serialize_compressed, deserialize


class TestSerializer(SimpleTestCase):

    def test_simple_serialisation(self):
        obj = {'hello': 123}
        self.assertEqual(deserialize(serialize(obj)), obj)

    def test_simple_serialisation_with_compression(self):
        obj = {'hello': 'world' * 256}
        data = serialize(obj)
        compressed_data = serialize_compressed(obj)
        self.assertLess(len(compressed_data), len(data))
        self.assertEqual(deserialize(compressed_data), obj)

    def test_matrix_serialisation(self):
        obj = scipy.sparse.csc_matrix((5, 4))
        new_obj = deserialize(serialize(obj))
        self.assertTrue(numpy.array_equal(obj.todense(), new_obj.todense()))

    def test_dtype_is_preserved(self):
        obj = scipy.sparse.csc_matrix((5, 4), dtype=numpy.uint16)
        new_obj = deserialize(serialize(obj))
        self.assertEqual(obj.dtype, new_obj.dtype)

@@ -1,12 +1,28 @@
+import sqlite3%0A%0A
 import numpy
@@ -1044,8 +1044,833 @@
 .dtype)%0A
+%0A    def test_sqlite_roundtrip(self):%0A        obj = %7B'hello': 123%7D%0A        data = serialize(obj)%0A        new_data = roundtrip_through_sqlite(sqlite3.Binary(data))%0A        new_obj = deserialize(new_data)%0A        self.assertEqual(new_obj, obj)%0A%0A    def test_sqlite_roundtrip_with_compression(self):%0A        obj = %7B'hello': 'world' * 256%7D%0A        data = serialize_compressed(obj)%0A        new_data = roundtrip_through_sqlite(sqlite3.Binary(data))%0A        new_obj = deserialize(new_data)%0A        self.assertEqual(new_obj, obj)%0A%0A%0Adef roundtrip_through_sqlite(value):%0A    db = sqlite3.connect(':memory:')%0A    db.execute('CREATE TABLE data (value BLOB)')%0A    db.execute('INSERT INTO data VALUES (?)', %5Bvalue%5D)%0A    result = db.execute('SELECT value FROM data')%0A    new_value = result.fetchone()%5B0%5D%0A    db.close()%0A    return new_value%0A

Test that serialized objects safely roundtrip through SQLite