I have a API
:
import stripe
class StripeWebHook(APIView):
permission_classes = (AllowAny,)
authentication_classes = ()
def post(self, request, *args, **kwargs):
payload = request.body
try:
event = stripe.Event.construct_from(
json.loads(payload), stripe.api_key
)
except ValueError as e:
return Response(status=400)
How can I write a test using patch
for testing the request to an external API (e.g. stripe.Event.create
) without transferring that function call from my main function?
I managed to test it by rewriting the function as follows:
def get_api_result(payload):
return stripe.Event.construct_from(
json.loads(payload), stripe.api_key
)
class StripeWebHook(APIView):
def post(self):
payload = request.body
res = get_api_result(payload)
# ...
and using mock
:
import mock
@mock.patch('get_api_result')
def test_payment(self, mockEvent) -> None:
#...
mockEvent.return_value = obj
But I don't like this approach. It doesn't seem right that I have to add another function just to mock it out.
I tried this
import stripe
class StripeWebHookTestCase(APITestCase):
@mock.patch('donation.views.stripe.Event.construct_from')
def test_stripe_web_hook(self, mockEvent) -> None:
# logic
mockEvent.return_value = object
resp = self.client.post(reverse('stripe-web-hook'))
But I get error Expecting value: line 1 column 1 (char 0)
Traceback
File "/usr/local/lib/python3.7/json/__init__.py", line 348, in loads
return _default_decoder.decode(s)
File "/usr/local/lib/python3.7/json/decoder.py", line 337, in decode
obj, end = self.raw_decode(s, idx=_w(s, 0).end())
File "/usr/local/lib/python3.7/json/decoder.py", line 355, in raw_decode
raise JSONDecodeError("Expecting value", s, err.value) from None
json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0)
structure of the project
project/
project/
donation/
tests/
test_view.py (StripeWebHookTestCase)
views.py (StripeWebHook)
settings/
manage.py