Completed
Pull Request — master (#1156)
by Mischa
02:21 queued 27s
created

coalib.tests.settings.make_temp()   A

Complexity

Conditions 1

Size

Total Lines 13

Duplication

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