'Python/Django Test: Mock Verification Service
I am attempting to write a test for a service that uses the Twilio Verification service. I am basing my test off of the following article: https://www.twilio.com/blog/testing-twilio-applications-python-pytest
However, I cannot seem to properly target the client.verify.services.verifications.create method from the TwilioRest module as the request always gets sent to the Twilio server.
Has anyone had any success properly mocking this method ?
verification/services.py
from decouple import config
from twilio.rest import Client
from twilio.base.exceptions import TwilioRestException
from .config import INVALID_PARAMETER, TOO_MANY_REQUESTS
account_sid_production = config("TWILIO_ACCOUNT_SID_PRODUCTION")
auth_token_production = config("TWILIO_AUTH_TOKEN_PRODUCTION")
verify_service_sid = config("TWILIO_VERIFY_SERVICE_SID")
client = Client(account_sid_production, auth_token_production)
def verification_service_create(phone_number, channel="sms"):
try:
client.verify.services(verify_service_sid).verifications.create(
to=phone_number, channel=channel
)
return (
True,
"Check your phone for verification code",
"Verification Code successfully sent",
)
except TwilioRestException as error:
if error.code == INVALID_PARAMETER:
return (
False,
"Phone value is incorrectly formatted or is not a valid phone number.",
"Use strict E.164 formatting, including the + sign,"
"for phone numbers in the To parameter. Example: +15017122661.",
)
if error.code == TOO_MANY_REQUESTS:
return (
False,
"You have sent too many requests to this service. Please try again later.",
"You have sent too many requests to this service. Please try again later.",
)
return (
False,
"Internal Error",
"Internal Error",
)
verification/tests/services/test_verification_service_create.py
from unittest.mock import patch
from django.test import TestCase
from verification.services import verification_service_create
class TwilioVerificationServiceCreateTest(
TestCase,
):
@patch(
"verification.services.client.verify.services.create", return_value=(True)
)
def test_verification_service_create_a(self, mock_verification_service_create):
mock_verification_service_create.return_value = True
is_success = verification_service_create("MOCK PHONE NUMBER")
# self.assertIs(mock_utils.called, True)
self.assertIs(is_success, True)
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
