Merge "hacking: force explicit import of python's mock"

This commit is contained in:
Zuul 2022-08-02 20:25:02 +00:00 committed by Gerrit Code Review
commit 4ca7955365
3 changed files with 46 additions and 0 deletions

View File

@ -1046,3 +1046,35 @@ def check_six(logical_line):
match = re.match(six_re, logical_line)
if match:
yield (0, "N370: Don't use or import six")
@core.flake8ext
def import_stock_mock(logical_line):
"""Use python's mock, not the mock library.
Since we `dropped support for python 2`__, we no longer need to use the
mock library, which existed to backport py3 functionality into py2. Change
Ib44b5bff657c8e76c4f701e14d51a4efda3f6d32 cut over to importing the stock
mock, which must be done by saying::
from unittest import mock
...because if you say::
import mock
...you may be getting the stock mock; or, due to transitive dependencies in
the environment, the library mock. This check can be removed in the future
(and we can start saying ``import mock`` again) if we manage to purge these
transitive dependencies.
.. __: https://review.opendev.org/#/c/687954/
N371
"""
if logical_line == 'import mock' or logical_line.startswith('from mock'):
yield (
0,
"N371: You must explicitly import python's mock: "
"``from unittest import mock``"
)

View File

@ -1030,3 +1030,16 @@ class HackingTestCase(test.NoDBTestCase):
"""
errors = [(x + 1, 0, 'N370') for x in range(4)]
self._assert_has_errors(code, checks.check_six, expected_errors=errors)
def test_import_stock_mock(self):
self._assert_has_errors(
"import mock",
checks.import_stock_mock, expected_errors=[(1, 0, 'N371')])
self._assert_has_errors(
"from mock import patch",
checks.import_stock_mock, expected_errors=[(1, 0, 'N371')])
code = """
from unittest import mock
import unittest.mock
"""
self._assert_has_no_errors(code, checks.import_stock_mock)

View File

@ -345,6 +345,7 @@ extension =
N368 = checks:do_not_use_mock_class_as_new_mock_value
N369 = checks:check_lockutils_rwlocks
N370 = checks:check_six
N371 = checks:import_stock_mock
paths =
./nova/hacking