小编典典

为什么python模拟补丁不起作用?

python

我有两个档案

秒杀

class T1(object):
    def foo(self, afd):
        return "foo"

    def get_foo(self):
        return self.foo(1)


def bar():
    return "bar"

test_spike.py:

from unittest import TestCase
import unittest
from mock import patch, MagicMock
from spike import T1, bar


class TestStuff(TestCase):
    @patch('spike.T1.foo', MagicMock(return_value='patched'))
    def test_foo(self):
        foo = T1().get_foo()
        self.assertEqual('patched', foo)

    @patch('spike.bar')
    def test_bar(self, mock_obj):
        mock_obj.return_value = 'patched'
        bar = bar()
        self.assertEqual('patched', bar)


if __name__ == "__main__":
    unittest.main()

当我运行时python test_spike.py,第一个测试用例将通过,但是第二个将失败。而我切换到use nosetests test_spike.py,则两个都失败了。

我不明白这是怎么发生的?这些情况本应全部通过。


阅读 136

收藏
2020-12-20

共1个答案

小编典典

对于 test_foo, 您没有正确使用补丁。您应该像这样使用它:

class TestFoo(TestCase):
@patch.object(T1, 'foo', MagicMock(return_value='patched'))
def test_foo(self):
    foo = T1().get_foo()
    self.assertEqual('patched', foo)

这给了我:

nosetests test_spike.py 
.
----------------------------------------------------------------------
Ran 1 test in 0.000s

OK

现在,第二个示例不起作用,因为您导入了bar函数(获取对其的引用),然后尝试对其进行模拟。模拟某些内容时,您无法更改变量的内容(对原始函数的引用)。要解决此问题,您应该使用@falsetru建议的方法,例如:

from unittest import TestCase
import unittest
from mock import patch
import spike


class TestFoo(TestCase):
    @patch('spike.bar')
    def test_bar(self, mock_obj):
        mock_obj.return_value = 'patched'
        value = spike.bar()
        self.assertEqual('patched', value)


if __name__ == "__main__":
    unittest.main()

这给了我:

python test_spike.py
.
----------------------------------------------------------------------
Ran 1 test in 0.000s

OK

但是当我尝试用鼻子跑它时,我得到:

 nosetests test_spike.py
F
======================================================================
FAIL: test_bar (src.test_spike.TestFoo)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "/home/zilva/envs/test/local/lib/python2.7/site-packages/mock/mock.py", line 1305, in patched
    return func(*args, **keywargs)
  File "/home/zilva/git/test/src/test_spike.py", line 11, in test_bar
    self.assertEqual('patched', value)
AssertionError: 'patched' != 'bar'

----------------------------------------------------------------------
Ran 1 test in 0.001s

FAILED (failures=1)

发生这种情况是因为我没有在正确的位置打补丁。我的目录结构是:

test/
└── src/
    ├── spike.py
    ├── test_spike.py
    └── __init__.py

并且我从src目录运行测试,因此我应该使用项目根目录下的路径进行修补,例如:

@patch('src.spike.bar')

这会给我:

nosetests test_spike.py
.
----------------------------------------------------------------------
Ran 1 test in 0.000s

OK

或者如果我在测试目录中:

nosetests src/test_spike.py
.
----------------------------------------------------------------------
Ran 1 test in 0.001s

OK
2020-12-20