python mock初步

Edit

从Android单元测试中,接触到Java的mock框架。参看这篇笔记《Android单元测试》。最近在做Dashboard Generator,要用python解析excel,ppt和网页,测试效率极低。所以考虑到可以用mock来代替一些耗时的操作和资源。于是接触到python的mock框架。
python mock在3.0中已经集成为内置类,但是2.7仍然需要用pip来安装。这也不难。然后在网上搜集了几篇还不错的文章,如下:

简介

因为是python语言的特性,所以Mock上手非常容易。窃以为比Java(Android) Mock要容易的多。

Mock vs. Stub/Fake

参看Using Mocks in Python,也可以参看Martin Fowler的一篇文章Mocks Aren’t Stubs
这里提到了Mock和Stub/Fake的区别。这是我以前一直没有注意到的。

为什么要用Mock?

A good unit test has to be repeatable, allowing you to isolate and identify a fault. But the test resource might give out stochastic results, or it might have widely varying response times. And as a result, you end up glossing over a potential showstopper.

测试必须是可重复的,解耦的。但代码用到的运行时资源往往是随机的,或者昂贵的(比如网页,总是在变化的,比如,download文件,非常耗时)。我们不能让我们的测试首先不能依赖于测试资源,其次需要有比较高的效率。

These are some of the reasons why you might want to use a mock in place of a test resource. A mock can present the same set of method interfaces as the resource to the test subject. But a mock is easier to setup, easier to manage. It can deliver deterministic results, and it can be customized to suit a particular test. And it can be easily updated to reflect changes in the actual resource.

Stubs & Fake

Stub

A stub presents a set of method interfaces to the test subject, the same set the subject would see in an actual test resource. When the test subject calls a stub method, the stub may respond with a predetermined set of results. It may raise an error or exception, also predetermined. A stub may track its interactions with the test subject, but it performs no tasks outside the narrow scope of its programming.

Fake

A fake also presents a set of method interfaces and tracks its interactions with the test subject. But unlike a stub, a fake actually processes input data from the test subject and produces results based on that data. In short, a fake is a functional, but non-production version of the actual test resource. It lacks the checks and balances found in resource, it uses simpler algorithms, and it seldom, if ever, stores or transports data.

Stub和Fake都是针对接口的模拟,在需要对状态进行测试的情况时,我们可以用Stub或者Fake。例如UnitTest++,就是用的Stub。
但是如果我们要测试具体的代码行为,我们往往要用到Mock。比如,一个函数调用了几次,用的什么参数,等等。

我的理解,其实他们三者之间并没有很明显的界限。用Mock的时候,针对一些需要模拟的接口,仍然可以有办法将之stub out。只是Mock并不擅长,方法不够直觉。同理Stub也可以用来mock掉一些对象。
Stub/Fake更像是应用于面向接口编程,而Mock更擅长于面向对象编程。

何时使用Mock

Of course, mocks are not without issues. Designing an accurate mock is difficult, especially if you have no reliable information on the test resource. You can try and find an open-source match, or you can make a guesstimate on the resource’s method interface. Whichever you choose, you can update the mock easily later on, should you get more detailed information on the preferred resource. Too many mocks can complicate a test, making it harder for you to track down a failure.
Best practice

  • is to limit a test case to one or two mocks
  • or use separate test cases for each mock/subject pairing.

如何使用

constructor

class Mock(spec=None, side_effect=None, return_value=DEFAULT, wraps=None, name=None, spec_set=None, **kwargs)

主要参数如下:

  • name: 只有标记作用,在print或者repr的时候可以看到,调试的时候有用
  • return_value: 最简单的对接口的stub化
  • side_effect: 其参数可以为列表或函数,若其返回值为DEFAULT,则采用return_value的值,若其返回值不是DEFAULT,则其会覆盖return_value的值
  • spec: 可以是string列表,也可以为class或instance。Accessing any attribute not in this list will raise an AttributeError.

side_effect为列表

>>> mock = Mock()
>>> mock.side_effect = [3, 2, 1]
>>> mock(), mock(), mock()
(3, 2, 1)

side_effect为函数,其参数与真实传入的参数相同

>>> side_effect = lambda value: value + 1
>>> mock = Mock(side_effect=side_effect)
>>> mock(3)
4
>>> mock(-8)
-7

对函数调用的检测

mock包含以下属性:

  • called
  • call_count
  • call_args
  • call_args_list
    含义显而易见,用法参考官方文档

method_calls & mock_calls

>>> mock = Mock()
>>> mock.method()
<Mock name='mock.method()' id='...'>
>>> mock.property.method.attribute()
<Mock name='mock.property.method.attribute()' id='...'>
>>> mock.method_calls
[call.method(), call.property.method.attribute()]

>>> mock = MagicMock()
>>> result = mock(1, 2, 3)
>>> mock.first(a=3)
<MagicMock name='mock.first()' id='...'>
>>> mock.second()
<MagicMock name='mock.second()' id='...'>
>>> int(mock)
1
>>> result(1)
<MagicMock name='mock()()' id='...'>
>>> expected = [call(1, 2, 3), call.first(a=3), call.second(),
... call.__int__(), call()(1)]
>>> mock.mock_calls == expected
True

assert

Mock提供了以下几种assert:

  • assert_called_once
  • assert_called_with
  • assert_called_once_with
  • assert_has_calls
  • assert_any_calls
    前面三个很直觉,后面两个稍作解释。

assert_any_call

The assert assert_any_call() checks if the test subject called a mocked method at any point of the test routine. This is regardless of how many other calls were made between the mocked method and the assert.

assert_has_calls

This one looks at a sequence of method calls, checks if they are in the right order and with the right arguments.

from mock import Mock, call

# The mock specification
class Foo(object):
_fooValue = 123

def callFoo(self):
pass

def doFoo(self, argValue):
pass

