Example #1
0
    def test_load_with_nagios_directives(self):
        """Loading some host with nagios directives."""
        # ces templates sont utilisés dans les fichiers
        for tplname in ["default", "linux"]:
            htpl = HostTemplate(tplname)
            self.hosttemplatefactory.register(htpl)
        # sans ça le no_secondary_groups.xml va pas passer
        htpl.add_group("dummy_group")
        f = HostFactory(
                os.path.join(TESTDATADIR, "xsd/hosts/ok"),
                self.hosttemplatefactory,
                self.testfactory,
            )

        # validation par XSD
        hosts = f.load(validation=True)
        testserver = hosts['example-nagios-spec.xml']
        nagios_hdirs = testserver.get('nagiosDirectives')["host"]
        print nagios_hdirs
        self.assertEquals(nagios_hdirs['max_check_attempts'], "5")
        self.assertEquals(nagios_hdirs['check_interval'], "10")
        self.assertEquals(nagios_hdirs['retry_interval'], "1")

        nagios_sdirs = testserver.get('nagiosSrvDirs')
        print nagios_sdirs
        self.assertEquals(nagios_sdirs['Interface eth0']['max_check_attempts'],
                          "5")
        self.assertEquals(nagios_sdirs['Interface eth0']['check_interval'],
                          "10")
        self.assertEquals(nagios_sdirs['Interface eth0']['retry_interval'],
                          "1")
Example #2
0
    def test_diamond_templates(self):
        """
        Attribut d'un hôte et héritage en diamant des templates (#921).

        Le template "default" définit la communauté SNMP à "public".
        Celle-ci est redéfinie dans "testtpl1" comme valant "not-public".
        Enfin, "testtpl2" est chargé après "testtpl1" et ne redéfinit
        PAS la communauté.

        Ce test vérifie que "testtpl2" n'écrase pas la communauté
        définie par "testtpl1" en chargeant à nouveau "default"
        (et donc, en réinitialisant la valeur à "public").
        """
        default = HostTemplate("default")
        default.add_attribute("snmpCommunity", "public")
        self.hosttemplatefactory.register(default)

        tpl1 = HostTemplate("testtpl1")
        tpl1.add_attribute("snmpCommunity", "not-public")
        self.hosttemplatefactory.register(tpl1)

        tpl2 = HostTemplate("testtpl2")
        self.hosttemplatefactory.register(tpl2)

        # Recharge les templates.
        self.hosttemplatefactory.load_templates()

        xmlfile = open(os.path.join(self.tmpdir, "localhost.xml"), "w")
        xmlfile.write("""
            <host name="localhost" address="127.0.0.1">
                <template>testtpl1</template>
                <template>testtpl2</template>
                <group>Linux servers</group>
            </host>
        """)
        xmlfile.close()

        f = HostFactory(
                self.tmpdir,
                self.hosttemplatefactory,
                self.testfactory,
            )

        hosts = f.load()
        print hosts
        # La communauté SNMP doit valoir "not-public"
        # (elle ne doit pas avoir été réinitialisée à "public").
        self.assertEquals(
            hosts['localhost'].get('snmpCommunity'),
            "not-public"
        )
Example #3
0
 def test_load(self):
     """Test of the loading of the conf test hosts"""
     xmlfile = open(os.path.join(self.tmpdir, "localhost.xml"), "w")
     xmlfile.write("""
         <host name="localhost" address="127.0.0.1">
             <group>Linux servers</group>
         </host>
     """)
     xmlfile.close()
     self.hosttemplatefactory.register(HostTemplate("default"))
     f = HostFactory(
             self.tmpdir,
             self.hosttemplatefactory,
             self.testfactory,
         )
     hosts = f.load()
     print hosts
     self.assertTrue(hosts.has_key('localhost'),
                     "localhost defined in conf")
