简体   繁体   中英

How to fake my response in pytest requests mock

My function that I am trying to test is returning list of strings :

def listForumsIds:
    response = requests.get(url)
    forums= response.json().get('forums')
    forumsIds= [forum['documentId'] for forum in forums]
    # return like: ['id1', 'id2', 'id3'.....]
    return forumsIds

My test function:

@requests_mock.mock()
def test_forms(self, m):
    # I also used json='response'
    m.get('valid url', text="response", status_code=200)
    resp = listForumsIds('valid url')
    # ERROR !!!!
    assert resp == "response"

I am getting error like: json.decoder.JSONDecodeError or str object has no attribute get

How to fake my response to be match return value of my function?

You have to pass the desired payload in the json field of the mocked response. Example, adapted to your code:

class MyTests(unittest.TestCase):

    @requests_mock.mock()
    def test_forms(self, m):
        payload = {"forums": [{"documentId": "id1"}]}
        m.register_uri("GET", "https://www.example.com", json=payload)
        ids = listForumsIds('https://www.example.com')
        assert ids == ['id1']

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM