asserts.py 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  1. #
  2. # Copyright 2014 Hewlett-Packard Development Company, L.P.
  3. #
  4. # SPDX-License-Identifier: Apache-2.0
  5. r"""
  6. ============================
  7. B101: Test for use of assert
  8. ============================
  9. This plugin test checks for the use of the Python ``assert`` keyword. It was
  10. discovered that some projects used assert to enforce interface constraints.
  11. However, assert is removed with compiling to optimised byte code (python -o
  12. producing \*.pyo files). This caused various protections to be removed.
  13. Consider raising a semantically meaningful error or ``AssertionError`` instead.
  14. Please see
  15. https://docs.python.org/3/reference/simple_stmts.html#the-assert-statement for
  16. more info on ``assert``.
  17. **Config Options:**
  18. You can configure files that skip this check. This is often useful when you
  19. use assert statements in test cases.
  20. .. code-block:: yaml
  21. assert_used:
  22. skips: ['*_test.py', '*test_*.py']
  23. :Example:
  24. .. code-block:: none
  25. >> Issue: Use of assert detected. The enclosed code will be removed when
  26. compiling to optimised byte code.
  27. Severity: Low Confidence: High
  28. CWE: CWE-703 (https://cwe.mitre.org/data/definitions/703.html)
  29. Location: ./examples/assert.py:1
  30. 1 assert logged_in
  31. 2 display_assets()
  32. .. seealso::
  33. - https://bugs.launchpad.net/juniperopenstack/+bug/1456193
  34. - https://bugs.launchpad.net/heat/+bug/1397883
  35. - https://docs.python.org/3/reference/simple_stmts.html#the-assert-statement
  36. - https://cwe.mitre.org/data/definitions/703.html
  37. .. versionadded:: 0.11.0
  38. .. versionchanged:: 1.7.3
  39. CWE information added
  40. """
  41. import fnmatch
  42. import bandit
  43. from bandit.core import issue
  44. from bandit.core import test_properties as test
  45. def gen_config(name):
  46. if name == "assert_used":
  47. return {"skips": []}
  48. @test.takes_config
  49. @test.test_id("B101")
  50. @test.checks("Assert")
  51. def assert_used(context, config):
  52. for skip in config.get("skips", []):
  53. if fnmatch.fnmatch(context.filename, skip):
  54. return None
  55. return bandit.Issue(
  56. severity=bandit.LOW,
  57. confidence=bandit.HIGH,
  58. cwe=issue.Cwe.IMPROPER_CHECK_OF_EXCEPT_COND,
  59. text=(
  60. "Use of assert detected. The enclosed code "
  61. "will be removed when compiling to optimised byte code."
  62. ),
  63. )