Example #4
0
 def setUp(self):
     setup_db()
     testfactory = TestFactory(confdir=settings["vigiconf"]["confdir"])
     self.tmpdir = setup_tmpdir()
     self.testfactory = TestFactory(confdir=self.tmpdir)
     self.hosttemplatefactory = HostTemplateFactory(self.testfactory)
     self.hosttemplatefactory.register(HostTemplate("default"))
     self.tpl = HostTemplate("testtpl1")
     self.hosttemplatefactory.register(self.tpl)
     conf.hostsConf = {}
     self.hostfactory = HostFactory(
         self.tmpdir,
         self.hosttemplatefactory,
         self.testfactory
     )
Example #5
0
 def setUp(self):
     setup_db()
     self.tmpdir = setup_tmpdir()
     os.mkdir(os.path.join(self.tmpdir, "hosts"))
     self.old_conf_path = settings["vigiconf"]["confdir"]
     settings["vigiconf"]["confdir"] = self.tmpdir
     testfactory = TestFactory(confdir=self.tmpdir)
     self.hosttemplatefactory = HostTemplateFactory(testfactory)
     self.hosttemplatefactory.register(HostTemplate("default"))
     self.hostfactory = HostFactory(
                     os.path.join(self.tmpdir, "hosts"),
                     self.hosttemplatefactory,
                     testfactory,
                   )
     self.hostsConf = self.hostfactory.hosts
     self.host = open(os.path.join(self.tmpdir, "hosts", "host.xml"), "w")
