'django mock sms send

I have a method that sends sms to your phone, how can I mock it?

services.py

def send_msg(phone_number):
    url = settings.SMS_API_URL
    params = {
              ...
              }
    resp = requests.get(url, params)
    status_code = resp.json().get('status_code')
    return status_code

tests.py

@pytest.mark.django_db
// mock it
def test_sms_send(api_client):
    data = {
        'phone_number': 'some_valid_phone_number'
    }
    response = api_client.post(reverse('phone_verify'), data=data)

    assert response.status_code == status.HTTP_200_OK


Solution 1:[1]

I would try monkey-patching this within your unit tests.

The idea is to add a step to enable you to replace the implementation of the function before your tests are running and the server is initiated.

Try this example from the docs (a bit modified):

import pytest

@pytest.hookimpl(tryfirst=True)
def patch_send_sms_function():
    import project.app.api_utils

    def _patched_send_sms(phone_number):
        return 200

    project.app.api_utils.send_sms = _patched_send_sms


@pytest.mark.django_db
def test_sms_send(api_client):
    ...

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Jossef Harush Kadouri