vendredi 13 mars 2020

How to mock POST requests in python using unittest.mock

I am trying to mock POST requests that are directed to another service.

This service takes a JSON input of the following format -

{
    'input' : 'data string'
}

And returns -

{
    'processed' : 'processed data string'
}

I have the following implementation to access this service -

FileA.py

class Client:
    def __init__(self, processing_url):
        self.processing_url = processing_url

    def process(self, data):
        resp = requests.post(url=self.processing_url, json={'input':data})
        return resp.json()['processed']


class Stuff:
    def __init__(self, config):
        self.config = config
        self.client = Client(config['url'])

        # Ping To Test
        processed = self.client.process("Hello World")

    def maker(self, data):
        # Tasks
        data_p = self.client.process(data)
        # Tasks
        return data_p

FileB.py

from FileA import Stuff

config = {'url':'http://....'}
stuff_maker = Stuff(config)

def do_things(data):
    # Things
    data = stuff_maker.maker(data)
    # Things
    return data

I want to test do_things function. What I have tried till now -

Test.py

from unittest.mock import Mock, patch
from FileB import do_things

@patch("FileA.Client.process.requests.post")
def test_things(mock_post):
    mock_post.return_value = Mock(ok=True)
    mock_post.return_value.json.return_value = {'processed':'_hello _world'}
    test_case = do_things("Hello World")
    assert #Some assertion case here.

The Error - I keep getting the error for client trying to connect to the service while pinging "Hello World" when I initalise the Client() in Stuff()

Aucun commentaire:

Enregistrer un commentaire