0%

python中常用的mock介绍

1
2
3
class Count():
def add(self):
pass
  • 用mock测试
1
2
3
4
5
6
7
8
9
10
11
12
13
14
from unittest import mock
import unittest
from modular import Count
class TestCount(unittest.TestCase):

def test_add(self):
count = Count()
count.add = mock.Mock(return_value=13)
result = count.add(8,5)
self.assertEqual(result,13)


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

HTTPretty

Python 的 HTTP 请求 mock 工具,不支持py3

  • 安装
1
pip install HTTPretty
  • 使用
1
2
3
4
5
6
7
8
9
10
11
12
13
14
import requests
import httpretty

def test_one():
httpretty.enable() # enable HTTPretty so that it will monkey patch the socket module
httpretty.register_uri(httpretty.GET, "http://yipit.com/",
body="Find the best daily deals")

response = requests.get('http://yipit.com')

assert response.text == "Find the best daily deals"

httpretty.disable() # disable afterwards, so that you will have no problems in code that uses that socket module
httpretty.reset() # reset H
  • post
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
import requests
from sure import expect
import httpretty


@httpretty.activate
def test_yipit_api_integration():
httpretty.register_uri(httpretty.POST, "http://api.yipit.com/foo/",
body='{"repositories": ["HTTPretty", "lettuce"]}')

response = requests.post('http://api.yipit.com/foo',
'{"username": "gabrielfalcao"}',
headers={
'content-type': 'text/json',
})

expect(response.text).to.equal('{"repositories": ["HTTPretty", "lettuce"]}')
expect(httpretty.last_request().method).to.equal("POST")
expect(httpretty.last_request().headers['content-type']).to.equal('text/json')
  • 也可以使用正则
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    @httpretty.activate
    def test_httpretty_should_allow_registering_regexes():
    u"HTTPretty should allow registering regexes"

    httpretty.register_uri(
    httpretty.GET,
    re.compile("api.yipit.com/v2/deal;brand=(\w+)"),
    body="Found brand",
    )

    response = requests.get('https://api.yipit.com/v2/deal;brand=GAP')
    expect(response.text).to.equal('Found brand')
    expect(httpretty.last_request().method).to.equal('GET')
    expect(httpretty.last_request().path).to.equal('/v1/deal;brand=GAP')

查看HTTPretty源码

httmock

针对 Python 2.6+ 和 3.2+ 生成 伪造请求的库。

  • 安装

    1
    pip install httmock
  • 使用

1
2
3
4
5
6
7
8
9
10
from httmock import urlmatch, HTTMock
import requests

@urlmatch(netloc=r'(.*\.)?google\.com$')
def google_mock(url, request):
return 'Feeling lucky, punk?'

with HTTMock(google_mock):
r = requests.get('http://google.com/')
print r.content # 'Feeling lucky, punk?'
1
2
3
4
5
6
7
8
9
10
11
12
13
from httmock import all_requests, HTTMock
import requests

@all_requests
def response_content(url, request):
return {'status_code': 200,
'content': 'Oh hai'}

with HTTMock(response_content):
r = requests.get('https://foo_bar')

print r.status_code
print r.content
  • cookie
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
from httmock import all_requests, response, HTTMock
import requests

@all_requests
def response_content(url, request):
headers = {'content-type': 'application/json',
'Set-Cookie': 'foo=bar;'}
content = {'message': 'API rate limit exceeded'}
return response(403, content, headers, None, 5, request)

with HTTMock(response_content):
r = requests.get('https://api.github.com/users/whatever')

print r.json().get('message')
print r.cookies['foo']

查看httmock源码