# create the mock object
mockFoo = Mock(spec = Foo)
print mockFoo
# returns <Mock spec='Foo' id='507120'>

mockFoo.callFoo()
mockFoo.doFoo("narf")
mockFoo.doFoo("zort")

fooCalls = [call.callFoo(), call.dooFoo("narf"), call.doFoo("zort")]

mockFoo.assert_has_calls(fooCalls)
# AssertionError: Calls not found.
# Expected: [call.callFoo(), call.dooFoo('narf'), call.doFoo('zort')]
# Actual: [call.callFoo(), call.doFoo('narf'), call.doFoo('zort')]

fooCalls = [call.callFoo(), call.dooFoo("narf"), call.doFoo("zort")]
mockFoo.assert_has_calls(fooCalls, any_order = True)
# AssertionError: (call.dooFoo('narf'),) not all found in call list

高阶特性

MagicMock vs. Mock

With Mock you can mock magic methods but you have to define them. MagicMock has “default implementations of most of the magic methods“.
If you don’t need to test any magic methods, Mock is adequate and doesn’t bring a lot of extraneous things into your tests. If you need to test a lot of magic methods MagicMock will save you some time.

哪些magic methods?看下面

  • lt: NotImplemented
  • gt: NotImplemented
  • le: NotImplemented
  • ge: NotImplemented
  • int : 1
  • contains : False
  • len : 1
  • iter : iter([])
  • exit : False
  • complex : 1j
  • float : 1.0
  • bool : True
  • nonzero : True
  • oct : ‘1’
  • hex : ‘0x1’
  • long : long(1)
  • index : 1
  • hash : default hash for the mock
  • str : default str for the mock
  • unicode : default unicode for the mock
  • sizeof: default sizeof for the mock
>>> mock = MagicMock()
>>> int(mock)
1
>>> len(mock)
0
>>> hex(mock)
'0x1'
>>> list(mock)
[]
>>> object() in mock
False

所谓magic methods就是一些内置的python运算符,而MagicMock支持这些运算符,Mock不支持

mock import

Mocking Python imports这里有提到。其实很简单,看代码

# A.py
import B
B.foo()

# test.py
A.B = mock.Mock()
A.B.foo.return_value = 123

mock class constructor

直接贴上实际的测试代码

mockSMBConnObj = mock.Mock()
mockSMBConn = mock.Mock(return_value=mockSMBConnObj) # mock constructor

mock对象的自动创建

当访问一个mock对象中不存在的属性时,mock会自动建立一个子mock对象,并且把正在访问的属性指向它,这个功能对于实现多级属性的mock很方便。

client = mock.Mock()
client.v2_client.get.return_value = '200'

上面例子中client.v2_client.get就是自动生成的mock对象
类似自动生成,我们还可以采用attach_mock的方法。不同的是,attach_mock会让被attach的双方具有父子关系,则对子mock的调用会被计入父的mock_calls。参考Attaching Mocks as Attributes

patch

通过patch,我们可以控制Mock对象的生存周期。意思就是在一个函数范围内,或者一个类的范围内,或者with语句的范围内mock掉一个对象。
有下面

decorator

>>> @patch('__main__.SomeClass')
... def function(normal_argument, mock_class):
... print mock_class is SomeClass
...
>>> function(None)
True

context manager

>>> class Class(object):
... def method(self):
... pass
...
>>> with patch('__main__.Class') as MockClass:
... instance = MockClass.return_value
... instance.method.return_value = 'foo'
... assert Class() is instance
... assert Class().method() == 'foo'

patcher

>>> Original = Class
>>> patcher = patch('__main__.Class', spec=True)
>>> MockClass = patcher.start()
>>> instance = MockClass()
>>> assert isinstance(instance, Original)
>>> patcher.stop()

patch.object和patch类似,只是写法不同,看下面对比:

@patch.object(SomeClass, 'class_method')
@patch('SomeClass.class_method')

patch还有很多种其他用法,patch.multiple, patch.dict等等。参看More Patch

其他未决的问题

其实还有很多mock高级的用法,例如,当我想mock掉win32com的时候,搜到的这个网页Mocking out python OS specific imports。其中有一段代码:

 modules = {
"_winreg": mock.MagicMock(),
"pythoncom": mock.MagicMock(),
"pywintypes": mock.MagicMock(),
"win32api": mock.MagicMock(),
"win32com": self.win32com,
"win32com.client": self.win32com.client,
"win32file": mock.MagicMock(),
"win32service": mock.MagicMock(),
"win32serviceutil": mock.MagicMock(),
"winerror": mock.MagicMock(),
"wmi": self.wmimock
}

self.module_patcher = mock.patch.dict("sys.modules", modules)
self.module_patcher.start()

还有如何mock掉win32com.client的对象?例如,待测代码如下

Application = win32com.client.Dispatch("PowerPoint.Application")
source_ppt = Application.Presentations.Open(path)
source_ppt.Slides.InsertFromFile(os.path.abspath(chart), index, 1, 1)

因为对win32com.client实现一无所知,不知道如何mock,推测mock代码如下,还未验证

mockApp = mock.Mock()
with mock.patch('MyModule.win32com.client.Dispatch', return_value=mockApp) as mockWin32com:
mockPpt = mock.Mock()
mockApp.Presnetations.Open.return_value = mockPpt
mockPpt.Slides.InsertFromFile.assert_called_once_with(...)

因为python的语言特性,python的Mock框架还是比Java的Mock框架要灵活很多。比如:对类构造函数的Mock,非常容易,而Java则需要经过特殊处理。还有对接口的fake化,用side_effect很容易实现,但是Java Mock则要用到when().thenAnswer(){}。麻烦又不直觉。

