File: test_test_mock.py

package info (click to toggle)
rally-openstack 3.0.0-7
  • links: PTS, VCS
  • area: main
  • in suites: trixie
  • size: 8,928 kB
  • sloc: python: 53,131; sh: 262; makefile: 38
file content (476 lines) | stat: -rw-r--r-- 14,784 bytes parent folder | download | duplicates (6)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
#    Licensed under the Apache License, Version 2.0 (the "License"); you may
#    not use this file except in compliance with the License. You may obtain
#    a copy of the License at
#
#         http://www.apache.org/licenses/LICENSE-2.0
#
#    Unless required by applicable law or agreed to in writing, software
#    distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
#    WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
#    License for the specific language governing permissions and limitations
#    under the License.

import ast
import sys
from unittest import mock

from tests.unit import test
from tests.unit import test_mock


class VariantsTestCase(test.TestCase):
    def setUp(self):
        self.variants = test_mock.Variants(["test", "foo", "bar"])
        super(VariantsTestCase, self).setUp()

    def test_print(self):
        self.assertEqual(
            "{'mock_test', 'mock_foo', 'mock_bar'}",
            repr(self.variants)
        )

    def test_print_long(self):
        variants = test_mock.Variants(["test", "foo", "bar", "buz"])
        self.assertEqual(
            "{'mock_test', 'mock_foo', 'mock_bar', ...}",
            repr(variants)
        )

    def test_equal(self):
        self.assertEqual(["test", "foo", "bar"], self.variants)
        self.assertEqual(self.variants, self.variants)

        mock_variants = mock.Mock(variants=["test", "foo", "bar"])
        self.assertEqual(mock_variants, self.variants)

        self.assertNotEqual(["abc"], self.variants)

    def test_contains(self):
        self.assertIn("test", self.variants)
        self.assertNotIn("abc", self.variants)


