Home > Back-end >  how to write tests for a function in which requests.get is called in a loop for different urls?
how to write tests for a function in which requests.get is called in a loop for different urls?

Time:10-15

I have a function which calls requests.get in a for loop for a given set of URLs. How can I patch requests.get such that I can set

requests.get.return_vaulue = something based on input URL

??

CodePudding user response:

You can define a function that returns some different output based on the given input URL and set that function as the side_effect of requests.get in your test method.

myscript.py (the script that contains the function that uses requests.get in a for loop):

import requests


def your_function(urls, body, ...):
    for url in urls:
        requests.get(...)

    return ...

...

test_myscript.py (the script that contains your test classes):

import unittest
from unittest.mock import patch

from myscript import your_function


def your_mock_function(url: str):
    if 'https' in url:
        return 1
    elif ...:
        return 2
    ...


class YourTestClass(unittest.TestCase):
    @patch('myscript.requests.get')
    def your_test_method(self, mock_requests_get):
        mock_requests_get.side_effect = your_mock_function

        # Test your function here...

CodePudding user response:

I guess the easiest way is to write a wrapper function, ie.

def my_requests(url, params=None, **kwargs):
    # some logic to run before requests.get
    response = requests.get(url, params=None, **kwargs)
    # some logic to run after eg.
    if some_decision(url):
       return 'my response'
    return response
   
    
  • Related