How to ignore warnings in Python unit tests (pytest / tox)

Problem:

You have a unit test case such as this one from UliEngineering

def test_ratio_to_dB_infinite(self):
    self.assertEqual(-np.inf, ratio_to_dB(0))
    self.assertEqual(-np.inf, ratio_to_dB(0, factor=dBFactor.Power))
    self.assertEqual(-np.inf, ratio_to_dB(-5))
    self.assertEqual(-np.inf, ratio_to_dB(-5, factor=dBFactor.Power))

which outputs a warning:

tests/Math/TestDecibel.py::TestDecibel::test_ratio_to_dB_infinite
  /home/uli/UliEngineering/UliEngineering/Math/Decibel.py:29: RuntimeWarning: divide by zero encountered in log10
    return np.log10(v)

Solution

You canĀ ignore that specific warning for this specific test caseby using a pytest annotation:

import pytest

@pytest.mark.filterwarnings("ignore:divide by zero encountered in log10")
def test_ratio_to_dB_infinite(self):
    self.assertEqual(-np.inf, ratio_to_dB(0))
    self.assertEqual(-np.inf, ratio_to_dB(0, factor=dBFactor.Power))
    self.assertEqual(-np.inf, ratio_to_dB(-5))
    self.assertEqual(-np.inf, ratio_to_dB(-5, factor=dBFactor.Power))

Other warnings will still be emitted.