使用side_effects修补os.path.isfile不在列表理解中工作

时间:2013-05-20 14:18:09

标签: python unit-testing mocking

我试图在Python类中练习以下方法:

def find_tests(self):
    tests_dir = glob.glob("tests/*")
    if not tests_dir:
        return None

    # Filter out only the files in tests/ then get the test names.
    tests = [os.path.basename(t) for t in tests_dir if os.path.isfile(t)]

通过以下测试:

@patch('glob.glob')
@patch('os.path.isfile')
def test_conductor_find_tests(self, mock_isfile, mock_glob):
    tests_directory = ['tests/00-test', 'tests/02-juju', 'tests/lib',
                       'tests/01-ubuntu']
    test_names = ['00-test', '01-ubuntu', '02-juju']
    files_exist = [True, True, False, True]
    mock_isfile.side_effects = files_exist
    mock_glob.return_value = tests_directory

    args = Arguments(tests = 'dummy')
    c = juju_test.Conductor(args)
    results = c.find_tests()

    mock_glob.assert_called_with('tests/*')
    self.assertEqual(results, test_names)

mock_isfile运行(使用mock_isfile.call_count验证),但是,它不会为第三个列表元素返回False,而是让所有人都通过,我最终会这样:

======================================================================
FAIL: test_conductor_find_tests (test.test_juju_test.JujuTestPluginTest)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "/usr/lib/python2.7/dist-packages/mock.py", line 1201, in patched
    return func(*args, **keywargs)
  File "/home/marco/Projects/juju-plugins/test/test_juju_test.py", line 51, in test_conductor_find_tests
    self.assertEqual(results, test_names)
AssertionError: Lists differ: ['00-test', '01-ubuntu', '02-j... != ['00-test', '01-ubuntu', '02-j...

First list contains 1 additional elements.
First extra element 3:
lib

- ['00-test', '01-ubuntu', '02-juju', 'lib']
?                                   -------

+ ['00-test', '01-ubuntu', '02-juju']

----------------------------------------------------------------------

为了正确获取os.path.isfile补丁以尊重这些返回值,我需要做些什么?

1 个答案:

答案 0 :(得分:1)

该属性称为side_effect,而不是side_effects