when(...).thenAnswer(new Answer() {
@Override
public Object answer(InvocationOnMock invocation) throws Throwable {
return value;
}
});
%23python%20mock%u521D%u6B65%0A@%28%u5B66%u4E60%u7B14%u8BB0%29%5Bpython%2C%20mock%2C%20unittest%5D%0A%0A%5BTOC%5D%0A%0A%u4ECEAndroid%u5355%u5143%u6D4B%u8BD5%u4E2D%uFF0C%u63A5%u89E6%u5230Java%u7684mock%u6846%u67B6%u3002%u53C2%u770B%u8FD9%u7BC7%u7B14%u8BB0%u300A%5BAndroid%u5355%u5143%u6D4B%u8BD5%5D%28https%3A//app.yinxiang.com/shard/s10/nl/161681/4769d75d-17cc-4dcc-96b8-b746bcae53c1%29%u300B%u3002%u6700%u8FD1%u5728%u505ADashboard%20Generator%uFF0C%u8981%u7528python%u89E3%u6790excel%uFF0Cppt%u548C%u7F51%u9875%uFF0C%u6D4B%u8BD5%u6548%u7387%u6781%u4F4E%u3002%u6240%u4EE5%u8003%u8651%u5230%u53EF%u4EE5%u7528mock%u6765%u4EE3%u66FF%u4E00%u4E9B%u8017%u65F6%u7684%u64CD%u4F5C%u548C%u8D44%u6E90%u3002%u4E8E%u662F%u63A5%u89E6%u5230python%u7684mock%u6846%u67B6%u3002%0Apython%20mock%u57283.0%u4E2D%u5DF2%u7ECF%u96C6%u6210%u4E3A%u5185%u7F6E%u7C7B%uFF0C%u4F46%u662F2.7%u4ECD%u7136%u9700%u8981%u7528pip%u6765%u5B89%u88C5%u3002%u8FD9%u4E5F%u4E0D%u96BE%u3002%u7136%u540E%u5728%u7F51%u4E0A%u641C%u96C6%u4E86%u51E0%u7BC7%u8FD8%u4E0D%u9519%u7684%u6587%u7AE0%uFF0C%u5982%u4E0B%uFF1A%0A-%20%5BPython%20Mock%u7684%u5165%u95E8%5D%28https%3A//app.yinxiang.com/shard/s10/nl/161681/1cb1675b-d132-408e-a88a-0eeb3d81fcc2%29%0A-%20%5BMocking%20Python%20imports%5D%28https%3A//app.yinxiang.com/shard/s10/nl/161681/d063563d-dc7d-4373-96a9-a0759de8e970%29%0A-%20%5BUsing%20Mocks%20in%20Python%5D%28https%3A//app.yinxiang.com/shard/s10/nl/161681/b12c60d1-416d-44da-8d6d-9ad1f39803dd%29%0A-%20%5BMock%u5B98%u65B9%u6587%u6863%5D%28http%3A//www.voidspace.org.uk/python/mock/mock.html%29%0A%0A%23%23%u7B80%u4ECB%0A%u56E0%u4E3A%u662Fpython%u8BED%u8A00%u7684%u7279%u6027%uFF0C%u6240%u4EE5Mock%u4E0A%u624B%u975E%u5E38%u5BB9%u6613%u3002%u7A83%u4EE5%u4E3A%u6BD4Java%28Android%29%20Mock%u8981%u5BB9%u6613%u7684%u591A%u3002%0A%23%23%23Mock%20vs.%20Stub/Fake%0A%u53C2%u770B%5BUsing%20Mocks%20in%20Python%5D%28https%3A//app.yinxiang.com/shard/s10/nl/161681/b12c60d1-416d-44da-8d6d-9ad1f39803dd%29%uFF0C%u4E5F%u53EF%u4EE5%u53C2%u770BMartin%20Fowler%u7684%u4E00%u7BC7%u6587%u7AE0%5BMocks%20Aren%27t%20Stubs%5D%28https%3A//martinfowler.com/articles/mocksArentStubs.html%29%u3002%0A%u8FD9%u91CC%u63D0%u5230%u4E86Mock%u548CStub/Fake%u7684%u533A%u522B%u3002%u8FD9%u662F%u6211%u4EE5%u524D%u4E00%u76F4%u6CA1%u6709%u6CE8%u610F%u5230%u7684%u3002%0A%0A%23%23%23%23%u4E3A%u4EC0%u4E48%u8981%u7528Mock%uFF1F%0A%3EA%20good%20unit%20test%20has%20to%20be%20**repeatable**%2C%20allowing%20you%20to%20**isolate**%20and%20identify%20a%20fault.%20But%20the%20test%20resource%20might%20give%20out%20stochastic%20results%2C%20or%20it%20might%20have%20widely%20varying%20response%20times.%20And%20as%20a%20result%2C%20you%20end%20up%20glossing%20over%20a%20potential%20showstopper.%0A%0A%u6D4B%u8BD5%u5FC5%u987B%u662F%u53EF%u91CD%u590D%u7684%uFF0C%u89E3%u8026%u7684%u3002%u4F46%u4EE3%u7801%u7528%u5230%u7684%u8FD0%u884C%u65F6%u8D44%u6E90%u5F80%u5F80%u662F%u968F%u673A%u7684%uFF0C%u6216%u8005%u6602%u8D35%u7684%uFF08%u6BD4%u5982%u7F51%u9875%uFF0C%u603B%u662F%u5728%u53D8%u5316%u7684%uFF0C%u6BD4%u5982%uFF0Cdownload%u6587%u4EF6%uFF0C%u975E%u5E38%u8017%u65F6%uFF09%u3002%u6211%u4EEC%u4E0D%u80FD%u8BA9%u6211%u4EEC%u7684%u6D4B%u8BD5%u9996%u5148%u4E0D%u80FD%u4F9D%u8D56%u4E8E%u6D4B%u8BD5%u8D44%u6E90%uFF0C%u5176%u6B21%u9700%u8981%u6709%u6BD4%u8F83%u9AD8%u7684%u6548%u7387%u3002%0A%0A%3EThese%20are%20some%20of%20the%20reasons%20why%20you%20might%20want%20to%20use%20a%20mock%20in%20place%20of%20a%20**test%20resource**.%20A%20mock%20can%20present%20the%20same%20set%20of%20method%20interfaces%20as%20the%20resource%20to%20the%20test%20subject.%20But%20a%20mock%20is%20easier%20to%20setup%2C%20easier%20to%20manage.%20It%20can%20deliver%20deterministic%20results%2C%20and%20it%20can%20be%20customized%20to%20suit%20a%20particular%20test.%20And%20it%20can%20be%20easily%20updated%20to%20reflect%20changes%20in%20the%20actual%20resource.%0A%0A%23%23%23%23Stubs%20%26%20Fake%0AStub%0A%3EA%20stub%20presents%20a%20set%20of%20method%20interfaces%20to%20the%20test%20subject%2C%20the%20same%20set%20the%20subject%20would%20see%20in%20an%20actual%20test%20resource.%20When%20the%20test%20subject%20calls%20a%20stub%20method%2C%20the%20stub%20may%20respond%20with%20a%20predetermined%20set%20of%20results.%20It%20may%20raise%20an%20error%20or%20exception%2C%20also%20predetermined.%20A%20stub%20may%20track%20its%20interactions%20with%20the%20test%20subject%2C%20but%20it%20performs%20no%20tasks%20outside%20the%20narrow%20scope%20of%20its%20programming.%0A%0AFake%0A%3EA%20fake%20also%20presents%20a%20set%20of%20method%20interfaces%20and%20tracks%20its%20interactions%20with%20the%20test%20subject.%20But%20unlike%20a%20stub%2C%20a%20fake%20actually%20processes%20input%20data%20from%20the%20test%20subject%20and%20produces%20results%20based%20on%20that%20data.%20In%20short%2C%20a%20fake%20is%20a%20functional%2C%20but%20non-production%20version%20of%20the%20actual%20test%20resource.%20It%20lacks%20the%20checks%20and%20balances%20found%20in%20resource%2C%20it%20uses%20simpler%20algorithms%2C%20and%20it%20seldom%2C%20if%20ever%2C%20stores%20or%20transports%20data.%0A%0AStub%u548CFake%u90FD%u662F%u9488%u5BF9%u63A5%u53E3%u7684%u6A21%u62DF%uFF0C%u5728%u9700%u8981%u5BF9%u72B6%u6001%u8FDB%u884C%u6D4B%u8BD5%u7684%u60C5%u51B5%u65F6%uFF0C%u6211%u4EEC%u53EF%u4EE5%u7528Stub%u6216%u8005Fake%u3002%u4F8B%u5982UnitTest++%uFF0C%u5C31%u662F%u7528%u7684Stub%u3002%0A%u4F46%u662F%u5982%u679C%u6211%u4EEC%u8981%u6D4B%u8BD5%u5177%u4F53%u7684%u4EE3%u7801%u884C%u4E3A%uFF0C%u6211%u4EEC%u5F80%u5F80%u8981%u7528%u5230Mock%u3002%u6BD4%u5982%uFF0C%u4E00%u4E2A%u51FD%u6570%u8C03%u7528%u4E86%u51E0%u6B21%uFF0C%u7528%u7684%u4EC0%u4E48%u53C2%u6570%uFF0C%u7B49%u7B49%u3002%0A%0A%u6211%u7684%u7406%u89E3%uFF0C%u5176%u5B9E%u4ED6%u4EEC%u4E09%u8005%u4E4B%u95F4%u5E76%u6CA1%u6709%u5F88%u660E%u663E%u7684%u754C%u9650%u3002%u7528Mock%u7684%u65F6%u5019%uFF0C%u9488%u5BF9%u4E00%u4E9B%u9700%u8981%u6A21%u62DF%u7684%u63A5%u53E3%uFF0C%u4ECD%u7136%u53EF%u4EE5%u6709%u529E%u6CD5%u5C06%u4E4Bstub%20out%u3002%u53EA%u662FMock%u5E76%u4E0D%u64C5%u957F%uFF0C%u65B9%u6CD5%u4E0D%u591F%u76F4%u89C9%u3002%u540C%u7406Stub%u4E5F%u53EF%u4EE5%u7528%u6765mock%u6389%u4E00%u4E9B%u5BF9%u8C61%u3002%0AStub/Fake%u66F4%u50CF%u662F%u5E94%u7528%u4E8E%u9762%u5411%u63A5%u53E3%u7F16%u7A0B%uFF0C%u800CMock%u66F4%u64C5%u957F%u4E8E%u9762%u5411%u5BF9%u8C61%u7F16%u7A0B%u3002%0A%0A%23%23%23%23%u4F55%u65F6%u4F7F%u7528Mock%0A%3EOf%20course%2C%20mocks%20are%20not%20without%20issues.%20Designing%20an%20accurate%20mock%20is%20difficult%2C%20especially%20if%20you%20have%20no%20reliable%20information%20on%20the%20test%20resource.%20You%20can%20try%20and%20find%20an%20open-source%20match%2C%20or%20you%20can%20make%20a%20guesstimate%20on%20the%20resource%27s%20method%20interface.%20Whichever%20you%20choose%2C%20you%20can%20update%20the%20mock%20easily%20later%20on%2C%20should%20you%20get%20more%20detailed%20information%20on%20the%20preferred%20resource.%20Too%20many%20mocks%20can%20complicate%20a%20test%2C%20making%20it%20harder%20for%20you%20to%20track%20down%20a%20failure.%20%0A%3E**Best%20practice**%20%0A%3E%20-%20is%20to%20limit%20a%20test%20case%20to%20**one%20or%20two%20mocks**%0A%3E%20-%20or%20use%20**separate%20test%20cases**%20for%20each%20mock/subject%20pairing.%0A%0A%0A%23%23%23%u5982%u4F55%u4F7F%u7528%0A%21%5BAlt%20text%7C400x0%5D%28./1486178612793.png%29%0A%0A%23%23%23%23constructor%0A%60%60%60%0Aclass%20Mock%28spec%3DNone%2C%20side_effect%3DNone%2C%20return_value%3DDEFAULT%2C%20wraps%3DNone%2C%20name%3DNone%2C%20spec_set%3DNone%2C%20**kwargs%29%0A%60%60%60%0A%u4E3B%u8981%u53C2%u6570%u5982%u4E0B%uFF1A%0A-%20name%3A%20%u53EA%u6709%u6807%u8BB0%u4F5C%u7528%uFF0C%u5728print%u6216%u8005repr%u7684%u65F6%u5019%u53EF%u4EE5%u770B%u5230%uFF0C%u8C03%u8BD5%u7684%u65F6%u5019%u6709%u7528%0A-%20return_value%3A%20%u6700%u7B80%u5355%u7684%u5BF9%u63A5%u53E3%u7684stub%u5316%0A-%20side_effect%3A%20%u5176%u53C2%u6570%u53EF%u4EE5%u4E3A%u5217%u8868%u6216%u51FD%u6570%uFF0C%u82E5%u5176%u8FD4%u56DE%u503C%u4E3ADEFAULT%uFF0C%u5219%u91C7%u7528return_value%u7684%u503C%uFF0C%u82E5%u5176%u8FD4%u56DE%u503C%u4E0D%u662FDEFAULT%uFF0C%u5219%u5176%u4F1A%u8986%u76D6return_value%u7684%u503C%0A-%20spec%3A%20%20%u53EF%u4EE5%u662Fstring%u5217%u8868%uFF0C%u4E5F%u53EF%u4EE5%u4E3Aclass%u6216instance%u3002Accessing%20any%20attribute%20not%20in%20this%20list%20will%20raise%20an%20AttributeError.%0A%0Aside_effect%u4E3A%u5217%u8868%0A%60%60%60%0A%3E%3E%3E%20mock%20%3D%20Mock%28%29%0A%3E%3E%3E%20mock.side_effect%20%3D%20%5B3%2C%202%2C%201%5D%0A%3E%3E%3E%20mock%28%29%2C%20mock%28%29%2C%20mock%28%29%0A%283%2C%202%2C%201%29%0A%60%60%60%0Aside_effect%u4E3A%u51FD%u6570%uFF0C%u5176%u53C2%u6570%u4E0E%u771F%u5B9E%u4F20%u5165%u7684%u53C2%u6570%u76F8%u540C%0A%60%60%60%0A%3E%3E%3E%20side_effect%20%3D%20lambda%20value%3A%20value%20+%201%0A%3E%3E%3E%20mock%20%3D%20Mock%28side_effect%3Dside_effect%29%0A%3E%3E%3E%20mock%283%29%0A4%0A%3E%3E%3E%20mock%28-8%29%0A-7%0A%60%60%60%0A%0A%23%23%23%23%u5BF9%u51FD%u6570%u8C03%u7528%u7684%u68C0%u6D4B%0Amock%u5305%u542B%u4EE5%u4E0B%u5C5E%u6027%uFF1A%0A-%20called%0A-%20call_count%0A-%20call_args%0A-%20call_args_list%0A%u542B%u4E49%u663E%u800C%u6613%u89C1%uFF0C%u7528%u6CD5%u53C2%u8003%5B%u5B98%u65B9%u6587%u6863%5D%28http%3A//www.voidspace.org.uk/python/mock/mock.html%29%0A%0Amethod_calls%20%26%20mock_calls%0A%60%60%60%0A%3E%3E%3E%20mock%20%3D%20Mock%28%29%0A%3E%3E%3E%20mock.method%28%29%0A%3CMock%20name%3D%27mock.method%28%29%27%20id%3D%27...%27%3E%0A%3E%3E%3E%20mock.property.method.attribute%28%29%0A%3CMock%20name%3D%27mock.property.method.attribute%28%29%27%20id%3D%27...%27%3E%0A%3E%3E%3E%20mock.method_calls%0A%5Bcall.method%28%29%2C%20call.property.method.attribute%28%29%5D%0A%0A%3E%3E%3E%20mock%20%3D%20MagicMock%28%29%0A%3E%3E%3E%20result%20%3D%20mock%281%2C%202%2C%203%29%0A%3E%3E%3E%20mock.first%28a%3D3%29%0A%3CMagicMock%20name%3D%27mock.first%28%29%27%20id%3D%27...%27%3E%0A%3E%3E%3E%20mock.second%28%29%0A%3CMagicMock%20name%3D%27mock.second%28%29%27%20id%3D%27...%27%3E%0A%3E%3E%3E%20int%28mock%29%0A1%0A%3E%3E%3E%20result%281%29%0A%3CMagicMock%20name%3D%27mock%28%29%28%29%27%20id%3D%27...%27%3E%0A%3E%3E%3E%20expected%20%3D%20%5Bcall%281%2C%202%2C%203%29%2C%20call.first%28a%3D3%29%2C%20call.second%28%29%2C%0A...%20call.__int__%28%29%2C%20call%28%29%281%29%5D%0A%3E%3E%3E%20mock.mock_calls%20%3D%3D%20expected%0ATrue%0A%60%60%60%0A%0A%23%23%23%23assert%0AMock%u63D0%u4F9B%u4E86%u4EE5%u4E0B%u51E0%u79CDassert%uFF1A%0A-%20assert_called_once%0A-%20assert_called_with%0A-%20assert_called_once_with%0A-%20assert_has_calls%0A-%20assert_any_calls%0A%u524D%u9762%u4E09%u4E2A%u5F88%u76F4%u89C9%uFF0C%u540E%u9762%u4E24%u4E2A%u7A0D%u4F5C%u89E3%u91CA%u3002%0A%0Aassert_any_call%0A%3EThe%20assert%20assert_any_call%28%29%20checks%20if%20the%20test%20subject%20called%20a%20mocked%20method%20at%20any%20point%20of%20the%20test%20routine.%20This%20is%20regardless%20of%20how%20many%20other%20calls%20were%20made%20between%20the%20mocked%20method%20and%20the%20assert.%20%0A%0Aassert_has_calls%0A%3EThis%20one%20looks%20at%20a%20sequence%20of%20method%20calls%2C%20checks%20if%20they%20are%20in%20the%20right%20order%20and%20with%20the%20right%20arguments.%0A%0A%60%60%60%0Afrom%20mock%20import%20Mock%2C%20call%0A%20%0A%23%20The%20mock%20specification%0Aclass%20Foo%28object%29%3A%0A%20%20%20%20_fooValue%20%3D%20123%0A%20%20%20%20%20%0A%20%20%20%20def%20callFoo%28self%29%3A%0A%20%20%20%20%20%20%20%20pass%0A%20%20%20%20%20%0A%20%20%20%20def%20doFoo%28self%2C%20argValue%29%3A%0A%20%20%20%20%20%20%20%20pass%0A%20%0A%23%20create%20the%20mock%20object%0AmockFoo%20%3D%20Mock%28spec%20%3D%20Foo%29%0Aprint%20mockFoo%0A%23%20returns%20%3CMock%20spec%3D%27Foo%27%20id%3D%27507120%27%3E%0A%20%0AmockFoo.callFoo%28%29%0AmockFoo.doFoo%28%22narf%22%29%0AmockFoo.doFoo%28%22zort%22%29%0A%20%0AfooCalls%20%3D%20%5Bcall.callFoo%28%29%2C%20call.dooFoo%28%22narf%22%29%2C%20call.doFoo%28%22zort%22%29%5D%0A%20%0AmockFoo.assert_has_calls%28fooCalls%29%0A%23%20AssertionError%3A%20Calls%20not%20found.%0A%23%20Expected%3A%20%5Bcall.callFoo%28%29%2C%20call.dooFoo%28%27narf%27%29%2C%20call.doFoo%28%27zort%27%29%5D%0A%23%20Actual%3A%20%5Bcall.callFoo%28%29%2C%20call.doFoo%28%27narf%27%29%2C%20call.doFoo%28%27zort%27%29%5D%0A%20%0AfooCalls%20%3D%20%5Bcall.callFoo%28%29%2C%20call.dooFoo%28%22narf%22%29%2C%20call.doFoo%28%22zort%22%29%5D%0AmockFoo.assert_has_calls%28fooCalls%2C%20any_order%20%3D%20True%29%0A%23%20AssertionError%3A%20%28call.dooFoo%28%27narf%27%29%2C%29%20not%20all%20found%20in%20call%20list%0A%60%60%60%0A%0A%23%23%u9AD8%u9636%u7279%u6027%0A%23%23%23MagicMock%20vs.%20Mock%0A%3EWith%20Mock%20you%20can%20mock%20magic%20methods%20but%20you%20have%20to%20define%20them.%20MagicMock%20has%20%22%5Bdefault%20implementations%20of%20most%20of%20the%20**magic%20methods**%5D%28http%3A//www.voidspace.org.uk/python/mock/magicmock.html%23mock.MagicMock%29%22.%0A%3EIf%20you%20don%27t%20need%20to%20test%20any%20magic%20methods%2C%20Mock%20is%20adequate%20and%20doesn%27t%20bring%20a%20lot%20of%20extraneous%20things%20into%20your%20tests.%20If%20you%20need%20to%20test%20a%20lot%20of%20magic%20methods%20MagicMock%20will%20save%20you%20some%20time.%0A%0A%u54EA%u4E9Bmagic%20methods%uFF1F%u770B%u4E0B%u9762%0A*%20__lt__%3A%20NotImplemented%0A*%20__gt__%3A%20NotImplemented%0A*%20__le__%3A%20NotImplemented%0A*%20__ge__%3A%20NotImplemented%0A*%20__int__%20%3A%201%0A*%20__contains__%20%3A%20False%0A*%20__len__%20%3A%201%0A*%20__iter__%20%3A%20iter%28%5B%5D%29%0A*%20__exit__%20%3A%20False%0A*%20__complex__%20%3A%201j%0A*%20__float__%20%3A%201.0%0A*%20__bool__%20%3A%20True%0A*%20__nonzero__%20%3A%20True%0A*%20__oct__%20%3A%20%u20181%u2019%0A*%20__hex__%20%3A%20%u20180x1%u2019%0A*%20__long__%20%3A%20long%281%29%0A*%20__index__%20%3A%201%0A*%20__hash__%20%3A%20default%20hash%20for%20the%20mock%0A*%20__str__%20%3A%20default%20str%20for%20the%20mock%0A*%20__unicode__%20%3A%20default%20unicode%20for%20the%20mock%0A*%20__sizeof__%3A%20default%20sizeof%20for%20the%20mock%0A%60%60%60%0A%3E%3E%3E%20mock%20%3D%20MagicMock%28%29%0A%3E%3E%3E%20int%28mock%29%0A1%0A%3E%3E%3E%20len%28mock%29%0A0%0A%3E%3E%3E%20hex%28mock%29%0A%270x1%27%0A%3E%3E%3E%20list%28mock%29%0A%5B%5D%0A%3E%3E%3E%20object%28%29%20in%20mock%0AFalse%0A%60%60%60%0A%u6240%u8C13magic%20methods%u5C31%u662F%u4E00%u4E9B%u5185%u7F6E%u7684python%u8FD0%u7B97%u7B26%uFF0C%u800CMagicMock%u652F%u6301%u8FD9%u4E9B%u8FD0%u7B97%u7B26%uFF0CMock%u4E0D%u652F%u6301%0A%0A%23%23%23mock%20import%0A%5BMocking%20Python%20imports%5D%28https%3A//app.yinxiang.com/shard/s10/nl/161681/d063563d-dc7d-4373-96a9-a0759de8e970%29%u8FD9%u91CC%u6709%u63D0%u5230%u3002%u5176%u5B9E%u5F88%u7B80%u5355%uFF0C%u770B%u4EE3%u7801%0A%60%60%60%0A%23%20A.py%0Aimport%20B%0AB.foo%28%29%0A%0A%23%20test.py%0AA.B%20%3D%20mock.Mock%28%29%0AA.B.foo.return_value%20%3D%20123%0A%60%60%60%0A%0A%23%23%23mock%20class%20constructor%0A%u76F4%u63A5%u8D34%u4E0A%u5B9E%u9645%u7684%u6D4B%u8BD5%u4EE3%u7801%0A%60%60%60python%0AmockSMBConnObj%20%3D%20mock.Mock%28%29%0AmockSMBConn%20%3D%20mock.Mock%28return_value%3DmockSMBConnObj%29%20%23%20mock%20constructor%0A%60%60%60%0A%0A%23%23%23mock%u5BF9%u8C61%u7684%u81EA%u52A8%u521B%u5EFA%0A%u5F53%u8BBF%u95EE%u4E00%u4E2Amock%u5BF9%u8C61%u4E2D%u4E0D%u5B58%u5728%u7684%u5C5E%u6027%u65F6%uFF0Cmock%u4F1A%u81EA%u52A8%u5EFA%u7ACB%u4E00%u4E2A%u5B50mock%u5BF9%u8C61%uFF0C%u5E76%u4E14%u628A%u6B63%u5728%u8BBF%u95EE%u7684%u5C5E%u6027%u6307%u5411%u5B83%uFF0C%u8FD9%u4E2A%u529F%u80FD%u5BF9%u4E8E%u5B9E%u73B0%u591A%u7EA7%u5C5E%u6027%u7684mock%u5F88%u65B9%u4FBF%u3002%0A%60%60%60%0Aclient%20%3D%20mock.Mock%28%29%0Aclient.v2_client.get.return_value%20%3D%20%27200%27%0A%60%60%60%0A%u4E0A%u9762%u4F8B%u5B50%u4E2D%60client.v2_client.get%60%u5C31%u662F%u81EA%u52A8%u751F%u6210%u7684mock%u5BF9%u8C61%0A%u7C7B%u4F3C%u81EA%u52A8%u751F%u6210%uFF0C%u6211%u4EEC%u8FD8%u53EF%u4EE5%u91C7%u7528%60attach_mock%60%u7684%u65B9%u6CD5%u3002%u4E0D%u540C%u7684%u662F%uFF0Cattach_mock%u4F1A%u8BA9%u88ABattach%u7684%u53CC%u65B9%u5177%u6709%u7236%u5B50%u5173%u7CFB%uFF0C%u5219%u5BF9%u5B50mock%u7684%u8C03%u7528%u4F1A%u88AB%u8BA1%u5165%u7236%u7684mock_calls%u3002%u53C2%u8003%5BAttaching%20Mocks%20as%20Attributes%5D%28http%3A//www.voidspace.org.uk/python/mock/mock.html%23attaching-mocks-as-attributes%29%0A%0A%23%23%23patch%0A%u901A%u8FC7patch%uFF0C%u6211%u4EEC%u53EF%u4EE5%u63A7%u5236Mock%u5BF9%u8C61%u7684%u751F%u5B58%u5468%u671F%u3002%u610F%u601D%u5C31%u662F%u5728%u4E00%u4E2A%u51FD%u6570%u8303%u56F4%u5185%uFF0C%u6216%u8005%u4E00%u4E2A%u7C7B%u7684%u8303%u56F4%u5185%uFF0C%u6216%u8005with%u8BED%u53E5%u7684%u8303%u56F4%u5185mock%u6389%u4E00%u4E2A%u5BF9%u8C61%u3002%0A%u6709%u4E0B%u9762%0A%0Adecorator%0A%60%60%60%0A%3E%3E%3E%20@patch%28%27__main__.SomeClass%27%29%0A...%20def%20function%28normal_argument%2C%20mock_class%29%3A%0A...%20%20%20%20%20print%20mock_class%20is%20SomeClass%0A...%0A%3E%3E%3E%20function%28None%29%0ATrue%0A%60%60%60%0A%0Acontext%20manager%0A%60%60%60%0A%3E%3E%3E%20class%20Class%28object%29%3A%0A...%20%20%20%20%20def%20method%28self%29%3A%0A...%20%20%20%20%20%20%20%20%20pass%0A...%0A%3E%3E%3E%20with%20patch%28%27__main__.Class%27%29%20as%20MockClass%3A%0A...%20%20%20%20%20instance%20%3D%20MockClass.return_value%0A...%20%20%20%20%20instance.method.return_value%20%3D%20%27foo%27%0A...%20%20%20%20%20assert%20Class%28%29%20is%20instance%0A...%20%20%20%20%20assert%20Class%28%29.method%28%29%20%3D%3D%20%27foo%27%0A%60%60%60%0A%0Apatcher%0A%60%60%60%0A%3E%3E%3E%20Original%20%3D%20Class%0A%3E%3E%3E%20patcher%20%3D%20patch%28%27__main__.Class%27%2C%20spec%3DTrue%29%0A%3E%3E%3E%20MockClass%20%3D%20patcher.start%28%29%0A%3E%3E%3E%20instance%20%3D%20MockClass%28%29%0A%3E%3E%3E%20assert%20isinstance%28instance%2C%20Original%29%0A%3E%3E%3E%20patcher.stop%28%29%0A%60%60%60%0A%0Apatch.object%u548Cpatch%u7C7B%u4F3C%uFF0C%u53EA%u662F%u5199%u6CD5%u4E0D%u540C%uFF0C%u770B%u4E0B%u9762%u5BF9%u6BD4%uFF1A%0A%60%60%60%0A@patch.object%28SomeClass%2C%20%27class_method%27%29%0A@patch%28%27SomeClass.class_method%27%29%0A%60%60%60%0A%0Apatch%u8FD8%u6709%u5F88%u591A%u79CD%u5176%u4ED6%u7528%u6CD5%uFF0Cpatch.multiple%2C%20patch.dict%u7B49%u7B49%u3002%u53C2%u770B%5BMore%20Patch%5D%28http%3A//www.voidspace.org.uk/python/mock/patch.html%23patch-dict%29%0A%0A%23%23%23%u5176%u4ED6%u672A%u51B3%u7684%u95EE%u9898%0A%u5176%u5B9E%u8FD8%u6709%u5F88%u591Amock%u9AD8%u7EA7%u7684%u7528%u6CD5%uFF0C%u4F8B%u5982%uFF0C%u5F53%u6211%u60F3mock%u6389win32com%u7684%u65F6%u5019%uFF0C%u641C%u5230%u7684%u8FD9%u4E2A%u7F51%u9875%5BMocking%20out%20python%20OS%20specific%20imports%5D%28http%3A//ilostmynotes.blogspot.com/2014/10/mocking-out-python-os-specific-imports.html%29%u3002%u5176%u4E2D%u6709%u4E00%u6BB5%u4EE3%u7801%uFF1A%0A%60%60%60%0A%20modules%20%3D%20%7B%0A%20%20%20%20%20%20%20%20%22_winreg%22%3A%20mock.MagicMock%28%29%2C%0A%20%20%20%20%20%20%20%20%22pythoncom%22%3A%20mock.MagicMock%28%29%2C%0A%20%20%20%20%20%20%20%20%22pywintypes%22%3A%20mock.MagicMock%28%29%2C%0A%20%20%20%20%20%20%20%20%22win32api%22%3A%20mock.MagicMock%28%29%2C%0A%20%20%20%20%20%20%20%20%22win32com%22%3A%20self.win32com%2C%0A%20%20%20%20%20%20%20%20%22win32com.client%22%3A%20self.win32com.client%2C%0A%20%20%20%20%20%20%20%20%22win32file%22%3A%20mock.MagicMock%28%29%2C%0A%20%20%20%20%20%20%20%20%22win32service%22%3A%20mock.MagicMock%28%29%2C%0A%20%20%20%20%20%20%20%20%22win32serviceutil%22%3A%20mock.MagicMock%28%29%2C%0A%20%20%20%20%20%20%20%20%22winerror%22%3A%20mock.MagicMock%28%29%2C%0A%20%20%20%20%20%20%20%20%22wmi%22%3A%20self.wmimock%0A%20%20%20%20%20%20%20%20%7D%0A%0Aself.module_patcher%20%3D%20mock.patch.dict%28%22sys.modules%22%2C%20modules%29%0Aself.module_patcher.start%28%29%0A%60%60%60%0A%u8FD8%u6709%u5982%u4F55mock%u6389win32com.client%u7684%u5BF9%u8C61%uFF1F%u4F8B%u5982%uFF0C%u5F85%u6D4B%u4EE3%u7801%u5982%u4E0B%0A%60%60%60%0AApplication%20%3D%20win32com.client.Dispatch%28%22PowerPoint.Application%22%29%0Asource_ppt%20%3D%20Application.Presentations.Open%28path%29%0Asource_ppt.Slides.InsertFromFile%28os.path.abspath%28chart%29%2C%20index%2C%201%2C%201%29%0A%60%60%60%0A%u56E0%u4E3A%u5BF9%60win32com.client%60%u5B9E%u73B0%u4E00%u65E0%u6240%u77E5%uFF0C%u4E0D%u77E5%u9053%u5982%u4F55mock%uFF0C%u63A8%u6D4Bmock%u4EE3%u7801%u5982%u4E0B%uFF0C%u8FD8%u672A%u9A8C%u8BC1%0A%60%60%60%0AmockApp%20%3D%20mock.Mock%28%29%0Awith%20mock.patch%28%27MyModule.win32com.client.Dispatch%27%2C%20return_value%3DmockApp%29%20as%20mockWin32com%3A%0A%09mockPpt%20%3D%20mock.Mock%28%29%0A%09mockApp.Presnetations.Open.return_value%20%3D%20mockPpt%0A%09mockPpt.Slides.InsertFromFile.assert_called_once_with%28...%29%0A%60%60%60%0A%0A%23%u603B%u7ED3%0A%u56E0%u4E3Apython%u7684%u8BED%u8A00%u7279%u6027%uFF0Cpython%u7684Mock%u6846%u67B6%u8FD8%u662F%u6BD4Java%u7684Mock%u6846%u67B6%u8981%u7075%u6D3B%u5F88%u591A%u3002%u6BD4%u5982%uFF1A%u5BF9%u7C7B%u6784%u9020%u51FD%u6570%u7684Mock%uFF0C%u975E%u5E38%u5BB9%u6613%uFF0C%u800CJava%u5219%u9700%u8981%u7ECF%u8FC7%u7279%u6B8A%u5904%u7406%u3002%u8FD8%u6709%u5BF9%u63A5%u53E3%u7684fake%u5316%uFF0C%u7528side_effect%u5F88%u5BB9%u6613%u5B9E%u73B0%uFF0C%u4F46%u662FJava%20Mock%u5219%u8981%u7528%u5230%60when%28%29.thenAnswer%28%29%7B%7D%60%u3002%u9EBB%u70E6%u53C8%u4E0D%u76F4%u89C9%u3002%0A%60%60%60%0Awhen%28...%29.thenAnswer%28new%20Answer%28%29%20%7B%0A%09@Override%0A%09public%20Object%20answer%28InvocationOnMock%20invocation%29%20throws%20Throwable%20%7B%0A%09%09return%20value%3B%0A%09%7D%0A%7D%29%3B%0A%60%60%60%0A