0

大多数关于 Python 模拟的建议都包含在单元测试框架之外的简短片段中。这个工作发现,我正在尝试遵循这个建议,但是一旦我将它嵌入到适当的单元测试中,它就不会成功。例如,这段代码在最后的注释中产生输出:

# foo.py
def some_fn():
    return 'some_fn'

class Foo( object ):
    def method_1( self ):
        return some_fn()

# bar.py (depends on foo.py)
import foo
class Bar( object ):
    def method_2( self ):
        tmp = foo.Foo()
        return tmp.method_1()

# test.py (tests bar.py)
import unittest
import bar
from mock import patch

class Test( unittest.TestCase ):
    def setUp( self ):
        pass
    def tearDown( self ):
        pass

    @patch( 'foo.some_fn' )
    def test_bar( self, mock_some_fn ):
        mock_some_fn.return_value = 'test-val-1'
        tmp = bar.Bar()
        print tmp.method_2()
        self.assertEqual( tmp.method_2(), 'test-val-1' )  # line 32
        mock_some_fn.return_value = 'test-val-2'
        self.assertEqual( tmp.method_2(), 'test-val-2' )

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

我在 PyDev 中运行并查看:

Finding files... done.
Importing test modules ... done.

some_fn
======================================================================
FAIL: test_bar (test.foo.all.Test)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "/usr/lib/python2.7/site-packages/mock.py", line 1201, in patched
    return func(*args, **keywargs)
  File "/home/russ/dev/workspace/python-mocking/test/foo/all.py", line 32, in test_bar
    self.assertEqual( tmp.method_2(), 'test-val-1' )
AssertionError: 'some_fn' != 'test-val-1'

----------------------------------------------------------------------
Ran 1 test in 0.002s

FAILED (failures=1)

删除单元测试框架,这段代码运行良好(这里,只是整个文件的test.py部分):

...
# test.py (tests bar.py)
import bar
from mock import patch

@patch( 'foo.some_fn' )
def test_bar( mock_some_fn ):
  mock_some_fn.return_value = 'test-val-1'
  tmp = bar.Bar()
  print tmp.method_2()
  assert tmp.method_2() == 'test-val-1'
  mock_some_fn.return_value = 'test-val-2'
  assert tmp.method_2() == 'test-val-2'

运行时成功产生:

~/dev/workspace/python-mocking/test/foo $ python
Python 2.7.5 (default, Nov  3 2014, 14:26:24) 
...
>>> import all0
>>> all0.test_bar()
test-val-1

我还必须做些什么才能使其在单元测试框架中运行?

4

1 回答 1

0

对我这个 Python 和 PyDev 新手来说,答案是这是一个 PyDev 问题。PyDev 似乎对如何设置项目的单元测试非常敏感。我通过将一个与此完全相同的新项目(包括单独的文件)组合在一起,成功地使这段代码工作。

python-mocking
+-- mocking_example
    +-- test
    |   +-- __init__.py
    |   `-- test.py
    +-- __init__.py
    +-- bar.py
    `-- foo.py

可能值得注意的是,上面的结构使得在test.py中必须导入 bar :

import mocking_example.bar

并以这种方式消费,即:

tmp = mocking_example.bar.Bar()
于 2015-02-19T17:31:22.517 回答