Example #1
0
class TestFactoryImportsTest(unittest.TestCase):
    def setUp(self):
        setup_db()
        tests_path = os.path.normpath(os.path.join(
                        os.path.dirname(__file__), "testdata"))
        self.testfactory = TestFactory(confdir=tests_path)
        self.host = Host(
            conf.hostsConf,
            "dummy", "testserver1",
            "192.168.1.1", "Servers",
        )

    def tearDown(self):
        teardown_db()

    def test_import(self):
        """
        Les imports doivent correctement être gérés par la TestFactory.
        """
        print self.testfactory.path
        self.testfactory.load_tests()
        testclasses = self.testfactory.get_test('Error', 'imports')
        self.assertEquals(1, len(testclasses))
        test = testclasses[0](self.host, None, None, None)

        # On ne peut pas utiliser self.assertRaises à cause du rebinding
        # des classes dans TestFactory.
        try:
            test.add_test()
        except VigiConfError, e:
            self.assertEquals(_("Import test was successful"), unicode(e))
        except Exception, e:
            self.fail("Unexpected exception of type %r" % type(e))
Example #2
0
def list_tests(args):
    from vigilo.vigiconf.lib.confclasses.test import TestFactory
    testfactory = TestFactory(confdir=settings["vigiconf"].get("confdir"))
    available_hclasses = sorted(testfactory.get_hclasses())
    wrapper = textwrap.TextWrapper(
        initial_indent=' ' * 4,
        subsequent_indent=' ' * 4,
        break_long_words=False,
    )
    print _("Available host classes:")
    for line in wrapper.wrap(", ".join(available_hclasses) + "."):
        print line

    if not args.classes:
        hclasses = available_hclasses
    else:
        hclasses = set()
        for hclass in args.classes:
            if hclass not in available_hclasses:
                LOGGER.warning(_("No such host class '%s'"), hclass)
            else:
                hclasses.add(hclass)

    if not hclasses:
        return

    for hclass in hclasses:
        testnames = sorted(testfactory.get_testnames([hclass]))
        print "\n" + (_("Tests for host class '%s':") % hclass)
        for line in wrapper.wrap(", ".join(testnames) + "."):
            print line
Example #3
0
 def test_generator_com(self):
     """Test the generation in C.E."""
     host = Host(conf.hostsConf, "dummy.xml", "testserver1",
                 "192.168.1.1", "Servers")
     testfactory = TestFactory(confdir=os.path.join(self.tmpdir, "conf"))
     test_list = testfactory.get_test("UpTime", host.classes)
     host.add_tests(test_list)
     nagios = Nagios()
     genmanager = GeneratorManager([nagios])
     genmanager.generate(DummyRevMan())
     self.assert_(os.path.exists(os.path.join(self.basedir, "localhost",
                  "nagios", "nagios.cfg")))
Example #4
0
 def setUp(self):
     setup_db()
     self.testfactory = TestFactory(confdir=settings["vigiconf"]["confdir"])
     self.host = Host(
         conf.hostsConf,
         "dummy", "testserver1",
         "192.168.1.1", "Servers",
     )
Example #5
0
 def setUp(self):
     setup_db()
     tests_path = os.path.normpath(os.path.join(
                     os.path.dirname(__file__), "testdata"))
     self.testfactory = TestFactory(confdir=tests_path)
     self.host = Host(
         conf.hostsConf,
         "dummy", "testserver1",
         "192.168.1.1", "Servers",
     )
Example #6
0
 def setUp(self):
     setup_db()
     self.testfactory = TestFactory(confdir=settings["vigiconf"]["confdir"])
     self.host = Host(conf.hostsConf, "dummy", u"testserver1",
                      u"192.168.1.1", u"Servers")
     self.expected = {
         "metrosrv": {
             "type": "passive",
             "weight": None,
             "warning_weight": None,
             "directives": {},
             "reRoutedBy": None,
         },
     }
