Пример #1
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)
Пример #2
0
class ParseHostTemplate(unittest.TestCase):

    def setUp(self):
        setup_db()
        self.tmpdir = setup_tmpdir()
        os.mkdir(os.path.join(self.tmpdir, "hosttemplates"))
        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.path = [ os.path.join(self.tmpdir,
                                          "hosttemplates"), ]
        self.defaultht = open(os.path.join(self.tmpdir, "hosttemplates",
                              "default.xml"), "w")
        self.defaultht.write('<?xml version="1.0"?>\n<templates>'
                '<template name="default"></template></templates>')
        self.defaultht.close()
        self.ht = open(os.path.join(self.tmpdir, "hosttemplates",
                       "test.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_template(self):
        """Test the parsing of a basic template declaration"""
        self.ht.write("""<?xml version="1.0"?>\n<templates>"""
                      """<template name="test"></template></templates>""")
        self.ht.close()
        try:
            self.hosttemplatefactory.load_templates()
        except KeyError:
            self.fail("template is not properly parsed")
        self.assertTrue("test" in self.hosttemplatefactory.templates,
               "template is not properly parsed")

    def test_attribute(self):
        self.ht.write("""<?xml version="1.0"?>
        <templates>
            <template name="test">
                <attribute name="testattr">testattrvalue</attribute>
            </template>
        </templates>""")
        self.ht.close()
        self.hosttemplatefactory.load_templates()
        attrs = self.hosttemplatefactory.templates["test"]["attributes"]
        self.assertTrue("testattr" in attrs and
                attrs["testattr"] == "testattrvalue",
                "The \"attribute\" tag is not properly parsed")

    def test_test(self):
        self.ht.write("""<?xml version="1.0"?>
        <templates>
        <template name="test">
            <test name="TestTest"/>
        </template>
        </templates>""")
        self.ht.close()
        try:
            self.hosttemplatefactory.load_templates()
        except KeyError:
            self.fail("The \"test\" tag is not properly parsed")
        self.assertEquals("TestTest",
               self.hosttemplatefactory.templates["test"]["tests"][0]["name"],
               "The \"test\" tag is not properly parsed")

    def test_test_args(self):
        """The \"test\" tag with arguments must be properly parsed"""
        self.ht.write("""<?xml version="1.0"?>
        <templates>
        <template name="test">
            <test name="TestTest">
                <arg name="TestArg1">TestValue1</arg>
                <arg name="TestArg2">TestValue2</arg>
            </test>
        </template>
        </templates>""")
        self.ht.close()
        try:
            self.hosttemplatefactory.load_templates()
        except KeyError:
            self.fail("The \"test\" tag with arguments is not properly parsed")
        tests = self.hosttemplatefactory.templates["test"]["tests"]
        self.assertEqual(len(tests), 1)
        self.assertEqual(tests[0]["name"], "TestTest")
        self.assertTrue("TestArg1" in tests[0]["args"])
        self.assertTrue("TestArg2" in tests[0]["args"])
        self.assertEqual(tests[0]["args"]["TestArg1"], "TestValue1")
        self.assertEqual(tests[0]["args"]["TestArg2"], "TestValue2")

    def test_test_args_list(self):
        """
        Listes de valeurs comme argument d'un test dans un modèle d'hôtes
        """
        self.ht.write("""<?xml version="1.0"?>
        <templates>
        <template name="test">
            <test name="TestTest">
                <arg name="multi">
                    <item>a</item>
                    <item>b</item>
                </arg>
            </test>
        </template>
        </templates>""")
        self.ht.close()
        try:
            self.hosttemplatefactory.load_templates()
        except KeyError:
            self.fail("The \"test\" tag with arguments is not properly parsed")
        tests = self.hosttemplatefactory.templates["test"]["tests"]
        self.assertEqual(len(tests), 1)
        self.assertEqual(tests[0]["name"], "TestTest")
        self.assertTrue("multi" in tests[0]["args"])
        self.assertEqual(tests[0]["args"]["multi"], ('a', 'b'))

    def test_test_weight(self):
        self.ht.write("""<?xml version="1.0"?>
        <templates>
        <template name="testtemplate">
            <test name="TestTest" weight="42">
                <arg name="TestArg1">TestValue1</arg>
                <arg name="TestArg2">TestValue2</arg>
            </test>
        </template>
        </templates>""")
        self.ht.close()
        self.hosttemplatefactory.load_templates()
        tests = self.hosttemplatefactory.templates["testtemplate"]["tests"]
        self.assertTrue("weight" in tests[0],
                "L'attribut weight du test n'est pas chargé")
        self.assertEquals(tests[0]["weight"], 42,
                "L'attribut weight n'a pas la bonne valeur")

    def test_test_weight_default(self):
        self.ht.write("""<?xml version="1.0"?>
        <templates>
        <template name="testtemplate">
            <test name="TestTest">
                <arg name="TestArg1">TestValue1</arg>
                <arg name="TestArg2">TestValue2</arg>
            </test>
        </template>
        </templates>""")
        self.ht.close()
        self.hosttemplatefactory.load_templates()
        tests = self.hosttemplatefactory.templates["test"]["tests"]
        # weight vaut None par défaut : la valeur de weight de l'hôte
        # sur lequel on applique le template sera utilisée ensuite.
        self.assertEquals(tests[0]["weight"], None,
                "L'attribut weight n'a pas la bonne valeur par défaut")

    def test_test_weight_invalid(self):
        self.ht.write("""<?xml version="1.0"?>
        <templates>
        <template name="testtemplate">
            <test name="TestTest" weight="invalid">
                <arg name="TestArg1">TestValue1</arg>
                <arg name="TestArg2">TestValue2</arg>
            </test>
        </template>
        </templates>""")
        self.ht.close()
        self.assertRaises(ParsingError,
                          self.hosttemplatefactory.load_templates)

    def test_test_warning_weight(self):
        self.ht.write("""<?xml version="1.0"?>
        <templates>
        <template name="testtemplate">
            <test name="TestTest" weight="45" warning_weight="42">
                <arg name="TestArg1">TestValue1</arg>
                <arg name="TestArg2">TestValue2</arg>
            </test>
        </template>
        </templates>""")
        self.ht.close()
        self.hosttemplatefactory.load_templates()
        tests = self.hosttemplatefactory.templates["testtemplate"]["tests"]
        self.assertTrue("warning_weight" in tests[0],
                "L'attribut warning_weight du test n'est pas chargé")
        self.assertEquals(tests[0]["warning_weight"], 42,
                "L'attribut warning_weight n'a pas la bonne valeur")

    def test_test_warning_weight_default(self):
        self.ht.write("""<?xml version="1.0"?>
        <templates>
        <template name="testtemplate">
            <test name="TestTest">
                <arg name="TestArg1">TestValue1</arg>
                <arg name="TestArg2">TestValue2</arg>
            </test>
        </template>
        </templates>""")
        self.ht.close()
        self.hosttemplatefactory.load_templates()
        tests = self.hosttemplatefactory.templates["test"]["tests"]
        # warning_weight vaut None par défaut dans un template,
        # la valeur du weight de l'hôte sera utilisée ensuite.
        self.assertEquals(tests[0]["warning_weight"], None,
                "L'attribut warning_weight n'a pas la bonne valeur par défaut")

    def test_test_warning_weight_invalid(self):
        self.ht.write("""<?xml version="1.0"?>
        <templates>
        <template name="testtemplate">
            <test name="TestTest" warning_weight="invalid">
                <arg name="TestArg1">TestValue1</arg>
                <arg name="TestArg2">TestValue2</arg>
            </test>
        </template>
        </templates>""")
        self.ht.close()
        self.assertRaises(ParsingError,
                          self.hosttemplatefactory.load_templates)

    def test_default_service_weight_template(self):
        """Le poids default_service_weight peut être déclaré dans un modèle"""
        self.ht.write("""<?xml version="1.0"?>
        <templates>
        <template name="test">
            <default_service_weight>42</default_service_weight>
        </template>
        </templates>""")
        self.ht.close()
        try:
            self.hosttemplatefactory.load_templates()
        except KeyError:
            self.fail("le poid \"default_service_weight\" n'est pas analysé "
                      "correctement")

    def test_default_service_warning_weight_template(self):
        """Le poids default_service_warning_weight peut être déclaré dans un modèle"""
        self.ht.write("""<?xml version="1.0"?>
        <templates>
        <template name="test">
            <default_service_warning_weight>42</default_service_warning_weight>
        </template>
        </templates>""")
        self.ht.close()
        try:
            self.hosttemplatefactory.load_templates()
        except KeyError:
            self.fail("le poid \"default_service_warning_weight\" n'est pas "
                      "analysé correctement")

    def test_group(self):
        self.ht.write("""<?xml version="1.0"?>
        <templates>
        <template name="test">
            <group>/Test group</group>
        </template>
        </templates>""")
        self.ht.close()
        self.hosttemplatefactory.load_templates()
        self.assertTrue("/Test group" in
                self.hosttemplatefactory.templates["test"]["groups"],
               "The \"group\" tag is not properly parsed")

    def test_parent(self):
        self.ht.write("""<?xml version="1.0"?>
        <templates>
            <template name="test1">
            </template>
            <template name="test2">
                <parent>test1</parent>
            </template>
        </templates>""")
        self.ht.close()
        self.hosttemplatefactory.load_templates()
        self.assertTrue("test1" in
                self.hosttemplatefactory.templates["test2"]["parent"],
               "The \"parent\" tag is not properly parsed")

    def test_template_weight(self):
        self.ht.write("""<?xml version="1.0"?>
        <templates>
            <template name="test">
                <weight>42</weight>
            </template>
        </templates>""")
        self.ht.close()
        self.hosttemplatefactory.load_templates()
        testdata = self.hosttemplatefactory.templates["test"]
        self.assertTrue("weight" in testdata,
                        "L'attribut weight n'est pas chargé")
        print testdata["weight"]
        self.assertEquals(testdata["weight"], 42,
                          "L'attribut weight n'a pas la bonne valeur")

    def test_template_weight_default(self):
        self.ht.write("""<?xml version="1.0"?>
        <templates>
            <template name="test">
            </template>
        </templates>""")
        self.ht.close()
        self.hosttemplatefactory.load_templates()
        testdata = self.hosttemplatefactory.templates["test"]
        print testdata
        self.assertTrue("weight" in testdata,
                     "L'attribut weight n'est pas réglé par défaut")
        self.assertEquals(testdata["weight"], None,
                    "L'attribut weight n'a pas la bonne valeur par défaut")

    def test_template_weight_invalid(self):
        self.ht.write("""<?xml version="1.0"?>
        <templates>
            <template name="test">
                <weight>invalid</weight>
            </template>
        </templates>""")
        self.ht.close()
        self.assertRaises(ParsingError,
                          self.hosttemplatefactory.load_templates)
Пример #3
0
class HostFactoryMethods(unittest.TestCase):

    def setUp(self):
        setup_db()
        self.tmpdir = setup_tmpdir()
        self.testfactory = TestFactory(confdir=self.tmpdir)
        self.hosttemplatefactory = HostTemplateFactory(self.testfactory)

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


    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")

    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")

    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"
        )
Пример #4
0
class HostTemplates(unittest.TestCase):

    def setUp(self):
        setup_db()
        testfactory = TestFactory(confdir=settings["vigiconf"]["confdir"])
        self.hosttemplatefactory = HostTemplateFactory(testfactory)
        self.hosttemplatefactory.register(HostTemplate("default"))
        self.tpl = HostTemplate("testtpl1")
        self.hosttemplatefactory.register(self.tpl)
        conf.hostsConf = {}
        self.host = Host(conf.hostsConf, "dummy", "testserver1",
                         "192.168.1.1", "Servers")

    def tearDown(self):
        conf.hostsConf = {}
        teardown_db()


    def test_add_test_simple(self):
        """Test for the add_test method, without test arguments"""
        self.tpl.add_test("UpTime")
        self.hosttemplatefactory.apply(self.host, "testtpl1")
        self.assertTrue(conf.hostsConf["testserver1"]["services"].has_key(
                        "UpTime"), "add_test does not work without test args")

    def test_add_test_args(self):
        """Test for the add_test method, with test arguments"""
        self.tpl.add_test("Interface", {"label":"Loopback", "ifname":"lo"})
        self.hosttemplatefactory.apply(self.host, "testtpl1")
        self.assertTrue(conf.hostsConf["testserver1"]["SNMPJobs"]
                [('Interface Loopback', 'service')]["params"]
                == ["lo", "Loopback", "i", "c"],
                "add_test does not work with test args")

    def test_add_group_simple(self):
        """Test for the add_group method, with one argument only"""
        self.tpl.add_group("/Test Group")
        self.hosttemplatefactory.apply(self.host, "testtpl1")
        self.assertTrue("/Test Group" in
                conf.hostsConf["testserver1"]["otherGroups"],
                "add_group does not work with one arg")

    def test_add_group_multiple(self):
        """Test for the add_group method, with multiple arguments"""
        self.tpl.add_group("/Test Group 1", "/Test Group 2")
        self.hosttemplatefactory.apply(self.host, "testtpl1")
        self.assertTrue("/Test Group 1" in
                conf.hostsConf["testserver1"]["otherGroups"],
                "add_group does not work with multiple args")
        self.assertTrue("/Test Group 2" in
                conf.hostsConf["testserver1"]["otherGroups"],
                "add_group does not work with multiple args")

    def test_add_attribute(self):
        """Test for the add_attribute method"""
        self.tpl.add_attribute("TestAttr", "TestVal")
        self.hosttemplatefactory.apply(self.host, "testtpl1")
        self.assertEqual(conf.hostsConf["testserver1"]["TestAttr"],
                         "TestVal", "add_attribute does not work")

    def test_add_default_service_weight(self):
        """Test for the add_weight method"""
        self.tpl.add_weight("default_service_weight", 12)
        self.hosttemplatefactory.apply(self.host, "testtpl1")
        self.assertEqual(conf.hostsConf["testserver1"][
            "default_service_weight"],
            12, "add_weight does not work")

    def test_add_default_service_warning_weight(self):
        """Test for the add_weight method"""
        self.tpl.add_weight("default_service_warning_weight", 12)
        self.hosttemplatefactory.apply(self.host, "testtpl1")
        self.assertEqual(conf.hostsConf["testserver1"][
            "default_service_warning_weight"],
            12, "add_weight does not work")

    def test_inherit_redefine_test(self):
        self.tpl.add_test("Interface", {"ifname":"eth0", "label":"Label1"})
        tpl2 = HostTemplate("testtpl2")
        tpl2.add_parent("testtpl1")
        tpl2.add_test("Interface", {"ifname":"eth0", "label":"Label2"})
        self.hosttemplatefactory.register(tpl2)
        # Reload the templates
        self.hosttemplatefactory.load_templates()
        intftest = None
        for test in self.hosttemplatefactory.templates["testtpl2"]["tests"]:
            if test["name"] == "Interface":
                intftest = test
        self.assertTrue(intftest is not None,
                        "inheritance does not work with tests")
        self.assertEqual(intftest["args"]["label"], "Label2",
                "child templates cannot redefine tests from parent templates")

    def test_deepcopy(self):
        """
        Test de la copie en profondeur
        If the template data from the parent is not copied with
        copy.deepcopy(), then the child's template data will propagate back
        into the parent
        """
        self.tpl.add_attribute("TestAttr1", "TestVal")
        tpl2 = HostTemplate("testtpl2")
        tpl2.add_parent("testtpl1")
        tpl2.add_attribute("TestAttr2", "TestVal")
        self.hosttemplatefactory.register(tpl2)
        # Reload the templates
        self.hosttemplatefactory.load_templates()
        tpldata = self.hosttemplatefactory.templates["testtpl1"]
        self.failIf(tpldata["attributes"].has_key("TestAttr2"),
                "inheritence taints parent templates")

    def test_defined_templates(self):
        self.hosttemplatefactory.load_templates()
        for tpl in self.hosttemplatefactory.templates.keys():
            self.hosttemplatefactory.apply(self.host, tpl)

    def test_parent_default(self):
        tpl1 = HostTemplate("testtpl2")
        tpl1.add_parent("testtpl1")
        self.hosttemplatefactory.register(tpl1)
        self.assertTrue("default" in
                self.hosttemplatefactory.templates["testtpl1"]["parent"],
                "The \"default\" template is not automatically added as "
                "parent to other templates")


    def test_add_nagios_hdirective(self):
        """Test for the add_nagios_directive method"""
        self.tpl.add_nagios_directive("max_check_attempts", "5")
        tpldata = self.hosttemplatefactory.templates["testtpl1"]
        self.assertEquals(
                tpldata["nagiosDirectives"]["host"]["max_check_attempts"],
                "5")


    def test_nagios_hdirs_apply_on_host(self):
        self.tpl.add_nagios_directive("retry_interval", "8")
        self.hosttemplatefactory.apply(self.host, "testtpl1")
        testserver1 = conf.hostsConf['testserver1']
        nagios_hdirs = testserver1.get('nagiosDirectives')["host"]
        self.assertEquals(nagios_hdirs['retry_interval'], "8",
                          "retry_interval=8")


    def test_nagios_sdirs_apply_on_all_service(self):
        """Nagios service directives for tests"""
        self.tpl.add_nagios_directive("retry_interval", "8", target="services")
        tpldata = self.hosttemplatefactory.templates["testtpl1"]
        self.assertEquals(
                tpldata["nagiosDirectives"]["services"]["retry_interval"],
                "8")


    def test_nagios_srvdirs_apply_on_service(self):
        """Nagios directives for tests"""
        self.tpl.add_test("UpTime", directives={"testdir": "testdirvalue"})
        self.hosttemplatefactory.apply(self.host, "testtpl1")
        ndirs = conf.hostsConf["testserver1"]["nagiosSrvDirs"]
        self.assertTrue("UpTime" in ndirs)
        self.assertTrue("testdir" in ndirs["UpTime"])
        self.assertEqual(ndirs["UpTime"]["testdir"], "testdirvalue")


    def test_nonexistant_test(self):
        """
        Une exception doit être levée si on cherche à ajouter un test inexistant.
        """
        self.tpl.add_test("NonExistant")
        self.assertRaises(ParsingError, self.hosttemplatefactory.apply,
                          self.host, "testtpl1")

    def test_attributes_hierarchy_order(self):
        """
        Les attributs doivent se faire surcharger dans l'ordre d'héritage
        """
        self.tpl.add_attribute("snmpCommunity", "comm1")
        self.hosttemplatefactory.apply(self.host, "testtpl1")
        self.assertEquals(conf.hostsConf['testserver1']['snmpCommunity'],
                "comm1", "La communauté SNMP doit être celle du dernier "
                "template et pas celle d'un de ses parents")

    def test_add_test_simple_active(self):
        """Ajout d'un service actif sur un hôte avec force-passive"""
        self.host.set_attribute("force-passive", True)
        self.tpl.add_test("HTTP")
        self.hosttemplatefactory.apply(self.host, "testtpl1")
        self.assertEqual("passive",
                conf.hostsConf["testserver1"]["services"]["HTTP"]["type"])