hacking: force explicit import of python's mock
Since we dropped support for python 2 [1], 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 will be using the third party mock library instead, which may or
may not be installed.
This commit adds hacking check N371 to enforce the former.
[1] https://review.opendev.org/#/c/687954/
Change-Id: I71439580e80d33cff62aba807df2b35164a47cbe
This commit is contained in:
committed by
Balazs Gibizer
parent
f8cf050a13
commit
c36782a96a
@@ -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``"
|
||||
)
|
||||
|
||||
@@ -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)
|
||||
|
||||
Reference in New Issue
Block a user