python中常用的mock介绍

mock

(Python 标准库) 一个用于伪造测试的库

使用

  • 被测试的类
class Count():
   def add(self):
       pass
  • 用mock测试
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

  • 安装
pip install HTTPretty
  • 使用
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
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')
  • 也可以使用正则
@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+ 生成 伪造请求的库。

  • 安装
pip install httmock
  • 使用
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?'
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
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源码

    原文作者:望月成三人
    原文地址: https://www.jianshu.com/p/8d15385681f4
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