Completed
Pull Request — master (#1073)
by Lasse
01:56
created

bears.tests.generate_local_bear_test()   B

Complexity

Conditions 1

Size

Total Lines 35

Duplication

Lines 0
Ratio 0 %
Metric Value
cc 1
dl 0
loc 35
rs 8.8571

3 Methods

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