Completed
Pull Request — master (#1431)
by Abdeali
01:38
created

bears.tests.LocalBearTestHelper.check_validity()   B

Complexity

Conditions 5

Size

Total Lines 44

Duplication

Lines 0
Ratio 0 %
Metric Value
cc 5
dl 0
loc 44
rs 8.0894
1
import queue
2
import unittest
3
4
from coalib.bears.LocalBear import LocalBear
5
from coalib.misc.ContextManagers import prepare_file
6
from coalib.results.Result import Result
7
from coalib.settings.Section import Section
8
from coalib.settings.Setting import Setting
9
from bears.tests.BearTestHelper import generate_skip_decorator
10
11
12
def execute_bear(bear, *args, **kwargs):
13
    try:
14
        bear_output_generator = bear.execute(*args, **kwargs)
15
        assert bear_output_generator is not None
16
    except AssertionError:
17
        msg = []
18
        while not bear.message_queue.empty():
19
            msg.append(bear.message_queue.get().message)
20
        raise AssertionError("Bear returned None on execution \n" +
21
                             "\n".join(msg))
22
    return list(bear_output_generator)
23
24
25
class LocalBearTestHelper(unittest.TestCase):  # pragma: no cover
26
    """
27
    This is a helper class for simplification of testing of local bears.
28
29
    Please note that all abstraction will prepare the lines so you don't need
30
    to do that if you use them.
31
32
    If you miss some methods, get in contact with us, we'll be happy to help!
33
    """
34
35
    def check_validity(self,
36
                       local_bear,
37
                       lines,
38
                       filename=None,
39
                       valid=True,
40
                       force_linebreaks=True,
41
                       create_tempfile=True):
42
        """
43
        Asserts that a check of the given lines with the given local bear
44
        either yields or does not yield any results.
45
46
        :param local_bear:       The local bear to check with.
47
        :param lines:            The lines to check. (string if single line
48
                                                      or List of strings)
49
        :param filename:         The filename, if it matters.
50
        :param valid:            Whether the lines are valid or not.
51
        :param force_linebreaks: Whether to append newlines at each line
52
                                 if needed. (Bears expect a \\n for every line)
53
        :param create_tempfile:  Whether to save lines in tempfile if needed.
54
        """
55
        print(lines)
56
        if isinstance(lines, str):
57
            lines = [lines]
58
59
        assert isinstance(self, unittest.TestCase)
60
        self.assertIsInstance(local_bear,
61
                              LocalBear,
62
                              msg="The given bear is not a local bear.")
63
        self.assertIsInstance(lines,
64
                              list,
65
                              msg="The given lines are not a list.")
66
67
        with prepare_file(lines, filename, force_linebreaks, create_tempfile) \
68
                as (lines, filename):
69
70
            bear_output = execute_bear(local_bear, filename, lines)
71
            if valid:
72
                msg = ("The local bear '{}' yields a result although it "
73
                       "shouldn't.".format(local_bear.__class__.__name__))
74
                self.assertEqual(bear_output, [], msg=msg)
75
            else:
76
                msg = ("The local bear '{}' yields no result although it "
77
                       "should.".format(local_bear.__class__.__name__))
78
                self.assertNotEqual(len(bear_output), 0, msg=msg)
79
80
    def check_results(self,
81
                      local_bear,
82
                      lines,
83
                      results,
84
                      filename=None,
85
                      check_order=False,
86
                      force_linebreaks=True,
87
                      create_tempfile=True):
88
        """
89
        Asserts that a check of the given lines with the given local bear does
90
        yield exactly the given results.
91
92
        :param local_bear:       The local bear to check with.
93
        :param lines:            The lines to check. (string if single line
94
                                                      or List of strings)
95
        :param results:          The expected result or list of results.
96
        :param filename:         The filename, if it matters.
97
        :param force_linebreaks: Whether to append newlines at each line
98
                                 if needed. (Bears expect a \\n for every line)
99
        :param create_tempfile:  Whether to save lines in tempfile if needed.
100
        """
101
        if isinstance(lines, str):
102
            lines = [lines]
103
        if isinstance(results, Result):
104
            results = [results]
105
106
        assert isinstance(self, unittest.TestCase)
107
        self.assertIsInstance(local_bear,
108
                              LocalBear,
109
                              msg="The given bear is not a local bear.")
110
        self.assertIsInstance(lines,
111
                              list,
112
                              msg="The given lines are not a list.")
113
        self.assertIsInstance(results,
114
                              list,
115
                              msg="The given results are not a list.")
116
117
        with prepare_file(lines, filename, force_linebreaks, create_tempfile) \
118
                as (lines, filename):
119
120
            bear_output = execute_bear(local_bear, filename, lines)
121
            msg = ("The local bear '{}' doesn't yield the right results. Or the"
122
                   " order may be wrong.".format(local_bear.__class__.__name__))
123
            if not check_order:
124
                self.assertEqual(sorted(bear_output), sorted(results), msg=msg)
125
            else:
126
                self.assertEqual(bear_output, results, msg=msg)
127
128
129
def verify_local_bear(bear,
130
                      valid_files,
131
                      invalid_files,
132
                      filename=None,
133
                      settings={},
134
                      force_linebreaks=True,
135
                      create_tempfile=True):
136
    """
137
    Generates a test for a local bear by checking the given valid and invalid
138
    file contents. Simply use it on your module level like:
139
140
    YourTestName = verify_local_bear(YourBear, (['valid line'],),
141
                                     (['invalid line'],))
142
143
    :param bear:             The Bear class to test.
144
    :param valid_files:      An iterable of files as a string list that won't
145
                             yield results.
146
    :param invalid_files:    An iterable of files as a string list that must
147
                             yield results.
148
    :param filename:         The filename to use for valid and invalid files.
149
    :param settings:         A dictionary of keys and values (both string) from
150
                             which settings will be created that will be made
151
                             available for the tested bear.
152
    :param force_linebreaks: Whether to append newlines at each line
153
                             if needed. (Bears expect a \\n for every line)
154
    :param create_tempfile:  Whether to save lines in tempfile if needed.
155
    :return:                 A unittest.TestCase object.
156
    """
157
    @generate_skip_decorator(bear)
158
    class LocalBearTest(LocalBearTestHelper):
159
160
        def setUp(self):
161
            self.section = Section('name')
162
            self.uut = bear(self.section,
163
                            queue.Queue())
164
            for name, value in settings.items():
165
                self.section.append(Setting(name, value))
166
167
        def test_valid_files(self):
168
            for file in valid_files:
169
                self.check_validity(self.uut,
170
                                    file,
171
                                    filename,
172
                                    valid=True,
173
                                    force_linebreaks=force_linebreaks,
174
                                    create_tempfile=create_tempfile)
175
176
        def test_invalid_files(self):
177
            for file in invalid_files:
178
                self.check_validity(self.uut,
179
                                    file,
180
                                    filename,
181
                                    valid=False,
182
                                    force_linebreaks=force_linebreaks,
183
                                    create_tempfile=create_tempfile)
184
185
    return LocalBearTest
186