From 8a65f6a76ecd83375ed77c2e97d96f70ebb45dd5 2014-09-07 20:46:04 From: Scott Sanderson Date: 2014-09-07 20:46:04 Subject: [PATCH] BUG: Explicitly close Tee in AssertPrints and AssertNotPrints Fixes a test failure caused by the Tee object being lazily closed only when an AssertPrints/AssertNotPrints object is garbage collected. --- diff --git a/IPython/testing/tools.py b/IPython/testing/tools.py index 5b95094..5970775 100644 --- a/IPython/testing/tools.py +++ b/IPython/testing/tools.py @@ -365,18 +365,21 @@ class AssertPrints(object): setattr(sys, self.channel, self.buffer if self.suppress else self.tee) def __exit__(self, etype, value, traceback): - if value is not None: - # If an error was raised, don't check anything else + try: + if value is not None: + # If an error was raised, don't check anything else + return False + self.tee.flush() + setattr(sys, self.channel, self.orig_stream) + printed = self.buffer.getvalue() + for s in self.s: + if isinstance(s, _re_type): + assert s.search(printed), notprinted_msg.format(s.pattern, self.channel, printed) + else: + assert s in printed, notprinted_msg.format(s, self.channel, printed) return False - self.tee.flush() - setattr(sys, self.channel, self.orig_stream) - printed = self.buffer.getvalue() - for s in self.s: - if isinstance(s, _re_type): - assert s.search(printed), notprinted_msg.format(s.pattern, self.channel, printed) - else: - assert s in printed, notprinted_msg.format(s, self.channel, printed) - return False + finally: + self.tee.close() printed_msg = """Found {0!r} in printed output (on {1}): ------- @@ -389,18 +392,24 @@ class AssertNotPrints(AssertPrints): Counterpart of AssertPrints""" def __exit__(self, etype, value, traceback): - if value is not None: - # If an error was raised, don't check anything else + try: + if value is not None: + # If an error was raised, don't check anything else + self.tee.close() + return False + self.tee.flush() + setattr(sys, self.channel, self.orig_stream) + printed = self.buffer.getvalue() + for s in self.s: + if isinstance(s, _re_type): + assert not s.search(printed),printed_msg.format( + s.pattern, self.channel, printed) + else: + assert s not in printed, printed_msg.format( + s, self.channel, printed) return False - self.tee.flush() - setattr(sys, self.channel, self.orig_stream) - printed = self.buffer.getvalue() - for s in self.s: - if isinstance(s, _re_type): - assert not s.search(printed), printed_msg.format(s.pattern, self.channel, printed) - else: - assert s not in printed, printed_msg.format(s, self.channel, printed) - return False + finally: + self.tee.close() @contextmanager def mute_warn():