首页 > Python如何测试HTTP客户端程序?

Python如何测试HTTP客户端程序?

打算写一个模拟HTTP客户端的程序(通过urlopen来发送和接收HTTP请求)。

需要写单元测试,初步打算使用unittest测试框架写测试用例。但是受具体环境限制,不能真正发送HTTP请求。
现在,退而求其次,写一个测试用例,不用发送请求并验证服务器返回的数据,只需要检查HTTP请求的头部和数据部分是否正确就好。
怎么写这种测试用例?
初步的想法是mock一个HTTP Server


OK,找到了unittest.mock
unittest.mock本来是用来在单元测试中hook第三方模块(类/函数)的(绕过原来的模块),但是HTTP请求也是通过某个函数发送的,也可以用它来模拟。


以下为示例:
main.py 待测程序

from urllib.request import urlopen


def func():
    url_ip = 'http://ifconfig.me/ip'
    ip = None
    try:
        ip = urlopen(url_ip)
    except:
        pass
    return ip


if __name__ == '__main__':
    print(func())

test.py 测试用例

import unittest
from unittest import mock

from main import func


class FuncTestCase(unittest.TestCase):
    @mock.patch('main.urlopen')
    def test_func(self, mock_open):
        mock_open.return_value = '127.0.0.1'
        #设置模拟函数的返回值
        result = func()
        #调用待测功能,但已经模拟了urlopen函数
        mock_open.assert_called_with('http://ifconfig.me/ip')
        #验证调用参数
        self.assertEqual(result, '127.0.0.1')
        #验证返回结果


if __name__ == '__main__':
    unittest.main()

缺陷:如果在func中调用了多次urlopen,则上述代码无法正常测试。
Update:可以通过设置mock对象的side_effect属性来用自己的函数替换系统函数(不过不太优雅)。


你可能需要这个。
http://docs.python-requests.org/en/latest/

【热门文章】
【热门文章】