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.
Which must be done by saying::

    from unittest import mock

...because if you say::

    import mock

...you definitely will not be getting the standard library mock.
That will always import the third party mock library.

This commit adds hacking check N366 to enforce the former.

This check can be removed in the future (and we can start saying
``import mock`` again) if we manage to purge these transitive
dependencies. I'm not holding my breath.

[1]https://review.opendev.org/#/c/688593/

Change-Id: I79b0a084b8a99c54ce175a520e039e5572c5165a
This commit is contained in:
zhangbailin 2020-04-02 18:27:11 +08:00 committed by Brin Zhang
parent 9915d7a5f7
commit 59fc114d30
3 changed files with 39 additions and 0 deletions

View File

@ -170,3 +170,31 @@ def check_explicit_underscore_import(logical_line, filename):
elif (translated_log.match(logical_line) or
string_translation.match(logical_line)):
yield(0, "M340: Found use of _() without explicit import of _ !")
@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.
Which must be done by saying::
from unittest import mock
...because if you say::
import mock
...you definitely will not be getting the standard library mock. That will
always import the third party mock library. 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/688593/
N366
"""
if logical_line == 'import mock':
yield (0, "N366: You must explicitly import python's mock: "
"``from unittest import mock``")

View File

@ -245,3 +245,13 @@ class HackingTestCase(base.TestCase):
self.assertEqual(len(list(checks.check_explicit_underscore_import(
"msg = _('My message')",
"magnum/tests/other_files3.py"))), 0)
def test_import_stock_mock(self):
self._assert_has_errors(
"import mock",
checks.import_stock_mock, expected_errors=[(1, 0, 'N366')])
code = """
from unittest import mock
import unittest.mock
"""
self._assert_has_no_errors(code, checks.import_stock_mock)

View File

@ -129,4 +129,5 @@ extension =
M339 = checks:no_xrange
M340 = checks:check_explicit_underscore_import
M352 = checks:no_log_warn
N366 = checks:import_stock_mock
paths = ./cyborg/hacking