Mikko Ohtamaa
Mikko Ohtamaa

Reputation: 83546

pytest: ignore third party library warnings with -Werror

I am running my unit tests as:

pytest -Werror

... to ensure my code does not raise any warnings.

However I am using third party libraries I cannot fix. These third party libraries are causing warnings which then will cause pytest -Werror to abort.

In my case the warning is DeprecationWarning so I cannot disable this warning by the exception class, as it is too wide and affects other code too.

How do I suppress the third party library warnings so that pytest ignores them?

I have tried:

    with warnings.catch_warnings():
        call_third_party_code_with_warnings()

... but pytest still terminates the test as ERROR and ignores warnings.catch_warnings.

Specifically warning is

  File "/Users/moo/Library/Caches/pypoetry/virtualenvs/trade-executor-8Oz1GdY1-py3.10/lib/python3.10/site-packages/jsonschema/validators.py", line 196, in __init_subclass__
    warnings.warn(
DeprecationWarning: Subclassing validator classes is not intended to be part of their public API. A future version will make doing so an error, as the behavior of subclasses isn't guaranteed to stay the same between releases of jsonschema. Instead, prefer composition of validators, wrapping them in an object owned entirely by the downstream library.

Disabling warning output in pyproject.toml seems to disable the warning output in pytest, but does not seem to affect -Werror flag exceptions.

filterwarnings = [
    "ignore:::.*.jsonschema",
    # DeprecationWarning: Subclassing validator classes is not intended to be part of their public API. A future version will make doing so an error, as the behavior of subclasses isn't guaranteed to stay the same between releases of jsonschema. Instead, prefer composition of validators, wrapping them in an object owned entirely by the downstream library.
    "ignore:::.*.validators",
    "ignore::DeprecationWarning:openapi_spec_validator.*:"
]

Upvotes: 1

Views: 1801

Answers (1)

Guy
Guy

Reputation: 50899

You can add filterwarnings in pytest.ini

[pytest]
filterwarnings = ignore::DeprecationWarning:THIRD_PARTY_NAME.*:

or ignore everything from this library if you prefer

filterwarnings = ignore:::.*.THIRD_PARTY_NAME

Edit

Instead of using -Werror flag you can use pytest.ini to get the same results and ignore the library

[pytest]
filterwarnings = 
    error
    ignore::DeprecationWarning

I know you don't want to silence completely this warning, how ever it's not raised from the third-party, it's raised from builtins.py.

You could try something like ignore::jsonschema.validators.DeprecationWarning, but I doubt it will work.

Upvotes: 5

Related Questions