
from node_builder_test import NodeBuilderTest, StupidModel
from elisa.core.tests.elisa_test_case import ElisaTestCase

from elisa.core import common

from elisa.extern.coherence.et import parse_xml

import os

class XdgEntryBuilderTest(NodeBuilderTest, ElisaTestCase):
    component_path = 'xmlmenu:xdg_entry_builder'
    entry_identifiers = ['xdg_desktop_path']
    data_path = 'data'
    file_name = 'xdg_test.xml'


    def test_get_entries(self):
        data_path = os.path.join(self.directory, self.data_path)
        xml_file = os.path.join(data_path, self.file_name)
        
        data = open(xml_file).read()
        data = data.replace('__PATH__', data_path)
        xml = parse_xml(data)
        root = xml.getroot()

        def done_callback(data):
            done_list = ['pidgin' , 'thunderbird' , 'firefox']
            # It should NOT read the directory-desktop-file
            self.assertEquals(len(data), 3)
            for item in data:
                text = item.text.lower()
                is_in = False
                # not nice way of testing it without knowing the order
                for i in done_list:
                    if i in text:
                        is_in = True
                        break

                if not is_in:
                    self.fail()
        
        test_entry = root.find('TestEntry')
        test_model = StupidModel()
        dfr = self.component.build_menu_entry(test_model, test_entry)
        dfr.addCallback(done_callback)
        return dfr

    def test_missing_path(self):

        data = """
            <MenuEntry type='xdg_desktop_path'>
            </MenuEntry>
            """
        xml = parse_xml(data)
        root = xml.getroot()

        def done_callback(data, test_model):
            self.assertEquals(data, [])
            self.assertEquals(test_model.children, [])
        
        test_model = StupidModel()
        test_model.children = []
        dfr = self.component.build_menu_entry(test_model, root)
        dfr.addCallback(done_callback, test_model)

    def test_wrong_path(self):

        data = """
            <MenuEntry type='xdg_desktop_path'>
            <Path>./file://*gradetz</Path>
            </MenuEntry>
            """
        xml = parse_xml(data)
        root = xml.getroot()

        def done_callback(data, test_model):
            self.assertEquals(data, [])
            self.assertEquals(test_model.children, [])
        
        test_model = StupidModel()
        test_model.children = []
        dfr = self.component.build_menu_entry(test_model, root)
        dfr.addCallback(done_callback, test_model)
