Pybandit to allow B311: pseudo-random generators to be used in tests

2.6k views Asked by At

I've used random.choice for tests. And Bandit is showing warnings.

x = random.choice(lists)

I know I could use # nosec comment to suppress the warning. But it would be inconvinent to do it in all lines

x = random.choice(lists)  # nosec

I want to allow random for file with tests_*.py using .bandit configuration files. I've found from other samples that you can do it for things like asserts like:

.bandit

assert_used:
    skips: ['test.py$', '^test_*.py']

So is there any way for B311 ?

3

There are 3 answers

2
awatts On

If you're using Python 3.6 or above then, in general, use the "secrets" library rather than the "random" library.

From the documentation The secrets module is used for generating cryptographically strong random numbers suitable for managing data such as passwords, account authentication, security tokens, and related secrets.

Whilst you might not need cryptographically strong random numbers for your tests, it's likely that it will not hurt either, unless your random number generated is seeded.

Seeding the random number generator will ensure that the random number generator emits the same random numbers on each run. This ensures your tests are reproducible. This is usually desirable.

If for some reason you do want to use truly random numbers then use secrets and bandit will not have a problem with it, and it avoids any special bandit configuration.

0
Arkemix On

You can skip it adding #nosec to the code.

Or You can skip the B311 using the --skip argument to the command line.

0
Cees Timmerman On

This is okay according to python -m bandit -r test

def test_fuzz():  # nosec
    for i in range(10):
        length = random.randint(0, 200)

If you don't want to label a line (which allows # nosec B311) or function with # nosec which also ignores B101, use --skips:

python -m bandit --skip B311 -r test

Maybe python -m pip install --upgrade bandit as 1.7 supports pyproject.toml though not by default so python -m bandit -r test --config pyproject.toml:

[tool.bandit]
skips = ["B101", "B311"]

pyproject.toml replaces setup.cfg in at least Visual Studio Code, so you might prefer python -m bandit -r test --ini setup.cfg:

[bandit]
skips = B101,B311

YAML's nesting allows configuration per test plugin, as you noted. Unfortunately B311 is not a plugin, but i've filed an enhancement request for that.