简体   繁体   English

如何在 pytest 请求模拟中伪造我的响应

[英]How to fake my response in pytest requests mock

My function that I am trying to test is returning list of strings :我要测试的函数是返回strings list

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我收到如下错误: json.decoder.JSONDecodeErrorstr 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.您必须在模拟响应的json字段中传递所需的有效负载。 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']

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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