0

I am trying to write a unit test that calls a function repeatedly and testing what happens if it gets run multiple times with the same inputs. A by-product of the function is that there are some warnings that are emitted whenever it is run. This results in code like:

with pytest.warns(RuntimeWarning, match='depends on the pytest parametrization'):
    output = func(**kwargs)

This gets really verbose when I use pytest.mark.parametrize, which then now results in multiple if pytest.warns(...) type code.

Can I specify to just ignore all warnings that are emitted in line for just a specific line in the unit test? E.g. something like this

with pytest.ignore_all_warnings():
    output = func(**kwargs)

Other Ways to Ignore Warnings

I am aware of can pytest ignore a specific warning? and in general ways to ignore warnings, but those ignore across files, and functions. I would like to just ignore warnings in a specific line of the unit test.

ajl123
  • 1,172
  • 5
  • 17
  • 40

1 Answers1

0

As described in the Python documentation, you can use the catch_warnings context manager to limit changes in the warnings filter to a code block. If you use it with an unspecific filter that ignores all warnings, you can suppress all warnings in a single line :

import warnings
...

with warnings.catch_warnings():
    # ignore all warnings
    warnings.filterwarnings('ignore')
    do_stuff()

This is not specific to pytest, but can be used in any code.

MrBean Bremen
  • 14,916
  • 3
  • 26
  • 46