Saturday, 31 August 2013

Who wins in battle between "don't mock 3rd party" and "ensure close() called"?

Who wins in battle between "don't mock 3rd party" and "ensure close()
called"?

I have this block of code I want to unit test:
@staticmethod
def _read_from_zip(pkg_zip_path):
"""
Return a |BlobCollection| instance loaded from *pkg_zip_path*.
"""
blobs = BlobCollection()
zipf = ZipFile(pkg_zip_path)
for name in zipf.namelist():
blobs[name] = zipf.read(name)
zipf.close()
root_uri = os.path.splitext(pkg_zip_path)[0]
return PhysPkg(blobs, root_uri)
It calls ZipFile, a library/third-party package, so I want to write a test
that integrates with ZipFile rather than mocking it out (don't mock
3rd-party code rule).
Here's the test I have so far. initializer_mock() is a helper function
that patches the __init__() method on a class, PhysPkg in this case:
from opcdiag.phys_pkg import PhysPkg
MINI_PKG_PATH = 'test_files/mini_pkg.zip'
@pytest.fixture
def init(self, request):
return initializer_mock(PhysPkg, request)
def it_can_construct_from_a_zip_package(self, init):
PhysPkg._read_from_zip(MINI_PKG_PATH)
expected_blobs = {'uri_1': b'blob_1\n', 'uri_2': b'blob_2\n'}
init.assert_called_once_with(expected_blobs, ROOT_URI)
The problem is, because I don't mock ZipFile, I don't see how I can test
that the close() method gets called.
Maybe I should write two tests? This one to ensure proper integration with
ZipFile by testing results and another with mocking ZipFile to ensure
close() gets called?

No comments:

Post a Comment