Completed
Pull Request — master (#1189)
by Lasse
02:32
created

bears.tests.LocalBearTest.test_invalid_files()   A

Complexity

Conditions 2

Size

Total Lines 3

Duplication

Lines 0
Ratio 0 %
Metric Value
cc 2
dl 0
loc 3
rs 10
1
from queue import Queue
2
import unittest
3
4
from coalib.bears.LocalBear import LocalBear
5
from coalib.settings.Section import Section
6
from coalib.settings.Setting import Setting
7
from bears.tests.BearTestHelper import generate_skip_decorator
8
9
10
class LocalBearTestHelper(unittest.TestCase):  # pragma: no cover
11
    """
12
    This is a helper class for simplification of testing of local bears.
13
14
    Please note that all abstraction will prepare the lines so you don't need
15
    to do that if you use them.
16
17
    If you miss some methods, get in contact with us, we'll be happy to help!
18
    """
19
    @staticmethod
20
    def prepare_lines(lines):
21
        """
22
        Adds a trailing newline to each line if needed. This is needed since
23
        the bears expect every line to have such a newline at the end.
24
25
        This function does not modify the given argument in-place, it returns
26
        a modified copy instead.
27
28
        :param lines: The lines to be prepared. This list will be altered so
29
                      you don't have to use the return value.
30
        :return:      The lines with a \n appended.
31
        """
32
        modified_lines = []
33
        for line in lines:
34
            modified_lines.append(line if line.endswith("\n") else line+"\n")
35
36
        return modified_lines
37
38
    def assertLinesValid(self,
39
                         local_bear,
40
                         lines,
41
                         filename="default",
42
                         prepare_lines=True):
43
        """
44
        Asserts that a check of the given lines with the given local bear does
45
        not yield any results.
46
47
        :param local_bear:    The local bear to check with.
48
        :param lines:         The lines to check. (List of strings)
49
        :param filename:      The filename, if it matters.
50
        :param prepare_lines: Whether to append newlines at each line if
51
                              needed. Use this with caution when disabling,
52
                              since bears expect to have a \n at the end of
53
                              each line.
54
        """
55
        assert isinstance(self, unittest.TestCase)
56
        self.assertIsInstance(local_bear,
57
                              LocalBear,
58
                              msg="The given bear is no local bear.")
59
        self.assertIsInstance(lines,
60
                              list,
61
                              msg="The given lines are not a list.")
62
63
        if prepare_lines:
64
            lines = LocalBearTestHelper.prepare_lines(lines)
65
66
        self.assertEqual(
67
            list(local_bear.execute(filename, lines)),
68
            [],
69
            msg="The local bear '{}' yields a result although it "
70
                "shouldn't.".format(local_bear.__class__.__name__))
71
72
    def assertLineValid(self,
73
                        local_bear,
74
                        line,
75
                        filename="default",
76
                        prepare_lines=True):
77
        """
78
        Asserts that a check of the given lines with the given local bear does
79
        not yield any results.
80
81
        :param local_bear:    The local bear to check with.
82
        :param line:          The lines to check. (List of strings)
83
        :param filename:      The filename, if it matters.
84
        :param prepare_lines: Whether to append newlines at each line if
85
                              needed. Use this with caution when disabling,
86
                              since bears expect to have a \n at the end of
87
                              each line.
88
        """
89
        self.assertLinesValid(local_bear, [line], filename, prepare_lines)
90
91
    def assertLinesInvalid(self,
92
                           local_bear,
93
                           lines,
94
                           filename="default",
95
                           prepare_lines=True):
96
        """
97
        Asserts that a check of the given lines with the given local bear does
98
        yield any results.
99
100
        :param local_bear:    The local bear to check with.
101
        :param lines:         The lines to check. (List of strings)
102
        :param filename:      The filename, if it matters.
103
        :param prepare_lines: Whether to append newlines at each line if
104
                              needed. Use this with caution when disabling,
105
                              since bears expect to have a \n at the end of
106
                              each line.
107
        """
108
        assert isinstance(self, unittest.TestCase)
109
        self.assertIsInstance(local_bear,
110
                              LocalBear,
111
                              msg="The given bear is no local bear.")
112
        self.assertIsInstance(lines,
113
                              list,
114
                              msg="The given lines are not a list.")
115
116
        if prepare_lines:
117
            lines = LocalBearTestHelper.prepare_lines(lines)
118
119
        self.assertNotEqual(
120
            len(list(local_bear.execute(filename, lines))),
121
            0,
122
            msg="The local bear '{}' yields no result although it "
123
                "should.".format(local_bear.__class__.__name__))
124
125
    def assertLineInvalid(self,
126
                          local_bear,
127
                          line,
128
                          filename="default",
129
                          prepare_lines=True):
130
        """
131
        Asserts that a check of the given lines with the given local bear does
132
        yield any results.
133
134
        :param self:          The unittest.TestCase object for assertions.
135
        :param local_bear:    The local bear to check with.
136
        :param line:          The lines to check. (List of strings)
137
        :param filename:      The filename, if it matters.
138
        :param prepare_lines: Whether to append newlines at each line if
139
                              needed. Use this with caution when disabling,
140
                              since bears expect to have a \n at the end of
141
                              each line.
142
        """
143
        self.assertLinesInvalid(local_bear, [line], filename, prepare_lines)
144
145
    def assertLinesYieldResults(self,
146
                                local_bear,
147
                                lines,
148
                                results,
149
                                filename="default",
150
                                check_order=False):
151
        """
152
        Asserts that a check of the given lines with the given local bear does
153
        yield exactly the given results.
154
155
        :param local_bear:  The local bear to check with.
156
        :param lines:       The lines to check. (List of strings)
157
        :param results:     The expected results.
158
        :param filename:    The filename, if it matters.
159
        :param check_order: Assert also that the results are in the same order
160
                            (defaults to False)
161
        """
162
        assert isinstance(self, unittest.TestCase)
163
        self.assertIsInstance(local_bear,
164
                              LocalBear,
165
                              msg="The given bear is no local bear.")
166
        self.assertIsInstance(lines,
167
                              list,
168
                              msg="The given lines are not a list.")
169
        self.assertIsInstance(results,
170
                              list,
171
                              msg="The given results are not a list.")
172
173
        if not check_order:
174
            self.assertEqual(
175
                sorted(local_bear.execute(
176
                    filename,
177
                    LocalBearTestHelper.prepare_lines(lines))),
178
                sorted(results),
179
                msg="The local bear '{}' yields not the right results or the "
180
                    "order may be wrong.".format(
181
                    local_bear.__class__.__name__))
182
        else:
183
            self.assertEqual(
184
                list(local_bear.execute(
185
                    filename,
186
                    LocalBearTestHelper.prepare_lines(lines))),
187
                results,
188
                msg="The local bear '{}' yields not the right results or the "
189
                    "order may be wrong.".format(
190
                    local_bear.__class__.__name__))
191
192
    def assertLineYieldsResults(self,
193
                                local_bear,
194
                                line,
195
                                results,
196
                                filename="default",
197
                                check_order=False):
198
        """
199
        Asserts that a check of the given line with the given local bear does
200
        yield exactly the given results.
201
202
        :param local_bear:  The local bear to check with.
203
        :param line:        The line to check. (String)
204
        :param results:     The expected results.
205
        :param filename:    The filename, if it matters.
206
        :param check_order: Assert also that the results are in the same order
207
                            (defaults to False)
208
        """
209
        self.assertLinesYieldResults(local_bear,
210
                                     [line],
211
                                     results,
212
                                     filename,
213
                                     check_order)
214
215
    def assertLineYieldsResult(self,
216
                               local_bear,
217
                               line,
218
                               result,
219
                               filename="default"):
220
        """
221
        Asserts that a check of the given line with the given local bear does
222
        yield the given result.
223
224
        :param local_bear: The local bear to check with.
225
        :param line:       The line to check. (String)
226
        :param result:     The expected result.
227
        :param filename:   The filename, if it matters.
228
        """
229
        self.assertLinesYieldResults(local_bear,
230
                                     [line],
231
                                     [result],
232
                                     filename,
233
                                     False)
234
235
    def assertLinesYieldResult(self,
236
                               local_bear,
237
                               lines,
238
                               result,
239
                               filename="default"):
240
        """
241
        Asserts that a check of the given lines with the given local bear does
242
        yield exactly the given result.
243
244
        :param local_bear: The local bear to check with.
245
        :param lines:      The lines to check. (String)
246
        :param result:     The expected result.
247
        :param filename:   The filename, if it matters.
248
        """
249
        self.assertLinesYieldResults(local_bear,
250
                                     lines,
251
                                     [result],
252
                                     filename,
253
                                     False)
254
255
256
def verify_local_bear(bear,
257
                      valid_files,
258
                      invalid_files,
259
                      filename='default',
260
                      settings={}):
261
    """
262
    Generates a test for a local bear by checking the given valid and invalid
263
    file contents. Simply use it on your module level like:
264
265
    YourTestName = verify_local_bear(YourBear, (['valid line'],),
266
                                     (['invalid line'],))
267
268
    :param bear:          The Bear class to test.
269
    :param valid_files:   An iterable of files as a string list that won't
270
                          yield results.
271
    :param invalid_files: An iterable of files as a string list that must
272
                          yield results.
273
    :param filename:      The filename to use for valid and invalid files.
274
    :param settings:      A dictionary of keys and values (both string) from
275
                          which settings will be created that will be made
276
                          available for the tested bear.
277
    :return:              A unittest.TestCase object.
278
    """
279
    @generate_skip_decorator(bear)
280
    class LocalBearTest(LocalBearTestHelper):
281
        def setUp(self):
282
            self.section = Section('name')
283
            self.uut = bear(self.section, Queue())
284
            for name, value in settings.items():
285
                self.section.append(Setting(name, value))
286
287
        def test_valid_files(self):
288
            for file in valid_files:
289
                self.assertLinesValid(self.uut, file, filename=filename)
290
291
        def test_invalid_files(self):
292
            for file in invalid_files:
293
                self.assertLinesInvalid(self.uut, file, filename=filename)
294
295
    return LocalBearTest
296