def test_classname_in_log(self): """Do a log and check if the classname is correctly in it""" _stderr = sys.stderr class Foobar: def somefunction(self): logger = fancylogger.getLogger(fname=True, clsname=True) logger.warn('we are logging something here') stringfile = StringIO() sys.stderr = stringfile handler = fancylogger.logToScreen() Foobar().somefunction() self.assertTrue('Foobar.somefunction' in stringfile.getvalue()) stringfile.close() # restore fancylogger.logToScreen(enable=False, handler=handler) # and again stringfile = StringIO() sys.stderr = stringfile handler = fancylogger.logToScreen() classless_function() self.assertTrue('unknown__getCallingClassName.classless_function' in stringfile.getvalue()) # restore fancylogger.logToScreen(enable=False, handler=handler) stringfile = StringIO() sys.stderr = stringfile fancylogger.setLogFormat("%(className)s blabla") handler = fancylogger.logToScreen() logger = fancylogger.getLogger(fname=False, clsname=False) logger.warning("blabla") txt = stringfile.getvalue() # this will only hold in debug mode, so also disable the test if __debug__: pattern = 'FancyLoggerTest' self.assertTrue(pattern in txt, "Pattern '%s' found in: %s" % (pattern, txt)) # restore fancylogger.logToScreen(enable=False, handler=handler) sys.stderr = _stderr
def test_cache(self): """Test the caching mechanism in the reporter.""" length = random.randint(1, 30) exit_code = random.randint(0, 3) threshold = random.randint(0, 10) message = ''.join( random.choice(string.printable) for x in range(length)) message = message.rstrip() (handle, filename) = tempfile.mkstemp() os.unlink(filename) os.close(handle) reporter = NagiosReporter('test_cache', filename, threshold, self.nagios_user) nagios_exit = [ NAGIOS_EXIT_OK, NAGIOS_EXIT_WARNING, NAGIOS_EXIT_CRITICAL, NAGIOS_EXIT_UNKNOWN ][exit_code] reporter.cache(nagios_exit, message) (handle, output_filename) = tempfile.mkstemp() os.close(handle) try: old_stdout = sys.stdout buffer = StringIO() sys.stdout = buffer reporter_test = NagiosReporter('test_cache', filename, threshold, self.nagios_user) reporter_test.report_and_exit() except SystemExit as err: line = buffer.getvalue().rstrip() sys.stdout = old_stdout buffer.close() self.assertTrue(err.code == nagios_exit[0]) self.assertTrue(line == "%s %s" % (nagios_exit[1], message)) os.unlink(filename)
def test_normal_warning_logging(self): """ Test if just using import logging, logging.warning still works after importing fancylogger (take this literally; this does not imply the root logging logger is a fancylogger) """ stringfile = StringIO() sys.stderr = stringfile msg = 'this is my string' logging.warning(msg) self.assertTrue(msg in stringfile.getvalue(), msg="'%s' in '%s'" % (msg, stringfile.getvalue())) msg = 'there are many like it' logging.getLogger().warning(msg) self.assertTrue(msg in stringfile.getvalue(), msg="'%s' in '%s'" % (msg, stringfile.getvalue())) msg = 'but this one is mine' logging.getLogger('mine').warning(msg) self.assertTrue(msg in stringfile.getvalue(), msg="'%s' in '%s'" % (msg, stringfile.getvalue()))
class TestSimpleNagios(TestCase): """Test for the SimpleNagios class.""" def setUp(self): """redirect stdout""" self.old_stdout = sys.stdout self.buffo = StringIO() sys.stdout = self.buffo user = getpwuid(os.getuid()) self.nagios_user = user.pw_name def tearDown(self): """Restore stdout""" self.buffo.close() sys.stdout = self.old_stdout def _basic_test_single_instance(self, kwargs, message, nagios_exit): """Basic test""" self.buffo.seek(0) self.buffo.truncate(0) raised_exception = None try: SimpleNagios(**kwargs) except SystemExit as err: raised_exception = err bo = self.buffo.getvalue().rstrip() self.assertEqual(bo, message) self.assertEqual(raised_exception.code, nagios_exit[0]) def _basic_test_single_instance_and_exit(self, fn, msg, message, nagios_exit): """Basic test""" self.buffo.seek(0) self.buffo.truncate(0) nagios = SimpleNagios() func = getattr(nagios, fn) raised_exception = None try: func(msg) except SystemExit as err: raised_exception = err bo = self.buffo.getvalue().rstrip() self.assertEqual(bo, message) self.assertEqual(raised_exception.code, nagios_exit[0]) def test_simple_single_instance(self): """Test what is generated when performance data is given, but not critical/warning""" kwargs = { 'message': 'hello', 'value1': 3, 'value1_warning': 5, 'value1_critical': 10, } self._basic_test_single_instance(kwargs, 'OK hello | value1=3;5;10;', NAGIOS_EXIT_OK) # outside warning range kwargs['value1'] = 5 self._basic_test_single_instance(kwargs, 'OK hello | value1=5;5;10;', NAGIOS_EXIT_OK) # goutside warning range, perfdata with warning in message kwargs['value1'] = 7 self._basic_test_single_instance(kwargs, 'WARNING value1 | value1=7;5;10;', NAGIOS_EXIT_WARNING) # outside critical range? kwargs['value1'] = 10 self._basic_test_single_instance(kwargs, 'WARNING value1 | value1=10;5;10;', NAGIOS_EXIT_WARNING) # greater kwargs['value1'] = 15 self._basic_test_single_instance(kwargs, 'CRITICAL value1 | value1=15;5;10;', NAGIOS_EXIT_CRITICAL) # mixed kwargsmore = { 'value0': 3, 'value0_warning': 5, 'value0_critical': 10, 'value2': 7, 'value2_warning': 5, 'value2_critical': 10, } kwargs.update(kwargsmore) # critical value in message self._basic_test_single_instance( kwargs, 'CRITICAL value1 | value0=3;5;10; value1=15;5;10; value2=7;5;10;', NAGIOS_EXIT_CRITICAL) # all warning values in message kwargs['value1'] = 7 self._basic_test_single_instance( kwargs, 'WARNING value1, value2 | value0=3;5;10; value1=7;5;10; value2=7;5;10;', NAGIOS_EXIT_WARNING) # warning in message kwargs['value1'] = 5 self._basic_test_single_instance( kwargs, 'WARNING value2 | value0=3;5;10; value1=5;5;10; value2=7;5;10;', NAGIOS_EXIT_WARNING) # no warning/critical; so regular message kwargs['value2'] = 5 self._basic_test_single_instance( kwargs, 'OK hello | value0=3;5;10; value1=5;5;10; value2=5;5;10;', NAGIOS_EXIT_OK) def test_simple_nagios_instance_and_nagios_exit(self): """Test the basic ok/warning/critical/unknown""" self._basic_test_single_instance_and_exit('ok', 'hello', 'OK hello', NAGIOS_EXIT_OK) self._basic_test_single_instance_and_exit('warning', 'hello', 'WARNING hello', NAGIOS_EXIT_WARNING) self._basic_test_single_instance_and_exit('critical', 'hello', 'CRITICAL hello', NAGIOS_EXIT_CRITICAL) self._basic_test_single_instance_and_exit('unknown', 'hello', 'UNKNOWN hello', NAGIOS_EXIT_UNKNOWN) def test_cache(self): """Test the caching""" (handle, filename) = tempfile.mkstemp() os.unlink(filename) n = SimpleNagios(_cache=filename, _cache_user=self.nagios_user) message = "mywarning" n.warning(message) os.close(handle) self.buffo.seek(0) self.buffo.truncate(0) raised_exception = None try: reporter_test = NagiosReporter('test_cache', filename, -1, self.nagios_user) reporter_test.report_and_exit() except SystemExit as err: raised_exception = err bo = self.buffo.getvalue().rstrip() self.assertEqual(bo, "WARNING %s" % message) self.assertEqual(raised_exception.code, NAGIOS_EXIT_WARNING[0]) statres = os.stat(filename) self.assertFalse(statres.st_mode & stat.S_IROTH) def test_world_readable(self): """Test world readable cache""" (handle, filename) = tempfile.mkstemp() os.unlink(filename) n = SimpleNagios(_cache=filename, _cache_user=self.nagios_user, _world_readable=True) n.ok("test") os.close(handle) try: reporter_test = NagiosReporter('test_cache', filename, -1, self.nagios_user) reporter_test.report_and_exit() except SystemExit: pass statres = os.stat(filename) self.assertTrue(statres.st_mode & stat.S_IROTH)
def test_zzz_fancylogger_as_rootlogger_logging(self): """ Test if just using import logging, logging with logging uses fancylogger after setting the root logger """ # test logging.root is loggin root logger # this is an assumption made to make the fancyrootlogger code work orig_root = logging.getLogger() self.assertEqual(logging.root, orig_root, msg='logging.root is the root logger') self.assertFalse(isinstance(logging.root, fancylogger.FancyLogger), msg='logging.root is not a FancyLogger') stringfile = StringIO() sys.stderr = stringfile handler = fancylogger.logToScreen() fancylogger.setLogLevelDebug() logger = fancylogger.getLogger() self.assertEqual(logger.handlers, [self.handler, handler], msg='active handler for root fancylogger') self.assertEqual(logger.level, fancylogger.getLevelInt('DEBUG'), msg='debug level set') msg = 'this is my string' logging.debug(msg) self.assertEqual( stringfile.getvalue(), '', msg= "logging.debug reports nothing when fancylogger loglevel is debug") fancylogger.setroot() self.assertTrue( isinstance(logging.root, fancylogger.FancyLogger), msg='logging.root is a FancyLogger after setRootLogger') self.assertEqual(logging.root.level, fancylogger.getLevelInt('DEBUG'), msg='debug level set for root') self.assertEqual(logger.level, logging.NOTSET, msg='original root fancylogger level set to NOTSET') self.assertEqual( logging.root.handlers, [self.handler, handler], msg='active handler for root logger from previous root fancylogger' ) self.assertEqual(logger.handlers, [], msg='no active handlers on previous root fancylogger') root_logger = logging.getLogger('') self.assertEqual( root_logger, logging.root, msg='logging.getLogger() returns logging.root FancyLogger') frl = fancylogger.getLogger() self.assertEqual( frl, logging.root, msg='fancylogger.getLogger() returns logging.root FancyLogger') logging.debug(msg) self.assertTrue( msg in stringfile.getvalue(), msg="logging.debug reports when fancylogger loglevel is debug") fancylogger.resetroot() self.assertEqual( logging.root, orig_root, msg='logging.root is the original root logger after resetroot') # restore fancylogger.logToScreen(enable=False, handler=handler)
def test_threshold(self, message="Hello"): """Test the threshold borking mechanism in the reporter.""" message = message.rstrip() threshold = 1 if message == '': return (handle, filename) = tempfile.mkstemp() os.unlink(filename) reporter = NagiosReporter('test_cache', filename, threshold, self.nagios_user) # redirect stdout old_stdout = sys.stdout buff = StringIO() sys.stdout = buff nagios_exit = NAGIOS_EXIT_OK reporter.cache(nagios_exit, message) os.close(handle) raised_exception = None try: reporter_test = NagiosReporter('test_cache', filename, threshold, self.nagios_user) reporter_test.report_and_exit() except SystemExit as err: raised_exception = err self.assertEqual(raised_exception.code, NAGIOS_EXIT_OK[0], "Exit with status when the cached data is recent") # restore stdout buff.close() sys.stdout = old_stdout reporter = NagiosReporter('test_cache', filename, threshold, self.nagios_user) reporter.cache(nagios_exit, message) time.sleep(threshold + 1) # redirect stdout old_stdout = sys.stdout buff = StringIO() sys.stdout = buff raised_exception = None try: reporter_test = NagiosReporter('test_cache', filename, threshold, self.nagios_user) reporter_test.report_and_exit() except SystemExit as err: raised_exception = err line = buff.getvalue().rstrip() # restore stdout buff.close() sys.stdout = old_stdout self.assertEqual(raised_exception.code, NAGIOS_EXIT_UNKNOWN[0], "Too old caches lead to unknown status") self.assertTrue( line.startswith( "%s test_cache gzipped JSON file too old (timestamp =" % (NAGIOS_EXIT_UNKNOWN[1]))) os.unlink(filename)