[英]Why is mock.patch class decorator not working?
I want to mock something for an entire class but the following minimal example is not working: 我想模拟整个类的内容,但以下最小示例不起作用:
import time
import six
if six.PY2:
import mock
else:
from unittest import mock
@mock.patch('time.sleep', mock.Mock(side_effect=Exception('dooooom')))
class Foo(object):
def bar(self):
print('before')
time.sleep(1)
print('after')
f = Foo()
f.bar()
I get this unexpected output: (why did time.sleep
not raise?) 我得到了这个意外的输出:(为什么
time.sleep
没有提高?)
before
after
However if I move the @mock.patch(...)
down 1 line so it is decorating the method bar
instead of the class Foo
then it works as expected: 但是,如果我将
@mock.patch(...)
向下移动1行,以使其装饰了方法bar
而不是Foo
类,则它将按预期工作:
before
...
Exception: blah
Why does @mock.patch
not work at the class level? 为什么
@mock.patch
在类级别上不起作用?
It turns out the class decorator only patches methods beginning with patch.TEST_PREFIX
which defaults to test
. 事实证明,类装饰器仅修补以
patch.TEST_PREFIX
开头(默认为test
。
So renaming the method to test_bar
or even testbar
makes the patch start working. 因此,将方法重命名为
test_bar
甚至testbar
会使补丁开始工作。
Patch can be used as a
TestCase
class decorator.修补程序可用作
TestCase
类装饰器。 It works by decorating each test method in the class.它通过装饰类中的每个测试方法来工作。 This reduces the boilerplate code when your test methods share a common patchings set.
当您的测试方法共享一个公共补丁集时,这会减少样板代码。 patch() finds tests by looking for method names that start with
patch.TEST_PREFIX
.patch()通过查找以
patch.TEST_PREFIX
开头的方法名称来查找测试。 By default this is'test'
, which matches the wayunittest
finds tests.默认情况下,这是
'test'
,它与unittest
查找测试的方式匹配。 You can specify an alternative prefix by settingpatch.TEST_PREFIX
.您可以通过设置
patch.TEST_PREFIX
来指定备用前缀。
Evidently this behaviour applies to any class whether inheriting from unittest.TestCase
or not. 显然,此行为适用于任何类,无论是否从
unittest.TestCase
继承。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.