2

I have a method in Python that looks like this (in comicfile.py):

from zipfile import ZipFile

...

class ComicFile():
    ...

    def page_count(self):
        """Return the number of pages in the file."""
        if self.file == None:
            raise ComicFile.FileNoneError()

        if not os.path.isfile(self.file):
            raise ComicFile.FileNotFoundError()

        with ZipFile(self.file) as zip:
            members = zip.namelist()
            pruned = self.prune_dirs(members)
            length = len(pruned)
            return length

I'm trying to write a unit test for this (I've already tested prune_dirs), and so for this is what I have (test_comicfile.py):

import unittest
import unittest.mock

import comicfile

...

class TestPageCount(unittest.TestCase):

    def setUp(self):
        self.comic_file = comicfile.ComicFile()

    @unittest.mock.patch('comicfile.ZipFile')
    def test_page_count(self, mock_zip_file):
        # Store as tuples to use as dictionary keys.
        members_dict = {('dir/', 'dir/file1', 'dir/file2'):2,
                        ('file1.jpg', 'file2.jpg', 'file3.jpg'):3
        }

        # Make the file point to something to prevent FileNoneError.
        self.comic_file.file = __file__

        for file_tuple, count in members_dict.items():
            mock_zip_file.return_value.namelist = list(file_tuple)
            self.assertEqual(count, self.comic_file.page_count())

When I run this test, I get the following:

F..ss....
======================================================================
FAIL: test_page_count (test_comicfile.TestPageCount)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "/usr/local/Cellar/python3/3.5.1/Frameworks/Python.framework/Versions/3.5/lib/python3.5/unittest/mock.py", line 1157, in patched
    return func(*args, **keywargs)
  File "/Users/chuck/Dropbox/Projects/chiv/chiv.cbstar/test_comicfile.py", line 86, in test_page_count
    self.assertEqual(count, self.comic_file.page_count())
AssertionError: 2 != 0

----------------------------------------------------------------------
Ran 9 tests in 0.010s

FAILED (failures=1, skipped=2)

OK, so self.comic_file.page_count() is returning 0. I tried placing the following line after members = zip.namelist() in page_count.

print('\nmembers -> ' + str(members))

During the test, I get this:

members -> <MagicMock name='ZipFile().__enter__().namelist()' id='4483358280'>

I'm quite new to unit testing and am quite nebulous on using unittest.mock, but my understanding is that mock_zip-file.return_value.namelist = list(file_tuple) should have made it so that the namelist method of the ZipFile class would return each of the file_tuple contents in turn. What it is doing I have no idea.

I think what I'm trying to do here is clear, but I can't seem to figure out how to override the namelist method so that my unit test is only testing this one function instead of having to deal with ZipFile as well.

4
  • Your code is confusing. Are 'ComicFile' and 'comicfile' 1 class (once misspelled) or 2? Should 'Zipfile' in the first snippet by 'self.Zipfile'? Without knowing the details, I wonder if you even need the mock. Each test should assume that everything else works. You only question that when a test fails. There needs to be a positive reason to mock something. For instance, 'the call will fail in the test setting' or 'calling a real object takes too much time or space' or 'the return is not deterministic'. Commented Jul 24, 2016 at 21:49
  • It's quite possible that I'm using non-Pythonic naming conventions, although I'm trying to conform to them. ComicFile is the class, comicfile is the module containing the class. ZipFile is imported via from zipfile import ZipeFile. I think I need to mock because if I don't, in order to test this I'd actually need to have zip files in the file system, and I just want to test that, if a zip file object returns a namelist, this function correctly counts the number of files.
    – Chuck
    Commented Jul 24, 2016 at 21:54
  • mock IS confusing, especially regarding context managers.
    – dm03514
    Commented Jul 24, 2016 at 22:09
  • Mocking an external resource is a good use. If I were not using it as a context manager and were only making the one function call, I might temporarily replace Zipfile with "class Zipfile:\n def namelist(): return ...". But for this case, I also learned something from dm03514's great answer. Commented Jul 24, 2016 at 22:36

1 Answer 1

2

ZipFile is instantiated as a context manager. to mock it you have to refer to its __enter__ method.

mock_zip_file.return_value.__enter__.return_value.namelist.return_value = list(file_tuple)

What you're trying to do is very clear, but the context manager adds complexity to the mocking.


One trick is that when a mock registers all calls made to it, in this example it is saying it has a call at:

members -> <MagicMock name='ZipFile().__enter__().namelist()' id='4483358280'>

This can guide you in registering your mocked object, replace all () with return_value

2
  • OK, first, tyvm. I copied and pasted and got the test to work and the prints I'd placed throughout the code show what I expect them to (the mocked members). Of course, I don't yet understand why it works, that's going to bug me until I figure it out. I've read the mock docs a few times, but I'll take a look at the article you linked to and perhaps that'll help me understand what that kind of code means.
    – Chuck
    Commented Jul 24, 2016 at 22:18
  • I (think) I understand now. If I'd set zip without the with block, but with just zip = ZipFile..., then mock_zip_file.return_value.namelist.return_value = list(file_tuple) would have worked. The __enter__ in the print you quoted should have alerted me that the path I was using to get to namevalue was incorrect.
    – Chuck
    Commented Jul 24, 2016 at 22:36

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.