Example #6
0
class HostAndHosttemplatesInheritance(unittest.TestCase):
    """
    Vérifie le comportement de l'héritage d'informations depuis les
    modèles d'hôtes à destination des hôtes eux-mêmes.
    """

    def setUp(self):
        setup_db()
        testfactory = TestFactory(confdir=settings["vigiconf"]["confdir"])
        self.tmpdir = setup_tmpdir()
        self.testfactory = TestFactory(confdir=self.tmpdir)
        self.hosttemplatefactory = HostTemplateFactory(self.testfactory)
        self.hosttemplatefactory.register(HostTemplate("default"))
        self.tpl = HostTemplate("testtpl1")
        self.hosttemplatefactory.register(self.tpl)
        conf.hostsConf = {}
        self.hostfactory = HostFactory(
            self.tmpdir,
            self.hosttemplatefactory,
            self.testfactory
        )

    def tearDown(self):
        teardown_db()
        shutil.rmtree(self.tmpdir)

    def test_inherit_test(self):
        """
        Héritage d'un test depuis un modèle d'hôte.

        Le template "testtpl1" ajoute le test "UpTime".
        Le template "testtpl2" hérite de "testtpl1".
        L'hôte "localhost" importe le template "testtpl2".
        Le test "UpTime" doit donc être appliqué à "localhost".
        """
        self.tpl.add_test("UpTime")
        tpl2 = HostTemplate("testtpl2")
        tpl2.add_parent("testtpl1")
        self.hosttemplatefactory.register(tpl2)
        # Reload the templates
        self.hosttemplatefactory.load_templates()

        xmlfile = open(os.path.join(self.tmpdir, "localhost.xml"), "w")
        xmlfile.write("""
            <host name="localhost" address="127.0.0.1">
                <template>testtpl2</template>
                <group>Linux servers</group>
            </host>
        """)
        xmlfile.close()
        hosts = self.hostfactory.load()
        print hosts
        self.assertTrue("UpTime" in hosts['localhost']['services'],
                        "inheritance does not work with tests")

    def test_inherit_group(self):
        """
        Héritage d'un groupe depuis un modèle d'hôte.

        Le template "testtpl1" s'ajoute au groupe "Test Group".
        Le template "testtpl2" hérite de "testtpl1".
        L'hôte "localhost" importe le template "testtpl2".
        L'hôte "localhost" devrait donc appartenir au groupe "Test Group".
        """
        self.tpl.add_group("Test Group")
        tpl2 = HostTemplate("testtpl2")
        tpl2.add_parent("testtpl1")
        self.hosttemplatefactory.register(tpl2)
        # Reload the templates
        self.hosttemplatefactory.load_templates()

        xmlfile = open(os.path.join(self.tmpdir, "localhost.xml"), "w")
        xmlfile.write("""
            <host name="localhost" address="127.0.0.1">
                <template>testtpl2</template>
            </host>
        """)
        xmlfile.close()
        hosts = self.hostfactory.load()
        print hosts
        self.assertTrue("Test Group" in
                hosts["localhost"]["otherGroups"],
                "inheritance does not work with groups")

    def test_inherit_attribute(self):
        """
        Héritage d'un attribut depuis un modèle d'hôte.

        Le template "testtpl1" ajoute l'attribut "TestAttr" valant "TestVal".
        Le template "testtpl2" hérite de "testtpl1".
        L'hôte "localhost" importe le template "testtpl2".
        L'hôte "localhost" devrait donc posséder cet attribut avec
        la valeur définie dans "testtpl1".
        """
        self.tpl.add_attribute("TestAttr", "TestVal")
        tpl2 = HostTemplate("testtpl2")
        tpl2.add_parent("testtpl1")
        self.hosttemplatefactory.register(tpl2)
        # Reload the templates
        self.hosttemplatefactory.load_templates()

        xmlfile = open(os.path.join(self.tmpdir, "localhost.xml"), "w")
        xmlfile.write("""
            <host name="localhost" address="127.0.0.1">
                <template>testtpl2</template>
                <group>Linux servers</group>
            </host>
        """)
        xmlfile.close()
        hosts = self.hostfactory.load()
        print hosts
        self.assertTrue(hosts['localhost'].has_key("TestAttr"),
                "inheritance does not work with attributes")
        self.assertEqual(hosts['localhost']["TestAttr"], "TestVal",
                "inheritance does not work with attributes")

    def test_inherit_redefine_attribute(self):
        """
        Héritage d'un attribut redéfini depuis un modèle d'hôte.

        Le template "testtpl1" ajoute l'attribut "TestAttr" valant "TestVal1".
        Le template "testtpl2" hérite de "testtpl1" et redéfinit "TestAttr"
        comme valant "TestVal2".
        L'hôte "localhost" importe le template "testtpl2".
        L'hôte "localhost" devrait donc posséder cet attribut avec
        la valeur définie dans "testtpl2".
        """
        self.tpl.add_attribute("TestAttr", "TestVal1")
        tpl2 = HostTemplate("testtpl2")
        tpl2.add_parent("testtpl1")
        self.tpl.add_attribute("TestAttr", "TestVal2")
        self.hosttemplatefactory.register(tpl2)
        # Reload the templates
        self.hosttemplatefactory.load_templates()

        xmlfile = open(os.path.join(self.tmpdir, "localhost.xml"), "w")
        xmlfile.write("""
            <host name="localhost" address="127.0.0.1">
                <template>testtpl2</template>
                <group>Linux servers</group>
            </host>
        """)
        xmlfile.close()
        hosts = self.hostfactory.load()
        print hosts
        self.assertTrue(hosts['localhost'].has_key("TestAttr"),
                "inheritance does not work with attributes")
        self.assertEqual(hosts['localhost']["TestAttr"], "TestVal2",
                "inheritance does not work with attributes")

    def test_inherit_multiple_test(self):
        """
        Héritage de tests issus de modèles d'hôtes multiples.

        L'hôte hérite d'un template qui hérite lui-même de deux templates
        définissant chacun 1 test. On s'assure que l'hôte hérite correctement
        des 2 tests.
        """
        self.tpl.add_test("Interface", {"ifname":"eth0", "label":"Label0"})
        tpl2 = HostTemplate("testtpl2")
        tpl2.add_test("Interface", {"ifname":"eth1", "label":"Label1"})
        self.hosttemplatefactory.register(tpl2)
        tpl3 = HostTemplate("testtpl3")
        tpl3.add_parent(["testtpl1", "testtpl2"])
        self.hosttemplatefactory.register(tpl3)
        # Reload the templates
        self.hosttemplatefactory.load_templates()

        xmlfile = open(os.path.join(self.tmpdir, "localhost.xml"), "w")
        xmlfile.write("""
            <host name="localhost" address="127.0.0.1">
                <template>testtpl3</template>
                <group>Linux servers</group>
            </host>
        """)
        xmlfile.close()
        hosts = self.hostfactory.load()
        print hosts

        for svc in ("Interface Label0", "Interface Label1"):
            self.assertTrue(svc in hosts['localhost']['services'],
                    "multiple inheritance does not work (%s)" % svc)
