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