37 lines
1.6 KiB
Python
37 lines
1.6 KiB
Python
import ast
|
|
import pathlib
|
|
import subprocess
|
|
import sys
|
|
import unittest
|
|
|
|
sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1]))
|
|
|
|
from repo_checks import ROOT
|
|
|
|
def patches(source: str) -> list[int]:
|
|
"""The line numbers where source names mock's patch, as an attribute of mock or imported from it."""
|
|
found = []
|
|
for node in ast.walk(ast.parse(source)):
|
|
if isinstance(node, ast.Attribute) and node.attr == "patch" and ast.unparse(node.value).split(".")[-1] == "mock":
|
|
found.append(node.lineno)
|
|
elif isinstance(node, ast.ImportFrom) and node.module == "unittest.mock" and any(alias.name == "patch" for alias in node.names):
|
|
found.append(node.lineno)
|
|
return sorted(found)
|
|
|
|
|
|
class NoPatchedGlobals(unittest.TestCase):
|
|
def test_no_python_file_under_bin_patches_a_global(self):
|
|
# A file not yet staged counts too, so a new suite is checked before its first commit.
|
|
listed = subprocess.run(["git", "ls-files", "--cached", "--others", "--exclude-standard", "bin/*.py"],capture_output=True, check=True, cwd=ROOT, text=True).stdout.split()
|
|
self.assertIn("bin/repo_checks/test_no_patched_globals.py", listed)
|
|
patching = {name for name in listed if patches((ROOT / name).read_text(encoding="utf-8"))}
|
|
self.assertEqual(patching, set(), "hand the code under test its effect as an argument instead")
|
|
|
|
def test_each_spelling_of_patch_is_found(self):
|
|
source = "import unittest.mock\nfrom unittest import mock\nfrom unittest.mock import Mock, patch\n\nunittest.mock.patch.dict(a, b)\nmock.patch.object(a, 'b')\nmock.patch('a.b')\nmock.Mock()\n"
|
|
self.assertEqual(patches(source), [3, 5, 6, 7])
|
|
|
|
|
|
if __name__ == "__main__":
|
|
unittest.main()
|