python mock一个类_python中常用的mock介绍

本文介绍了Python中用于测试模拟的三个库:Mock(Python标准库)、HTTPretty(HTTP请求模拟工具)和httmock。通过示例展示了如何使用它们来替换真实依赖,进行单元测试。Mock可以模拟类的方法;HTTPretty专注于HTTP请求的模拟,支持GET和POST;httmock提供了一种简洁的方式模拟HTTP响应。
摘要由CSDN通过智能技术生成

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')

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']

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值