Example #7
0
class ParseHost(unittest.TestCase):

    def setUp(self):
        setup_db()
        self.tmpdir = setup_tmpdir()
        os.mkdir(os.path.join(self.tmpdir, "hosts"))
        self.old_conf_path = settings["vigiconf"]["confdir"]
        settings["vigiconf"]["confdir"] = self.tmpdir
        testfactory = TestFactory(confdir=self.tmpdir)
        self.hosttemplatefactory = HostTemplateFactory(testfactory)
        self.hosttemplatefactory.register(HostTemplate("default"))
        self.hostfactory = HostFactory(
                        os.path.join(self.tmpdir, "hosts"),
                        self.hosttemplatefactory,
                        testfactory,
                      )
        self.hostsConf = self.hostfactory.hosts
        self.host = open(os.path.join(self.tmpdir, "hosts", "host.xml"), "w")

    def tearDown(self):
        # This has been overwritten in setUp, reset it
        settings["vigiconf"]["confdir"] = self.old_conf_path
        shutil.rmtree(self.tmpdir)
        teardown_db()

    def test_host(self):
        """Test the parsing of a basic host declaration"""
        GroupLoader().load()
        self.host.write("""<?xml version="1.0"?>
        <host name="testserver1" address="192.168.1.1" ventilation="Servers">
            <group>/Servers/Linux servers</group>
        </host>""")
        self.host.close()
        self.hostfactory._loadhosts(os.path.join(self.tmpdir, "hosts",
                                    "host.xml"))
        print self.hostsConf
        self.assert_(self.hostsConf.has_key("testserver1"),
                "host is not properly parsed")
        self.assert_(self.hostsConf["testserver1"]["name"] == "testserver1",
                "host name is not properly parsed")
        self.assert_(self.hostsConf["testserver1"]["address"] == "192.168.1.1",
                "host address is not properly parsed")
        self.assert_(self.hostsConf["testserver1"]["serverGroup"] == "Servers",
                "host main group is not properly parsed")

    def test_host_passive(self):
        """Parsing d'un hôte passif"""
        GroupLoader().load()
        self.host.write("""<?xml version="1.0"?>
        <host name="testserver1" address="192.168.1.1" ventilation="Servers">
            <force-passive/>
            <group>/Servers/Linux servers</group>
        </host>""")
        self.host.close()
        self.hostfactory._loadhosts(os.path.join(self.tmpdir, "hosts",
                                    "host.xml"))
        print self.hostsConf
        self.assertTrue(self.hostsConf["testserver1"]["force-passive"],
                "L'attribut force-passive n'est pas correctement parsé")

    def test_template(self):
        self.host.write("""<?xml version="1.0"?>
        <host name="testserver1" address="192.168.1.1" ventilation="Servers">
            <template>linux</template>
        </host>""")
        self.host.close()
        htpl = HostTemplate("linux")
        htpl.add_group("Linux servers")
        self.hosttemplatefactory.register(htpl)
        self.hostfactory._loadhosts(os.path.join(self.tmpdir, "hosts",
                                    "host.xml"))
        print self.hostsConf
        self.assertTrue("Linux servers" in
                        self.hostsConf["testserver1"]["otherGroups"],
                        "The \"template\" tag is not properly parsed")

    def test_template_passive(self):
        self.host.write("""<?xml version="1.0"?>
        <host name="testserver1" address="192.168.1.1" ventilation="Servers">
            <force-passive/>
            <template>linux</template>
        </host>""")
        self.host.close()
        htpl = HostTemplate("linux")
        htpl.add_group("Linux servers")
        self.hosttemplatefactory.register(htpl)
        self.hostfactory._loadhosts(os.path.join(self.tmpdir, "hosts",
                                    "host.xml"))
        print self.hostsConf
        self.assertTrue(self.hostsConf["testserver1"]["force-passive"],
                "L'attribut force-passive n'est pas conservé après "
                "application d'un template")

    def test_attribute(self):
        self.host.write("""<?xml version="1.0"?>
        <host name="testserver1" address="192.168.1.1" ventilation="Servers">
            <attribute name="cpulist">2</attribute>
            <group>/Servers</group>
        </host>""")
        self.host.close()
        self.hostfactory._loadhosts(os.path.join(self.tmpdir, "hosts",
                                    "host.xml"))
        print self.hostsConf
        self.assert_(self.hostsConf["testserver1"].has_key("cpulist") and
                     self.hostsConf["testserver1"]["cpulist"] == "2",
                     "The \"attribute\" tag is not properly parsed")

    def test_tag_host(self):
        self.host.write("""<?xml version="1.0"?>
        <host name="testserver1" address="192.168.1.1" ventilation="Servers">
            <tag service="Host" name="important">2</tag>
            <group>/Servers</group>
        </host>""")
        self.host.close()
        self.hostfactory._loadhosts(os.path.join(self.tmpdir, "hosts",
                                    "host.xml"))
        print self.hostsConf
        self.assert_("tags" in self.hostsConf["testserver1"] and
               "important" in self.hostsConf["testserver1"]["tags"] and
                self.hostsConf["testserver1"]["tags"]["important"] == "2",
                "The \"tag\" tag for hosts is not properly parsed")

    def test_nagios_directive_host(self):
        self.host.write("""<?xml version="1.0"?>
        <host name="testserver1" address="192.168.1.1" ventilation="Servers">
            <nagios>
                <directive name="obsess_over_host">1</directive>
            </nagios>
            <test name="UpTime"/>
            <group>/Servers</group>
        </host>""")
        self.host.close()
        self.hostfactory._loadhosts(os.path.join(self.tmpdir, "hosts",
                                    "host.xml"))
        print self.hostsConf
        self.assert_("host" in self.hostsConf["testserver1"]["nagiosDirectives"] and
               "obsess_over_host" in self.hostsConf["testserver1"]["nagiosDirectives"]["host"] and
                self.hostsConf["testserver1"]["nagiosDirectives"]["host"]["obsess_over_host"] == "1",
                "The \"directive\" for hosts is not properly parsed")

    def test_nagios_directive_service(self):
        self.host.write("""<?xml version="1.0"?>
        <host name="testserver1" address="192.168.1.1" ventilation="Servers">
            <nagios>
                <directive target="services" name="obsess_over_service">1</directive>
            </nagios>
            <test name="UpTime"/>
            <group>/Servers</group>
        </host>""")
        self.host.close()
        self.hostfactory._loadhosts(os.path.join(self.tmpdir, "hosts",
                                    "host.xml"))
        print self.hostsConf
        self.assert_("host" in self.hostsConf["testserver1"]["nagiosDirectives"] and
               "obsess_over_service" in self.hostsConf["testserver1"]["nagiosDirectives"]["services"] and
                self.hostsConf["testserver1"]["nagiosDirectives"]["services"]["obsess_over_service"] == "1",
                "The \"directive\" for services is not properly parsed")

    def test_tag_service(self):
        self.host.write("""<?xml version="1.0"?>
        <host name="testserver1" address="192.168.1.1" ventilation="Servers">
            <test name="UpTime"/>
            <tag service="UpTime" name="important">2</tag>
            <group>/Servers</group>
        </host>""")
        self.host.close()
        self.hostfactory._loadhosts(os.path.join(self.tmpdir, "hosts",
                                    "host.xml"))
        self.assertTrue("tags" in
                self.hostsConf["testserver1"]["services"]["UpTime"]
                and "important" in
                self.hostsConf["testserver1"]["services"]["UpTime"]["tags"]
                and self.hostsConf["testserver1"]["services"]
                ["UpTime"]["tags"]["important"] == "2",
               "The \"tag\" tag for services is not properly parsed")

    def test_group(self):
        GroupLoader().load()
        self.host.write("""<?xml version="1.0"?>
        <host name="testserver1" address="192.168.1.1" ventilation="Servers">
            <group>Linux servers</group>
        </host>""")
        self.host.close()
        self.hostfactory._loadhosts(os.path.join(self.tmpdir, "hosts",
                                    "host.xml"))
        print self.hostsConf
        self.assertTrue("Linux servers" in
                self.hostsConf["testserver1"]["otherGroups"],
                "The \"group\" tag is not properly parsed")

    def test_group_multiple(self):
        GroupLoader().load()
        self.host.write("""<?xml version="1.0"?>
        <host name="testserver1" address="192.168.1.1" ventilation="Servers">
            <group>Linux servers</group>
            <group>AIX servers</group>
        </host>""")
        self.host.close()
        self.hostfactory._loadhosts(os.path.join(self.tmpdir, "hosts",
                                    "host.xml"))
        print self.hostsConf
        self.assertTrue("Linux servers" in
                self.hostsConf["testserver1"]["otherGroups"]
                and "AIX servers" in
                self.hostsConf["testserver1"]["otherGroups"],
                "The \"group\" tag does not handle multiple values")

    def test_test(self):
        self.host.write("""<?xml version="1.0"?>
        <host name="testserver1" address="192.168.1.1" ventilation="Servers">
            <test name="Interface">
                <arg name="label">eth0</arg>
                <arg name="ifname">eth0</arg>
            </test>
            <group>/Servers</group>
        </host>""")
        self.host.close()
        self.hostfactory._loadhosts(os.path.join(self.tmpdir, "hosts",
                                    "host.xml"))
        print self.hostsConf
        self.assertTrue(('Interface eth0', 'service') in
                self.hostsConf["testserver1"]["SNMPJobs"],
                "The \"test\" tag is not properly parsed")

    def test_default_test_weights(self):
        """
        La valeur par défaut du poids et du poids WARNING des services.
        """
        self.host.write("""<?xml version="1.0"?>
        <host name="testserver1" address="192.168.1.1" ventilation="Servers">
            <test name="UpTime"/>
            <group>Servers</group>
        </host>""")
        self.host.close()
        self.hostfactory._loadhosts(os.path.join(self.tmpdir, "hosts",
                                    "host.xml"))
        print self.hostsConf
        self.assertEquals(
                self.hostsConf["testserver1"]["services"] \
                              ["UpTime"]["weight"],
                None, "L'attribut weight n'a pas la bonne valeur")
        self.assertEquals(
                self.hostsConf["testserver1"]["services"] \
                              ["UpTime"]["warning_weight"],
                None, "L'attribut warning_weight n'a pas la bonne valeur")

    def test_test_weight_override (self):
        """
        La valeur par défaut du poids des services peut être surchargée.
        """
        self.host.write("""<?xml version="1.0"?>
        <host name="testserver1" address="192.168.1.1" ventilation="Servers">
            <test name="UpTime" weight="42" />
            <group>Servers</group>
        </host>""")
        self.host.close()
        self.hostfactory._loadhosts(os.path.join(self.tmpdir, "hosts",
                                    "host.xml"))
        print self.hostsConf
        self.assertEquals(
                self.hostsConf["testserver1"]["services"] \
                              ["UpTime"]["weight"],
                42, "L'attribut weight n'a pas la bonne valeur")
        self.assertEquals(
                self.hostsConf["testserver1"]["services"] \
                              ["UpTime"]["warning_weight"],
                None, "L'attribut warning_weight n'a pas la bonne valeur")

    def test_test_warning_weight_override(self):
        """Poids WARNING par défaut des services peut être surchargée."""
        self.host.write("""<?xml version="1.0"?>
        <host name="testserver1" address="192.168.1.1" ventilation="Servers">
            <test name="UpTime" weight="42" warning_weight="12" />
            <group>Servers</group>
        </host>""")
        self.host.close()
        self.hostfactory._loadhosts(os.path.join(self.tmpdir, "hosts",
                                    "host.xml"))
        print self.hostsConf
        self.assertEquals(
                self.hostsConf["testserver1"]["services"] \
                              ["UpTime"]["warning_weight"],
                12, "L'attribut weight n'a pas la bonne valeur")

    def test_test_weight_invalid(self):
        """Valeur incorrecte du poids par défaut des services."""
        self.host.write("""<?xml version="1.0"?>
        <host name="testserver1" ventilation="Servers">
            <test name="UpTime" weight="invalid" />
            <group>/Servers</group>
        </host>""")
        self.host.close()
        filepath = os.path.join(self.tmpdir, "hosts", "host.xml")
        self.assertRaises(ParsingError, self.hostfactory._loadhosts, filepath)

    def test_test_warning_weight_invalid(self):
        """Valeur incorrecte du poids WARNING par défaut des services."""
        self.host.write("""<?xml version="1.0"?>
        <host name="testserver1" ventilation="Servers">
            <test name="UpTime" warning_weight="invalid" />
            <group>/Servers</group>
        </host>""")
        self.host.close()
        filepath = os.path.join(self.tmpdir, "hosts", "host.xml")
        self.assertRaises(ParsingError, self.hostfactory._loadhosts, filepath)

    def test_test_nonexistant(self):
        """
        Une exception doit être levée si on cherche à ajouter un test inexistant.
        """
        self.host.write("""<?xml version="1.0"?>
        <host name="testserver1" address="192.168.1.1">
            <test name="NonExistant"/>
            <group>/Servers</group>
        </host>""")
        self.host.close()
        filepath = os.path.join(self.tmpdir, "hosts", "host.xml")
        self.assertRaises(ParsingError, self.hostfactory._loadhosts, filepath)

    def test_ventilation_explicit_server(self):
        """Ventilation en utilisant un groupe explicitement nommé."""
        GroupLoader().load()
        self.host.write("""<?xml version="1.0"?>
        <host name="foo" address="127.0.0.1" ventilation="Vigilo">
            <test name="Interface" weight="42" warning_weight="41">
                <arg name="label">eth0</arg>
                <arg name="ifname">eth0</arg>
            </test>
            <group>/Servers/Linux servers</group>
        </host>
        """)
        self.host.close()
        self.hostfactory._loadhosts(os.path.join(self.tmpdir, "hosts",
                                    "host.xml"))
        print self.hostsConf
        # L'attribut ventilation a été donné explicitement.
        self.assertEqual(self.hostsConf['foo']['serverGroup'], 'Vigilo')

    def test_missing_group_association(self):
        """Hôte associé à aucun groupe opérationnel."""
        self.host.write("""<?xml version="1.0"?>
        <host name="foo" address="127.0.0.1" ventilation="Vigilo">
            <test name="Interface" weight="41" warning_weight="42">
                <arg name="label">eth0</arg>
                <arg name="ifname">eth0</arg>
            </test>
        </host>
        """)
        self.host.close()
        # Un hôte doit toujours être associé à au moins un <group>.
        # La vérification ne peut pas être faite au niveau du schéma XSD
        # car on perdrait alors la possibilité d'utiliser un ordre quelconque
        # pour les balises de définition d'un hôte.
        self.assertRaises(ParsingError, self.hostfactory._loadhosts,
            os.path.join(self.tmpdir, "hosts", "host.xml"))

    def test_test_missing_args(self):
        """Ajout d'un test auquel il manque des arguments sur un hôte."""
        # Le test "TCP" nécessite normalement un argument "port".
        self.host.write("""<?xml version="1.0"?>
        <host name="testserver1" address="192.168.1.1" ventilation="Servers">
            <test name="TCP"/>
            <group>/Servers</group>
        </host>""")
        self.host.close()
        # Une exception TypeError indiquant qu'il n'y pas assez d'arguments
        # doit être levée.
        self.assertRaises(VigiConfError,
            self.hostfactory._loadhosts,
            os.path.join(self.tmpdir, "hosts", "host.xml")
        )

    def test_test_additional_args(self):
        """Ajout d'un test avec trop d'arguments sur un hôte."""
        # Le test "TCP" n'accepte pas d'argument "unknown".
        self.host.write("""<?xml version="1.0"?>
        <host name="testserver1" address="192.168.1.1" ventilation="Servers">
            <test name="TCP">
                <arg name="port">1234</arg>
                <arg name="unknown_arg"> ... </arg>
            </test>
            <group>/Servers</group>
        </host>""")
        self.host.close()
        # Une exception TypeError indiquant qu'un paramètre inconnu
        # a été passé doit être levée.
        self.assertRaises(VigiConfError,
            self.hostfactory._loadhosts,
            os.path.join(self.tmpdir, "hosts", "host.xml")
        )

    def test_host_weight(self):
        GroupLoader().load()
        self.host.write("""<?xml version="1.0"?>
        <host name="testserver1">
            <weight>42</weight>
            <group>/Servers/Linux servers</group>
        </host>""")
        self.host.close()
        self.hostfactory._loadhosts(os.path.join(self.tmpdir, "hosts",
                                    "host.xml"))
        print self.hostsConf
        self.assert_("weight" in self.hostsConf["testserver1"],
                     "L'attribut weight n'est pas chargé")
        self.assertEquals(self.hostsConf["testserver1"]["weight"], 42,
                          "L'attribut weight n'a pas la bonne valeur")

    def test_host_weight_default(self):
        GroupLoader().load()
        self.host.write("""<?xml version="1.0"?>
        <host name="testserver1">
            <group>/Servers/Linux servers</group>
        </host>""")
        self.host.close()
        self.hostfactory._loadhosts(os.path.join(self.tmpdir, "hosts",
                                    "host.xml"))
        print self.hostsConf
        self.assert_("weight" in self.hostsConf["testserver1"],
                     "L'attribut weight n'est pas réglé par défaut")
        self.assertEquals(self.hostsConf["testserver1"]["weight"], 1,
                          "L'attribut weight n'a pas la bonne valeur "
                          "par défaut")

    def test_host_weight_invalid(self):
        GroupLoader().load()
        self.host.write("""<?xml version="1.0"?>
        <host name="testserver1">
            <weight>invalid</weight>
            <group>/Servers/Linux servers</group>
        </host>""")
        self.host.close()
        filepath = os.path.join(self.tmpdir, "hosts", "host.xml")
        self.assertRaises(ParsingError, self.hostfactory._loadhosts, filepath)

    def test_class_after_template(self):
        """Les classes doivent pouvoir être déclarées après les templates"""
        self.host.write("""<?xml version="1.0"?>
        <host name="testserver1" address="192.168.1.1" ventilation="Servers">
            <template>linux</template>
            <class>linux</class>
        </host>""")
        self.host.close()
        htpl = HostTemplate("linux")
        htpl.add_group("Linux servers")
        htpl.add_test("RAID")
        self.hosttemplatefactory.register(htpl)
        try:
            self.hostfactory._loadhosts(os.path.join(self.tmpdir, "hosts",
                                        "host.xml"))
        except ParsingError, e:
            print e
            self.fail("L'ordre des balises class et template est important")
        self.assertTrue("RAID" in self.hostsConf["testserver1"]["services"],
                        "L'ordre des balises class et template est important")