如何模拟我的单元测试的输入目录?

时间:2016-06-28 13:48:02

标签: python python-2.7 unit-testing mocking

与我之前的一个问题相关:How to unit test a method that calculates the size of a dir? 我想对这个功能进行单元测试:

def get_dir_size(dir_path):
    """Determine the size of a dir.

    This function also takes into account the allocated size of
    directories (4096 bytes).

    Note: The function may crash on symlinks with something like:
    OSError: [Errno 40] Too many levels of symbolic links

    :param dir_path (str): path to the directory
    :return: size in bytes.
    """
    tot_size = 0
    for (root_path, dirnames, filenames) in os.walk(dir_path):
        for f in filenames:
            fpath = os.path.join(root_path, f)
            tot_size += os.path.getsize(fpath)
        tot_size += os.path.getsize(root_path)
    return tot_size

所以根据我的理解,我必须嘲笑os.walk函数

import threedi_utils

@mock.patch('threedi_utils.files.os.walk')
def test_get_dir_size_can_get_dir_size(self, mock_walk):
    mock_walk.return_value(5000)
    size = threedi_utils.files.get_dir_size(self.test_path)
    self.assertEqual(size, 5000)

但是mock_walk.return_value(5000)没有效果,因为我的测试失败了

Traceback (most recent call last):
  File "/home/vagrant/.buildout/eggs/mock-1.3.0-py2.7.egg/mock/mock.py", line 1305, in patched
    return func(*args, **keywargs)
  File "/srv/lib/threedi_utils/tests/test_files.py", line 55, in test_get_dir_size_can_get_dir_size
    self.assertEqual(size, 5000)
AssertionError: 0 != 5000

我错过了什么?

1 个答案:

答案 0 :(得分:-1)

好的,我正走错了路。应该嘲笑os.path.getsize()方法。另外,需要像.return_value = 5000

一样提供返回值
@mock.patch('threedi_utils.files.os.path.getsize')
def test_get_dir_size_can_get_dir_size(self, mock_size):
    mock_size.return_value = 50
    size = threedi_utils.files.get_dir_size(self.test_path)
    self.assertEqual(size, 750)
    self.tearDown()