'How can I make bandit skip B101 within tests?

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?



Solution 1:[1]

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.

Solution 2:[2]

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"]

Solution 3:[3]

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.

Solution 4:[4]

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

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2 diegovalenzuelaiturra
Solution 3
Solution 4 Shivam_kira