python - Pytest 如何模拟 requests库中的Response对象?
迷茫
迷茫 2017-04-17 17:33:01
[Python讨论组]

请问如何在 Pytest 框架中模拟requests库中的Response对象?

涉及到的主体代码如下:

def get_address(phone):
    url = 'http://www.ip138.com:8080/search.asp?action=mobile&mobile=%s' % (phone)
    r = requests.get(url)
    r.encoding = 'GBK'
    soup = BeautifulSoup(r.text, 'html.parser')
    try:
        data = soup.find_all('td')[6].text.split('\xa0')
    except IndexError:
        data = False
    print(data)
    return data

测试代码如下:

correct_response = requests.get('http://www.ip138.com:8080/search.asp?action=mobile&mobile=13012345678')
wrong_response = requests.get('http://www.ip138.com:8080/search.asp?action=mobile&mobile=110')

def test_get_address(monkeypatch):
    def test1(phone):
        return correct_response

    def test2(phone):
        return wrong_response

    monkeypatch.setattr('requests.get', test1)
    assert cli.get_address('13012345678') == ['重庆', '']
    monkeypatch.setattr('requests.get', test2)
    assert cli.get_address('110') == False

我希望可以构造一个Response对象,并在test函数中直接返回,但是Response对象中的text函数是无法修改的。

迷茫
迷茫

业精于勤,荒于嬉;行成于思,毁于随。

全部回复(1)
PHPz

requests.models

很简单, 初始化一个实例, 设置 Response.content 属性就好了. text, json, file 等属性都是由 content 通过处理得到的, 也就是说 content 才是响应的正文部分.

看看源代码就啥都知道了

热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 意见反馈 讲师合作 广告合作 最新更新 English
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送
PHP中文网APP
随时随地碎片化学习
PHP中文网抖音号
发现有趣的

Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号