From 8ef0ef772bd43084e6b0aacea4ab3aa3b63235fa Mon Sep 17 00:00:00 2001 From: Brant Watson Date: Mon, 14 Nov 2016 15:50:16 -0600 Subject: [PATCH] Implement __nonzero__ for SpooledBytesIO, SpooledStringIO An empty StringIO instance still has a "truthy" value. In order to user SpooledBytesIO with the ZipFile library, the object instance needs to be considered truthy. This patch implements __nonzero__ so that the truthyness does not fall back on the underlying __len__ implementation. Added a test that verifies a SpooledBytesIO is compatible with the ZipFile library. --- boltons/ioutils.py | 3 +++ tests/test_ioutils.py | 17 +++++++++++++++++ 2 files changed, 20 insertions(+) diff --git a/boltons/ioutils.py b/boltons/ioutils.py index 1ce0b68..8648697 100644 --- a/boltons/ioutils.py +++ b/boltons/ioutils.py @@ -180,6 +180,9 @@ class SpooledIOBase(object): def __ne__(self, other): return not self.__eq__(other) + def __nonzero__(self): + return True + class SpooledBytesIO(SpooledIOBase): """ diff --git a/tests/test_ioutils.py b/tests/test_ioutils.py index 98494f1..b8a6027 100644 --- a/tests/test_ioutils.py +++ b/tests/test_ioutils.py @@ -3,6 +3,7 @@ import random import string import sys from unittest import TestCase +from zipfile import ZipFile, ZIP_DEFLATED from boltons import ioutils @@ -154,6 +155,13 @@ class BaseTestMixin(object): self.assertTrue(self.spooled_flo.isatty() is True or self.spooled_flo.isatty() is False) + def test_truthy(self): + """Make sure empty instances are still considered truthy""" + self.spooled_flo.seek(0) + self.spooled_flo.truncate() + if not self.spooled_flo: + raise AssertionError("Instance is not truthy") + class TestSpooledBytesIO(TestCase, BaseTestMixin, AssertionsMixin): linesep = os.linesep.encode('ascii') @@ -219,6 +227,15 @@ class TestSpooledBytesIO(TestCase, BaseTestMixin, AssertionsMixin): self.spooled_flo.rollover() self.assertIsNone(self.spooled_flo.flush()) + def test_zip_compat(self): + """Make sure object is compatible with ZipFile library""" + self.spooled_flo.seek(0) + self.spooled_flo.truncate() + doc = ZipFile(self.spooled_flo, 'w', ZIP_DEFLATED) + doc.writestr("content.txt", "test") + self.assertTrue('content.txt' in doc.namelist()) + doc.close() + class TestSpooledStringIO(TestCase, BaseTestMixin, AssertionsMixin): linesep = os.linesep