Skip to content

Instantly share code, notes, and snippets.

@thoroc
Last active April 14, 2022 10:48
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/faeb48c2b0192e2fcbb7408b07013277 to your computer and use it in GitHub Desktop.
Save thoroc/faeb48c2b0192e2fcbb7408b07013277 to your computer and use it in GitHub Desktop.
mock request object

Simple scenario to demontrate how to mock requests' post

============================================================================== 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 2 items

test.py::test__call_soap_endpoint_ok PASSED                                                                                                                                [ 50%]
test.py::test__call_soap_endpoint_exception PASSED                                                                                                                         [100%]

=============================================================================== 2 passed in 0.17s ================================================================================
from http import HTTPStatus
from unittest.mock import patch
from urllib.error import HTTPError
import pytest
import requests
class CustomException(Exception):
_message: str = "Custom Exception"
def __init__(self, message: str = None):
if message:
self._message = message
super().__init__(self._message)
@property
def message(self):
return self._message
class SoapClient:
_ENDPOINT = "http://localhost:8080/ws/services/Soap/mock"
_HEADERS = {
"Content-Type": "text/xml;charset=UTF-8",
}
def _call_soap_endpoint(self, payload: str) -> requests.Response:
""" Calls the privacy manager soap endpoint """
try:
return requests.post(
url=self._ENDPOINT,
data=payload,
headers=self._HEADERS
)
except HTTPError as http_error:
raise CustomException() from http_error
@patch("requests.post")
def test__call_soap_endpoint_ok(mock_post_requests):
# Arrange
mock_post_requests.return_value.status_code = HTTPStatus.OK.value
mock_post_requests.return_value.content = HTTPStatus.OK.description
payload = """
<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/">
<soapenv:Body>
<mock:Content xmlns:mock="http://mock.com/">
<status>SUCCESS</status>
</mock:Content>
</soapenv:Body>
</soapenv:Envelope>
"""
# Act
client = SoapClient()
response = client._call_soap_endpoint(payload) # pylint: disable=protected-access
# Assert
assert response.status_code == HTTPStatus.OK.value
assert response.content == HTTPStatus.OK.description
@patch("requests.post")
def test__call_soap_endpoint_exception(mock_post_requests):
# Arrange
mock_post_requests.side_effect = CustomException("Soap Call failed")
payload = """
<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/">
<soapenv:Body>
<mock:Content xmlns:mock="http://mock.com/">
<status>FAILURE</status>
</mock:Content>
</soapenv:Body>
</soapenv:Envelope>
"""
# Act
client = SoapClient()
with pytest.raises(CustomException) as exc_info:
client._call_soap_endpoint(payload) # pylint: disable=protected-access
# Assert
assert exc_info.value.message == "Soap Call failed"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment