示例#1
0
class TestNagiosExits(TestCase):
    """Test for all things exiting with nagios results."""
    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 test_exit_from_errorcode(self):
        """test calling the correct exit function."""

        for (ec, expected) in [
            (0, NAGIOS_EXIT_OK),
            (1, NAGIOS_EXIT_WARNING),
            (2, NAGIOS_EXIT_CRITICAL),
            (3, NAGIOS_EXIT_UNKNOWN),
            (101, NAGIOS_EXIT_UNKNOWN),
        ]:
            try:
                exit_from_errorcode(ec, "boem")
            except SystemExit as err:
                print(err)
                self.assertTrue(err.code == expected[0])
示例#2
0
    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
示例#3
0
    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)
示例#4
0
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)
示例#5
0
    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)