Example #7
0
    def setUp(self):
        setup_db()
        self.tmpdir = setup_tmpdir()
        self.old_conf_path = settings["vigiconf"]["confdir"]
        settings["vigiconf"]["confdir"] = os.path.join(self.tmpdir, "conf.d")
        os.mkdir(settings["vigiconf"]["confdir"])

        # Prepare necessary directories
        # TODO: commenter les divers repertoires
        setup_deploy_dir()
        self.host = Host(conf.hostsConf, "dummy", u"testserver1",
                         u"192.168.1.1", u"Servers")
        testfactory = TestFactory(confdir=settings["vigiconf"]["confdir"])
        test_list = testfactory.get_test("UpTime", self.host.classes)
        self.host.add_tests(test_list)
        self.dispatchator = make_dispatchator()
        # Disable qualification, validation, stop and start scripts
        for app in self.dispatchator.apps_mgr.applications:
            app.validation = None
            app.start_command = None
            app.stop_command = None
        # Don't check the installed revisions
        self.dispatchator.force = ("deploy", "db-sync")
Example #8
0
class TestFactoryTest(unittest.TestCase):

    def setUp(self):
        setup_db()
        self.testfactory = TestFactory(confdir=settings["vigiconf"]["confdir"])
        self.host = Host(
            conf.hostsConf,
            "dummy", "testserver1",
            "192.168.1.1", "Servers",
        )

    def tearDown(self):
        teardown_db()


    def test_get_testnames(self):
        """Test for the get_testname method"""
        testnames = self.testfactory.get_testnames()
        self.assertTrue("UpTime" in testnames, "get_testnames does not work")

    def test_get_hclasses(self):
        """Test for the get_hclasses method"""
        hclasses = self.testfactory.get_hclasses()
        self.assertTrue("all" in hclasses, "get_hclasses does not work")

    def test_list_test_paths(self):
        """
        La liste des chemins des tests doit contenir ceux de VigiConf et ceux de l'admin sys
        """
        default_path = os.path.normpath(os.path.join(
                            os.path.dirname(__file__), "..", "tests"))
        sysadmin_path = os.path.join(settings["vigiconf"]["confdir"], "tests")
        print self.testfactory.path
        self.assertTrue(len(self.testfactory.path) >= 2)
        self.assertEqual(self.testfactory.path[0], default_path)
        self.assertEqual(self.testfactory.path[-1], sysadmin_path)
