Add a hacking check for importing mock library

We should only be using unittest.mock since we're python3-only,
so add and enable a hacking check that will catch it.

Change-Id: I64847f329ee3e1a3377a8c63df90c697d8b74c86
This commit is contained in:
Brian Haley 2020-06-09 14:46:36 -04:00
parent 28c311ccd7
commit 6ed2660676
4 changed files with 46 additions and 0 deletions

View File

@ -15,3 +15,4 @@ Below you can find a list of checks specific to this repository.
- [N343] Production code must not import from ovn_octavia_provider.tests.*
- [N344] Python 3: Do not use filter(lambda obj: test(obj), data). Replace it
with [obj for obj in data if test(obj)].
- [N347] Test code must not import mock library

View File

@ -42,6 +42,9 @@ tests_imports_from2 = re.compile(
r"\bfrom[\s]+ovn_octavia_provider[\s]+import[\s]+tests\b")
no_line_continuation_backslash_re = re.compile(r'.*(\\)\n')
import_mock = re.compile(r"\bimport[\s]+mock\b")
import_from_mock = re.compile(r"\bfrom[\s]+mock[\s]+import\b")
@core.flake8ext
def check_assert_called_once_with(logical_line, filename):
@ -162,3 +165,19 @@ def check_python3_no_filter(logical_line):
if filter_match.match(logical_line):
yield(0, msg)
@core.flake8ext
def check_no_import_mock(logical_line, filename, noqa):
"""N347 - Test code must not import mock library."""
msg = ("N347: Test code must not import mock library")
if noqa:
return
if 'ovn_octavia_provider/tests/' not in filename:
return
for regex in import_mock, import_from_mock:
if re.match(regex, logical_line):
yield(0, msg)

View File

@ -221,3 +221,28 @@ class HackingTestCase(base.BaseTestCase):
self.assertLinePasses(f, "[obj for obj in data if test(obj)]")
self.assertLinePasses(f, "filter(function, range(0,10))")
self.assertLinePasses(f, "lambda x, y: x+y")
def test_check_no_import_mock(self):
pass_line = 'from unittest import mock'
fail_lines = ('import mock',
'import mock as mock_lib',
'from mock import patch')
self.assertEqual(
0, len(list(
checks.check_no_import_mock(
pass_line,
"ovn_octavia_provider/tests/test_fake.py",
None))))
for fail_line in fail_lines:
self.assertEqual(
0, len(list(
checks.check_no_import_mock(
fail_line,
"ovn_octavia_provider/common/utils.py",
None))))
self.assertEqual(
1, len(list(
checks.check_no_import_mock(
fail_line,
"ovn_octavia_provider/tests/test_fake.py",
None))))

View File

@ -121,6 +121,7 @@ extension =
N332 = checks:check_assertequal_for_httpcode
N343 = checks:check_no_imports_from_tests
N344 = checks:check_python3_no_filter
N347 = checks:check_no_import_mock
paths =./ovn_octavia_provider/hacking
[testenv:genconfig]