class FuncMockArgsDecoratorsCheckerTestCase(test.TestCase):
    code = """
@mock.patch("os.path.join")
@mock.patch("pkg.module1.OtherObject.method")
@mock.patch("pkg.module2.MyClassObject.method")
@mock.patch.object(pkg.SomeKindOfObject, "abc")
@mock.patch.object(pkg.MyClassObject, "abc")
def test_func(self, mock_args, mock_args2, mock_some_longer_args):
    pass
"""
    code_mock_decorators = [
        ["abc", "my_class_object_abc", "pkg_my_class_object_abc"],
        ["some_kind_of_object_abc", "pkg_some_kind_of_object_abc"],
        [
            "method",
            "my_class_object_method",
            "module2_my_class_object_method",
            "pkg_module2_my_class_object_method"
        ],
        [
            "other_object_method",
            "module1_other_object_method",
            "pkg_module1_other_object_method",
        ],
        [
            "join",
            "path_join",
            "os_path_join"
        ],
    ]
    code_mock_args = ["args", "args2", "some_longer_args"]

    def setUp(self):
        super(FuncMockArgsDecoratorsCheckerTestCase, self).setUp()
        self.visitor = test_mock.FuncMockArgsDecoratorsChecker()
        self.visitor.classname_python = ""
        self.visitor.globals_["EXPR"] = "expression"
        self.tree = self._parse_expr(self.code)

    def _parse_expr(self, code):
        firstbody = ast.parse(code).body[0]
        if isinstance(firstbody, ast.Expr):
            return firstbody.value
        return firstbody

    def test__get_name(self):
        self.assertEqual(
            "os.path.join",
            self.visitor._get_name(self._parse_expr("os.path.join"))
        )

    def test__get_value_str(self):
        self.assertEqual(
            "not.your.fault",
            self.visitor._get_value(self._parse_expr("'not.your.fault'"))
        )

    def test__get_value_mod(self):
        self.assertEqual(
            "some.crazy.mod.expression",
            self.visitor._get_value(
                self._parse_expr("'some.crazy.mod.%s' % EXPR")
            )
        )

    def test__get_value_add(self):
        self.assertEqual(
            "expression.some.crazy.add",
            self.visitor._get_value(
                self._parse_expr("EXPR + '.some.crazy.add'")
            )
        )

    def test__get_value_global(self):
        self.assertEqual(
            "expression",
            self.visitor._get_value(
                self._parse_expr("EXPR")
            )
        )

    def test__get_value_none(self):
        self.assertRaises(
            ValueError,
            self.visitor._get_value,
            ast.parse("import abc")
        )

    def test__get_value_asserts(self):
        self.assertRaises(
            ValueError,
            self.visitor._get_value,
            self._parse_expr("EXPR % 'abc'")
        )

        self.assertRaises(
            ValueError,
            self.visitor._get_value,
            self._parse_expr("'abc' + EXPR")
        )

    def test__camelcase_to_python_camel(self):
        self.assertEqual(
            "some_class_name",
            self.visitor._camelcase_to_python("SomeClassName")
        )

    def test__camelcase_to_python_python(self):
        self.assertEqual(
            "some_python_name",
            self.visitor._camelcase_to_python("some_python_name")
        )

    def test__get_mocked_class_value_variants_matches_class(self):
        self.visitor.classname_python = "foo_class"
        self.assertEqual(
            ["mocked_obj", "foo_class_mocked_obj"],
            self.visitor._get_mocked_class_value_variants(
                class_name="FooClass",
                mocked_name="MockedObj"
            )
        )

    def test__get_mocked_class_value_variants_different_class(self):
        self.visitor.classname_python = "foo_class"
        self.assertEqual(
            ["bar_class_mocked_obj"],
            self.visitor._get_mocked_class_value_variants(
                class_name="BarClass",
                mocked_name="MockedObj"
            )
        )

    def test__add_pkg_optional_prefixes(self):
        self.assertEqual(
            ["foo", "bar", "bar_class_bar", "pkg_bar_class_bar",
             "some_pkg_bar_class_bar"],
            self.visitor._add_pkg_optional_prefixes(
                "some.pkg.BarClass".split("."),
                ["foo", "bar"]
            )
        )

    def test__get_mocked_name_variants_single(self):
        self.assertEqual(
            ["foo_bar"],
            self.visitor._get_mocked_name_variants(
                "FooBar"
            )
        )

        self.assertEqual(
            ["foobar"],
            self.visitor._get_mocked_name_variants(
                "foobar"
            )
        )

    def test__get_mocked_name_variants_classname(self):
        self.visitor.classname_python = "foo_bar"
        self.assertEqual(
            ["method", "foo_bar_method", "pkg_foo_bar_method"],
            self.visitor._get_mocked_name_variants(
                "pkg.FooBar.method"
            )
        )

        self.visitor.classname_python = ""
        self.assertEqual(
            ["foo_bar_method", "pkg_foo_bar_method"],
            self.visitor._get_mocked_name_variants(
                "pkg.FooBar.method"
            )
        )

    def test__get_mocked_name_variants_pkg(self):
        self.assertEqual(
            ["method", "pkg_method", "long_pkg_method",
             "some_long_pkg_method"],
            self.visitor._get_mocked_name_variants(
                "some.long.pkg.method"
            )
        )

    def test__get_mock_decorators_variants(self):
        self.visitor.classname_python = "my_class_object"
        self.assertEqual(
            self.code_mock_decorators,
            self.visitor._get_mock_decorators_variants(self.tree)
        )

    def test__get_mock_args(self):
        self.assertEqual(
            self.code_mock_args,
            self.visitor._get_mock_args(self.tree)
        )

    def test_visit_Assign(self):
        self.visitor.globals_ = {}

        self.visitor.visit_Assign(
            self._parse_expr("ABC = '20' + '40'")
        )
        self.assertEqual(
            {"ABC": "2040"},
            self.visitor.globals_
        )

        self.visitor.visit_Assign(
            self._parse_expr("abc = 20 + 40")
        )
        self.assertEqual(
            {"ABC": "2040", "abc": 60},
            self.visitor.globals_
        )

    def test_visit_ClassDef(self):
        self.visitor.visit_ClassDef(
            self._parse_expr("class MyObject(object): pass")
        )
        self.assertEqual(
            "my_object",
            self.visitor.classname_python
        )

        self.visitor.visit_ClassDef(
            self._parse_expr("class YourObjectTestCase(object): pass")
        )
        self.assertEqual(
            "your_object",
            self.visitor.classname_python
        )

    def test_visit_FunctionDef_empty_decs(self):
        self.visitor._get_mock_decorators_variants = mock.Mock(
            return_value=[]
        )

        self.assertIsNone(self.visitor.visit_FunctionDef(self.tree))
        self.assertEqual([], self.visitor.errors)

        self.visitor._get_mock_decorators_variants.assert_called_once_with(
            self.tree
        )

    def test_visit_FunctionDef_good(self):
        self.visitor._get_mock_decorators_variants = mock.Mock(
            return_value=[
                ["foo", "foo_bar", "pkg_foo_bar"]
            ]
        )
        self.visitor._get_mock_args = mock.Mock(
            return_value=["pkg_foo_bar"]
        )

        self.assertIsNone(self.visitor.visit_FunctionDef(self.tree))
        self.assertEqual([], self.visitor.errors)

        self.visitor._get_mock_decorators_variants.assert_called_once_with(
            self.tree
        )
        self.visitor._get_mock_args.assert_called_once_with(
            self.tree
        )

    def test_visit_FunctionDef_misnamed(self):
        variants = test_mock.Variants(
            ["foo", "foo_bar", "pkg_foo_bar", "a"]
        )
        self.visitor._get_mock_decorators_variants = mock.Mock(
            return_value=[variants]
        )
        self.visitor._get_mock_args = mock.Mock(
            return_value=["bar_foo_misnamed"]
        )

        self.assertIsNone(self.visitor.visit_FunctionDef(self.tree))
        if sys.version_info < (3, 8):
            # https://github.com/python/cpython/pull/9731
            lineno = 2
        else:
            lineno = 7
        self.assertEqual(
            [
                {
                    "lineno": lineno,
                    "messages": [
                        "Argument 'mock_bar_foo_misnamed' misnamed; should be "
                        "either of %s that is derived from the mock decorator "
                        "args.\n" % variants
                    ],
                    "mismatch_pairs": [
                        ("bar_foo_misnamed", variants)
                    ]
                }
            ],
            self.visitor.errors)

        self.visitor._get_mock_decorators_variants.assert_called_once_with(
            self.tree
        )
        self.visitor._get_mock_args.assert_called_once_with(
            self.tree
        )

    def test_visit_FunctionDef_mismatch_args(self):
        variants = test_mock.Variants(
            ["foo", "foo_bar", "pkg_foo_bar", "a"]
        )
        self.visitor._get_mock_decorators_variants = mock.Mock(
            return_value=[variants]
        )
        self.visitor._get_mock_args = mock.Mock(
            return_value=["bar_foo_misnamed", "mismatched"]
        )

        self.assertIsNone(self.visitor.visit_FunctionDef(self.tree))
        if sys.version_info < (3, 8):
            # https://github.com/python/cpython/pull/9731
            lineno = 2
        else:
            lineno = 7
        self.assertEqual(
            [
                {
                    "lineno": lineno,
                    "messages": [
                        "Argument 'mock_bar_foo_misnamed' misnamed; should be "
                        "either of %s that is derived from the mock decorator "
                        "args.\n" % variants,
                        "Missing or malformed decorator for 'mock_mismatched' "
                        "argument."
                    ],
                    "args": self.visitor._get_mock_args.return_value,
                    "decs": [variants]
                }
            ],
            self.visitor.errors)

        self.visitor._get_mock_decorators_variants.assert_called_once_with(
            self.tree
        )
        self.visitor._get_mock_args.assert_called_once_with(
            self.tree
        )

    def test_visit_FunctionDef_mismatch_decs(self):
        variants = test_mock.Variants(
            ["foo", "foo_bar", "pkg_foo_bar", "a"]
        )
        self.visitor._get_mock_decorators_variants = mock.Mock(
            return_value=[variants]
        )
        self.visitor._get_mock_args = mock.Mock(
            return_value=[]
        )

        self.assertIsNone(self.visitor.visit_FunctionDef(self.tree))
        if sys.version_info < (3, 8):
            # https://github.com/python/cpython/pull/9731
            lineno = 2
        else:
            lineno = 7
        self.assertEqual(
            [
                {
                    "lineno": lineno,
                    "messages": [
                        "Missing or malformed argument for {'mock_foo', "
                        "'mock_foo_bar', 'mock_pkg_foo_bar', ...} decorator."
                    ],
                    "args": self.visitor._get_mock_args.return_value,
                    "decs": [variants]
                }
            ],
            self.visitor.errors)

        self.visitor._get_mock_decorators_variants.assert_called_once_with(
            self.tree
        )
        self.visitor._get_mock_args.assert_called_once_with(
            self.tree
        )

    def test_visit(self):
        self.visitor.classname_python = "my_class_object"
        self.visitor.visit(self.tree)

        self.assertEqual(
            self.code_mock_args,
            self.visitor.errors[0]["args"]
        )

        self.assertEqual(
            self.code_mock_decorators,
            self.visitor.errors[0]["decs"]
        )

        if sys.version_info < (3, 8):
            # https://github.com/python/cpython/pull/9731
            lineno = 2
        else:
            lineno = 7
        self.assertEqual(lineno, self.visitor.errors[0]["lineno"])

    def test_visit_ok(self):
        self.visitor.classname_python = "my_class_object"
        self.visitor.visit(
            self._parse_expr(
                """
class MyClassObjectTestCase(object):
    @mock.patch("foo.bar.MyClassObject.yep")
    @mock.patch("foo.bar.ClassName.ok")
    @mock.patch.object(pkg.FooClass, "method")
    def test_mockings(self, mock_pkg_foo_class_method, mock_class_name_ok,
                      mock_yep):
        pass
""")
        )

        self.assertEqual(
            [],
            self.visitor.errors
        )