Debian Codegraph @

saltpylint/blacklist.py

raw symbols SCIP
1 """
2 saltpylint.blacklist
3 ~~~~~~~~~~~~~~~~~~~~
4
5 Checks blacklisted imports and code usage on salt
6 """
7
8 import contextlib
9 import fnmatch
10 import os
11
12 import astroid
13 from pylint.checkers import BaseChecker
14 from pylint.checkers import utils
15
16 BLACKLISTED_IMPORTS_MSGS = {
17 "E9402": (
18 "Uses of a blacklisted module %r: %s",
19 "blacklisted-module",
20 "Used a module marked as blacklisted is imported.",
21 ),
22 "E9403": (
23 "Uses of a blacklisted external module %r: %s",
24 "blacklisted-external-module",
25 "Used a module marked as blacklisted is imported.",
26 ),
27 "E9404": (
28 "Uses of a blacklisted import %r: %s",
29 "blacklisted-import",
30 "Used an import marked as blacklisted.",
31 ),
32 "E9405": (
33 "Uses of an external blacklisted import %r: %s",
34 "blacklisted-external-import",
35 "Used an external import marked as blacklisted.",
36 ),
37 "E9406": (
38 "Uses of blacklisted test module execution code: %s",
39 "blacklisted-test-module-execution",
40 "Uses of blacklisted test module execution code.",
41 ),
42 "E9407": (
43 "Uses of blacklisted sys.path updating through 'ensure_in_syspath'. "
44 "Please remove the import and any calls to 'ensure_in_syspath()'.",
45 "blacklisted-syspath-update",
46 "Uses of blacklisted sys.path updating through ensure_in_syspath.",
47 ),
48 }
49
50
51 class BlacklistedImportsChecker(BaseChecker):
52 name = "blacklisted-imports"
53 msgs = BLACKLISTED_IMPORTS_MSGS
54 priority = -2
55
56 def open(self):
57 self.blacklisted_modules = (
58 "salttesting",
59 "integration",
60 "unit",
61 "mock",
62 "six",
63 "distutils.version",
64 "unittest",
65 "unittest2",
66 )
67
68 def visit_import(self, node):
69 """Triggered when an import statement is seen."""
70 module_filename = node.root().file
71 if fnmatch.fnmatch(module_filename, "__init__.py*") and not fnmatch.fnmatch(
72 module_filename,
73 "test_*.py*",
74 ):
75 return
76 node.root()
77 names = [name for name, _ in node.names]
78
79 for name in names:
80 self._check_blacklisted_module(node, name)
81
82 def visit_importfrom(self, node):
83 """Triggered when a from statement is seen."""
84 module_filename = node.root().file
85 if fnmatch.fnmatch(module_filename, "__init__.py*") and not fnmatch.fnmatch(
86 module_filename,
87 "test_*.py*",
88 ):
89 return
90 basename = node.modname
91 self._check_blacklisted_module(node, basename)
92
93 def _check_blacklisted_module(self, node, mod_path):
94 """Check if the module is blacklisted."""
95 for mod_name in self.blacklisted_modules:
96 if mod_path == mod_name or mod_path.startswith(mod_name + "."):
97 names = []
98 for name, name_as in node.names:
99 if name_as:
100 names.append(f"{name} as {name_as}")
101 else:
102 names.append(name)
103 try:
104 import_from_module = node.modname
105 if import_from_module == "salttesting.helpers":
106 for name in names:
107 if name == "ensure_in_syspath":
108 self.add_message("blacklisted-syspath-update", node=node)
109 continue
110 msg = f"Please use 'from tests.support.helpers import {name}'"
111 self.add_message("blacklisted-module", node=node, args=(mod_path, msg))
112 continue
113 if import_from_module in (
114 "salttesting.mock",
115 "mock",
116 "unittest.mock",
117 "unittest2.mock",
118 ):
119 for name in names:
120 msg = f"Please use 'from tests.support.mock import {name}'"
121 if import_from_module in (
122 "salttesting.mock",
123 "unittest.mock",
124 "unittest2.mock",
125 ):
126 message_id = "blacklisted-module"
127 else:
128 message_id = "blacklisted-external-module"
129 self.add_message(message_id, node=node, args=(mod_path, msg))
130 continue
131 if import_from_module == "salttesting.parser":
132 for name in names:
133 msg = f"Please use 'from tests.support.parser import {name}'"
134 self.add_message("blacklisted-module", node=node, args=(mod_path, msg))
135 continue
136 if import_from_module == "salttesting.case":
137 for name in names:
138 msg = f"Please use 'from tests.support.case import {name}'"
139 self.add_message("blacklisted-module", node=node, args=(mod_path, msg))
140 continue
141 if import_from_module == "salttesting.unit":
142 for name in names:
143 msg = f"Please use 'from tests.support.unit import {name}'"
144 self.add_message("blacklisted-module", node=node, args=(mod_path, msg))
145 continue
146 if import_from_module.startswith(("unittest", "unittest2")):
147 for name in names:
148 msg = f"Please use 'from tests.support.unit import {name}'"
149 self.add_message("blacklisted-module", node=node, args=(mod_path, msg))
150 continue
151 if import_from_module == "salttesting.mixins":
152 for name in names:
153 msg = f"Please use 'from tests.support.mixins import {name}'"
154 self.add_message("blacklisted-module", node=node, args=(mod_path, msg))
155 continue
156 if import_from_module == "six":
157 for name in names:
158 msg = f"Please use 'from salt.ext.six import {name}'"
159 self.add_message("blacklisted-module", node=node, args=(mod_path, msg))
160 continue
161 if import_from_module == "distutils.version":
162 for name in names:
163 msg = f"Please use 'from salt.utils.versions import {name}'"
164 self.add_message("blacklisted-module", node=node, args=(mod_path, msg))
165 continue
166 if names:
167 for name in names:
168 if name in (
169 "TestLoader",
170 "TextTestRunner",
171 "TestCase",
172 "expectedFailure",
173 "TestSuite",
174 "skipIf",
175 "TestResult",
176 ):
177 msg = f"Please use 'from tests.support.unit import {name}'"
178 self.add_message(
179 "blacklisted-module",
180 node=node,
181 args=(mod_path, msg),
182 )
183 continue
184 if name in ("SaltReturnAssertsMixin", "SaltMinionEventAssertsMixin"):
185 msg = f"Please use 'from tests.support.mixins import {name}'"
186 self.add_message(
187 "blacklisted-module",
188 node=node,
189 args=(mod_path, msg),
190 )
191 continue
192 if name in ("ModuleCase", "SyndicCase", "ShellCase", "SSHCase"):
193 msg = f"Please use 'from tests.support.case import {name}'"
194 self.add_message(
195 "blacklisted-module",
196 node=node,
197 args=(mod_path, msg),
198 )
199 continue
200 if name == "run_tests":
201 self.add_message(
202 "blacklisted-test-module-execution",
203 node=node,
204 args=(
205 "Please remove the 'if __name__ == \"__main__\":' section from the "
206 "end of the module"
207 ),
208 )
209 continue
210 if mod_name in ("integration", "unit"):
211 if name in (
212 "SYS_TMP_DIR",
213 "TMP",
214 "FILES",
215 "PYEXEC",
216 "MOCKBIN",
217 "SCRIPT_DIR",
218 "TMP_STATE_TREE",
219 "TMP_PRODENV_STATE_TREE",
220 "TMP_CONF_DIR",
221 "TMP_SUB_MINION_CONF_DIR",
222 "TMP_SYNDIC_MINION_CONF_DIR",
223 "TMP_SYNDIC_MASTER_CONF_DIR",
224 "CODE_DIR",
225 "TESTS_DIR",
226 "CONF_DIR",
227 "PILLAR_DIR",
228 "TMP_SCRIPT_DIR",
229 "ENGINES_DIR",
230 "LOG_HANDLERS_DIR",
231 "INTEGRATION_TEST_DIR",
232 ):
233 msg = f"Please use 'from tests.support.paths import {name}'"
234 self.add_message(
235 "blacklisted-import",
236 node=node,
237 args=(mod_path, msg),
238 )
239 continue
240 self.add_message(
241 "blacklisted-import",
242 node=node,
243 args=(
244 mod_path,
245 f"Please use 'from tests.{mod_path} import {name}'",
246 ),
247 )
248 continue
249 self.add_message(
250 "blacklisted-module",
251 node=node,
252 args=(
253 mod_path,
254 "Please report this error to SaltStack so we can fix it: "
255 f"Trying to import {name} from {mod_path}",
256 ),
257 )
258 except AttributeError:
259 if mod_name in (
260 "integration",
261 "unit",
262 "mock",
263 "six",
264 "distutils.version",
265 "unittest",
266 "unittest2",
267 ):
268 if mod_name in ("integration", "unit"):
269 msg = f"Please use 'import tests.{mod_name} as {mod_name}'"
270 message_id = "blacklisted-import"
271 elif mod_name == "mock":
272 msg = f"Please use 'import tests.support.{mod_name} as {mod_name}'"
273 message_id = "blacklisted-external-import"
274 elif mod_name == "six":
275 msg = f"Please use 'import salt.ext.{name} as {name}'"
276 message_id = "blacklisted-external-import"
277 elif mod_name == "distutils.version":
278 msg = "Please use 'import salt.utils.versions' instead"
279 message_id = "blacklisted-import"
280 elif mod_name.startswith(("unittest", "unittest2")):
281 msg = f"Please use 'import tests.support.unit as {mod_name}' instead"
282 message_id = "blacklisted-import"
283 self.add_message(message_id, node=node, args=(mod_path, msg))
284 continue
285 msg = f"Please report this error to SaltStack so we can fix it: Trying to import {mod_path}"
286 self.add_message("blacklisted-import", node=node, args=(mod_path, msg))
287
288
289 BLACKLISTED_LOADER_USAGE_MSGS = {
290 "E9501": (
291 "Blacklisted salt loader dunder usage. Setting dunder attribute %r to module %r. "
292 "Use 'salt.support.mock' and 'patch.dict()' instead.",
293 "unmocked-patch-dunder",
294 "Uses a blacklisted salt loader dunder usage in tests.",
295 ),
296 "E9502": (
297 "Blacklisted salt loader dunder usage. Setting attribute %r to module %r. "
298 "Use 'salt.support.mock' and 'patch()' instead.",
299 "unmocked-patch",
300 "Uses a blacklisted salt loader dunder usage in tests.",
301 ),
302 "E9503": (
303 "Blacklisted salt loader dunder usage. Updating dunder attribute %r on module %r. "
304 "Use 'salt.support.mock' and 'patch.dict()' instead.",
305 "unmocked-patch-dunder-update",
306 "Uses a blacklisted salt loader dunder usage in tests.",
307 ),
308 }
309
310
311 class BlacklistedLoaderModulesUsageChecker(BaseChecker):
312 name = "blacklisted-unmocked-patching"
313 msgs = BLACKLISTED_LOADER_USAGE_MSGS
314 priority = -2
315
316 def open(self):
317 self.process_module = False
318 self.salt_dunders = (
319 "__opts__",
320 "__salt__",
321 "__runner__",
322 "__context__",
323 "__utils__",
324 "__ext_pillar__",
325 "__thorium__",
326 "__states__",
327 "__serializers__",
328 "__ret__",
329 "__grains__",
330 "__pillar__",
331 "__sdb__",
332 "__proxy__",
333 "__low__",
334 "__orchestration_jid__",
335 "__running__",
336 "__intance_id__",
337 "__lowstate__",
338 "__env__",
339 )
340 self.imported_salt_modules = {}
341
342 def close(self):
343 self.process_module = False
344 self.imported_salt_modules = {}
345
346 def visit_module(self, node):
347 module_filename = node.root().file
348 if not fnmatch.fnmatch(os.path.basename(module_filename), "test_*.py*"):
349 return
350 self.process_module = True
351
352 def leave_module(self, node):
353 if self.process_module:
354 # Reset
355 self.process_module = False
356 self.imported_salt_modules = {}
357
358 def visit_import(self, node):
359 """Triggered when an import statement is seen."""
360 if self.process_module:
361 # Store salt imported modules
362 for module, import_as in node.names:
363 if not module.startswith("salt"):
364 continue
365 if import_as and import_as not in self.imported_salt_modules:
366 self.imported_salt_modules[import_as] = module
367 continue
368 if module not in self.imported_salt_modules:
369 self.imported_salt_modules[module] = module
370
371 def visit_importfrom(self, node):
372 """Triggered when a from statement is seen."""
373 if self.process_module:
374 if not node.modname.startswith("salt"):
375 return
376 # Store salt imported modules
377 for module, import_as in node.names:
378 if import_as and import_as not in self.imported_salt_modules:
379 self.imported_salt_modules[import_as] = import_as
380 continue
381 if module not in self.imported_salt_modules:
382 self.imported_salt_modules[module] = module
383
384 def visit_assign(self, node, *args):
385 if not self.process_module:
386 return
387
388 node_left = node.targets[0]
389
390 if isinstance(node_left, astroid.Subscript):
391 # Were're changing an existing attribute
392 if not isinstance(node_left.value, astroid.Attribute):
393 return
394 if node_left.value.attrname in self.salt_dunders:
395 if node_left.value.expr.name in self.imported_salt_modules:
396 self.add_message(
397 "unmocked-patch-dunder-update",
398 node=node,
399 args=(
400 node_left.value.attrname,
401 self.imported_salt_modules[node_left.value.expr.name],
402 ),
403 )
404 return
405
406 if not isinstance(node_left, astroid.AssignAttr):
407 return
408
409 try:
410 if node_left.expr.name not in self.imported_salt_modules:
411 # If attributes are not being set on salt's modules,
412 # leave it alone, for now!
413 return
414 except AttributeError:
415 # This might not be what we're looking for
416 return
417
418 # we're assigning to an imported salt module!
419 if node_left.attrname in self.salt_dunders:
420 # We're changing salt dunders
421 self.add_message(
422 "unmocked-patch-dunder",
423 node=node,
424 args=(node_left.attrname, self.imported_salt_modules[node_left.expr.name]),
425 )
426 return
427
428 # Changing random attributes
429 self.add_message(
430 "unmocked-patch",
431 node=node,
432 args=(node_left.attrname, self.imported_salt_modules[node_left.expr.name]),
433 )
434
435
436 RESOURCE_LEAKAGE_MSGS = {
437 "W8470": ("Resource leakage detected. %s ", "resource-leakage", "Resource leakage detected."),
438 }
439
440
441 class ResourceLeakageChecker(BaseChecker):
442 name = "resource-leakage"
443 msgs = RESOURCE_LEAKAGE_MSGS
444 priority = -2
445
446 def open(self):
447 self.inside_with_ctx = False
448
449 def close(self):
450 self.inside_with_ctx = False
451
452 def visit_with(self, node):
453 self.inside_with_ctx = True
454
455 def leave_with(self, node):
456 self.inside_with_ctx = False
457
458 def visit_call(self, node):
459 if isinstance(node.func, astroid.Attribute):
460 if node.func.attrname == "fopen" and self.inside_with_ctx is False:
461 msg = (
462 "Please call 'salt.utils.files.fopen' using the 'with' context "
463 "manager, otherwise the file handle won't be closed and "
464 "resource leakage will occur."
465 )
466 self.add_message("resource-leakage", node=node, args=(msg,))
467 elif (
468 isinstance(node.func, astroid.Name)
469 and utils.is_builtin(node.func.name)
470 and node.func.name == "open"
471 ):
472 if self.inside_with_ctx:
473 msg = (
474 "Please use 'with salt.utils.files.fopen()' instead of "
475 "'with open()'. It assures salt does not leak "
476 "file handles."
477 )
478 else:
479 msg = (
480 "Please use 'salt.utils.files.fopen()' instead of 'open()' "
481 "using the 'with' context manager, otherwise the file "
482 "handle won't be closed and resource leakage will occur."
483 )
484 self.add_message("resource-leakage", node=node, args=(msg,))
485
486
487 MOVED_TEST_CASE_CLASSES_MSGS = {
488 "E9490": (
489 "Moved test case base class detected. %s",
490 "moved-test-case-class",
491 "Moved test case base class detected.",
492 ),
493 "E9491": (
494 "Moved test case mixin class detected. %s",
495 "moved-test-case-mixin",
496 "Moved test case mixin class detected.",
497 ),
498 }
499
500
501 class MovedTestCaseClassChecker(BaseChecker):
502 name = "moved-test-case-class"
503 msgs = MOVED_TEST_CASE_CLASSES_MSGS
504 priority = -2
505
506 def open(self):
507 self.process_module = False
508
509 def close(self):
510 self.process_module = False
511
512 def visit_module(self, node):
513 module_filename = node.root().file
514 if not fnmatch.fnmatch(os.path.basename(module_filename), "test_*.py*"):
515 return
516 self.process_module = True
517
518 def leave_module(self, node):
519 if self.process_module:
520 # Reset
521 self.process_module = False
522
523 def visit_importfrom(self, node):
524 """Triggered when a from statement is seen."""
525 if self.process_module:
526 if not node.modname.startswith("tests.integration"):
527 return
528 # Store salt imported modules
529 for module, import_as in node.names:
530 if import_as:
531 self._check_moved_imports(node, module, import_as)
532 continue
533 self._check_moved_imports(node, module)
534
535 def visit_classdef(self, node):
536 for base in node.bases:
537 if not hasattr(base, "attrname"):
538 continue
539 if base.attrname in ("TestCase",):
540 msg = f"Please use 'from tests.support.unit import {base.attrname}'"
541 self.add_message("moved-test-case-class", node=node, args=(msg,))
542 if base.attrname in ("ModuleCase", "SyndicCase", "ShellCase", "SSHCase"):
543 msg = f"Please use 'from tests.support.case import {base.attrname}'"
544 self.add_message("moved-test-case-class", node=node, args=(msg,))
545 if base.attrname in (
546 "AdaptedConfigurationTestCaseMixin",
547 "ShellCaseCommonTestsMixin",
548 "SaltMinionEventAssertsMixin",
549 ):
550 msg = f"Please use 'from tests.support.mixins import {base.attrname}'"
551 self.add_message("moved-test-case-mixin", node=node, args=(msg,))
552
553 def _check_moved_imports(self, node, module, import_as=None):
554 for name, name_as in node.names:
555 if name not in ("ModuleCase", "SyndicCase", "ShellCase", "SSHCase"):
556 continue
557 if name_as:
558 msg = f"Please use 'from tests.support.case import {name} as {name_as}'"
559 else:
560 msg = f"Please use 'from tests.support.case import {name}'"
561 self.add_message("moved-test-case-class", node=node, args=(msg,))
562
563
564 BLACKLISTED_FUNCTIONS_MSGS = {
565 "E9601": (
566 "Use of blacklisted function %s (use %s instead)",
567 "blacklisted-function",
568 "Used a function marked as blacklisted",
569 ),
570 }
571
572
573 class BlacklistedFunctionsChecker(BaseChecker):
574 name = "blacklisted-functions"
575 msgs = BLACKLISTED_FUNCTIONS_MSGS
576 priority = -2
577 max_depth = 20
578
579 options = (
580 (
581 "blacklisted-functions",
582 {
583 "default": "",
584 "type": "string",
585 "metavar": "bad1=good1,bad2=good2",
586 "help": "List of blacklisted functions and their recommended replacements",
587 },
588 ),
589 )
590
591 def open(self):
592 self.blacklisted_functions = {}
593 blacklist = [x.strip() for x in self.linter.config.blacklisted_functions.split(",")]
594 for item in blacklist:
595 try:
596 key, val = (x.strip() for x in item.split("="))
597 except ValueError:
598 pass
599 else:
600 self.blacklisted_functions[key] = val
601
602 def _get_full_name(self, node):
603 try:
604 func = utils.safe_infer(node.func)
605 if func.name.__str__() == "Uninferable":
606 return None
607 except Exception:
608 func = None
609 if func is None:
610 return None
611 ret = []
612 depth = 0
613 while func is not None:
614 depth += 1
615 if depth > self.max_depth:
616 # Prevent endless loop
617 return None
618 try:
619 ret.append(func.name)
620 except AttributeError:
621 return None
622 func = func.parent
623 # ret will contain the levels of the function from last to first (e.g.
624 # ['walk', 'os']. Reverse it and join with dots to get the correct
625 # full name for the function.
626 return ".".join(ret[::-1])
627
628 def visit_call(self, node):
629 if self.blacklisted_functions:
630 full_name = self._get_full_name(node)
631 if full_name is not None:
632 with contextlib.suppress(KeyError):
633 self.add_message(
634 "blacklisted-function",
635 node=node,
636 args=(full_name, self.blacklisted_functions[full_name]),
637 )
638
639
640 def register(linter):
641 """Required method to auto register this checker."""
642 linter.register_checker(ResourceLeakageChecker(linter))
643 linter.register_checker(BlacklistedImportsChecker(linter))
644 linter.register_checker(MovedTestCaseClassChecker(linter))
645 linter.register_checker(BlacklistedLoaderModulesUsageChecker(linter))
646 linter.register_checker(BlacklistedFunctionsChecker(linter))