'Mocking a helper function in django view test

I have a view function that initiates user login requests

it looks something like this:

def initiate_login(request):
    # get request parameters
    return check_user_and_send_otp(login_id)

The request is then processed by another function

def check_user_and_send_otp(login_id):
    # check if user exits
    return send_otp_to_user(phone_number)

And then another function

def send_otp_to_user(phone_number):
    # sends a message to user
    return response

The problem is while testing my code, I don't want to send messages to a phone number while testing.

My login test function looks somewhat like this, is it possible to mock it without changing my code?

    def test_login_initiator(self):
    response = self.client.post(self.login_url, data=self.login_data, content_type="application/json", **self.headers)
    self.assertEqual(response.status_code, 200)

All these functions that were called by others are located in seperate modules



Solution 1:[1]

If you don't want to actually receive the message on a physical phone, you can use online sms receivers. Check out this blog.

Additionally, you can send messages through other free online services like Way2sms. You just have to google them up. To do this from within Python, you need to use web parsing using urllib2/requests and beautifulsoup, which is a totally new question.

Or you can skip this function by simply commenting out the message sender code or returning true from the function.

If you wanna live dangerously, think about making a config file which can help you to make switches that tell whether to execute something or not.

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