[Add] Utility class to hide prints during testing

Provides with HidePrints context manager and @HidePrints.hide decorator
This commit is contained in:
Darius Arnold 2018-07-13 21:33:27 +02:00
parent 3b52b7a28f
commit 10aa0360bc
2 changed files with 79 additions and 0 deletions

27
tests/__init__.py Normal file
View File

@ -0,0 +1,27 @@
# -*- coding: utf-8 -*-
# --------------------------------------------------------
# Purpose: Convience imports for PyLoT
#
'''
================================================
PyLoT - the Python picking and Localization Tool
================================================
This python library contains a graphical user interfaces for picking
seismic phases. This software needs ObsPy (http://github.com/obspy/obspy/wiki)
and the Qt4 libraries to be installed first.
PILOT has been developed in Mathworks' MatLab. In order to distribute
PILOT without facing portability problems, it has been decided to re-
develop the software package in Python. The great work of the ObsPy
group allows easy handling of a bunch of seismic data and PyLoT will
benefit a lot compared to the former MatLab version.
The development of PyLoT is part of the joint research project MAGS2.
:copyright:
The PyLoT Development Team
:license:
GNU Lesser General Public License, Version 3
(http://www.gnu.org/copyleft/lesser.html)
'''

52
tests/utils.py Normal file
View File

@ -0,0 +1,52 @@
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""Utilities/helpers for testing"""
import sys
import os
class HidePrints:
"""
Context manager that hides all standard output within its body.
The optional hide_prints argument can be used to quickly enable printing during debugging of tests.
Use (This will result in all console output of noisy_function to be suppressed):
from tests.utils import HidePrints
with HidePrints():
noise_function()
"""
@staticmethod
def hide(func, *args, **kwargs):
"""Decorator that hides all prints of the decorated function.
Use:
from tests.utils import HidePrints
@HidePrints.hide
def noise()
print("NOISE")
"""
def silencer(*args, **kwargs):
with HidePrints():
func(*args, **kwargs)
return silencer
def __init__(self, hide_prints=True):
"""Create object with hide_prints=False to disable print hiding"""
self.hide = hide_prints
def __enter__(self):
"""Redirect stdout to /dev/null, save old stdout"""
if self.hide:
self._original_stdout = sys.stdout
devnull = open(os.devnull, "w")
sys.stdout = devnull
def __exit__(self, exc_type, exc_val, exc_tb):
"""Reinstate old stdout"""
if self.hide:
sys.stdout = self._original_stdout