Example #9
0
class HostMethods(unittest.TestCase):

    def setUp(self):
        setup_db()
        self.testfactory = TestFactory(confdir=settings["vigiconf"]["confdir"])
        self.host = Host(conf.hostsConf, "dummy", u"testserver1",
                         u"192.168.1.1", u"Servers")
        self.expected = {
            "metrosrv": {
                "type": "passive",
                "weight": None,
                "warning_weight": None,
                "directives": {},
                "reRoutedBy": None,
            },
        }

    def tearDown(self):
        teardown_db()

    def test_add_metro_service(self):
        """Test for the add_metro_service host method"""
        test_list = self.testfactory.get_test("Interface", self.host.classes)
        self.host.add_tests(test_list, {"label":"eth1", "ifname":"eth1"})
        self.host.add_metro_service("Traffic in eth1", "ineth1", 10, 20)
        self.assertEqual(
            conf.hostsConf["testserver1"]["services"]["Traffic in eth1"],
            self.expected["metrosrv"])
        self.assert_('ineth1' in conf.hostsConf["testserver1"]["metro_services"])
        self.assertEqual(
            conf.hostsConf["testserver1"]["metro_services"]['ineth1'],
            {
                'servicename': 'Traffic in eth1',
                'warning': 10,
                'critical': 20,
                'factor': 1.0,
            }
        )

    def test_priority_host_hosttemplate(self):
        """Test priorite du parametrage des hosts sur les hosttemplates"""
        test_list = self.testfactory.get_test("Interface", self.host.classes)
        self.host.add_tests(test_list, {"label":"eth0", "ifname":"eth0"})
        self.host.add_metro_service("Traffic in eth0", "ineth0", 10, 20)
        self.assertEqual(
            conf.hostsConf["testserver1"]["services"]["Traffic in eth0"],
            self.expected["metrosrv"])

    def test_add_metro_service_INTF(self):
        """Test for the add_metro_service function in the Interface test"""
        test_list = self.testfactory.get_test("Interface", self.host.classes)
        self.host.add_tests(test_list, {"label":"eth0", "ifname":"eth0",
                                        "warn": (10, 20), "crit": (30, 40)})
        self.assertEqual(
            conf.hostsConf["testserver1"]["services"]["Traffic in eth0"],
            self.expected["metrosrv"])
        self.assert_('ineth0' in conf.hostsConf["testserver1"]["metro_services"])
        self.assertEqual(
            conf.hostsConf["testserver1"]["metro_services"]['ineth0'],
            {
                'servicename': 'Traffic in eth0',
                'warning': 10,
                'critical': 30,
                'factor': 8,
            }
        )

        self.assertEqual(
            conf.hostsConf["testserver1"]["services"]["Traffic out eth0"],
            self.expected["metrosrv"])
        self.assert_('outeth0' in conf.hostsConf["testserver1"]["metro_services"])
        self.assertEqual(
            conf.hostsConf["testserver1"]["metro_services"]['outeth0'],
            {
                'servicename': 'Traffic out eth0',
                'warning': 20,
                'critical': 40,
                'factor': 8,
            }
        )

    def test_invalid_INTF_admin_value(self):
        """Valeurs autorisées pour le paramètre 'admin' du test Interface."""
        test_list = self.testfactory.get_test("Interface", self.host.classes)

        # Les valeurs i/w/c doivent être acceptées.
        for value in ('i', 'w', 'c'):
            self.host.add_tests(test_list, {"label":"eth0", "ifname":"eth0",
                                            "admin": value})
            self.assertEqual(
                conf.hostsConf["testserver1"]["SNMPJobs"]\
                    [ ("Interface eth0", "service") ]['params'],
                # 'c' correspond à la valeur par défaut de "dormant".
                ['eth0', 'eth0', value, 'c'])

        # Les autres valeurs doivent être rejetées.
        self.assertRaises(ParsingError, self.host.add_tests,
            test_list, {"label":"eth0", "ifname":"eth0", "admin": ''})

    def test_invalid_INTF_dormant_value(self):
        """Valeurs autorisées pour le paramètre 'dormant' du test Interface."""
        test_list = self.testfactory.get_test("Interface", self.host.classes)

        # Les valeurs i/w/c doivent être acceptées.
        for value in ('i', 'w', 'c'):
            self.host.add_tests(test_list, {"label":"eth0", "ifname":"eth0",
                                            "dormant": value})
            self.assertEqual(
                conf.hostsConf["testserver1"]["SNMPJobs"]\
                    [ ("Interface eth0", "service") ]['params'],
                # 'i' correspond à la valeur par défaut de "admin".
                ['eth0', 'eth0', 'i', value])

        # Les autres valeurs doivent être rejetées.
        self.assertRaises(ParsingError, self.host.add_tests,
            test_list, {"label":"eth0", "ifname":"eth0", "dormant": ''})

    def test_add_tag_hosts(self):
        """Test for the add_tag method on hosts"""
        self.host.add_tag("Host", "important", 2)
        self.assertEqual(conf.hostsConf["testserver1"]["tags"],
                         {"important": 2})

    def test_add_tag_services(self):
        """Test for the add_tag method on services"""
        test_list = self.testfactory.get_test("UpTime", self.host.classes)
        self.host.add_tests(test_list)
        self.host.add_tag("UpTime", "security", 1)
        self.assertEqual({"security": 1},
                conf.hostsConf["testserver1"]["services"]["UpTime"]["tags"])

    def test_add_trap(self):
        """Test for the add_trap method on hosts"""
        data = {}
        data["command"] = "test_path_to_script"
        data["service"] = "test_serv"
        data["label"] = "test.label"
        self.host.add_trap("test_serv", "1.2.3.4.5.6.7.8.9", data)
        trapdata = conf.hostsConf["testserver1"]["snmpTrap"]["test_serv"]
        self.assertEqual(trapdata["1.2.3.4.5.6.7.8.9"]["label"], "test.label")

    def test_add_group(self):
        """Test for the add_group method on hosts"""
        self.host.add_group("/Test Group")
        self.assertTrue("/Test Group" in
                conf.hostsConf["testserver1"]["otherGroups"],
                "add_group does not work")

    def test_add_collector_service(self):
        """Test for the add_collector_service method on hosts"""
        self.host.add_collector_service(
            "TestAddCS",
            "TestAddCSFunction",
            ["fake arg 1"],
            ["GET/.1.3.6.1.2.1.1.3.0"]
        )
        hostdata = conf.hostsConf["testserver1"]
        self.assertEqual(hostdata["services"]["TestAddCS"]["type"],
                "passive", "add_collector_service does not fill the "
                "services sub-hashmap")
        self.assertEqual(hostdata["SNMPJobs"][("TestAddCS", "service")],
                { 'function': "TestAddCSFunction",
                  'params': ["fake arg 1"],
                  'vars': ["GET/.1.3.6.1.2.1.1.3.0"],
                  'reRouteFor': None },
                "add_collector_service does not fill the SNMPJobs sub-hashmap")

    def test_add_collector_service_reroute(self):
        """Test for the add_collector_service host method with rerouting"""
        host2 = Host(conf.hostsConf, "dummy", "testserver2", "192.168.1.2", "Servers")
        host2.add_collector_service(
            "TestAddCSReRoute",
            "TestAddCSReRouteFunction",
            ["fake arg 1"],
            ["GET/.1.3.6.1.2.1.1.3.0"],
            reroutefor={
                'host': "testserver1",
                "service": "TestAddCSReRoute",
            },
        )
        hdata1 = conf.hostsConf["testserver1"]
        hdata2 = conf.hostsConf["testserver2"]
        self.assertEqual(hdata1["services"]["TestAddCSReRoute"]["type"],
            "passive", "add_collector_service rerouting does not work "
            "with the services sub-hashmap")
        self.assertEqual(hdata2["SNMPJobs"][("TestAddCSReRoute", "service")],
                { 'function': "TestAddCSReRouteFunction",
                  'params': ["fake arg 1"],
                  'vars': ["GET/.1.3.6.1.2.1.1.3.0"],
                  'reRouteFor': {
                    'host': "testserver1",
                    "service": "TestAddCSReRoute"
                  },
                }, "add_collector_service rerouting does not work "
                "with the SNMPJobs sub-hashmap")

    def test_add_collector_metro(self):
        """Test for the add_collector_metro host method"""
        self.host.add_collector_metro("TestAddCS", "TestAddCSMFunction",
                            ["fake arg 1"], ["GET/.1.3.6.1.2.1.1.3.0"],
                            "GAUGE", label="TestAddCSLabel")
        self.assertEqual(
            conf.hostsConf["testserver1"]["dataSources"]["TestAddCS"],
            {'dsType':"GAUGE", 'label': "TestAddCSLabel",
             "max": None, "min": None, "rra_template": None},
            "add_collector_metro does not fill the dataSources sub-hashmap")
        self.assertEqual(
            conf.hostsConf["testserver1"]["SNMPJobs"][("TestAddCS","perfData")],
            {'function': "TestAddCSMFunction", 'params': ["fake arg 1"],
             'vars': ["GET/.1.3.6.1.2.1.1.3.0"], 'reRouteFor': None},
            "add_collector_metro does not fill the SNMPJobs sub-hashmap")

    def test_add_collector_metro_reroute(self):
        """Test for the add_collector_metro host method with rerouting"""
        host2 = Host(conf.hostsConf, "dummy", u"testserver2",
                     u"192.168.1.2", "Servers")
        host2.add_collector_metro("TestAddCSReRoute", "TestAddCSRRMFunction",
                ["fake arg 1"], ["GET/.1.3.6.1.2.1.1.3.0"],
                "GAUGE", label="TestAddCSReRouteLabel",
                reroutefor={'host': "testserver1",
                            "service": "TestAddCSReRoute"} )
        t1ds = conf.hostsConf["testserver1"]["dataSources"]
        t2snmp = conf.hostsConf["testserver2"]["SNMPJobs"]
        self.assertEqual(t1ds["TestAddCSReRoute"],
            {'dsType':"GAUGE", 'label': "TestAddCSReRouteLabel",
             "max": None, "min": None, "rra_template": None},
            "add_collector_metro rerouting does not work with the "
            "dataSources sub-hashmap")
        self.assertEqual(t2snmp[("TestAddCSReRoute","perfData")],
            {'function': "TestAddCSRRMFunction", 'params': ["fake arg 1"],
             'vars': ["GET/.1.3.6.1.2.1.1.3.0"], 'reRouteFor':
             {'host':"testserver1", "service" : "TestAddCSReRoute"}},
            "add_collector_service ReRouting does not work with the "
            "SNMPJobs sub-hashmap")

    def test_add_nagios_hdirective(self):
        """Test for the add_nagios_directive method"""
        host = Host(conf.hostsConf, "dummy", u"testserver2",
                    u"192.168.1.2", "Servers")
        host.add_nagios_directive("max_check_attempts", "5")
        nagios_hdirs = conf.hostsConf["testserver2"]["nagiosDirectives"]["host"]
        self.assertEquals(nagios_hdirs["max_check_attempts"], "5")

    def test_add_nagios_sdirective(self):
        """Test for the add_nagios_directive method"""
        host = Host(conf.hostsConf, "dummy", u"test2",
                    u"192.168.1.2", "Servers")
        host.add_nagios_directive("max_check_attempts", "5", target="services")
        nagios_sdirs = conf.hostsConf["test2"]["nagiosDirectives"]["services"]
        self.assertEquals(nagios_sdirs["max_check_attempts"], "5")

    def test_add_nagios_service_directive_INTF(self):
        """Nagios directives for tests"""
        test_list = self.testfactory.get_test("Interface", self.host.classes)
        self.host.add_tests(test_list, {"label":"eth0", "ifname":"eth0"},
                            directives={"testdirective": "testdirvalue"})
        nsd = conf.hostsConf["testserver1"]["nagiosSrvDirs"]
        self.assertEquals(nsd["Interface eth0"]["testdirective"],
                          "testdirvalue")

    def test_add_graph(self):
        self.host.add(self.host.name, "dataSources", "dummyds", {})
        graph = self.host.add_graph("testgraph", ["dummyds"], "lines", "test")
        self.assertTrue("testgraph" in
                        conf.hostsConf["testserver1"]["graphItems"])

    def test_make_cdef(self):
        cdef = self.host.make_rrd_cdef("testcdef", "1,1,+")
        self.assertTrue("testcdef" in
                        conf.hostsConf["testserver1"]["dataSources"])
        graph = self.host.add_graph("testgraph", [cdef], "lines", "test")
        print conf.hostsConf["testserver1"]["graphItems"]["testgraph"]["cdefs"]
        self.assertEqual(conf.hostsConf["testserver1"]["graphItems"][
                "testgraph"]["cdefs"], [{"name": "testcdef", "cdef": "1,1,+"}])

    def test_make_cdef_unicode(self):
        self.assertRaises(VigiConfError, self.host.make_rrd_cdef,
                          u"test éèçà", "1,1,+")

    def test_make_cdef_8bit(self):
        self.assertRaises(VigiConfError, self.host.make_rrd_cdef,
                          "test éèçà", "1,1,+")