Completed
Pull Request — master (#1569)
by Lasse
01:37
created

test_find_user_config()   B

Complexity

Conditions 2

Size

Total Lines 34

Duplication

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