1# Copyright (C) 2017-2021 Pier Carlo Chiodi 2# 3# This program is free software: you can redistribute it and/or modify 4# it under the terms of the GNU General Public License as published by 5# the Free Software Foundation, either version 3 of the License, or 6# (at your option) any later version. 7# 8# This program is distributed in the hope that it will be useful, 9# but WITHOUT ANY WARRANTY; without even the implied warranty of 10# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 11# GNU General Public License for more details. 12# 13# You should have received a copy of the GNU General Public License 14# along with this program. If not, see <http://www.gnu.org/licenses/>. 15 16import logging 17import os 18import sys 19import unittest 20 21 22class CaptureLog(logging.Handler): 23 24 def __init__(self, *args, **kwargs): 25 self.reset_messages() 26 super(CaptureLog, self).__init__(*args, **kwargs) 27 28 def reset_messages(self): 29 self.msgs = [] 30 self.warnings = [] 31 32 def emit(self, record): 33 self.acquire() 34 try: 35 if record.levelname.lower() == "error": 36 self.msgs.append(record.getMessage()) 37 if record.levelname.lower() == "warning": 38 self.warnings.append(record.getMessage()) 39 finally: 40 self.release() 41 42 def reset(self): 43 self.acquire() 44 try: 45 self._reset_messages() 46 finally: 47 self.release() 48 49class ARouteServerTestCase(unittest.TestCase): 50 51 NEED_TO_CAPTURE_LOG = False 52 SHORT_DESCR = "" 53 DEBUG = False 54 SKIP_ON_TRAVIS = False 55 56 def _capture_log(self): 57 self.logger_handler = None 58 if self.NEED_TO_CAPTURE_LOG: 59 logger = logging.getLogger() 60 self.logger_handler = CaptureLog(level="DEBUG") 61 logger.addHandler(self.logger_handler) 62 63 self.logger_handler.reset_messages() 64 65 def clear_log(self): 66 if self.logger_handler: 67 self.logger_handler.reset_messages() 68 69 def _setUp(self): 70 pass 71 72 def setUp(self): 73 self._capture_log() 74 self._setUp() 75 76 @classmethod 77 def _setUpClass(cls): 78 pass 79 80 @classmethod 81 def setUpClass(cls): 82 cls._setUpClass() 83 84 @classmethod 85 def _tearDownClass(cls): 86 pass 87 88 @classmethod 89 def tearDownClass(cls): 90 cls._tearDownClass() 91 92 @classmethod 93 def print_msg(cls, s): 94 sys.stderr.write("{}\n".format(s)) 95 96 @classmethod 97 def debug(cls, s): 98 if cls.DEBUG or "DEBUG" in os.environ: 99 cls.print_msg("DEBUG: {}".format(s)) 100 101 @classmethod 102 def info(cls, s): 103 cls.print_msg(s) 104 105 def shortDescription(self): 106 return self._testMethodDoc.format(self.SHORT_DESCR) 107