Completed
Pull Request — master (#1156)
by Mischa
01:41
created

test_nonexistent_file()   B

Complexity

Conditions 5

Size

Total Lines 14

Duplication

Lines 0
Ratio 0 %
Metric Value
cc 5
dl 0
loc 14
rs 8.5455
1
import os
2
import sys
3
import re
4
import tempfile
5
import unittest
6
from contextlib import contextmanager
7
from pyprint.NullPrinter import NullPrinter
8
from pyprint.ClosableObject import close_objects
9
10
sys.path.insert(0, ".")
11
from coalib.misc.Constants import Constants
12
from coalib.settings.ConfigurationGathering import (gather_configuration,
13
                                                    find_user_config)
14
from coalib.output.printers.LogPrinter import LogPrinter
15
16
17
class ConfigurationGatheringTest(unittest.TestCase):
18
    def setUp(self):
19
        self.log_printer = LogPrinter(NullPrinter())
20
21
    def tearDown(self):
22
        close_objects(self.log_printer)
23
24
    @staticmethod
25
    @contextmanager
26
    def make_temp():
27
        """
28
        Creates a temporary file with a closed stream.
29
30
        :return: A contextmanager retrieving the file path.
31
        """
32
        temporary = tempfile.mkstemp()
33
        os.close(temporary[0])
34
        try:
35
            yield temporary[1]
36
        finally:
37
            os.remove(temporary[1])
38
39
    def test_gather_configuration(self):
40
        args = (lambda *args: True, self.log_printer)
41
42
        # Passing the default coafile name only triggers a warning.
43
        gather_configuration(*args, arg_list=["-c abcdefghi/invalid/.coafile"])
44
45
        # Using a bad filename explicitly exits coala.
46
        with self.assertRaises(SystemExit):
47
            gather_configuration(
48
                *args,
49
                arg_list=["-S", "test=5", "-c", "some_bad_filename"])
50
51
        with ConfigurationGatheringTest.make_temp() as temporary:
52
            sections, local_bears, global_bears, targets = (
53
                gather_configuration(
54
                    *args,
55
                    arg_list=["-S", "test=5", "-c", temporary, "-s"]))
56
57
        self.assertEqual(str(sections["default"]),
58
                         "Default {config : " + repr(temporary) + ", save : "
59
                             "'True', test : '5'}")
60
61
        with ConfigurationGatheringTest.make_temp() as temporary:
62
            sections, local_bears, global_bears, targets = (
63
                gather_configuration(*args,
64
                                     arg_list=["-S test=5",
65
                                               "-c " + temporary,
66
                                               "-b LineCountBear -s"]))
67
68
        self.assertEqual(len(local_bears["default"]), 0)
69
70
    def test_default_coafile_parsing(self):
71
        tmp = Constants.system_coafile
72
73
        Constants.system_coafile = os.path.abspath(os.path.join(
74
            os.path.dirname(os.path.realpath(__file__)),
75
            "section_manager_test_files",
76
            "default_coafile"))
77
78
        sections, local_bears, global_bears, targets = gather_configuration(
79
            lambda *args: True,
80
            self.log_printer)
81
82
        self.assertEqual(str(sections["test"]),
83
                         "test {value : '1', testval : '5'}")
84
85
        Constants.system_coafile = tmp
86
87
    def test_user_coafile_parsing(self):
88
        tmp = Constants.user_coafile
89
90
        Constants.user_coafile = os.path.abspath(os.path.join(
91
            os.path.dirname(os.path.realpath(__file__)),
92
            "section_manager_test_files",
93
            "default_coafile"))
94
95
        sections, local_bears, global_bears, targets = gather_configuration(
96
            lambda *args: True,
97
            self.log_printer)
98
99
        self.assertEqual(str(sections["test"]),
100
                         "test {value : '1', testval : '5'}")
101
102
        Constants.user_coafile = tmp
103
104
    def test_nonexistent_file(self):
105
        filename = "bad.one/test\neven with bad chars in it"
106
        with self.assertRaises(SystemExit):
107
            gather_configuration(lambda *args: True,
108
                                 self.log_printer,
109
                                 arg_list=['-S', "config=" + filename])
110
111
        tmp = Constants.system_coafile
112
        Constants.system_coafile = filename
113
114
        with self.assertRaises(SystemExit):
115
            gather_configuration(lambda *args: True, self.log_printer)
116
117
        Constants.system_coafile = tmp
118
119
    def test_merge(self):
120
        tmp = Constants.system_coafile
121
        Constants.system_coafile = os.path.abspath(os.path.join(
122
            os.path.dirname(os.path.realpath(__file__)),
123
            "section_manager_test_files",
124
            "default_coafile"))
125
126
        config = os.path.abspath(os.path.join(
127
            os.path.dirname(os.path.realpath(__file__)),
128
            "section_manager_test_files",
129
            ".coafile"))
130
131
        # Check merging of default_coafile and .coafile
132
        sections, local_bears, global_bears, targets = gather_configuration(
133
            lambda *args: True,
134
            self.log_printer,
135
            arg_list=["-c", re.escape(config)])
136
137
        self.assertEqual(str(sections["test"]),
138
                         "test {value : '2'}")
139
        self.assertEqual(str(sections["test-2"]),
140
                         "test-2 {files : '.', bears : 'LineCountBear'}")
141
142
        # Check merging of default_coafile, .coafile and cli
143
        sections, local_bears, global_bears, targets = gather_configuration(
144
            lambda *args: True,
145
            self.log_printer,
146
            arg_list=["-c",
147
                      re.escape(config),
148
                      "-S",
149
                      "test.value=3",
150
                      "test-2.bears=",
151
                      "test-5.bears=TestBear2"])
152
153
        self.assertEqual(str(sections["test"]), "test {value : '3'}")
154
        self.assertEqual(str(sections["test-2"]),
155
                         "test-2 {files : '.', bears : ''}")
156
        self.assertEqual(str(sections["test-3"]),
157
                         "test-3 {files : 'MakeFile'}")
158
        self.assertEqual(str(sections["test-4"]),
159
                         "test-4 {bears : 'TestBear'}")
160
        self.assertEqual(str(sections["test-5"]),
161
                         "test-5 {bears : 'TestBear2'}")
162
163
        Constants.system_coafile = tmp
164
165
    def test_merge_defaults(self):
166
        with ConfigurationGatheringTest.make_temp() as temporary:
167
            sections, local_bears, global_bears, targets = (
168
                gather_configuration(lambda *args: True,
169
                                     self.log_printer,
170
                                     arg_list=["-S",
171
                                               "value=1",
172
                                               "test.value=2",
173
                                               "-c",
174
                                               temporary]))
175
176
        self.assertEqual(sections["default"],
177
                         sections["test"].defaults)
178
179
    def test_back_saving(self):
180
        filename = os.path.join(tempfile.gettempdir(),
181
                                "SectionManagerTestFile")
182
183
        # We need to use a bad filename or this will parse coalas .coafile
184
        gather_configuration(
185
            lambda *args: True,
186
            self.log_printer,
187
            arg_list=['-S',
188
                      "save=" + re.escape(filename),
189
                      "-c=some_bad_filename"])
190
191
        with open(filename, "r") as f:
192
            lines = f.readlines()
193
        self.assertEqual(["[Default]\n", "config = some_bad_filename\n"],
194
                         lines)
195
196
        gather_configuration(
197
            lambda *args: True,
198
            self.log_printer,
199
            arg_list=['-S',
200
                      "save=true",
201
                      "config=" + re.escape(filename),
202
                      "test.value=5"])
203
204
        with open(filename, "r") as f:
205
            lines = f.readlines()
206
        os.remove(filename)
207
        self.assertEqual(["[Default]\n",
208
                          "config = " + filename + "\n",
209
                          "\n",
210
                          "[test]\n",
211
                          "value = 5\n"], lines)
212
213
    def test_targets(self):
214
        sections, local_bears, global_bears, targets = gather_configuration(
215
            lambda *args: True,
216
            self.log_printer,
217
            arg_list=["default", "test1", "test2"])
218
219
        self.assertEqual(targets, ["default", "test1", "test2"])
220
221
    def test_find_user_config(self):
222
        current_dir = os.path.abspath(os.path.dirname(__file__))
223
        c_file = os.path.join(current_dir,
224
                              "section_manager_test_files",
225
                              "project",
226
                              "test.c")
227
228
        retval = find_user_config(c_file, 1)
229
        self.assertEqual("", retval)
230
231
        retval = find_user_config(c_file, 2)
232
        self.assertEqual(os.path.join(current_dir,
233
                                      "section_manager_test_files",
234
                                      ".coafile"), retval)
235
236
        # Using a bad filename explicitly exits coala.
237
        with self.assertRaises(SystemExit):
238
            sections, dummy, dummy, dummy = gather_configuration(
239
                lambda *args: True,
240
                self.log_printer,
241
                arg_list=["--find-config", "-c", "some_bad_filename"])
242
243
        sections, dummy, dummy, dummy = gather_configuration(
244
            lambda *args: True,
245
            self.log_printer,
246
            arg_list=["--find-config"])
247
248
        self.assertRegex(str(sections["default"]),
249
                         ".*find_config : 'True'.*, config : '.*'")
250
251
252
if __name__ == '__main__':
253
    unittest.main(verbosity=2)
254