"""
@package tests.test_database
unit tests for pmsco.database

the purpose of these tests is to help debugging the code.

to run the tests, change to the directory which contains the tests directory, and execute =nosetests=.

@pre nose must be installed (python-nose package on Debian).

@author Matthias Muntwiler, matthias.muntwiler@psi.ch

@copyright (c) 2016 by Paul Scherrer Institut @n
Licensed under the Apache License, Version 2.0 (the "License"); @n
  you may not use this file except in compliance with the License.
  You may obtain a copy of the License at
  http://www.apache.org/licenses/LICENSE-2.0
"""

import numpy as np
import unittest
import pmsco.database.util as util
import pmsco.dispatch as dispatch


class TestDatabase(unittest.TestCase):
    def setUp(self):
        pass

    def tearDown(self):
        pass

    @classmethod
    def setup_class(cls):
        # before any methods in this class
        pass

    @classmethod
    def teardown_class(cls):
        # teardown_class() after any methods in this class
        pass

    def test_regular_params(self):
        d1 = {'parA': 1.234, 'par_B': 5.678, '_model': 91, '_rfac': 0.534}
        d2 = util.regular_params(d1)
        d3 = {'parA': d1['parA'], 'par_B': d1['par_B']}
        self.assertEqual(d2, d3)
        self.assertIsNot(d2, d1)

    def test_special_params(self):
        d1 = {'parA': 1.234, 'par_B': 5.678, '_model': 91, '_rfac': 0.534, '_db_model_id': 99}
        d2 = util.special_params(d1)
        d3 = {'model': d1['_model'], 'rfac': d1['_rfac']}
        self.assertEqual(d2, d3)
        self.assertIsNot(d2, d1)

        dt = [('parA', 'f4'), ('par_B', 'f4'), ('_model', 'i4'), ('_rfac', 'f4'), ('_db_model_id', 'f4')]
        arr = np.zeros(1, dtype=dt)
        for k, v in d1.items():
            arr[0][k] = v
        d4 = util.special_params(arr[0])
        self.assertEqual(d4.keys(), d3.keys())
        for k in d4:
            self.assertAlmostEqual(d4[k], d3[k])

        cid1 = dispatch.CalcID(1, 2, 3, 4, -1)
        cid2 = util.special_params(cid1)
        cid3 = {'model': 1, 'scan': 2, 'domain': 3, 'emit': 4, 'region': -1}
        self.assertEqual(cid2, cid3)

        l1 = d1.keys()
        l2 = util.special_params(l1)
        l3 = d3.keys()
        self.assertEqual(list(l2), list(l3))

        t1 = tuple(l1)
        t2 = util.special_params(t1)
        t3 = tuple(l3)
        self.assertEqual(t2, t3)


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