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源码

©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

  • mock (Python 标准库) 一个用于伪造测试的库 使用 被测试的类 用mock测试 HTTPretty P...
    望月成三人阅读 3,135评论 1 7
  • # Python 资源大全中文版 我想很多程序员应该记得 GitHub 上有一个 Awesome - XXX 系列...
    小迈克阅读 3,127评论 1 3
  • 1. Mock测试介绍 定义在单元测试过程中,对于某些不容易构造或者不容易获取的对象,用一个虚拟对象来创建以便测试...
    GGarrett阅读 4,886评论 0 1
  • Python 面向对象Python从设计之初就已经是一门面向对象的语言,正因为如此,在Python中创建一个类和对...
    顺毛阅读 4,372评论 4 16
  • Web UI测试自动化 splinter - web UI测试工具,基于selnium封装。 selenium -...
    Thea0216阅读 6,474评论 2 48

友情链接更多精彩内容