Skip to content

Instantly share code, notes, and snippets.

@thoroc
Last active April 15, 2022 15:10
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save thoroc/ff61bfa8c67fbce6619f7b7458978c0b to your computer and use it in GitHub Desktop.
Save thoroc/ff61bfa8c67fbce6619f7b7458978c0b to your computer and use it in GitHub Desktop.
pytest raises example

Simple scenario to demontrate how to assert for custom exception

============================================================================== test session starts ===============================================================================
platform darwin -- Python 3.7.10, pytest-6.1.1, py-1.11.0, pluggy-0.13.1 -- /python/.venv/bin/python3
cachedir: .pytest_cache
rootdir: /python, configfile: pytest.ini
plugins: Faker-13.3.3, anyio-3.5.0, mock-3.3.1, cov-2.10.1, icdiff-0.5
collected 5 items

test.py::test__get_status_ok[SUCCESS-True] PASSED                                                                                                                      [ 20%]
test.py::test__get_status_ok[FAILURE-False] PASSED                                                                                                                     [ 40%]
test.py::test__get_status_ok[PENDING-False] PASSED                                                                                                                     [ 60%]
test.py::test__get_status_invalid_payload PASSED                                                                                                                           [ 80%]
test.py::test__get_status_exception PASSED                                                                                                                             [100%]

=============================================================================== 5 passed in 0.12s ================================================================================
import pytest
class CustomException(Exception):
MALFORMED_PAYLOAD_ERROR = "Malformed payload"
INVALID_PAYLOAD_ERROR = "Invalid payload"
_message: str = "Custom Exception"
_error: str = ""
def __init__(self, message: str = None, error: object = None):
if message is not None:
self._message = message
if error is not None:
self._error = error if isinstance(error, str) else repr(error)
super().__init__(self._message)
@property
def message(self):
return self._message
@property
def error(self):
return self._error
class MyClass:
STATUS_SUCCESS = "SUCCESS"
STATUS_FAILURE = "FAILURE"
STATUS_PENDING = "PENDING"
def _get_status(self, payload: dict) -> bool:
try:
status = payload["body"]["status"]
if status == self.STATUS_SUCCESS:
return True
elif status in (self.STATUS_FAILURE, self.STATUS_PENDING):
return False
else:
raise CustomException(
message=CustomException.INVALID_PAYLOAD_ERROR,
error=status
)
except KeyError as exc:
raise CustomException(
message=CustomException.MALFORMED_PAYLOAD_ERROR,
error=exc
) from exc
@pytest.mark.parametrize("payload_status, expected_result", [
(MyClass.STATUS_SUCCESS, True),
(MyClass.STATUS_FAILURE, False),
(MyClass.STATUS_PENDING, False),
])
def test__get_status_ok(payload_status, expected_result):
# Arrange
payload = {"body": {"status": payload_status}}
instance = MyClass()
# Act
status = instance._get_status(payload) # pylint: disable=protected-access
# Assert
assert status == expected_result
def test__get_status_invalid_payload():
# Arrange
payload = {"body": {"status": "UNKNOWN"}}
# Act
with pytest.raises(CustomException) as exc_info:
MyClass()._get_status(payload) # pylint: disable=protected-access
# Assert
assert exc_info.value.message == CustomException.INVALID_PAYLOAD_ERROR
assert exc_info.value.error == "UNKNOWN"
def test__get_status_exception():
# Arrange
payload = {"body": {}}
instance = MyClass()
# Act
with pytest.raises(CustomException) as exc_info:
instance._get_status(payload) # pylint: disable=protected-access
# Assert
assert exc_info.value.message == CustomException.MALFORMED_PAYLOAD_ERROR
assert exc_info.value.error == repr(KeyError("status"))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment