How can I make bandit skip B101 within tests?

13.6k views Asked by At

I'm using bandit to check my code for potential security issues:

bandit -r git-repository/

However, the most common item found by bandit is B101. It is triggered by assert statements within tests. I use pytest, so this is not a concern, but a good practice. I've now created a .bandit file with

[bandit]
skips: B101

But that also skips a lot of other code. Is there a solution to this issue?

7

There are 7 answers

0
angelo-peronio On BEST ANSWER

A possible solution is to tell bandit to skip tests altogether. Assuming your code lives in a src subfolder, run

bandit --configfile bandit.yaml --recursive src

with the following bandit.yaml in the project's root directory

# Do not check paths including `/tests/`:
# they use `assert`, leading to B101 false positives.
exclude_dirs:
    - '/tests/'

There is a bunch of related issues and pull requests.

Update: I like Diego's solution better.

8
janpeterka On

Based on documentation, your config should look like skips: ['B101'], not skips: B101 (which you have).

EDIT:
Ok, so if I understand correctly, you want to skip B101 on your tests folder. I am not aware of any way to specify this, but I can think of hack of a sort - just run bandit two times - once ignoring tests, and once only on tests skipping B101. I know, it's not most elegant way, but it should solve your problem.

0
Shivam_kira On

You can configure files that skip this check. This is often useful when you use assert statements in test cases.

bandit --configfile bandit.yaml

with the following bandit.yaml in the project's root directory

assert_used:
  skips: ['*_test.py', 'test_*.py']

Link to the original doc

0
Julio Batista Silva On

I have the following in my pyproject.toml:

[tool.bandit]
exclude_dirs = [".venv", "tests"]
skips = ["B307"]

From the command line I just add -c pyproject.toml and bandit reads the configuration from there.

In VSCode:

"python.linting.banditArgs": [
    "--configfile",
    "pyproject.toml"
]
0
Serhii Kushchenko On

How I achieved bandit skip B101 within tests in Visual Studio Code:

  1. in the project's root I have bandit.yaml file with the following content:
assert_used:
    skips: ["*/test_*.py"]
  1. In the settings.json file I have:
"python.linting.banditArgs": [
    "-r",
    "--configfile",
    "${workspaceFolder}/bandit.yaml"
],
2
diegovalenzuelaiturra On

Based on this comment,

when using --recursive the whole path is fnmatched against the glob_list, therefore an --exclude_dir expression test_*.py doesn't matches and excludes (py)test files in subdirectories, for that */test_*.py is needed.

The following configuration should solve your problem:

assert_used:
  skips: ["*/test_*.py", "*/test_*.py"]
0
Aaron Alphonso On

Just wanted to add to the answers above and mention the toml equivalent of skipping assert_used for specific files:

[tool.bandit.assert_used]
skips = ['*_test.py', '*/test_*.py']