Skip to content

Instantly share code, notes, and snippets.

@ods
Created August 11, 2022 11:54
Show Gist options
  • Save ods/b8bfd793dcf63eef67687fd3089e8ad5 to your computer and use it in GitHub Desktop.
Save ods/b8bfd793dcf63eef67687fd3089e8ad5 to your computer and use it in GitHub Desktop.
pytest.raises() variation accepting None for cases when no exception is expected
from contextlib import nullcontext
from typing import ContextManager, Optional, Union
import pytest
def maybe_raises(
exception: Union[type[BaseException], tuple[type[BaseException], ...]]
) -> ContextManager[Optional[pytest.ExceptionInfo[BaseException]]]:
if exception is None:
return nullcontext()
else:
return pytest.raises(exception)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment