MCPcopy Create free account
hub / github.com/ipython/ipython / AssertPrints

Class AssertPrints

IPython/testing/tools.py:339–379  ·  view source on GitHub ↗

Context manager for testing that code prints certain text. Examples -------- >>> with AssertPrints("abc", suppress=False): ... print("abcd") ... print("def") ... abcd def

Source from the content-addressed store, hash-verified

337"""
338
339class AssertPrints(object):
340 """Context manager for testing that code prints certain text.
341
342 Examples
343 --------
344 >>> with AssertPrints("abc", suppress=False):
345 ... print("abcd")
346 ... print("def")
347 ...
348 abcd
349 def
350 """
351 def __init__(self, s, channel='stdout', suppress=True):
352 self.s = s
353 if isinstance(self.s, (str, _re_type)):
354 self.s = [self.s]
355 self.channel = channel
356 self.suppress = suppress
357
358 def __enter__(self):
359 self.orig_stream = getattr(sys, self.channel)
360 self.buffer = MyStringIO()
361 self.tee = Tee(self.buffer, channel=self.channel)
362 setattr(sys, self.channel, self.buffer if self.suppress else self.tee)
363
364 def __exit__(self, etype, value, traceback):
365 try:
366 if value is not None:
367 # If an error was raised, don't check anything else
368 return False
369 self.tee.flush()
370 setattr(sys, self.channel, self.orig_stream)
371 printed = self.buffer.getvalue()
372 for s in self.s:
373 if isinstance(s, _re_type):
374 assert s.search(printed), notprinted_msg.format(s.pattern, self.channel, printed)
375 else:
376 assert s in printed, notprinted_msg.format(s, self.channel, printed)
377 return False
378 finally:
379 self.tee.close()
380
381printed_msg = """Found {0!r} in printed output (on {1}):
382-------

Calls

no outgoing calls