Skip to content

Instantly share code, notes, and snippets.

@leorochael
Last active February 11, 2021 14:56
Show Gist options
  • Save leorochael/a3163c324641939128bd01ded646673d to your computer and use it in GitHub Desktop.
Save leorochael/a3163c324641939128bd01ded646673d to your computer and use it in GitHub Desktop.
Fixture for when you're getting warnings deep in your code during test
"""
Add this fixture to a file containing a test, or to your global `conftest.py`, to turn warnings into errors.
This way the test will break at the warning point, and your traceback will likely contain all functions or methods
responsible for creating the conditions for the warning being raised.
For instance, in the case of a `SettingWithCopyWarning` from pandas, the function that tries to mutate a dataframe
view/slice might not be the function that created the dataframe view/slice in the first place, but that function
is probably in the stack somewhere.
So converting the warning into an error causes a traceback that makes the origin of the problematic dataframe
easier to locate...
"""
@pytest.fixture(autouse=True)
def setting_with_copy_warning_error():
import warnings
from pandas.core.common import SettingWithCopyWarning
with warnings.catch_warnings(record=True) as w:
warnings.filterwarnings("error", category=SettingWithCopyWarning)
yield w
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment