Home > other >  Trying to test a function but in test it returns None?
Trying to test a function but in test it returns None?

Time:03-15

I Have this function that I wish to test, this is how it looks like.

def myfunction():
        response = requests.post(url,params=params,headers=headers,data=data)
        response = response.json()
        return response["Findme"].lower()

My test script:

@mock.patch('requests.post',return_value="{'Findme': 'test'}")
def test_myfunction(mocked_post):
    **assert myfunction() == "test"**

When i run the test, i keep getting None for myfunction(), but when i remove the response.json() it works?

Please can anyone assist me.

CodePudding user response:

As mentioned by Deep Space, your returned object does not have a json method, as it is of type str. If you want to have the same behavior as in the tested function, you have to provide an object with that method:

class MockResponse:
    """Mocks relevant part of requests.Response"""
    def __init__(self, s):
        self.json_string = s

    def json(self):
        return json.loads(self.json_string)


@mock.patch("requests.post", return_value=MockResponse('{"Findme": "test"}'))
def test_myfunction(mocked_post):
    assert myfunction() == "test"

This way, an object of type MockResponse is returned from the mocked post function, that can be deserialized using json().

You could also mock the return value of json directly instead of mocking the return value of post, if you want to do this. In this case you wouldn't need an extra class:

@mock.patch("requests.post")
def test_myfunction(mocked_post):
    mocked_post.return_value.json.return_value = {"Findme": "test"}
    assert myfunction() == "test"
  • Related