For the first time, I'm using Python to create a library, and I'm trying to take the opportunity in this project to learn unit testing. I've written a first method and I want to write some unit tests for it. (Yes, I know that TDD requires I write the test first, I'll get there, really.)
The method is fairly simple, but it expects that the class has a
if __name__ == '__main__':
archive = ArchiveFile()
script_path = path.realpath(__file__)
parent_dir = path.abspath(path.join(script_path, os.pardir))
targ_dir = path.join(parent_dir, 'files')
targ_file = path.join(targ_dir, 'test.zip' )
archive.file = targ_file
"""Return the number of files in the archive."""
if self.file == None:
with ZipFile(self.file) as zip:
members = zip.namelist()
# Remove folder members if there are any.
pruned = [item for item in members if not item.endswith('/')]
What needs to be done is to use the
mock library to create a fake version of
ZipFile that won't object to there not actually being a file, but will instead return valid lists when using the
@unittest.mock.patch('comicfile.ZipFile') def test_page_count(self, mock_zip_file): comic_file = ComicFile() members = ['dir/', 'dir/file1', 'dir/file2'] mock_zip_file.return_value.__enter__.return_value.namelist.return_value \ = members self.assertEqual(2, self.comic_file.page_count())
__enter__.return_value portion above is necessary because in the code being tested the
ZipFile instance is being created within a context manager.