import json
import unittest

import numpy as np

from connectome.function import TestResult, GreaterThan
from util.universal_json import UniversalJSONEncoder


class TestUniversalJSONEncoder(unittest.TestCase):
    def test_deconde_encode_test_result(self):
        obj = TestResult("criterion_name", GreaterThan(.4), np.asarray(.2), False)
        dct = json.loads(json.dumps(obj, cls=UniversalJSONEncoder))
        self.assertEqual(dct["score"], .2)

    def test_encode_numpy_scalar(self):
        obj = np.asarray(.2)
        json.dumps(obj, cls=UniversalJSONEncoder)

    def test_encode_numpy_arr_1d(self):
        arr = np.array([1,2,3])
        arr_decoded = json.loads(json.dumps(arr, cls=UniversalJSONEncoder))
        self.assertEqual([1,2,3], arr_decoded)

    def test_encode_numpy_arr_2d(self):
        arr = np.array([[1,2],
                        [3,4]])
        arr_decoded = json.loads(json.dumps(arr, cls=UniversalJSONEncoder))
        expected = [[1,2],
                    [3,4]]
        for expected_row, actual_row in zip(expected, arr_decoded):
            self.assertEqual(expected_row, actual_row)


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