Related to a earlier question of mine: How to unit test a method that calculates the size of a dir? I want to unit test this function:
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
So from what I understood I have to mock the os.walk
function
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)
But mock_walk.return_value(5000)
goes without effect as my test fails
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
What am I missing?
Ok, I was heading down the wrong path. Should have mocked the os.path.getsize()
method. Plus, the return value needs to be provided like this .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()
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.