~christopher-hunt08/maus/maus_integrated_kalman

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
"""
Tests for core configuration (datacards)
"""

import json
import unittest
import os
import sys
import io

from Configuration import Configuration

class ConfigurationTestCase(unittest.TestCase): #pylint: disable = R0904
    """
    Tests for core configuration (datacards)
    """

    @classmethod
    def setUp(cls): # pylint: disable=C0103
        """Move system args out of the way"""
        cls.temp_argv = sys.argv
        sys.argv = [""]

    @classmethod
    def tearDown(cls): # pylint: disable=C0103
        """Put system args back"""
        sys.argv = cls.temp_argv

    def test_defaults(self):
        """Check that we load configuration defaults correctly"""
        a_config = Configuration()
        maus_config = json.loads(a_config.getConfigJSON())

        ## test setup
        maus_root_dir = os.environ.get('MAUS_ROOT_DIR')
        self.assertNotEqual(maus_root_dir,  None)

        config_dict = {}
        default_filename = \
                    '%s/src/common_py/ConfigurationDefaults.py' % maus_root_dir
        exec(open(default_filename,'r').read(), globals(), #pylint:disable=W0122
                                              config_dict) #pylint:disable=W0122

        # compare; note we are allowed additional entries in maus_config that
        # are hard coded (e.g. version number)
        exclusions = [
          "maus_version", # changed at runtime, tested below 
          "reconstruction_geometry_filename", # changed at runtime, tested below
          "os", # module needed to use environment variables
          "__doc__", # docstring from ConfigurationDefaults
        ]
        for key in config_dict.keys():
            if key not in exclusions:
                self.assertEqual(config_dict[key], maus_config[key])

    def test_version(self):
        """Check that the version is defined correctly"""
        config = json.loads(Configuration().getConfigJSON())
        words = config['maus_version'].split()
        self.assertEqual(words[0], 'MAUS')
        assert words[1] == 'development' or words[1] == 'release'
        self.assertEqual(words[2], 'version')
        numbers = words[-1].split('.')
        self.assertEqual(len(numbers), 3)
        for num in numbers:
            int(num) # should be able to convert to number

    def test_recon_filename(self):
        """Check that the version is defined correctly"""
        # default should have them equal if reconstruction_geometry_filename is
        # empty string
        config = json.loads(Configuration().getConfigJSON())
        string_file = io.StringIO\
                       (u"reconstruction_geometry_filename = ''\n"+\
                        u"simulation_geometry_filename = 'Test.dat'\n")
        self.assertEqual(config['simulation_geometry_filename'], 
                         config['reconstruction_geometry_filename'])

        # else should be different
        string_file = io.StringIO\
                       (u"reconstruction_geometry_filename = 'Test.dat'")
        conf = Configuration()
        value = json.loads(conf.getConfigJSON(string_file))
        self.assertEqual(value['reconstruction_geometry_filename'], 'Test.dat')
        

    def test_new_value(self):
        """Test that we can create a configuration value from an input file"""
        string_file = io.StringIO(u"test = 4")
        config = Configuration()
        value = config.getConfigJSON(string_file)

        json_value = json.loads(value)
        self.assertEqual(json_value["test"], 4)

    def test_overwrite_value(self):
        """Test that we can overwrite configuration value from an input file"""
        string_file = io.StringIO\
                       (u"simulation_geometry_filename = 'Stage4Something.dat'")
        conf = Configuration()
        value = conf.getConfigJSON(string_file)

        json_value = json.loads(value)
        self.assertEqual(json_value["simulation_geometry_filename"],
                         'Stage4Something.dat')

    def test_string_to_bool(self):
        """Test conversion from string to boolean type"""
        for a_string in ["tRue", "t", "Y", "1", "yEs"]:
            self.assertTrue(Configuration().string_to_bool(a_string))
        for a_string in ["faLse", "f", "N", "0", "nO"]:
            self.assertFalse(Configuration().string_to_bool(a_string))
        self.assertRaises(ValueError, Configuration().string_to_bool, "bob")
        self.assertRaises(TypeError, Configuration().string_to_bool, 0)

    def test_command_line_args_str(self):
        """Test parsing string from command line to configuration"""
        sys.argv = ["", "-input_string", "test_in"]
        test_out = Configuration().command_line_arguments({
                                                      "input_string":""})
        self.assertEqual(test_out["input_string"], "test_in")


    def test_command_line_args_number(self):
        """Test parsing number from command line to configuration"""
        sys.argv = ["", "-input_int", "10"] # int as int okay
        test_out = Configuration().command_line_arguments({
                                                      "input_int":0})
        self.assertEqual(test_out["input_int"], 10)

        sys.argv = ["", "-input_float", "10.1"] # float as int -> error
        self.assertRaises(ValueError, Configuration().command_line_arguments, {
                                                      "input_float":0}) # int

        sys.argv = ["", "-input_float", "10"] # int as float -> float
        test_out = Configuration().command_line_arguments({
                                                      "input_float":0.})
        self.assertEqual(type(test_out["input_float"]), type(10.))
        self.assertAlmostEqual(test_out["input_float"], float(10))

        sys.argv = ["", "-input_float", "10."]# float as float -> float
        test_out = Configuration().command_line_arguments({
                                                      "input_float":0.})
        self.assertAlmostEqual(test_out["input_float"], 10.)

    def test_command_line_args_bool(self):
        """Test parsing bool from command line to configuration"""
        sys.argv = ["", "-input_bool", "yEs"]
        test_out = Configuration().command_line_arguments({
                                                      "input_bool":True})
        self.assertEqual(test_out["input_bool"], True)

        sys.argv = ["", "-input_bool", "bob"] 
        self.assertRaises(ValueError, Configuration().command_line_arguments, 
                                                           {"input_bool":True})

    def test_command_line_args_dict(self):
        """Test parsing bool from command line to configuration"""
        sys.argv = ["", "-input_dict", "{}"]
        self.assertRaises(NotImplementedError, 
                      Configuration().command_line_arguments, {"input_dict":{}})

        sys.argv = ["", "-input_list", "[]"]
        self.assertRaises(NotImplementedError,
                      Configuration().command_line_arguments, {"input_list":[]})

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