Пример #1
0
    def testLoad(self):
        dirlist = [
            u"../plugins/testempty1", u"../plugins/testempty2",
            u"../plugins/testempty2"
        ]
        loader = PluginsLoader(Application)
        loader.load(dirlist)

        self.assertEqual(len(loader), 2)
        self.assertEqual(loader[u"TestEmpty1"].name, u"TestEmpty1")
        self.assertEqual(loader[u"TestEmpty1"].version, u"0.1")
        self.assertEqual(loader[u"TestEmpty1"].description,
                         u"This plugin is empty")
        self.assertEqual(loader[u"TestEmpty1"].application, Application)

        self.assertEqual(loader[u"TestEmpty2"].name, u"TestEmpty2")
        self.assertEqual(loader[u"TestEmpty2"].version, u"0.1")
        self.assertEqual(loader[u"TestEmpty2"].description,
                         u"This plugin is empty")

        # Проверим, как работает итерация
        for plugin in loader:
            self.assertTrue(plugin == loader[u"TestEmpty1"]
                            or plugin == loader[u"TestEmpty2"])

        loader.clear()
        self.assertEqual(len(loader), 0)
Пример #2
0
    def testLoad(self):
        dirlist = [u"../test/plugins/testempty1",
                   u"../test/plugins/testempty2",
                   u"../test/plugins/testempty2"]
        loader = PluginsLoader(Application)
        loader.load(dirlist)

        self.assertEqual(len(loader), 2)
        self.assertEqual(loader[u"TestEmpty1"].name, u"TestEmpty1")
        self.assertEqual(loader[u"TestEmpty1"].version, u"0.1")
        self.assertEqual(loader[u"TestEmpty1"].description,
                         u"This plugin is empty")
        self.assertEqual(loader[u"TestEmpty1"].application, Application)

        self.assertEqual(loader[u"TestEmpty2"].name, u"TestEmpty2")
        self.assertEqual(loader[u"TestEmpty2"].version, u"0.1")
        self.assertEqual(loader[u"TestEmpty2"].description,
                         u"This plugin is empty")

        # Проверим, как работает итерация
        for plugin in loader:
            self.assertTrue(plugin == loader[u"TestEmpty1"] or
                            plugin == loader[u"TestEmpty2"])

        loader.clear()
        self.assertEqual(len(loader), 0)
Пример #3
0
class PluginNameTest (unittest.TestCase):
    """Тесты плагина PluginName"""
    def setUp (self):
        self.__createWiki()

        dirlist = [u"../plugins/pluginname"]

        self.loader = PluginsLoader(Application)
        self.loader.load (dirlist)


    def tearDown (self):
        removeDir (self.path)
        self.loader.clear()


    def __createWiki (self):
        # Здесь будет создаваться вики
        self.path = u"../test/testwiki"
        removeDir (self.path)

        self.rootwiki = WikiDocument.create (self.path)

        WikiPageFactory().create (self.rootwiki, u"Страница 1", [])
        self.testPage = self.rootwiki[u"Страница 1"]


    def testPluginLoad (self):
        self.assertEqual (len (self.loader), 1)
Пример #4
0
class TemplateTest (unittest.TestCase):
    """Тесты плагина Template"""
    def setUp (self):
        self.__createWiki()

        dirlist = [u"../plugins/template"]

        self.loader = PluginsLoader(Application)
        self.loader.load (dirlist)


    def tearDown (self):
        removeDir (self.path)
        self.loader.clear()


    def __createWiki (self):
        # Здесь будет создаваться вики
        self.path = mkdtemp (prefix=u'Абырвалг абыр')

        self.wikiroot = WikiDocument.create (self.path)

        WikiPageFactory().create (self.wikiroot, u"Страница 1", [])
        self.testPage = self.wikiroot[u"Страница 1"]


    def testPluginLoad (self):
        self.assertEqual (len (self.loader), 1)
Пример #5
0
class PluginNameTest(unittest.TestCase):
    """Тесты плагина PluginName"""
    def setUp(self):
        self.__createWiki()

        dirlist = [u"../plugins/pluginname"]

        self.loader = PluginsLoader(Application)
        self.loader.load(dirlist)

    def tearDown(self):
        removeDir(self.path)
        self.loader.clear()

    def __createWiki(self):
        # Здесь будет создаваться вики
        self.path = u"../test/testwiki"
        removeDir(self.path)

        self.rootwiki = WikiDocument.create(self.path)

        WikiPageFactory().create(self.rootwiki, u"Страница 1", [])
        self.testPage = self.rootwiki[u"Страница 1"]

    def testPluginLoad(self):
        self.assertEqual(len(self.loader), 1)
Пример #6
0
class SnippetsVarDialogTest(unittest.TestCase, BaseOutWikerGUIMixin):
    def setUp(self):
        self.initApplication()
        mainWnd = self.application.mainWindow
        plugins_dir = ["plugins/snippets"]

        self.loader = PluginsLoader(self.application)
        self.loader.load(plugins_dir)

        from snippets.gui.variablesdialog import VariablesDialog
        self._dialog = VariablesDialog(mainWnd)

    def tearDown(self):
        self._dialog.Destroy()
        self.loader.clear()
        self.destroyApplication()

    def test_empty(self):
        variables = self._dialog.getVarDict()
        self.assertEqual(variables, {})

    def test_single_empty(self):
        self._dialog.addStringVariable('test')
        variables = self._dialog.getVarDict()
        self.assertEqual(variables, {'test': ''})

    def test_single(self):
        self._dialog.addStringVariable('test')
        self._dialog.setStringVariable('test', 'Проверка')

        variables = self._dialog.getVarDict()
        self.assertEqual(variables, {'test': 'Проверка'})

    def test_two_items(self):
        self._dialog.addStringVariable('test_1')
        self._dialog.addStringVariable('test_2')

        self._dialog.setStringVariable('test_1', 'Проверка_1')
        self._dialog.setStringVariable('test_2', 'Проверка_2')

        variables = self._dialog.getVarDict()
        self.assertEqual(variables, {'test_1': 'Проверка_1',
                                     'test_2': 'Проверка_2'})

    def test_no_item(self):
        self.assertRaises(KeyError,
                          self._dialog.setStringVariable,
                          'test',
                          'test')
Пример #7
0
class SnippetsVarDialogTest(BaseMainWndTest):
    def setUp(self):
        BaseMainWndTest.setUp(self)
        mainWnd = Application.mainWindow
        plugins_dir = [u"../plugins/snippets"]

        self.loader = PluginsLoader(Application)
        self.loader.load(plugins_dir)

        from snippets.gui.variablesdialog import VariablesDialog
        self._dialog = VariablesDialog(mainWnd)

    def tearDown(self):
        self._dialog.Destroy()
        self.loader.clear()
        BaseMainWndTest.tearDown(self)

    def test_empty(self):
        variables = self._dialog.getVarDict()
        self.assertEqual(variables, {})

    def test_single_empty(self):
        self._dialog.addStringVariable(u'test')
        variables = self._dialog.getVarDict()
        self.assertEqual(variables, {u'test': u''})

    def test_single(self):
        self._dialog.addStringVariable(u'test')
        self._dialog.setStringVariable(u'test', u'Проверка')

        variables = self._dialog.getVarDict()
        self.assertEqual(variables, {u'test': u'Проверка'})

    def test_two_items(self):
        self._dialog.addStringVariable(u'test_1')
        self._dialog.addStringVariable(u'test_2')

        self._dialog.setStringVariable(u'test_1', u'Проверка_1')
        self._dialog.setStringVariable(u'test_2', u'Проверка_2')

        variables = self._dialog.getVarDict()
        self.assertEqual(variables, {u'test_1': u'Проверка_1',
                                     u'test_2': u'Проверка_2'})

    def test_no_item(self):
        self.assertRaises(KeyError,
                          self._dialog.setStringVariable,
                          u'test',
                          u'test')
Пример #8
0
class SnippetsVarDialogTest(BaseMainWndTest):
    def setUp(self):
        BaseMainWndTest.setUp(self)
        mainWnd = Application.mainWindow
        plugins_dir = [u"../plugins/snippets"]

        self.loader = PluginsLoader(Application)
        self.loader.load(plugins_dir)

        from snippets.gui.variablesdialog import VariablesDialog
        self._dialog = VariablesDialog(mainWnd)

    def tearDown(self):
        self._dialog.Destroy()
        self.loader.clear()
        BaseMainWndTest.tearDown(self)

    def test_empty(self):
        variables = self._dialog.getVarDict()
        self.assertEqual(variables, {})

    def test_single_empty(self):
        self._dialog.addStringVariable(u'test')
        variables = self._dialog.getVarDict()
        self.assertEqual(variables, {u'test': u''})

    def test_single(self):
        self._dialog.addStringVariable(u'test')
        self._dialog.setStringVariable(u'test', u'Проверка')

        variables = self._dialog.getVarDict()
        self.assertEqual(variables, {u'test': u'Проверка'})

    def test_two_items(self):
        self._dialog.addStringVariable(u'test_1')
        self._dialog.addStringVariable(u'test_2')

        self._dialog.setStringVariable(u'test_1', u'Проверка_1')
        self._dialog.setStringVariable(u'test_2', u'Проверка_2')

        variables = self._dialog.getVarDict()
        self.assertEqual(variables, {
            u'test_1': u'Проверка_1',
            u'test_2': u'Проверка_2'
        })

    def test_no_item(self):
        self.assertRaises(KeyError, self._dialog.setStringVariable, u'test',
                          u'test')
Пример #9
0
class SnippetsVarDialogTest(unittest.TestCase, BaseOutWikerGUIMixin):
    def setUp(self):
        self.initApplication()
        mainWnd = self.application.mainWindow
        plugins_dir = ["../plugins/snippets"]

        self.loader = PluginsLoader(self.application)
        self.loader.load(plugins_dir)

        from snippets.gui.variablesdialog import VariablesDialog
        self._dialog = VariablesDialog(mainWnd)

    def tearDown(self):
        self._dialog.Destroy()
        self.loader.clear()
        self.destroyApplication()

    def test_empty(self):
        variables = self._dialog.getVarDict()
        self.assertEqual(variables, {})

    def test_single_empty(self):
        self._dialog.addStringVariable('test')
        variables = self._dialog.getVarDict()
        self.assertEqual(variables, {'test': ''})

    def test_single(self):
        self._dialog.addStringVariable('test')
        self._dialog.setStringVariable('test', 'Проверка')

        variables = self._dialog.getVarDict()
        self.assertEqual(variables, {'test': 'Проверка'})

    def test_two_items(self):
        self._dialog.addStringVariable('test_1')
        self._dialog.addStringVariable('test_2')

        self._dialog.setStringVariable('test_1', 'Проверка_1')
        self._dialog.setStringVariable('test_2', 'Проверка_2')

        variables = self._dialog.getVarDict()
        self.assertEqual(variables, {'test_1': 'Проверка_1',
                                     'test_2': 'Проверка_2'})

    def test_no_item(self):
        self.assertRaises(KeyError,
                          self._dialog.setStringVariable,
                          'test',
                          'test')
Пример #10
0
class LangListTest(unittest.TestCase, BaseOutWikerGUIMixin):
    def setUp(self):
        self.initApplication()

        dirlist = ["../plugins/source"]

        self.loader = PluginsLoader(self.application)
        self.loader.load(dirlist)

        from source.langlist import LangList
        self._langlist = LangList()

    def tearDown(self):
        self.loader.clear()
        self.destroyApplication()

    def test_all(self):
        self.assertIn('Ada', self._langlist.allNames())
        self.assertIn('HTML + Angular2', self._langlist.allNames())
        self.assertIn('1S', self._langlist.allNames())

    def test_getAllDesignations(self):
        self.assertEqual(self._langlist.getAllDesignations('Ada'),
                         ('ada', 'ada95', 'ada2005'))
        self.assertEqual(self._langlist.getAllDesignations('ANTLR'),
                         ('antlr',))

    def test_getAllDesignations_invalid(self):
        self.assertIsNone(self._langlist.getAllDesignations('adsfa asdfadf'))

    def test_getDesignation(self):
        self.assertEqual(self._langlist.getDesignation('Ada'), 'ada')
        self.assertEqual(self._langlist.getDesignation('ANTLR'), 'antlr')
        self.assertEqual(self._langlist.getDesignation('C++'), 'cpp')

    def test_getDesignation_invalid(self):
        self.assertIsNone(self._langlist.getDesignation('adfasdfaf'))

    def test_getLangName(self):
        self.assertEqual(self._langlist.getLangName('ada'), 'Ada')
        self.assertEqual(self._langlist.getLangName('ada2005'), 'Ada')
        self.assertEqual(self._langlist.getLangName('html+spitfire'),
                         'HTML+Cheetah')

    def test_getLangName_invalid(self):
        self.assertIsNone(self._langlist.getLangName('asdfadsfads'))
Пример #11
0
class LangListTest(unittest.TestCase, BaseOutWikerGUIMixin):
    def setUp(self):
        self.initApplication()

        dirlist = ["plugins/source"]

        self.loader = PluginsLoader(self.application)
        self.loader.load(dirlist)

        from source.langlist import LangList
        self._langlist = LangList()

    def tearDown(self):
        self.loader.clear()
        self.destroyApplication()

    def test_all(self):
        self.assertIn('Ada', self._langlist.allNames())
        self.assertIn('HTML + Angular2', self._langlist.allNames())
        self.assertIn('1S', self._langlist.allNames())

    def test_getAllDesignations(self):
        self.assertEqual(self._langlist.getAllDesignations('Ada'),
                         ('ada', 'ada95', 'ada2005'))
        self.assertEqual(self._langlist.getAllDesignations('ANTLR'),
                         ('antlr', ))

    def test_getAllDesignations_invalid(self):
        self.assertIsNone(self._langlist.getAllDesignations('adsfa asdfadf'))

    def test_getDesignation(self):
        self.assertEqual(self._langlist.getDesignation('Ada'), 'ada')
        self.assertEqual(self._langlist.getDesignation('ANTLR'), 'antlr')
        self.assertEqual(self._langlist.getDesignation('C++'), 'cpp')

    def test_getDesignation_invalid(self):
        self.assertIsNone(self._langlist.getDesignation('adfasdfaf'))

    def test_getLangName(self):
        self.assertEqual(self._langlist.getLangName('ada'), 'Ada')
        self.assertEqual(self._langlist.getLangName('ada2005'), 'Ada')
        self.assertEqual(self._langlist.getLangName('html+spitfire'),
                         'HTML+Cheetah')

    def test_getLangName_invalid(self):
        self.assertIsNone(self._langlist.getLangName('asdfadsfads'))
Пример #12
0
class SnippetsVarPanelTest(BaseMainWndTest):
    def setUp(self):
        BaseMainWndTest.setUp(self)
        mainWnd = Application.mainWindow
        plugins_dir = [u"../plugins/snippets"]

        self.loader = PluginsLoader(Application)
        self.loader.load(plugins_dir)

        from snippets.gui.variablesdialog import VaraiblesPanel

        self._panel = VaraiblesPanel(mainWnd)

    def tearDown(self):
        self.loader.clear()
        BaseMainWndTest.tearDown(self)

    def test_empty(self):
        variables = self._panel.getVarDict()
        self.assertEqual(variables, {})

    def test_single_empty(self):
        self._panel.addStringVariable(u"test")
        variables = self._panel.getVarDict()
        self.assertEqual(variables, {u"test": u""})

    def test_single(self):
        self._panel.addStringVariable(u"test")
        self._panel.setVarString(u"test", u"Проверка")

        variables = self._panel.getVarDict()
        self.assertEqual(variables, {u"test": u"Проверка"})

    def test_two_items(self):
        self._panel.addStringVariable(u"test_1")
        self._panel.addStringVariable(u"test_2")

        self._panel.setVarString(u"test_1", u"Проверка_1")
        self._panel.setVarString(u"test_2", u"Проверка_2")

        variables = self._panel.getVarDict()
        self.assertEqual(variables, {u"test_1": u"Проверка_1", u"test_2": u"Проверка_2"})

    def test_no_item(self):
        self.assertRaises(KeyError, self._panel.setVarString, u"test", u"test")
Пример #13
0
class MarkdownPolyactionsTest(BaseEditorPolyactionsTest):
    """Test polyactions for Markdown pages"""
    def setUp(self):
        dirlist = [u"../plugins/markdown"]
        self.loader = PluginsLoader(Application)
        self.loader.load(dirlist)
        super(MarkdownPolyactionsTest, self).setUp()

    def tearDown(self):
        self.loader.clear()
        super(MarkdownPolyactionsTest, self).tearDown()

    def _createPage(self):
        from markdown.markdownpage import MarkdownPageFactory
        return MarkdownPageFactory().create(self.wikiroot,
                                            u"Markdown-страница", [])

    def _getEditor(self):
        return Application.mainWindow.pagePanel.pageView.codeEditor
Пример #14
0
class HtmlFormatterTest(unittest.TestCase):
    """Тесты плагина HtmlFormatter"""
    def setUp(self):
        dirlist = [u"../plugins/htmlformatter"]

        self.loader = PluginsLoader(Application)
        self.loader.load(dirlist)

    def tearDown(self):
        self.loader.clear()

    def testPluginLoad(self):
        self.assertEqual(len(self.loader), 1)

    def testFactory(self):
        from htmlformatter.paragraphimprover import ParagraphHtmlImprover
        factory = HtmlImproverFactory(Application)

        self.assertEqual(type(factory['pimprover']), ParagraphHtmlImprover)
Пример #15
0
class MarkdownPolyactionsTest (BaseEditorPolyactionsTest):
    """Test polyactions for Markdown pages"""
    def setUp(self):
        dirlist = [u"../plugins/markdown"]
        self.loader = PluginsLoader(Application)
        self.loader.load(dirlist)
        super(MarkdownPolyactionsTest, self).setUp()

    def tearDown(self):
        self.loader.clear()
        super(MarkdownPolyactionsTest, self).tearDown()

    def _createPage(self):
        from markdown.markdownpage import MarkdownPageFactory
        return MarkdownPageFactory().create(self.wikiroot,
                                            u"Markdown-страница",
                                            [])

    def _getEditor(self):
        return Application.mainWindow.pagePanel.pageView.codeEditor
Пример #16
0
class HtmlFormatterTest(unittest.TestCase):
    """Тесты плагина HtmlFormatter"""

    def setUp(self):
        dirlist = [u"../plugins/htmlformatter"]

        self.loader = PluginsLoader(Application)
        self.loader.load(dirlist)

    def tearDown(self):
        self.loader.clear()

    def testPluginLoad(self):
        self.assertEqual(len(self.loader), 1)

    def testFactory(self):
        from htmlformatter.paragraphimprover import ParagraphHtmlImprover

        factory = HtmlImproverFactory(Application)

        self.assertEqual(type(factory["pimprover"]), ParagraphHtmlImprover)
Пример #17
0
class HtmlFormatterTest (unittest.TestCase, BaseOutWikerMixin):
    """Тесты плагина HtmlFormatter"""

    def setUp(self):
        self.initApplication()
        dirlist = ["../plugins/htmlformatter"]

        self.loader = PluginsLoader(self.application)
        self.loader.load(dirlist)

    def tearDown(self):
        self.loader.clear()
        self.destroyApplication()

    def testPluginLoad(self):
        self.assertEqual(len(self.loader), 1)

    def testFactory(self):
        from htmlformatter.paragraphimprover import ParagraphHtmlImprover
        factory = HtmlImproverFactory(self.application)

        self.assertEqual(type(factory['pimprover']), ParagraphHtmlImprover)
Пример #18
0
class HackPage_SetAliasTest(unittest.TestCase, BaseOutWikerGUIMixin):
    def setUp(self):
        self.initApplication()
        self.wikiroot = self.createWiki()

        self.__createWiki()
        self.testPage = self.wikiroot["Страница 1"]

        dirlist = ["../plugins/hackpage"]

        self._loader = PluginsLoader(self.application)
        self._loader.load(dirlist)

        Tester.dialogTester.clear()

    def tearDown(self):
        Tester.dialogTester.clear()
        self.application.wikiroot = None

        removeDir(self.wikiroot.path)
        self._loader.clear()

        self.destroyApplication()
        self.destroyWiki(self.wikiroot)

    def __createWiki(self):
        WikiPageFactory().create(self.wikiroot, "Страница 1", [])

    def _setValue(self, dialog, value):
        dialog.Value = value
        return wx.ID_OK

    def test_set_alias_default_01(self):
        from hackpage.utils import setAliasWithDialog

        Tester.dialogTester.appendOk()

        setAliasWithDialog(self.testPage, self.application)

        self.assertEqual(self.testPage.alias, None)
        self.assertEqual(Tester.dialogTester.count, 0)

    def test_set_alias_default_02(self):
        from hackpage.utils import setAliasWithDialog

        Tester.dialogTester.appendCancel()

        setAliasWithDialog(self.testPage, self.application)

        self.assertEqual(self.testPage.alias, None)
        self.assertEqual(Tester.dialogTester.count, 0)

    def test_set_alias_01(self):
        from hackpage.utils import setAliasWithDialog

        alias = 'Псевдоним страницы'

        Tester.dialogTester.append(self._setValue, alias)

        setAliasWithDialog(self.testPage, self.application)

        self.assertEqual(self.testPage.alias, alias)
        self.assertEqual(Tester.dialogTester.count, 0)

    def test_set_alias_02(self):
        from hackpage.utils import setAliasWithDialog

        alias = '   Псевдоним страницы   '

        Tester.dialogTester.append(self._setValue, alias)

        setAliasWithDialog(self.testPage, self.application)

        self.assertEqual(self.testPage.alias, alias)
        self.assertEqual(Tester.dialogTester.count, 0)

    def test_set_alias_03(self):
        from hackpage.utils import setAliasWithDialog

        self.testPage.alias = 'Псевдоним страницы'

        Tester.dialogTester.append(self._setValue, '')

        setAliasWithDialog(self.testPage, self.application)

        self.assertEqual(self.testPage.alias, None)
        self.assertEqual(Tester.dialogTester.count, 0)
Пример #19
0
class ChangePageUidTest(BaseMainWndTest):
    """Тесты плагина ChangePageUid"""

    def setUp(self):
        BaseMainWndTest.setUp(self)

        self.filesPath = u"../test/samplefiles/"
        self.__createWiki()

        dirlist = [u"../plugins/changepageuid"]

        self._loader = PluginsLoader(Application)
        self._loader.load(dirlist)

        from changepageuid.dialog import ChangeUidDialog

        self._dlg = ChangeUidDialog(Application.mainWindow)
        Tester.dialogTester.clear()

        self.testPage = self.wikiroot[u"Страница 1"]

    def tearDown(self):
        Application.wikiroot = None

        removeDir(self.path)
        self._dlg.Destroy()
        self._loader.clear()

        BaseMainWndTest.tearDown(self)

    def __createWiki(self):
        WikiPageFactory().create(self.wikiroot, u"Страница 1", [])
        WikiPageFactory().create(self.wikiroot, u"Страница 2", [])

    def testPluginLoad(self):
        self.assertEqual(len(self._loader), 1)

    def testDestroy(self):
        Application.wikiroot = None
        self._loader.clear()

    def testUidDefault(self):
        self._createDialogController()
        uid = Application.pageUidDepot.createUid(self.testPage)

        self.assertEqual(self._dlg.uid, uid)

    def testUid_01(self):
        controller = self._createDialogController()
        uid = Application.pageUidDepot.createUid(self.testPage)

        # Не изменяем свой идентификатора
        self.assertEqual(len(controller.validate(uid)), 0)

    def testUid_02(self):
        controller = self._createDialogController()
        uid = Application.pageUidDepot.createUid(self.wikiroot[u"Страница 2"])

        # Такой идентификатор уже есть
        self.assertNotEqual(len(controller.validate(uid)), 0)

    def testUid_03(self):
        controller = self._createDialogController()

        self.assertEqual(len(controller.validate(u"asdfsdfasdf_124323")), 0)
        self.assertEqual(len(controller.validate(u"__Абырвалг")), 0)
        self.assertNotEqual(len(controller.validate(u"adfadf/")), 0)
        self.assertNotEqual(len(controller.validate(u"adfadf asdfasdf")), 0)

    def _createDialogController(self):
        from changepageuid.dialogcontroller import DialogController

        return DialogController(Application, self._dlg, self.testPage)
Пример #20
0
class LightboxPluginTest (unittest.TestCase):
    def setUp(self):
        self.encoding = "utf8"

        self.__createWiki()

        dirlist = [u"../plugins/lightbox"]

        self.loader = PluginsLoader(Application)
        self.loader.load (dirlist)
        
        self.factory = ParserFactory()
        self.parser = self.factory.make (self.testPage, Application.config)
    

    def __createWiki (self):
        # Здесь будет создаваться вики
        self.path = u"../test/testwiki"
        removeWiki (self.path)

        self.rootwiki = WikiDocument.create (self.path)

        WikiPageFactory.create (self.rootwiki, u"Страница 1", [])
        self.testPage = self.rootwiki[u"Страница 1"]
        

    def tearDown(self):
        removeWiki (self.path)
        self.loader.clear()


    def testPluginLoad (self):
        self.assertEqual ( len (self.loader), 1)


    def testContentParse1 (self):
        text = u"""Бла-бла-бла (:lightbox:) бла-бла-бла"""

        validResult = u"""$("a[href$='.jpg']"""

        result = self.parser.toHtml (text)
        self.assertTrue (validResult in result)


    def testHeaders (self):
        text = u"""Бла-бла-бла (:lightbox:) бла-бла-бла"""

        result = self.parser.toHtml (text)

        self.assertTrue (u'<script type="text/javascript" src="./__attach/__thumb/jquery-1.7.2.min.js"></script>' in self.parser.head)

        self.assertTrue (u'<link rel="stylesheet" href="./__attach/__thumb/jquery.fancybox.css" type="text/css" media="screen" />' in self.parser.head)

        self.assertTrue (u'<script type="text/javascript" src="./__attach/__thumb/jquery.fancybox.pack.js"></script>' in self.parser.head)


    def testSingleHeaders (self):
        """
        Проверка, что заголовки добавляются только один раз
        """
        text = u"""Бла-бла-бла (:lightbox:) бла-бла-бла (:lightbox:)"""

        result = self.parser.toHtml (text)

        header = u'<script type="text/javascript" src="./__attach/__thumb/jquery-1.7.2.min.js"></script>'

        posfirst = self.parser.head.find (header)
        poslast = self.parser.head.rfind (header)

        self.assertEqual (posfirst, poslast)


    def testFiles (self):
        text = u"""Бла-бла-бла (:lightbox:) бла-бла-бла"""

        result = self.parser.toHtml (text)

        dirname = u"__attach/__thumb"
        files = ["jquery.fancybox.css", 
                "blank.gif", 
                "fancybox_loading.gif",
                "jquery-1.7.2.min.js",
                "jquery.fancybox.pack.js",
                "fancybox_sprite.png"
                ]

        for fname in files:
            fullpath = os.path.join (self.testPage.path, dirname, fname)
            self.assertTrue (os.path.exists (fullpath))
Пример #21
0
class TOC_GeneratorTest (unittest.TestCase):
    """Тесты плагина TableOfContents"""
    def setUp (self):
        dirlist = [u"../plugins/tableofcontents"]

        self.loader = PluginsLoader(Application)
        self.loader.load (dirlist)


    def tearDown (self):
        self.loader.clear()


    def testEmpty (self):
        from tableofcontents.tocwikigenerator import TOCWikiGenerator

        generator = TOCWikiGenerator(Application.config)
        items = []

        result = generator.make (items)

        result_valid = u''''''

        self.assertEqual (result, result_valid)


    def testToc_01 (self):
        from tableofcontents.contentsparser import Section
        from tableofcontents.tocwikigenerator import TOCWikiGenerator

        generator = TOCWikiGenerator(Application.config)
        items = [Section (u"Абырвалг 123", 1, u"")]

        result = generator.make (items)

        result_valid = u'''* Абырвалг 123'''

        self.assertEqual (result, result_valid)


    def testToc_02 (self):
        from tableofcontents.contentsparser import Section
        from tableofcontents.tocwikigenerator import TOCWikiGenerator

        generator = TOCWikiGenerator(Application.config)
        items = [
            Section (u"Абырвалг 123", 1, u""),
            Section (u"Абырвалг 12345", 1, u""),
        ]

        result = generator.make (items)

        result_valid = u'''* Абырвалг 123
* Абырвалг 12345'''

        self.assertEqual (result, result_valid)


    def testToc_03 (self):
        from tableofcontents.contentsparser import Section
        from tableofcontents.tocwikigenerator import TOCWikiGenerator

        generator = TOCWikiGenerator(Application.config)
        items = [
            Section (u"Абырвалг 123", 1, u""),
            Section (u"Абырвалг 12345", 2, u""),
        ]

        result = generator.make (items)

        result_valid = u'''* Абырвалг 123
** Абырвалг 12345'''

        self.assertEqual (result, result_valid)


    def testToc_04 (self):
        from tableofcontents.contentsparser import Section
        from tableofcontents.tocwikigenerator import TOCWikiGenerator

        generator = TOCWikiGenerator(Application.config)
        items = [
            Section (u"Абырвалг 123", 1, u""),
            Section (u"Абырвалг 12345", 5, u""),
        ]

        result = generator.make (items)

        result_valid = u'''* Абырвалг 123
***** Абырвалг 12345'''

        self.assertEqual (result, result_valid)


    def testToc_05 (self):
        from tableofcontents.contentsparser import Section
        from tableofcontents.tocwikigenerator import TOCWikiGenerator

        generator = TOCWikiGenerator(Application.config)
        items = [
            Section (u"Абырвалг 1", 1, u""),
            Section (u"Абырвалг 2", 2, u""),
            Section (u"Абырвалг 3", 3, u""),
            Section (u"Абырвалг 1", 1, u""),
        ]

        result = generator.make (items)

        result_valid = u'''* Абырвалг 1
** Абырвалг 2
*** Абырвалг 3
* Абырвалг 1'''

        self.assertEqual (result, result_valid)


    def testToc_06 (self):
        from tableofcontents.contentsparser import Section
        from tableofcontents.tocwikigenerator import TOCWikiGenerator

        generator = TOCWikiGenerator(Application.config)
        items = [
            Section (u"Абырвалг 123", 2, u""),
            Section (u"Абырвалг 12345", 3, u""),
        ]

        result = generator.make (items)

        result_valid = u'''* Абырвалг 123
** Абырвалг 12345'''

        self.assertEqual (result, result_valid)


    def testToc_07 (self):
        from tableofcontents.contentsparser import Section
        from tableofcontents.tocwikigenerator import TOCWikiGenerator

        generator = TOCWikiGenerator(Application.config)
        items = [
            Section (u"Абырвалг 123", 5, u""),
            Section (u"Абырвалг 12345", 5, u""),
        ]

        result = generator.make (items)

        result_valid = u'''* Абырвалг 123
* Абырвалг 12345'''

        self.assertEqual (result, result_valid)


    def testAnchors_01 (self):
        from tableofcontents.contentsparser import Section
        from tableofcontents.tocwikigenerator import TOCWikiGenerator

        WikiConfig (Application.config).linkStyleOptions.value = 0

        generator = TOCWikiGenerator(Application.config)
        items = [
            Section (u"Абырвалг 1", 1, u"якорь1"),
            Section (u"Абырвалг 2", 2, u"якорь2"),
        ]

        result = generator.make (items)

        result_valid = u'''* [[Абырвалг 1 -> #якорь1]]
** [[Абырвалг 2 -> #якорь2]]'''

        self.assertEqual (result, result_valid)


    def testAnchors_02 (self):
        from tableofcontents.contentsparser import Section
        from tableofcontents.tocwikigenerator import TOCWikiGenerator

        WikiConfig (Application.config).linkStyleOptions.value = 1

        generator = TOCWikiGenerator(Application.config)
        items = [
            Section (u"Абырвалг 1", 1, u"якорь1"),
            Section (u"Абырвалг 2", 2, u"якорь2"),
        ]

        result = generator.make (items)

        result_valid = u'''* [[#якорь1 | Абырвалг 1]]
** [[#якорь2 | Абырвалг 2]]'''

        self.assertEqual (result, result_valid)


    def testAnchors_03 (self):
        from tableofcontents.contentsparser import Section
        from tableofcontents.tocwikigenerator import TOCWikiGenerator

        WikiConfig (Application.config).linkStyleOptions.value = 2

        generator = TOCWikiGenerator(Application.config)
        items = [
            Section (u"Абырвалг 1", 1, u"якорь1"),
            Section (u"Абырвалг 2", 2, u"якорь2"),
        ]

        result = generator.make (items)

        result_valid = u'''* [[Абырвалг 1 -> #якорь1]]
** [[Абырвалг 2 -> #якорь2]]'''

        self.assertEqual (result, result_valid)
Пример #22
0
class InsertEdgeTest(unittest.TestCase, BaseOutWikerGUIMixin):
    def setUp(self):
        self.initApplication()
        self.wikiroot = self.createWiki()
        dirlist = ["plugins/diagrammer"]

        self.loader = PluginsLoader(Application)
        self.loader.load(dirlist)

        from diagrammer.gui.insertedgedialog import InsertEdgeDialog

        self._dlg = InsertEdgeDialog(None)
        Tester.dialogTester.clear()

    def tearDown(self):
        self.loader.clear()
        self._dlg.Destroy()
        self.destroyApplication()
        self.destroyWiki(self.wikiroot)

    def testArrows_01(self):
        import diagrammer.gui.insertedgedialog

        controller = diagrammer.gui.insertedgedialog.InsertEdgeControllerNone(
            self._dlg)

        Tester.dialogTester.appendOk()
        self._dlg.firstName = "А"
        self._dlg.secondName = "Б"

        result = controller.getResult()

        self.assertEqual(result, "А -- Б")

    def testArrows_02(self):
        import diagrammer.gui.insertedgedialog

        controller = diagrammer.gui.insertedgedialog.InsertEdgeControllerLeft(
            self._dlg)

        Tester.dialogTester.appendOk()
        self._dlg.firstName = "А"
        self._dlg.secondName = "Б"

        result = controller.getResult()

        self.assertEqual(result, "А <- Б")

    def testArrows_03(self):
        import diagrammer.gui.insertedgedialog

        controller = diagrammer.gui.insertedgedialog.InsertEdgeControllerRight(
            self._dlg)

        Tester.dialogTester.appendOk()
        self._dlg.firstName = "А"
        self._dlg.secondName = "Б"

        result = controller.getResult()

        self.assertEqual(result, "А -> Б")

    def testArrows_04(self):
        import diagrammer.gui.insertedgedialog

        controller = diagrammer.gui.insertedgedialog.InsertEdgeControllerBoth(
            self._dlg)

        Tester.dialogTester.appendOk()
        self._dlg.firstName = "А"
        self._dlg.secondName = "Б"

        result = controller.getResult()

        self.assertEqual(result, "А <-> Б")

    def testEmptyNames_01(self):
        import diagrammer.gui.insertedgedialog

        controller = diagrammer.gui.insertedgedialog.InsertEdgeControllerBoth(
            self._dlg)

        Tester.dialogTester.appendOk()
        self._dlg.firstName = ""
        self._dlg.secondName = ""

        result = controller.getResult()

        self.assertIn("1", result)
        self.assertIn("2", result)

    def testEmptyNames_02(self):
        import diagrammer.gui.insertedgedialog

        controller = diagrammer.gui.insertedgedialog.InsertEdgeControllerBoth(
            self._dlg)

        Tester.dialogTester.appendOk()
        self._dlg.firstName = "А"
        self._dlg.secondName = ""

        result = controller.getResult()

        self.assertNotIn("1", result)
        self.assertIn("А", result)
        self.assertIn("2", result)

    def testEmptyNames_03(self):
        import diagrammer.gui.insertedgedialog

        controller = diagrammer.gui.insertedgedialog.InsertEdgeControllerBoth(
            self._dlg)

        Tester.dialogTester.appendOk()
        self._dlg.firstName = ""
        self._dlg.secondName = "Б"

        result = controller.getResult()

        self.assertIn("1", result)
        self.assertNotIn("2", result)
        self.assertIn("Б", result)

    def testLabel_01(self):
        import diagrammer.gui.insertedgedialog

        controller = diagrammer.gui.insertedgedialog.InsertEdgeControllerRight(
            self._dlg)

        Tester.dialogTester.appendOk()
        self._dlg.firstName = "А"
        self._dlg.secondName = "Б"
        self._dlg.label = "Абырвалг"

        result = controller.getResult()

        self.assertEqual(result, 'А -> Б [label = "Абырвалг"]')

    def testStyleLine_01(self):
        import diagrammer.gui.insertedgedialog

        controller = diagrammer.gui.insertedgedialog.InsertEdgeControllerRight(
            self._dlg)

        Tester.dialogTester.appendOk()
        self._dlg.firstName = "А"
        self._dlg.secondName = "Б"
        self._dlg.setStyleIndex(0)

        result = controller.getResult()

        self.assertEqual(result, 'А -> Б')

    def testStyleLine_02(self):
        import diagrammer.gui.insertedgedialog

        controller = diagrammer.gui.insertedgedialog.InsertEdgeControllerRight(
            self._dlg)

        Tester.dialogTester.appendOk()
        self._dlg.firstName = "А"
        self._dlg.secondName = "Б"
        self._dlg.setStyleIndex(1)

        result = controller.getResult()

        self.assertEqual(result, 'А -> Б [style = solid]')

    def testStyleLine_03(self):
        import diagrammer.gui.insertedgedialog

        controller = diagrammer.gui.insertedgedialog.InsertEdgeControllerRight(
            self._dlg)

        Tester.dialogTester.appendOk()
        self._dlg.firstName = "А"
        self._dlg.secondName = "Б"
        self._dlg.setStyleIndex(2)

        result = controller.getResult()

        self.assertEqual(result, 'А -> Б [style = dotted]')

    def testStyleLine_04(self):
        import diagrammer.gui.insertedgedialog

        controller = diagrammer.gui.insertedgedialog.InsertEdgeControllerRight(
            self._dlg)

        Tester.dialogTester.appendOk()
        self._dlg.firstName = "А"
        self._dlg.secondName = "Б"
        self._dlg.setStyleIndex(3)

        result = controller.getResult()

        self.assertEqual(result, 'А -> Б [style = dashed]')

    def testStyleLine_05(self):
        import diagrammer.gui.insertedgedialog

        controller = diagrammer.gui.insertedgedialog.InsertEdgeControllerRight(
            self._dlg)

        Tester.dialogTester.appendOk()
        self._dlg.firstName = "А"
        self._dlg.secondName = "Б"
        self._dlg.label = "Абырвалг"
        self._dlg.setStyleIndex(3)

        result = controller.getResult()

        self.assertEqual(result, 'А -> Б [label = "Абырвалг", style = dashed]')

    def testStyleArrow_01(self):
        import diagrammer.gui.insertedgedialog

        controller = diagrammer.gui.insertedgedialog.InsertEdgeControllerRight(
            self._dlg)

        Tester.dialogTester.appendOk()
        self._dlg.firstName = "А"
        self._dlg.secondName = "Б"
        self._dlg.setArrowStyleIndex(0)

        result = controller.getResult()

        self.assertEqual(result, 'А -> Б')

    def testStyleArrow_02(self):
        import diagrammer.gui.insertedgedialog

        controller = diagrammer.gui.insertedgedialog.InsertEdgeControllerRight(
            self._dlg)

        Tester.dialogTester.appendOk()
        self._dlg.firstName = "А"
        self._dlg.secondName = "Б"
        self._dlg.setArrowStyleIndex(1)

        result = controller.getResult()

        self.assertEqual(result, 'А -> Б [hstyle = generalization]')

    def testStyleArrow_03(self):
        import diagrammer.gui.insertedgedialog

        controller = diagrammer.gui.insertedgedialog.InsertEdgeControllerRight(
            self._dlg)

        Tester.dialogTester.appendOk()
        self._dlg.firstName = "А"
        self._dlg.secondName = "Б"
        self._dlg.setArrowStyleIndex(2)

        result = controller.getResult()

        self.assertEqual(result, 'А -> Б [hstyle = composition]')

    def testStyleArrow_04(self):
        import diagrammer.gui.insertedgedialog

        controller = diagrammer.gui.insertedgedialog.InsertEdgeControllerRight(
            self._dlg)

        Tester.dialogTester.appendOk()
        self._dlg.firstName = "А"
        self._dlg.secondName = "Б"
        self._dlg.setArrowStyleIndex(3)

        result = controller.getResult()

        self.assertEqual(result, 'А -> Б [hstyle = aggregation]')

    def testStyleArrow_05(self):
        import diagrammer.gui.insertedgedialog

        controller = diagrammer.gui.insertedgedialog.InsertEdgeControllerRight(
            self._dlg)

        Tester.dialogTester.appendOk()
        self._dlg.firstName = "А"
        self._dlg.secondName = "Б"
        self._dlg.setStyleIndex(3)
        self._dlg.setArrowStyleIndex(3)

        result = controller.getResult()

        self.assertEqual(result,
                         'А -> Б [style = dashed, hstyle = aggregation]')

    def testLineColor_01(self):
        import diagrammer.gui.insertedgedialog

        controller = diagrammer.gui.insertedgedialog.InsertEdgeControllerRight(
            self._dlg)

        Tester.dialogTester.appendOk()
        self._dlg.firstName = "А"
        self._dlg.secondName = "Б"
        self._dlg.isLineColorChanged = True
        self._dlg.lineColor = "yellow"

        result = controller.getResult()

        self.assertEqual(result, 'А -> Б [color = "yellow"]')

    def testLineColor_02(self):
        import diagrammer.gui.insertedgedialog

        controller = diagrammer.gui.insertedgedialog.InsertEdgeControllerRight(
            self._dlg)

        Tester.dialogTester.appendOk()
        self._dlg.firstName = "А"
        self._dlg.secondName = "Б"
        self._dlg.isLineColorChanged = False
        self._dlg.lineColor = "yellow"

        result = controller.getResult()

        self.assertEqual(result, 'А -> Б')

    def testLineColor_03(self):
        import diagrammer.gui.insertedgedialog

        controller = diagrammer.gui.insertedgedialog.InsertEdgeControllerRight(
            self._dlg)

        Tester.dialogTester.appendOk()
        self._dlg.firstName = "А"
        self._dlg.secondName = "Б"
        self._dlg.isLineColorChanged = True
        self._dlg.lineColor = "#AAAAAA"

        result = controller.getResult()

        self.assertEqual(result, 'А -> Б [color = "#AAAAAA"]')

    def testLineColor_04(self):
        import diagrammer.gui.insertedgedialog

        controller = diagrammer.gui.insertedgedialog.InsertEdgeControllerRight(
            self._dlg)

        Tester.dialogTester.appendOk()
        self._dlg.firstName = "А"
        self._dlg.secondName = "Б"
        self._dlg.isLineColorChanged = True
        self._dlg.lineColor = "#AAAAAA"
        self._dlg.setArrowStyleIndex(3)

        result = controller.getResult()

        self.assertEqual(result,
                         'А -> Б [hstyle = aggregation, color = "#AAAAAA"]')

    def testFontSize_01(self):
        import diagrammer.gui.insertedgedialog

        controller = diagrammer.gui.insertedgedialog.InsertEdgeControllerRight(
            self._dlg)

        Tester.dialogTester.appendOk()
        self._dlg.firstName = "А"
        self._dlg.secondName = "Б"
        self._dlg.isFontSizeChanged = True
        self._dlg.fontSize = 11

        result = controller.getResult()

        self.assertEqual(result, 'А -> Б [fontsize = 11]')

    def testFontSize_02(self):
        import diagrammer.gui.insertedgedialog

        controller = diagrammer.gui.insertedgedialog.InsertEdgeControllerRight(
            self._dlg)

        Tester.dialogTester.appendOk()
        self._dlg.firstName = "А"
        self._dlg.secondName = "Б"
        self._dlg.isFontSizeChanged = False
        self._dlg.fontSize = 15

        result = controller.getResult()

        self.assertEqual(result, 'А -> Б')

    def testFontSize_03(self):
        import diagrammer.gui.insertedgedialog

        controller = diagrammer.gui.insertedgedialog.InsertEdgeControllerRight(
            self._dlg)

        Tester.dialogTester.appendOk()
        self._dlg.firstName = "А"
        self._dlg.secondName = "Б"
        self._dlg.isFontSizeChanged = True
        self._dlg.fontSize = 11
        self._dlg.label = "Абырвалг"

        result = controller.getResult()

        self.assertEqual(result, 'А -> Б [label = "Абырвалг", fontsize = 11]')

    def testTextColor_01(self):
        import diagrammer.gui.insertedgedialog

        controller = diagrammer.gui.insertedgedialog.InsertEdgeControllerRight(
            self._dlg)

        Tester.dialogTester.appendOk()
        self._dlg.firstName = "А"
        self._dlg.secondName = "Б"
        self._dlg.isTextColorChanged = True
        self._dlg.textColor = "yellow"

        result = controller.getResult()

        self.assertEqual(result, 'А -> Б [textcolor = "yellow"]')

    def testTextColor_02(self):
        import diagrammer.gui.insertedgedialog

        controller = diagrammer.gui.insertedgedialog.InsertEdgeControllerRight(
            self._dlg)

        Tester.dialogTester.appendOk()
        self._dlg.firstName = "А"
        self._dlg.secondName = "Б"
        self._dlg.isTextColorChanged = False
        self._dlg.textColor = "yellow"

        result = controller.getResult()

        self.assertEqual(result, 'А -> Б')

    def testTextColor_03(self):
        import diagrammer.gui.insertedgedialog

        controller = diagrammer.gui.insertedgedialog.InsertEdgeControllerRight(
            self._dlg)

        Tester.dialogTester.appendOk()
        self._dlg.firstName = "А"
        self._dlg.secondName = "Б"
        self._dlg.isTextColorChanged = True
        self._dlg.textColor = "#AAAAAA"

        result = controller.getResult()

        self.assertEqual(result, 'А -> Б [textcolor = "#AAAAAA"]')

    def testTextColor_04(self):
        import diagrammer.gui.insertedgedialog

        controller = diagrammer.gui.insertedgedialog.InsertEdgeControllerRight(
            self._dlg)

        Tester.dialogTester.appendOk()
        self._dlg.firstName = "А"
        self._dlg.secondName = "Б"
        self._dlg.isTextColorChanged = True
        self._dlg.textColor = "#AAAAAA"
        self._dlg.setArrowStyleIndex(3)

        result = controller.getResult()

        self.assertEqual(
            result, 'А -> Б [hstyle = aggregation, textcolor = "#AAAAAA"]')

    def testThick_01(self):
        import diagrammer.gui.insertedgedialog

        controller = diagrammer.gui.insertedgedialog.InsertEdgeControllerRight(
            self._dlg)

        Tester.dialogTester.appendOk()
        self._dlg.firstName = "А"
        self._dlg.secondName = "Б"
        self._dlg.thick = True

        result = controller.getResult()

        self.assertEqual(result, 'А -> Б [thick]')

    def testThick_02(self):
        import diagrammer.gui.insertedgedialog

        controller = diagrammer.gui.insertedgedialog.InsertEdgeControllerRight(
            self._dlg)

        Tester.dialogTester.appendOk()
        self._dlg.firstName = "А"
        self._dlg.secondName = "Б"
        self._dlg.thick = False

        result = controller.getResult()

        self.assertEqual(result, 'А -> Б')

    def testThick_03(self):
        import diagrammer.gui.insertedgedialog

        controller = diagrammer.gui.insertedgedialog.InsertEdgeControllerRight(
            self._dlg)

        Tester.dialogTester.appendOk()
        self._dlg.firstName = "А"
        self._dlg.secondName = "Б"
        self._dlg.thick = True
        self._dlg.setStyleIndex(1)

        result = controller.getResult()

        self.assertEqual(result, 'А -> Б [style = solid, thick]')

    def testFolded_01(self):
        import diagrammer.gui.insertedgedialog

        controller = diagrammer.gui.insertedgedialog.InsertEdgeControllerRight(
            self._dlg)

        Tester.dialogTester.appendOk()
        self._dlg.firstName = "А"
        self._dlg.secondName = "Б"
        self._dlg.folded = True

        result = controller.getResult()

        self.assertEqual(result, 'А -> Б [folded]')

    def testFolded_02(self):
        import diagrammer.gui.insertedgedialog

        controller = diagrammer.gui.insertedgedialog.InsertEdgeControllerRight(
            self._dlg)

        Tester.dialogTester.appendOk()
        self._dlg.firstName = "А"
        self._dlg.secondName = "Б"
        self._dlg.folded = False

        result = controller.getResult()

        self.assertEqual(result, 'А -> Б')

    def testFolded_03(self):
        import diagrammer.gui.insertedgedialog

        controller = diagrammer.gui.insertedgedialog.InsertEdgeControllerRight(
            self._dlg)

        Tester.dialogTester.appendOk()
        self._dlg.firstName = "А"
        self._dlg.secondName = "Б"
        self._dlg.folded = True
        self._dlg.setStyleIndex(1)

        result = controller.getResult()

        self.assertEqual(result, 'А -> Б [style = solid, folded]')
Пример #23
0
class SourceAttachmentPluginTest(unittest.TestCase, BaseOutWikerGUIMixin):
    """
    Тесты интерфейса для плагина Source
    """
    def setUp(self):
        self.__pluginname = "Source"
        self.initApplication()
        self.wikiroot = self.createWiki()
        self.testPage = WikiPageFactory().create(self.wikiroot, "Страница 1",
                                                 [])

        dirlist = ["plugins/source"]

        self.loader = PluginsLoader(self.application)
        self.loader.load(dirlist)

        self.config = self.loader[self.__pluginname].config
        self.config.tabWidth.value = 4
        self.config.defaultLanguage.remove_option()
        self.application.config.remove_section(self.config.section)

        from source.insertdialogcontroller import InsertDialogController
        self.dialog = FakeInsertDialog()
        self.controller = InsertDialogController(self.testPage, self.dialog,
                                                 self.config)

    def tearDown(self):
        self.application.config.remove_section(self.config.section)
        self.loader.clear()
        self.destroyApplication()
        self.destroyWiki(self.wikiroot)

    def testAttachment1(self):
        self.controller.showDialog()

        self.assertEqual(self.dialog.attachmentComboBox.GetCount(), 0)

    def testAttachment2(self):
        # Путь, где лежат примеры исходников в разных кодировках
        self.samplefilesPath = "testdata/samplefiles/sources"
        Attachment(self.testPage).attach(
            [os.path.join(self.samplefilesPath, "source_utf8.py")])
        Attachment(self.testPage).attach(
            [os.path.join(self.samplefilesPath, "source_cp1251.cs")])

        self.controller.showDialog()

        self.assertEqual(self.dialog.attachmentComboBox.GetSelection(), 0)
        self.assertEqual(self.dialog.attachmentComboBox.GetCount(), 2)
        self.assertEqual(self.dialog.attachmentComboBox.GetItems(),
                         ["source_cp1251.cs", "source_utf8.py"])

    def testAttachment3(self):
        # Путь, где лежат примеры исходников в разных кодировках
        self.samplefilesPath = "testdata/samplefiles/sources"
        Attachment(self.testPage).attach(
            [os.path.join(self.samplefilesPath, "source_utf8.py")])
        Attachment(self.testPage).attach(
            [os.path.join(self.samplefilesPath, "source_cp1251.cs")])

        self.controller.showDialog()

        self.dialog.fileCheckBox.SetValue(True)
        self.controller.updateFileChecked()

        self.dialog.attachmentComboBox.SetSelection(0)
        self.dialog.encodingComboBox.SetSelection(0)

        result = self.controller.getCommandStrings()

        self.assertEqual(
            result,
            ('(:source file="Attach:source_cp1251.cs":)', '(:sourceend:)'))

    def testAttachment4(self):
        # Путь, где лежат примеры исходников в разных кодировках
        self.samplefilesPath = "testdata/samplefiles/sources"
        Attachment(self.testPage).attach(
            [os.path.join(self.samplefilesPath, "source_utf8.py")])
        Attachment(self.testPage).attach(
            [os.path.join(self.samplefilesPath, "source_cp1251.cs")])

        self.controller.showDialog()

        self.dialog.fileCheckBox.SetValue(True)
        self.controller.updateFileChecked()

        self.dialog.attachmentComboBox.SetSelection(1)
        self.dialog.encodingComboBox.SetSelection(0)

        result = self.controller.getCommandStrings()

        self.assertEqual(
            result,
            ('(:source file="Attach:source_utf8.py":)', '(:sourceend:)'))

    def testAttachment5(self):
        # Путь, где лежат примеры исходников в разных кодировках
        self.samplefilesPath = "testdata/samplefiles/sources"
        Attachment(self.testPage).attach(
            [os.path.join(self.samplefilesPath, "source_utf8.py")])
        Attachment(self.testPage).attach(
            [os.path.join(self.samplefilesPath, "source_cp1251.cs")])

        self.controller.showDialog()

        self.dialog.fileCheckBox.SetValue(True)
        self.controller.updateFileChecked()

        self.dialog.attachmentComboBox.SetSelection(0)
        self.dialog.encodingComboBox.SetSelection(2)

        result = self.controller.getCommandStrings()

        self.assertEqual(
            result,
            ('(:source file="Attach:source_cp1251.cs" encoding="cp1251":)',
             '(:sourceend:)'))

    def testAttachment6(self):
        # Путь, где лежат примеры исходников в разных кодировках
        self.samplefilesPath = "testdata/samplefiles/sources"
        Attachment(self.testPage).attach(
            [os.path.join(self.samplefilesPath, "source_utf8.py")])
        Attachment(self.testPage).attach(
            [os.path.join(self.samplefilesPath, "source_cp1251.cs")])

        self.config.languageList.value = ["cpp", "csharp", "haskell"]

        self.controller.showDialog()

        self.dialog.fileCheckBox.SetValue(True)

        # Т.к. при изменении состояния флажка события не возникают,
        # Вручную обновим список языков
        self.controller.loadLanguagesState()

        self.dialog.attachmentComboBox.SetSelection(0)
        self.dialog.encodingComboBox.SetSelection(2)
        self.dialog.languageComboBox.SetSelection(3)

        result = self.controller.getCommandStrings()

        self.assertEqual(result, (
            '(:source file="Attach:source_cp1251.cs" encoding="cp1251" lang="haskell":)',
            '(:sourceend:)'))

    def testAttachment7(self):
        # Путь, где лежат примеры исходников в разных кодировках
        self.samplefilesPath = "testdata/samplefiles/sources"
        Attachment(self.testPage).attach(
            [os.path.join(self.samplefilesPath, "source_utf8.py")])
        Attachment(self.testPage).attach(
            [os.path.join(self.samplefilesPath, "source_cp1251.cs")])

        self.config.languageList.value = ["cpp", "haskell", "csharp"]

        self.controller.showDialog()

        self.dialog.fileCheckBox.SetValue(True)
        self.dialog.attachmentComboBox.SetSelection(0)
        self.dialog.encodingComboBox.SetSelection(2)
        self.dialog.languageComboBox.SetSelection(0)

        result = self.controller.getCommandStrings()

        self.assertEqual(
            result,
            ('(:source file="Attach:source_cp1251.cs" encoding="cp1251":)',
             '(:sourceend:)'))

    def testAttachment8(self):
        # Путь, где лежат примеры исходников в разных кодировках
        self.samplefilesPath = "testdata/samplefiles/sources"
        Attachment(self.testPage).attach(
            [os.path.join(self.samplefilesPath, "source_utf8.py")])
        Attachment(self.testPage).attach(
            [os.path.join(self.samplefilesPath, "source_cp1251.cs")])

        self.config.languageList.value = ["cpp", "csharp", "haskell"]

        self.controller.showDialog()

        self.dialog.fileCheckBox.SetValue(True)

        # Т.к. при изменении состояния флажка события не возникают,
        # Вручную обновим список языков
        self.controller.loadLanguagesState()

        self.dialog.attachmentComboBox.SetSelection(0)
        self.dialog.encodingComboBox.SetSelection(0)
        self.dialog.languageComboBox.SetSelection(1)

        result = self.controller.getCommandStrings()

        self.assertEqual(
            result, ('(:source file="Attach:source_cp1251.cs" lang="csharp":)',
                     '(:sourceend:)'))

    def testAttachment9(self):
        # Путь, где лежат примеры исходников в разных кодировках
        self.samplefilesPath = "testdata/samplefiles/sources"
        Attachment(self.testPage).attach(
            [os.path.join(self.samplefilesPath, "source_utf8.py")])
        Attachment(self.testPage).attach(
            [os.path.join(self.samplefilesPath, "source_cp1251.cs")])

        self.config.languageList.value = ["cpp", "csharp", "haskell"]

        self.controller.showDialog()

        self.dialog.fileCheckBox.SetValue(True)

        # Т.к. при изменении состояния флажка события не возникают,
        # Вручную обновим список языков
        self.controller.loadLanguagesState()

        self.dialog.attachmentComboBox.SetSelection(0)
        self.dialog.encodingComboBox.SetSelection(0)
        self.dialog.languageComboBox.SetSelection(1)
        self.dialog.tabWidthSpin.SetValue(10)

        result = self.controller.getCommandStrings()

        self.assertEqual(result, (
            '(:source file="Attach:source_cp1251.cs" lang="csharp" tabwidth="10":)',
            '(:sourceend:)'))
Пример #24
0
class InsertDiagramTest (unittest.TestCase):
    def setUp(self):
        dirlist = [u"../plugins/diagrammer"]

        self.loader = PluginsLoader(Application)
        self.loader.load (dirlist)

        from diagrammer.gui.insertdiagramdialog import (
            InsertDiagramDialog,
            InsertDiagramController
        )

        self._dlg = InsertDiagramDialog(None)
        self._controller = InsertDiagramController (self._dlg)
        Tester.dialogTester.clear()


    def tearDown(self):
        self._dlg.Destroy()
        self.loader.clear()


    def testDefault (self):
        Tester.dialogTester.appendOk()

        begin, end = self._controller.getResult ()

        self.assertEqual (begin, u"(:diagram:)\n")
        self.assertEqual (end, u"\n(:diagramend:)")


    def testShape_01 (self):
        Tester.dialogTester.appendOk()
        self._dlg.setShapeSelection (0)

        begin, end = self._controller.getResult ()

        valid_begin = u'''(:diagram:)
default_shape = actor;
'''

        self.assertEqual (begin, valid_begin)
        self.assertEqual (end, u"\n(:diagramend:)")


    def testShape_02 (self):
        Tester.dialogTester.appendOk()
        self._dlg.setShapeSelection (1)

        begin, end = self._controller.getResult ()

        valid_begin = u'''(:diagram:)
default_shape = beginpoint;
'''

        self.assertEqual (begin, valid_begin)
        self.assertEqual (end, u"\n(:diagramend:)")


    def testShape_03 (self):
        Tester.dialogTester.appendOk()

        # Значение по умолчанию
        self._dlg.setShapeSelection (2)

        begin, end = self._controller.getResult ()

        self.assertEqual (begin, u"(:diagram:)\n")
        self.assertEqual (end, u"\n(:diagramend:)")


    def testNodeColor_01 (self):
        Tester.dialogTester.appendOk()
        self._dlg.isBackColorChanged = True
        self._dlg.backColor = u"white"

        begin, end = self._controller.getResult ()

        valid_begin = u'''(:diagram:)
default_node_color = "white";
'''

        self.assertEqual (begin, valid_begin)
        self.assertEqual (end, u'\n(:diagramend:)')


    def testNodeColor_02 (self):
        Tester.dialogTester.appendOk()
        self._dlg.isBackColorChanged = False
        self._dlg.backColor = u"black"

        begin, end = self._controller.getResult ()

        self.assertEqual (begin, u'(:diagram:)\n')
        self.assertEqual (end, u'\n(:diagramend:)')


    def testNodeColor_03 (self):
        Tester.dialogTester.appendOk()
        self._dlg.isBackColorChanged = True
        self._dlg.backColor = u"#AAAAAA"

        begin, end = self._controller.getResult ()

        valid_begin = u'''(:diagram:)
default_node_color = "#AAAAAA";
'''

        self.assertEqual (begin, valid_begin)
        self.assertEqual (end, u'\n(:diagramend:)')


    def testNodeColor_04 (self):
        Tester.dialogTester.appendOk()
        self._dlg.isBackColorChanged = True
        self._dlg.backColor = u"#AAAAAA"
        self._dlg.setShapeSelection (0)

        begin, end = self._controller.getResult ()

        valid_begin = u'''(:diagram:)
default_shape = actor;
default_node_color = "#AAAAAA";
'''

        self.assertEqual (begin, valid_begin)
        self.assertEqual (end, u'\n(:diagramend:)')


    def testTextColor_01 (self):
        Tester.dialogTester.appendOk()
        self._dlg.isTextColorChanged = True
        self._dlg.textColor = u"white"

        begin, end = self._controller.getResult ()

        valid_begin = u'''(:diagram:)
default_textcolor = "white";
'''

        self.assertEqual (begin, valid_begin)
        self.assertEqual (end, u'\n(:diagramend:)')


    def testTextColor_02 (self):
        Tester.dialogTester.appendOk()
        self._dlg.isTextColorChanged = False
        self._dlg.textColor = u"black"

        begin, end = self._controller.getResult ()

        self.assertEqual (begin, u'(:diagram:)\n')
        self.assertEqual (end, u'\n(:diagramend:)')


    def testTextColor_03 (self):
        Tester.dialogTester.appendOk()
        self._dlg.isTextColorChanged = True
        self._dlg.textColor = u"#AAAAAA"

        begin, end = self._controller.getResult ()

        valid_begin = u'''(:diagram:)
default_textcolor = "#AAAAAA";
'''

        self.assertEqual (begin, valid_begin)
        self.assertEqual (end, u'\n(:diagramend:)')


    def testTextColor_04 (self):
        Tester.dialogTester.appendOk()
        self._dlg.isTextColorChanged = True
        self._dlg.textColor = u"#AAAAAA"
        self._dlg.setShapeSelection (0)

        begin, end = self._controller.getResult ()

        valid_begin = u'''(:diagram:)
default_shape = actor;
default_textcolor = "#AAAAAA";
'''

        self.assertEqual (begin, valid_begin)
        self.assertEqual (end, u'\n(:diagramend:)')


    def testFontSize_01 (self):
        Tester.dialogTester.appendOk()
        self._dlg.isFontSizeChanged = True
        self._dlg.fontSize = 20

        begin, end = self._controller.getResult ()

        valid_begin = u'''(:diagram:)
default_fontsize = 20;
'''

        self.assertEqual (begin, valid_begin)
        self.assertEqual (end, u'\n(:diagramend:)')


    def testFontSize_02 (self):
        Tester.dialogTester.appendOk()
        self._dlg.isFontSizeChanged = False
        self._dlg.fontSize = 20

        begin, end = self._controller.getResult ()

        valid_begin = u'''(:diagram:)
'''

        self.assertEqual (begin, valid_begin)
        self.assertEqual (end, u'\n(:diagramend:)')


    def testFontSize_03 (self):
        Tester.dialogTester.appendOk()
        self._dlg.setShapeSelection (0)
        self._dlg.isFontSizeChanged = True
        self._dlg.fontSize = 20

        begin, end = self._controller.getResult ()

        valid_begin = u'''(:diagram:)
default_shape = actor;
default_fontsize = 20;
'''

        self.assertEqual (begin, valid_begin)
        self.assertEqual (end, u'\n(:diagramend:)')


    def testWidth_01 (self):
        Tester.dialogTester.appendOk()
        self._dlg.isWidthChanged = True
        self._dlg.width = 200

        begin, end = self._controller.getResult ()

        valid_begin = u'''(:diagram:)
node_width = 200;
'''

        self.assertEqual (begin, valid_begin)
        self.assertEqual (end, u'\n(:diagramend:)')


    def testWidth_02 (self):
        Tester.dialogTester.appendOk()
        self._dlg.isWidthChanged = False
        self._dlg.width = 200

        begin, end = self._controller.getResult ()

        valid_begin = u'''(:diagram:)
'''

        self.assertEqual (begin, valid_begin)
        self.assertEqual (end, u'\n(:diagramend:)')


    def testWidth_03 (self):
        Tester.dialogTester.appendOk()
        self._dlg.setShapeSelection (0)
        self._dlg.isWidthChanged = True
        self._dlg.width = 200

        begin, end = self._controller.getResult ()

        valid_begin = u'''(:diagram:)
default_shape = actor;
node_width = 200;
'''

        self.assertEqual (begin, valid_begin)
        self.assertEqual (end, u'\n(:diagramend:)')


    def testHeight_01 (self):
        Tester.dialogTester.appendOk()
        self._dlg.isHeightChanged = True
        self._dlg.height = 200

        begin, end = self._controller.getResult ()

        valid_begin = u'''(:diagram:)
node_height = 200;
'''

        self.assertEqual (begin, valid_begin)
        self.assertEqual (end, u'\n(:diagramend:)')


    def testHeight_02 (self):
        Tester.dialogTester.appendOk()
        self._dlg.isHeightChanged = False
        self._dlg.height = 200

        begin, end = self._controller.getResult ()

        valid_begin = u'''(:diagram:)
'''

        self.assertEqual (begin, valid_begin)
        self.assertEqual (end, u'\n(:diagramend:)')


    def testHeight_03 (self):
        Tester.dialogTester.appendOk()
        self._dlg.setShapeSelection (0)
        self._dlg.isHeightChanged = True
        self._dlg.height = 200

        begin, end = self._controller.getResult ()

        valid_begin = u'''(:diagram:)
default_shape = actor;
node_height = 200;
'''

        self.assertEqual (begin, valid_begin)
        self.assertEqual (end, u'\n(:diagramend:)')


    def testOrientation_01 (self):
        self._dlg.orientationIndex = 0

        Tester.dialogTester.appendOk()

        begin, end = self._controller.getResult ()

        valid_begin = u'''(:diagram:)
'''

        self.assertEqual (begin, valid_begin)
        self.assertEqual (end, u'\n(:diagramend:)')


    def testOrientation_02 (self):
        self._dlg.orientationIndex = 1

        Tester.dialogTester.appendOk()

        begin, end = self._controller.getResult ()

        valid_begin = u'''(:diagram:)
orientation = portrait;
'''

        self.assertEqual (begin, valid_begin)
        self.assertEqual (end, u'\n(:diagramend:)')


    def testOrientation_03 (self):
        self._dlg.orientationIndex = 1
        self._dlg.setShapeSelection (0)

        Tester.dialogTester.appendOk()

        begin, end = self._controller.getResult ()

        valid_begin = u'''(:diagram:)
orientation = portrait;
default_shape = actor;
'''

        self.assertEqual (begin, valid_begin)
        self.assertEqual (end, u'\n(:diagramend:)')


    def testSpanWidth_01 (self):
        Tester.dialogTester.appendOk()
        self._dlg.isSpanWidthChanged = True
        self._dlg.spanWidth = 200

        begin, end = self._controller.getResult ()

        valid_begin = u'''(:diagram:)
span_width = 200;
'''

        self.assertEqual (begin, valid_begin)
        self.assertEqual (end, u'\n(:diagramend:)')


    def testSpanWidth_02 (self):
        Tester.dialogTester.appendOk()
        self._dlg.isSpanWidthChanged = False
        self._dlg.spanWidth = 200

        begin, end = self._controller.getResult ()

        valid_begin = u'''(:diagram:)
'''

        self.assertEqual (begin, valid_begin)
        self.assertEqual (end, u'\n(:diagramend:)')


    def testSpanWidth_03 (self):
        Tester.dialogTester.appendOk()
        self._dlg.setShapeSelection (0)
        self._dlg.isSpanWidthChanged = True
        self._dlg.spanWidth = 200

        begin, end = self._controller.getResult ()

        valid_begin = u'''(:diagram:)
default_shape = actor;
span_width = 200;
'''

        self.assertEqual (begin, valid_begin)
        self.assertEqual (end, u'\n(:diagramend:)')


    def testSpanHeight_01 (self):
        Tester.dialogTester.appendOk()
        self._dlg.isSpanHeightChanged = True
        self._dlg.spanHeight = 200

        begin, end = self._controller.getResult ()

        valid_begin = u'''(:diagram:)
span_height = 200;
'''

        self.assertEqual (begin, valid_begin)
        self.assertEqual (end, u'\n(:diagramend:)')


    def testSpanHeight_02 (self):
        Tester.dialogTester.appendOk()
        self._dlg.isSpanHeightChanged = False
        self._dlg.spanHeight = 200

        begin, end = self._controller.getResult ()

        valid_begin = u'''(:diagram:)
'''

        self.assertEqual (begin, valid_begin)
        self.assertEqual (end, u'\n(:diagramend:)')


    def testSpanHeight_03 (self):
        Tester.dialogTester.appendOk()
        self._dlg.setShapeSelection (0)
        self._dlg.isSpanHeightChanged = True
        self._dlg.spanHeight = 200

        begin, end = self._controller.getResult ()

        valid_begin = u'''(:diagram:)
default_shape = actor;
span_height = 200;
'''

        self.assertEqual (begin, valid_begin)
        self.assertEqual (end, u'\n(:diagramend:)')
Пример #25
0
class UpdateControllerTest(unittest.TestCase, BaseOutWikerGUIMixin):
    """Tests for the UpdateNotifier plugin."""
    def setUp(self):
        self.initApplication()
        self.loader = PluginsLoader(self.application)
        self.loader.load(["plugins/updatenotifier"])

    def tearDown(self):
        self.loader.clear()
        self.destroyApplication()

    def test_filter_empty_01(self):
        from updatenotifier.updatecontroller import UpdateController

        plugin = self.loader['UpdateNotifier']
        controller = UpdateController(self.application, plugin)

        currentVersionsDict = {}
        latestVersionsDict = {}

        result = controller.filterUpdatedApps(currentVersionsDict,
                                              latestVersionsDict)

        self.assertEqual(result, {})

    def test_filter_empty_02(self):
        from updatenotifier.updatecontroller import UpdateController

        plugin = self.loader['UpdateNotifier']
        controller = UpdateController(self.application, plugin)

        currentVersionsDict = {'test_01': '0.1'}
        latestVersionsDict = {}

        result = controller.filterUpdatedApps(currentVersionsDict,
                                              latestVersionsDict)

        self.assertEqual(result, {})

    def test_filter_empty_03(self):
        from updatenotifier.updatecontroller import UpdateController

        plugin = self.loader['UpdateNotifier']
        controller = UpdateController(self.application, plugin)

        currentVersionsDict = {}
        latestVersionsDict = {
            'test_01': AppInfo('test', None),
        }

        result = controller.filterUpdatedApps(currentVersionsDict,
                                              latestVersionsDict)

        self.assertEqual(result, {})

    def test_filter_empty_04(self):
        from updatenotifier.updatecontroller import UpdateController

        plugin = self.loader['UpdateNotifier']
        controller = UpdateController(self.application, plugin)

        latestVersion = Version(1, 0)
        latestVersionInfo = VersionInfo(latestVersion)

        currentVersionsDict = {}
        latestVersionsDict = {
            'test_01': AppInfo('test', None, versionsList=[latestVersionInfo]),
        }

        result = controller.filterUpdatedApps(currentVersionsDict,
                                              latestVersionsDict)

        self.assertEqual(result, {})

    def test_filter_empty_05(self):
        from updatenotifier.updatecontroller import UpdateController

        plugin = self.loader['UpdateNotifier']
        controller = UpdateController(self.application, plugin)

        latestVersion = Version(1, 0)
        latestVersionInfo = VersionInfo(latestVersion)

        currentVersionsDict = {'test_02': '1.0'}
        latestVersionsDict = {
            'test_01': AppInfo('test', None, versionsList=[latestVersionInfo]),
        }

        result = controller.filterUpdatedApps(currentVersionsDict,
                                              latestVersionsDict)

        self.assertEqual(result, {})

    def test_filter_empty_06(self):
        from updatenotifier.updatecontroller import UpdateController

        plugin = self.loader['UpdateNotifier']
        controller = UpdateController(self.application, plugin)

        latestVersion = Version(1, 0)
        latestVersionInfo = VersionInfo(latestVersion)

        currentVersionsDict = {'test_01': '1.0'}
        latestVersionsDict = {
            'test_01': AppInfo('test', None, versionsList=[latestVersionInfo]),
        }

        result = controller.filterUpdatedApps(currentVersionsDict,
                                              latestVersionsDict)

        self.assertEqual(result, {})

    def test_filter_07(self):
        from updatenotifier.updatecontroller import UpdateController

        plugin = self.loader['UpdateNotifier']
        controller = UpdateController(self.application, plugin)

        latestVersion = Version(1, 1)
        latestVersionInfo = VersionInfo(latestVersion)

        currentVersionsDict = {'test_01': '1.0'}
        latestVersionsDict = {
            'test_01': AppInfo('test', None, versionsList=[latestVersionInfo]),
        }

        result = controller.filterUpdatedApps(currentVersionsDict,
                                              latestVersionsDict)

        self.assertEqual(len(result), 1)
        self.assertEqual(result['test_01'].appname, 'test')

    def test_filter_empty_08(self):
        from updatenotifier.updatecontroller import UpdateController

        plugin = self.loader['UpdateNotifier']
        controller = UpdateController(self.application, plugin)

        latestVersion = Version(0, 9)
        latestVersionInfo = VersionInfo(latestVersion)

        currentVersionsDict = {'test_01': '1.0'}
        latestVersionsDict = {
            'test_01': AppInfo('test', None, versionsList=[latestVersionInfo]),
        }

        result = controller.filterUpdatedApps(currentVersionsDict,
                                              latestVersionsDict)

        self.assertEqual(result, {})

    def test_filter_09(self):
        from updatenotifier.updatecontroller import UpdateController

        plugin = self.loader['UpdateNotifier']
        controller = UpdateController(self.application, plugin)

        latestVersion = Version(1, 1)
        latestVersionInfo = VersionInfo(latestVersion)

        currentVersionsDict = {
            'test_01': '1.0',
            'test_02': '2.0',
        }

        latestVersionsDict = {
            'test_01': AppInfo('test', None, versionsList=[latestVersionInfo]),
        }

        result = controller.filterUpdatedApps(currentVersionsDict,
                                              latestVersionsDict)

        self.assertEqual(len(result), 1)
        self.assertEqual(result['test_01'].appname, 'test')
Пример #26
0
class UpdateControllerTest(unittest.TestCase, BaseOutWikerGUIMixin):
    """Tests for the UpdateNotifier plugin."""

    def setUp(self):
        self.initApplication()
        self.loader = PluginsLoader(self.application)
        self.loader.load(["../plugins/updatenotifier"])

    def tearDown(self):
        self.loader.clear()
        self.destroyApplication()

    def test_filter_empty_01(self):
        from updatenotifier.updatecontroller import UpdateController

        plugin = self.loader['UpdateNotifier']
        controller = UpdateController(self.application, plugin)

        currentVersionsDict = {}
        latestVersionsDict = {}

        result = controller.filterUpdatedApps(currentVersionsDict,
                                              latestVersionsDict)

        self.assertEqual(result, {})

    def test_filter_empty_02(self):
        from updatenotifier.updatecontroller import UpdateController

        plugin = self.loader['UpdateNotifier']
        controller = UpdateController(self.application, plugin)

        currentVersionsDict = {'test_01': '0.1'}
        latestVersionsDict = {}

        result = controller.filterUpdatedApps(currentVersionsDict,
                                              latestVersionsDict)

        self.assertEqual(result, {})

    def test_filter_empty_03(self):
        from updatenotifier.updatecontroller import UpdateController

        plugin = self.loader['UpdateNotifier']
        controller = UpdateController(self.application, plugin)

        currentVersionsDict = {}
        latestVersionsDict = {
            'test_01': AppInfo('test', None),
        }

        result = controller.filterUpdatedApps(currentVersionsDict,
                                              latestVersionsDict)

        self.assertEqual(result, {})

    def test_filter_empty_04(self):
        from updatenotifier.updatecontroller import UpdateController

        plugin = self.loader['UpdateNotifier']
        controller = UpdateController(self.application, plugin)

        latestVersion = Version(1, 0)
        latestVersionInfo = VersionInfo(latestVersion)

        currentVersionsDict = {}
        latestVersionsDict = {
            'test_01': AppInfo('test',
                               None,
                               versionsList=[latestVersionInfo]),
        }

        result = controller.filterUpdatedApps(currentVersionsDict,
                                              latestVersionsDict)

        self.assertEqual(result, {})

    def test_filter_empty_05(self):
        from updatenotifier.updatecontroller import UpdateController

        plugin = self.loader['UpdateNotifier']
        controller = UpdateController(self.application, plugin)

        latestVersion = Version(1, 0)
        latestVersionInfo = VersionInfo(latestVersion)

        currentVersionsDict = {'test_02': '1.0'}
        latestVersionsDict = {
            'test_01': AppInfo('test',
                               None,
                               versionsList=[latestVersionInfo]),
        }

        result = controller.filterUpdatedApps(currentVersionsDict,
                                              latestVersionsDict)

        self.assertEqual(result, {})

    def test_filter_empty_06(self):
        from updatenotifier.updatecontroller import UpdateController

        plugin = self.loader['UpdateNotifier']
        controller = UpdateController(self.application, plugin)

        latestVersion = Version(1, 0)
        latestVersionInfo = VersionInfo(latestVersion)

        currentVersionsDict = {'test_01': '1.0'}
        latestVersionsDict = {
            'test_01': AppInfo('test',
                               None,
                               versionsList=[latestVersionInfo]),
        }

        result = controller.filterUpdatedApps(currentVersionsDict,
                                              latestVersionsDict)

        self.assertEqual(result, {})

    def test_filter_07(self):
        from updatenotifier.updatecontroller import UpdateController

        plugin = self.loader['UpdateNotifier']
        controller = UpdateController(self.application, plugin)

        latestVersion = Version(1, 1)
        latestVersionInfo = VersionInfo(latestVersion)

        currentVersionsDict = {'test_01': '1.0'}
        latestVersionsDict = {
            'test_01': AppInfo('test',
                               None,
                               versionsList=[latestVersionInfo]),
        }

        result = controller.filterUpdatedApps(currentVersionsDict,
                                              latestVersionsDict)

        self.assertEqual(len(result), 1)
        self.assertEqual(result['test_01'].appname, 'test')

    def test_filter_empty_08(self):
        from updatenotifier.updatecontroller import UpdateController

        plugin = self.loader['UpdateNotifier']
        controller = UpdateController(self.application, plugin)

        latestVersion = Version(0, 9)
        latestVersionInfo = VersionInfo(latestVersion)

        currentVersionsDict = {'test_01': '1.0'}
        latestVersionsDict = {
            'test_01': AppInfo('test',
                               None,
                               versionsList=[latestVersionInfo]),
        }

        result = controller.filterUpdatedApps(currentVersionsDict,
                                              latestVersionsDict)

        self.assertEqual(result, {})

    def test_filter_09(self):
        from updatenotifier.updatecontroller import UpdateController

        plugin = self.loader['UpdateNotifier']
        controller = UpdateController(self.application, plugin)

        latestVersion = Version(1, 1)
        latestVersionInfo = VersionInfo(latestVersion)

        currentVersionsDict = {'test_01': '1.0',
                               'test_02': '2.0',
                               }

        latestVersionsDict = {
            'test_01': AppInfo('test',
                               None,
                               versionsList=[latestVersionInfo]),
        }

        result = controller.filterUpdatedApps(currentVersionsDict,
                                              latestVersionsDict)

        self.assertEqual(len(result), 1)
        self.assertEqual(result['test_01'].appname, 'test')
Пример #27
0
class CommandExecTest(unittest.TestCase):
    def setUp(self):
        self.maxDiff = None

        self.__createWiki()
        self.testPage = self.wikiroot['Страница 1']

        dirlist = ['../plugins/externaltools']

        self.loader = PluginsLoader(Application)
        self.loader.load(dirlist)

        self.factory = ParserFactory()
        self.parser = self.factory.make(self.testPage, Application.config)

    def __createWiki(self):
        # Здесь будет создаваться вики
        self.path = mkdtemp(prefix='Абырвалг абыр')
        self.wikiroot = WikiDocument.create(self.path)
        WikiPageFactory().create(self.wikiroot, 'Страница 1', [])

    def tearDown(self):
        removeDir(self.path)
        self.loader.clear()

    def testPluginLoad(self):
        self.assertEqual(len(self.loader), 1)

    def testEmpty(self):
        text = '(:exec:)(:execend:)'
        validResult = ''

        result = self.parser.toHtml(text)
        self.assertEqual(result, validResult)

    def testLinkSimple_01(self):
        text = '''(:exec:)gvim(:execend:)'''

        # <a href="exec://exec/?com1=gvim&title=gvim">gvim</a>
        result = self.parser.toHtml(text)
        self.assertIn('href="exec://exec/?', result)
        self.assertIn('com1=gvim', result)
        self.assertIn('title=gvim', result)
        self.assertIn('>gvim</a>', result)

    def testLinkSimple_02(self):
        text = '''(:exec:)

        gvim

(:execend:)'''

        # <a href="exec://exec/?com1=gvim&title=gvim">gvim</a>
        result = self.parser.toHtml(text)

        self.assertIn('href="exec://exec/?', result)
        self.assertIn('com1=gvim', result)
        self.assertIn('title=gvim', result)
        self.assertIn('>gvim</a>', result)

    def testLinkSimple_03(self):
        text = '''(:exec:)
gvim -d "Первый файл.txt" "Второй файл.txt"
(:execend:)'''
        # <a href="exec://exec/?com1=gvim&com1=-d&com1=%D0%9F%D0%B5%D1%80%D0%B2%D1%8B%D0%B9+%D1%84%D0%B0%D0%B9%D0%BB.txt&com1=%D0%92%D1%82%D0%BE%D1%80%D0%BE%D0%B9+%D1%84%D0%B0%D0%B9%D0%BB.txt&title=gvim">gvim</a>

        result = self.parser.toHtml(text)

        self.assertIn('href="exec://exec/?', result)
        self.assertIn(
            'com1=gvim&com1=-d&com1=%D0%9F%D0%B5%D1%80%D0%B2%D1%8B%D0%B9+%D1%84%D0%B0%D0%B9%D0%BB.txt&com1=%D0%92%D1%82%D0%BE%D1%80%D0%BE%D0%B9+%D1%84%D0%B0%D0%B9%D0%BB.txt',
            result)
        self.assertIn('title=gvim', result)
        self.assertIn('>gvim</a>', result)

    def testLinkTitle_01(self):
        text = '''(:exec title="Запуск gvim":)gvim(:execend:)'''

        # <a href="exec://exec/?com1=gvim&title=%D0%97%D0%B0%D0%BF%D1%83%D1%81%D0%BA">Запуск gvim</a>
        result = self.parser.toHtml(text)
        self.assertIn('href="exec://exec/?', result)
        self.assertIn('com1=gvim', result)
        self.assertIn('title=%D0%97%D0%B0%D0%BF%D1%83%D1%81%D0%BA', result)
        self.assertIn('>Запуск gvim</a>', result)

    def testButton_01(self):
        text = '''(:exec format="button":)gvim(:execend:)'''

        # exec://exec/?com1=gvim&title=gvim
        result = self.parser.toHtml(text)
        self.assertIn('location.href="exec://exec/?', result)
        self.assertIn('com1=gvim', result)
        self.assertIn('title=gvim', result)
        self.assertIn('<button', result)
        self.assertIn('>gvim</button>', result)

    def testButton_02(self):
        text = '''(:exec format="button" title="Запуск":)gvim(:execend:)'''

        result = self.parser.toHtml(text)
        self.assertIn('location.href="exec://exec/?', result)
        self.assertIn('com1=gvim', result)
        self.assertIn('<button', result)
        self.assertIn('>Запуск</button>', result)
Пример #28
0
class LightboxPluginTest(unittest.TestCase):
    def setUp(self):
        self.encoding = "utf8"

        self.__createWiki()

        dirlist = ["../plugins/lightbox"]

        self.loader = PluginsLoader(Application)
        self.loader.load(dirlist)

        self.factory = ParserFactory()
        self.parser = self.factory.make(self.testPage, Application.config)

    def __createWiki(self):
        # Здесь будет создаваться вики
        self.path = mkdtemp(prefix='Абырвалг абыр')

        self.wikiroot = WikiDocument.create(self.path)

        WikiPageFactory().create(self.wikiroot, "Страница 1", [])
        self.testPage = self.wikiroot["Страница 1"]

    def tearDown(self):
        removeDir(self.path)
        self.loader.clear()

    def testPluginLoad(self):
        self.assertEqual(len(self.loader), 1)

    def testContentParse1(self):
        text = """Бла-бла-бла (:lightbox:) бла-бла-бла"""

        validResult = """$("a[href$='.jpg']"""

        result = self.parser.toHtml(text)
        self.assertTrue(validResult in result)

    def testHeaders(self):
        text = """Бла-бла-бла (:lightbox:) бла-бла-бла"""

        self.parser.toHtml(text)

        self.assertTrue(
            '<script type="text/javascript" src="./__attach/__thumb/jquery-1.7.2.min.js"></script>'
            in self.parser.head)

        self.assertTrue(
            '<link rel="stylesheet" href="./__attach/__thumb/jquery.fancybox.css" type="text/css" media="screen" />'
            in self.parser.head)

        self.assertTrue(
            '<script type="text/javascript" src="./__attach/__thumb/jquery.fancybox.pack.js"></script>'
            in self.parser.head)

    def testSingleHeaders(self):
        """
        Проверка, что заголовки добавляются только один раз
        """
        text = """Бла-бла-бла (:lightbox:) бла-бла-бла (:lightbox:)"""

        self.parser.toHtml(text)

        header = '<script type="text/javascript" src="./__attach/__thumb/jquery-1.7.2.min.js"></script>'

        posfirst = self.parser.head.find(header)
        poslast = self.parser.head.rfind(header)

        self.assertEqual(posfirst, poslast)

    def testFiles(self):
        text = """Бла-бла-бла (:lightbox:) бла-бла-бла"""

        self.parser.toHtml(text)

        dirname = "__attach/__thumb"
        files = [
            "jquery.fancybox.css", "blank.gif", "fancybox_loading.gif",
            "jquery-1.7.2.min.js", "jquery.fancybox.pack.js",
            "fancybox_sprite.png"
        ]

        for fname in files:
            fullpath = os.path.join(self.testPage.path, dirname, fname)
            self.assertTrue(os.path.exists(fullpath))
Пример #29
0
class SourceAttachmentPluginTest (unittest.TestCase):
    """
    Тесты интерфейса для плагина Source
    """

    def setUp(self):
        self.__pluginname = u"Source"

        self.__createWiki()

        dirlist = [u"../plugins/source"]

        self.loader = PluginsLoader(Application)
        self.loader.load(dirlist)

        self.config = self.loader[self.__pluginname].config
        self.config.tabWidth.value = 4
        self.config.defaultLanguage.remove_option()
        Application.config.remove_section(self.config.section)

        from source.insertdialogcontroller import InsertDialogController
        self.dialog = FakeInsertDialog ()
        self.controller = InsertDialogController (self.testPage, self.dialog, self.config)


    def __createWiki (self):
        # Здесь будет создаваться вики
        self.path = mkdtemp (prefix=u'Абырвалг абыр')

        self.wikiroot = WikiDocument.create (self.path)

        WikiPageFactory().create (self.wikiroot, u"Страница 1", [])
        self.testPage = self.wikiroot[u"Страница 1"]


    def tearDown(self):
        removeDir (self.path)
        Application.config.remove_section (self.config.section)
        self.loader.clear()


    def testAttachment1 (self):
        self.controller.showDialog()

        self.assertEqual (self.dialog.attachmentComboBox.GetCount(), 0)


    def testAttachment2 (self):
        # Путь, где лежат примеры исходников в разных кодировках
        self.samplefilesPath = u"../test/samplefiles/sources"
        Attachment(self.testPage).attach ([os.path.join (self.samplefilesPath, u"source_utf8.py")])
        Attachment(self.testPage).attach ([os.path.join (self.samplefilesPath, u"source_cp1251.cs")])

        self.controller.showDialog()

        self.assertEqual (self.dialog.attachmentComboBox.GetSelection(), 0)
        self.assertEqual (self.dialog.attachmentComboBox.GetCount(), 2)
        self.assertEqual (self.dialog.attachmentComboBox.GetItems(),
                          [u"source_cp1251.cs", u"source_utf8.py"])


    def testAttachment3 (self):
        # Путь, где лежат примеры исходников в разных кодировках
        self.samplefilesPath = u"../test/samplefiles/sources"
        Attachment(self.testPage).attach ([os.path.join (self.samplefilesPath, u"source_utf8.py")])
        Attachment(self.testPage).attach ([os.path.join (self.samplefilesPath, u"source_cp1251.cs")])

        self.controller.showDialog()

        self.dialog.fileCheckBox.SetValue(True)
        self.controller.updateFileChecked()

        self.dialog.attachmentComboBox.SetSelection (0)
        self.dialog.encodingComboBox.SetSelection (0)

        result = self.controller.getCommandStrings()

        self.assertEqual (result, (u'(:source file="Attach:source_cp1251.cs":)', u'(:sourceend:)'))


    def testAttachment4 (self):
        # Путь, где лежат примеры исходников в разных кодировках
        self.samplefilesPath = u"../test/samplefiles/sources"
        Attachment(self.testPage).attach ([os.path.join (self.samplefilesPath, u"source_utf8.py")])
        Attachment(self.testPage).attach ([os.path.join (self.samplefilesPath, u"source_cp1251.cs")])

        self.controller.showDialog()

        self.dialog.fileCheckBox.SetValue(True)
        self.controller.updateFileChecked()

        self.dialog.attachmentComboBox.SetSelection (1)
        self.dialog.encodingComboBox.SetSelection (0)

        result = self.controller.getCommandStrings()

        self.assertEqual (result, (u'(:source file="Attach:source_utf8.py":)', u'(:sourceend:)'))


    def testAttachment5 (self):
        # Путь, где лежат примеры исходников в разных кодировках
        self.samplefilesPath = u"../test/samplefiles/sources"
        Attachment(self.testPage).attach ([os.path.join (self.samplefilesPath, u"source_utf8.py")])
        Attachment(self.testPage).attach ([os.path.join (self.samplefilesPath, u"source_cp1251.cs")])

        self.controller.showDialog()

        self.dialog.fileCheckBox.SetValue(True)
        self.controller.updateFileChecked()

        self.dialog.attachmentComboBox.SetSelection (0)
        self.dialog.encodingComboBox.SetSelection (2)

        result = self.controller.getCommandStrings()

        self.assertEqual (result, (u'(:source file="Attach:source_cp1251.cs" encoding="cp1251":)', u'(:sourceend:)'))


    def testAttachment6 (self):
        # Путь, где лежат примеры исходников в разных кодировках
        self.samplefilesPath = u"../test/samplefiles/sources"
        Attachment(self.testPage).attach ([os.path.join (self.samplefilesPath, u"source_utf8.py")])
        Attachment(self.testPage).attach ([os.path.join (self.samplefilesPath, u"source_cp1251.cs")])

        self.config.languageList.value = [u"cpp", u"csharp", u"haskell"]

        self.controller.showDialog()

        self.dialog.fileCheckBox.SetValue(True)

        # Т.к. при изменении состояния флажка события не возникают,
        # Вручную обновим список языков
        self.controller.loadLanguagesState()

        self.dialog.attachmentComboBox.SetSelection (0)
        self.dialog.encodingComboBox.SetSelection (2)
        self.dialog.languageComboBox.SetSelection (3)

        result = self.controller.getCommandStrings()

        self.assertEqual (result, (u'(:source file="Attach:source_cp1251.cs" encoding="cp1251" lang="haskell":)', u'(:sourceend:)'))


    def testAttachment7 (self):
        # Путь, где лежат примеры исходников в разных кодировках
        self.samplefilesPath = u"../test/samplefiles/sources"
        Attachment(self.testPage).attach ([os.path.join (self.samplefilesPath, u"source_utf8.py")])
        Attachment(self.testPage).attach ([os.path.join (self.samplefilesPath, u"source_cp1251.cs")])

        self.config.languageList.value = [u"cpp", u"haskell", u"csharp"]

        self.controller.showDialog()

        self.dialog.fileCheckBox.SetValue(True)
        self.dialog.attachmentComboBox.SetSelection (0)
        self.dialog.encodingComboBox.SetSelection (2)
        self.dialog.languageComboBox.SetSelection (0)

        result = self.controller.getCommandStrings()

        self.assertEqual (result, (u'(:source file="Attach:source_cp1251.cs" encoding="cp1251":)', u'(:sourceend:)'))


    def testAttachment8 (self):
        # Путь, где лежат примеры исходников в разных кодировках
        self.samplefilesPath = u"../test/samplefiles/sources"
        Attachment(self.testPage).attach ([os.path.join (self.samplefilesPath, u"source_utf8.py")])
        Attachment(self.testPage).attach ([os.path.join (self.samplefilesPath, u"source_cp1251.cs")])

        self.config.languageList.value = [u"cpp", u"csharp", u"haskell"]

        self.controller.showDialog()

        self.dialog.fileCheckBox.SetValue(True)

        # Т.к. при изменении состояния флажка события не возникают,
        # Вручную обновим список языков
        self.controller.loadLanguagesState()

        self.dialog.attachmentComboBox.SetSelection (0)
        self.dialog.encodingComboBox.SetSelection (0)
        self.dialog.languageComboBox.SetSelection (2)

        result = self.controller.getCommandStrings()

        self.assertEqual (result, (u'(:source file="Attach:source_cp1251.cs" lang="csharp":)', u'(:sourceend:)'))


    def testAttachment9 (self):
        # Путь, где лежат примеры исходников в разных кодировках
        self.samplefilesPath = u"../test/samplefiles/sources"
        Attachment(self.testPage).attach ([os.path.join (self.samplefilesPath, u"source_utf8.py")])
        Attachment(self.testPage).attach ([os.path.join (self.samplefilesPath, u"source_cp1251.cs")])

        self.config.languageList.value = [u"cpp", u"csharp", u"haskell"]

        self.controller.showDialog()

        self.dialog.fileCheckBox.SetValue(True)

        # Т.к. при изменении состояния флажка события не возникают,
        # Вручную обновим список языков
        self.controller.loadLanguagesState()

        self.dialog.attachmentComboBox.SetSelection (0)
        self.dialog.encodingComboBox.SetSelection (0)
        self.dialog.languageComboBox.SetSelection (2)
        self.dialog.tabWidthSpin.SetValue (10)

        result = self.controller.getCommandStrings()

        self.assertEqual (result, (u'(:source file="Attach:source_cp1251.cs" lang="csharp" tabwidth="10":)', u'(:sourceend:)'))
Пример #30
0
class PageStatisticsTest(unittest.TestCase, BaseOutWikerGUIMixin):
    """Тесты плагина Statistics применительно к статистике страницы"""
    def setUp(self):
        self.__pluginname = "Statistics"
        self.initApplication()
        self.wikiroot = self.createWiki()

        dirlist = ["plugins/statistics"]

        self.loader = PluginsLoader(self.application)
        self.loader.load(dirlist)

        filesPath = "testdata/samplefiles/"
        self.files = ["accept.png", "add.png", "anchor.png", "dir"]
        self.fullFilesPath = [
            os.path.join(filesPath, fname) for fname in self.files
        ]

    def tearDown(self):
        self.loader.clear()
        self.destroyApplication()
        self.destroyWiki(self.wikiroot)

    def testPluginLoad(self):
        self.assertEqual(len(self.loader), 1)

    def testSymbolsCountWiki(self):
        from statistics.pagestat import PageStat

        WikiPageFactory().create(self.wikiroot, "Страница 1", [])
        testPage = self.wikiroot["Страница 1"]

        testPage.content = "Бла бла бла"
        pageStat = PageStat(testPage)

        self.assertEqual(pageStat.symbols, 11)

    def testSymbolsCountHtml(self):
        from statistics.pagestat import PageStat

        HtmlPageFactory().create(self.wikiroot, "Страница 1", [])
        testPage = self.wikiroot["Страница 1"]

        testPage.content = "Бла бла бла"
        pageStat = PageStat(testPage)

        self.assertEqual(pageStat.symbols, 11)

    def testSymbolsCountText(self):
        from statistics.pagestat import PageStat

        TextPageFactory().create(self.wikiroot, "Страница 1", [])
        testPage = self.wikiroot["Страница 1"]

        testPage.content = "Бла бла бла"
        pageStat = PageStat(testPage)

        self.assertEqual(pageStat.symbols, 11)

    def testSymbolsCountSearch(self):
        def runTest():
            from statistics.pagestat import PageStat

            SearchPageFactory().create(self.wikiroot, "Страница 1", [])
            testPage = self.wikiroot["Страница 1"]

            pageStat = PageStat(testPage)
            pageStat.symbols

        self.assertRaises(TypeError, runTest)

    def testSymbolsNotWhiteSpacesWiki(self):
        from statistics.pagestat import PageStat

        WikiPageFactory().create(self.wikiroot, "Страница 1", [])
        testPage = self.wikiroot["Страница 1"]

        testPage.content = "Бла бла бла\r\n\t\t\tАбырвалг  "
        pageStat = PageStat(testPage)

        self.assertEqual(pageStat.symbolsNotWhiteSpaces, 17)

    def testSymbolsNotWhiteSpacesHtml(self):
        from statistics.pagestat import PageStat

        HtmlPageFactory().create(self.wikiroot, "Страница 1", [])
        testPage = self.wikiroot["Страница 1"]

        testPage.content = "Бла бла бла\r\n\t\t\tАбырвалг  "
        pageStat = PageStat(testPage)

        self.assertEqual(pageStat.symbolsNotWhiteSpaces, 17)

    def testSymbolsNotWhiteSpacesText(self):
        from statistics.pagestat import PageStat

        TextPageFactory().create(self.wikiroot, "Страница 1", [])
        testPage = self.wikiroot["Страница 1"]

        testPage.content = "Бла бла бла\r\n\t\t\tАбырвалг  "
        pageStat = PageStat(testPage)

        self.assertEqual(pageStat.symbolsNotWhiteSpaces, 17)

    def testSymbolsNotWhiteSpacesSearch(self):
        def runTest():
            from statistics.pagestat import PageStat

            SearchPageFactory().create(self.wikiroot, "Страница 1", [])
            testPage = self.wikiroot["Страница 1"]

            pageStat = PageStat(testPage)
            pageStat.symbolsNotWhiteSpaces

        self.assertRaises(TypeError, runTest)

    def testLinesWiki1(self):
        from statistics.pagestat import PageStat

        WikiPageFactory().create(self.wikiroot, "Страница 1", [])
        testPage = self.wikiroot["Страница 1"]

        testPage.content = """Бла бла бла
Еще одна строка
И еще строка
Последняя строка"""

        pageStat = PageStat(testPage)

        self.assertEqual(pageStat.lines, 4)

    def testLinesWiki2(self):
        from statistics.pagestat import PageStat

        WikiPageFactory().create(self.wikiroot, "Страница 1", [])
        testPage = self.wikiroot["Страница 1"]

        testPage.content = """Бла бла бла
Еще одна строка

И еще строка

Последняя строка

"""

        pageStat = PageStat(testPage)

        self.assertEqual(pageStat.lines, 4)

    def testLinesHtml1(self):
        from statistics.pagestat import PageStat

        HtmlPageFactory().create(self.wikiroot, "Страница 1", [])
        testPage = self.wikiroot["Страница 1"]

        testPage.content = """Бла бла бла
Еще одна строка
И еще строка
Последняя строка"""

        pageStat = PageStat(testPage)

        self.assertEqual(pageStat.lines, 4)

    def testLinesHtml2(self):
        from statistics.pagestat import PageStat

        HtmlPageFactory().create(self.wikiroot, "Страница 1", [])
        testPage = self.wikiroot["Страница 1"]

        testPage.content = """Бла бла бла
Еще одна строка

И еще строка

Последняя строка

"""

        pageStat = PageStat(testPage)

        self.assertEqual(pageStat.lines, 4)

    def testLinesText1(self):
        from statistics.pagestat import PageStat

        TextPageFactory().create(self.wikiroot, "Страница 1", [])
        testPage = self.wikiroot["Страница 1"]

        testPage.content = """Бла бла бла
Еще одна строка
И еще строка
Последняя строка"""

        pageStat = PageStat(testPage)

        self.assertEqual(pageStat.lines, 4)

    def testLinesText2(self):
        from statistics.pagestat import PageStat

        TextPageFactory().create(self.wikiroot, "Страница 1", [])
        testPage = self.wikiroot["Страница 1"]

        testPage.content = """Бла бла бла
Еще одна строка

И еще строка

Последняя строка

"""

        pageStat = PageStat(testPage)

        self.assertEqual(pageStat.lines, 4)

    def testWordsWiki1(self):
        from statistics.pagestat import PageStat

        WikiPageFactory().create(self.wikiroot, "Страница 1", [])
        testPage = self.wikiroot["Страница 1"]

        testPage.content = """Бла бла бла
Еще одна строка

И еще строка

Последняя строка

"""

        pageStat = PageStat(testPage)

        self.assertEqual(pageStat.words, 11)

    def testWordsWiki2(self):
        from statistics.pagestat import PageStat

        WikiPageFactory().create(self.wikiroot, "Страница 1", [])
        testPage = self.wikiroot["Страница 1"]

        testPage.content = """Бла бла бла.
Еще одна строка111 222 333

И еще строка ... ... ;;; @#$%#$

Последняя строка

"""

        pageStat = PageStat(testPage)

        self.assertEqual(pageStat.words, 13)

    def testWordsHtml1(self):
        from statistics.pagestat import PageStat

        HtmlPageFactory().create(self.wikiroot, "Страница 1", [])
        testPage = self.wikiroot["Страница 1"]

        testPage.content = """Бла бла бла
Еще одна строка

И еще строка

Последняя строка

"""

        pageStat = PageStat(testPage)

        self.assertEqual(pageStat.words, 11)

    def testWordsHtml2(self):
        from statistics.pagestat import PageStat

        HtmlPageFactory().create(self.wikiroot, "Страница 1", [])
        testPage = self.wikiroot["Страница 1"]

        testPage.content = """Бла бла бла.
Еще одна строка111 222 333

И еще строка ... ... ;;; @#$%#$

Последняя строка

"""

        pageStat = PageStat(testPage)

        self.assertEqual(pageStat.words, 13)

    def testWordsText1(self):
        from statistics.pagestat import PageStat

        TextPageFactory().create(self.wikiroot, "Страница 1", [])
        testPage = self.wikiroot["Страница 1"]

        testPage.content = """Бла бла бла
Еще одна строка

И еще строка

Последняя строка

"""

        pageStat = PageStat(testPage)

        self.assertEqual(pageStat.words, 11)

    def testWordsText2(self):
        from statistics.pagestat import PageStat

        TextPageFactory().create(self.wikiroot, "Страница 1", [])
        testPage = self.wikiroot["Страница 1"]

        testPage.content = """Бла бла бла.
Еще одна строка111 222 333

И еще строка ... ... ;;; @#$%#$

Последняя строка

"""

        pageStat = PageStat(testPage)

        self.assertEqual(pageStat.words, 13)

    def testWordsSearch(self):
        def runTest():
            from statistics.pagestat import PageStat

            SearchPageFactory().create(self.wikiroot, "Страница 1", [])
            testPage = self.wikiroot["Страница 1"]

            pageStat = PageStat(testPage)
            pageStat.words

        self.assertRaises(TypeError, runTest)

    def testAttachmentsCountWiki1(self):
        from statistics.pagestat import PageStat

        WikiPageFactory().create(self.wikiroot, "Страница 1", [])
        testPage = self.wikiroot["Страница 1"]

        pageStat = PageStat(testPage)

        self.assertEqual(pageStat.attachmentsCount, 0)

    def testAttachmentsCountWiki2(self):
        from statistics.pagestat import PageStat

        WikiPageFactory().create(self.wikiroot, "Страница 1", [])
        testPage = self.wikiroot["Страница 1"]
        Attachment(testPage).attach(self.fullFilesPath[0:1])

        pageStat = PageStat(testPage)

        self.assertEqual(pageStat.attachmentsCount, 1)

    def testAttachmentsCountWiki3(self):
        from statistics.pagestat import PageStat

        WikiPageFactory().create(self.wikiroot, "Страница 1", [])
        testPage = self.wikiroot["Страница 1"]
        Attachment(testPage).attach(self.fullFilesPath[0:3])

        pageStat = PageStat(testPage)

        self.assertEqual(pageStat.attachmentsCount, 3)

    def testAttachmentsCountWiki4(self):
        from statistics.pagestat import PageStat

        WikiPageFactory().create(self.wikiroot, "Страница 1", [])
        testPage = self.wikiroot["Страница 1"]
        Attachment(testPage).attach(self.fullFilesPath)

        pageStat = PageStat(testPage)

        self.assertEqual(pageStat.attachmentsCount, 6)

    def testAttachmentsCountSearch1(self):
        from statistics.pagestat import PageStat

        SearchPageFactory().create(self.wikiroot, "Страница 1", [])
        testPage = self.wikiroot["Страница 1"]
        Attachment(testPage).attach(self.fullFilesPath)

        pageStat = PageStat(testPage)

        self.assertEqual(pageStat.attachmentsCount, 6)

    def testAttachmentsSizeWiki1(self):
        from statistics.pagestat import PageStat

        WikiPageFactory().create(self.wikiroot, "Страница 1", [])
        testPage = self.wikiroot["Страница 1"]

        pageStat = PageStat(testPage)

        self.assertEqual(pageStat.attachmentsSize, 0)

    def testAttachmentsSizeWiki2(self):
        from statistics.pagestat import PageStat

        WikiPageFactory().create(self.wikiroot, "Страница 1", [])
        testPage = self.wikiroot["Страница 1"]
        Attachment(testPage).attach(self.fullFilesPath[0:1])

        pageStat = PageStat(testPage)

        self.assertEqual(pageStat.attachmentsSize, 781)

    def testAttachmentsSizeWiki3(self):
        from statistics.pagestat import PageStat

        WikiPageFactory().create(self.wikiroot, "Страница 1", [])
        testPage = self.wikiroot["Страница 1"]
        Attachment(testPage).attach(self.fullFilesPath[0:3])

        pageStat = PageStat(testPage)

        self.assertEqual(pageStat.attachmentsSize, 2037)

    def testAttachmentsSizeWiki4(self):
        from statistics.pagestat import PageStat

        WikiPageFactory().create(self.wikiroot, "Страница 1", [])
        testPage = self.wikiroot["Страница 1"]
        Attachment(testPage).attach(self.fullFilesPath)

        pageStat = PageStat(testPage)

        self.assertAlmostEqual(pageStat.attachmentsSize, 11771, delta=300)

    def testAttachmentsSizeSearch1(self):
        from statistics.pagestat import PageStat

        SearchPageFactory().create(self.wikiroot, "Страница 1", [])
        testPage = self.wikiroot["Страница 1"]
        Attachment(testPage).attach(self.fullFilesPath)

        pageStat = PageStat(testPage)

        self.assertAlmostEqual(pageStat.attachmentsSize, 11771, delta=300)
Пример #31
0
class SourceFilePluginTest(unittest.TestCase):
    """
    Тесты на работу с раскраской прикрепленных файлов
    """

    def setUp(self):
        self.__pluginname = u"Source"

        self.__createWiki()

        dirlist = [u"../plugins/source"]

        # Путь, где лежат примеры исходников в разных кодировках
        self.samplefilesPath = u"../test/samplefiles/sources"

        self.loader = PluginsLoader(Application)
        self.loader.load(dirlist)

        self.config = self.loader[self.__pluginname].config
        self.config.tabWidth.value = 4
        self.config.defaultLanguage.remove_option()

        self.factory = ParserFactory()
        self.parser = self.factory.make(self.testPage, Application.config)

    def __readFile(self, path):
        with open(path) as fp:
            result = unicode(fp.read(), "utf8")

        return result

    def __createWiki(self):
        # Здесь будет создаваться вики
        self.path = u"../test/testwiki"
        removeWiki(self.path)

        self.rootwiki = WikiDocument.create(self.path)

        WikiPageFactory.create(self.rootwiki, u"Страница 1", [])
        self.testPage = self.rootwiki[u"Страница 1"]

    def tearDown(self):
        removeWiki(self.path)
        self.loader.clear()

    def testHighlightFile1(self):
        Attachment(self.testPage).attach([os.path.join(self.samplefilesPath, u"source_utf8.py")])
        content = u'(:source file="source_utf8.py" lang="text":)'
        self.testPage.content = content

        generator = HtmlGenerator(self.testPage)
        htmlpath = generator.makeHtml(Style().getPageStyle(self.testPage))
        result = self.__readFile(htmlpath)

        self.assertTrue(u"__correctSysPath()" in result)
        self.assertTrue(u"Плагин, добавляющий обработку команды (:source:) в википарсер" in result)

    def testHighlightFile2(self):
        Attachment(self.testPage).attach([os.path.join(self.samplefilesPath, u"source_utf8.py")])
        content = u'(:source file="Attach:source_utf8.py" lang="text":)'
        self.testPage.content = content

        generator = HtmlGenerator(self.testPage)
        htmlpath = generator.makeHtml(Style().getPageStyle(self.testPage))
        result = self.__readFile(htmlpath)

        self.assertTrue(u"__correctSysPath()" in result)
        self.assertTrue(u"Плагин, добавляющий обработку команды (:source:) в википарсер" in result)

    def testHighlightFile3(self):
        Attachment(self.testPage).attach([os.path.join(self.samplefilesPath, u"source_utf8.py")])
        content = u'(:source file="  source_utf8.py  " lang="text":)'
        self.testPage.content = content

        generator = HtmlGenerator(self.testPage)
        htmlpath = generator.makeHtml(Style().getPageStyle(self.testPage))
        result = self.__readFile(htmlpath)

        self.assertTrue(u"__correctSysPath()" in result)
        self.assertTrue(u"Плагин, добавляющий обработку команды (:source:) в википарсер" in result)

    def testHighlightFile4(self):
        Attachment(self.testPage).attach([os.path.join(self.samplefilesPath, u"source_utf8.py")])
        content = u'(:source file="  Attach:source_utf8.py  " lang="text":)'
        self.testPage.content = content

        generator = HtmlGenerator(self.testPage)
        htmlpath = generator.makeHtml(Style().getPageStyle(self.testPage))
        result = self.__readFile(htmlpath)

        self.assertTrue(u"__correctSysPath()" in result)
        self.assertTrue(u"Плагин, добавляющий обработку команды (:source:) в википарсер" in result)

    def testHighlightFile5(self):
        Attachment(self.testPage).attach([os.path.join(self.samplefilesPath, u"source_utf8.py")])
        content = u'(:source file="source_utf8.py" lang="text":)(:sourceend:)'
        self.testPage.content = content

        generator = HtmlGenerator(self.testPage)
        htmlpath = generator.makeHtml(Style().getPageStyle(self.testPage))
        result = self.__readFile(htmlpath)

        self.assertTrue(u"__correctSysPath()" in result)
        self.assertTrue(u"Плагин, добавляющий обработку команды (:source:) в википарсер" in result)

    def testHighlightFile6(self):
        Attachment(self.testPage).attach([os.path.join(self.samplefilesPath, u"source_utf8.py")])
        content = u'(:source file="source_utf8.py" lang="text":)bla-bla-bla(:sourceend:)'
        self.testPage.content = content

        generator = HtmlGenerator(self.testPage)
        htmlpath = generator.makeHtml(Style().getPageStyle(self.testPage))
        result = self.__readFile(htmlpath)

        self.assertTrue(u"__correctSysPath()" in result)
        self.assertTrue(u"Плагин, добавляющий обработку команды (:source:) в википарсер" in result)
        self.assertTrue(u"bla-bla-bla" not in result)

    def testHighlightFile7(self):
        """
        Явное задание языка для раскраски
        """
        Attachment(self.testPage).attach([os.path.join(self.samplefilesPath, u"source_utf8.py")])
        content = u'(:source file="source_utf8.py" lang="python":)'
        self.testPage.content = content

        generator = HtmlGenerator(self.testPage)
        htmlpath = generator.makeHtml(Style().getPageStyle(self.testPage))
        result = self.__readFile(htmlpath)

        self.assertTrue(u'<span class="kn">import</span> <span class="nn">os.path</span>' in result)
        self.assertTrue(
            u'<span class="bp">self</span><span class="o">.</span><span class="n">__correctSysPath</span><span class="p">()</span>'
            in result
        )

    def testHighlightFile8(self):
        """
        Нет явного задания языка
        """
        Attachment(self.testPage).attach([os.path.join(self.samplefilesPath, u"source_utf8.py")])
        content = u'(:source file="source_utf8.py":)'
        self.testPage.content = content

        generator = HtmlGenerator(self.testPage)
        htmlpath = generator.makeHtml(Style().getPageStyle(self.testPage))
        result = self.__readFile(htmlpath)

        self.assertTrue(u'<span class="kn">import</span> <span class="nn">os.path</span>' in result)
        self.assertTrue(
            u'<span class="bp">self</span><span class="o">.</span><span class="n">__correctSysPath</span><span class="p">()</span>'
            in result
        )

    def testHighlightFile9(self):
        """
        Явное задание языка, не соответствующее расширению файла
        """
        Attachment(self.testPage).attach([os.path.join(self.samplefilesPath, u"source_utf8.py")])
        content = u'(:source file="source_utf8.py" lang="text":)'
        self.testPage.content = content

        generator = HtmlGenerator(self.testPage)
        htmlpath = generator.makeHtml(Style().getPageStyle(self.testPage))
        result = self.__readFile(htmlpath)

        self.assertTrue(u'<span class="kn">import</span> <span class="nn">os.path</span>' not in result)
        self.assertTrue(u"import os.path" in result)

        self.assertTrue(
            u'<span class="bp">self</span><span class="o">.</span><span class="n">__correctSysPath</span><span class="p">()</span>'
            not in result
        )
        self.assertTrue(u"__correctSysPath()" in result)

    def testHighlightFile10(self):
        """
        Проверка случая, если прикрепленного с заданным именем файла нет
        """
        content = u'(:source file="source_utf8111.py" lang="text":)'
        self.testPage.content = content

        generator = HtmlGenerator(self.testPage)
        htmlpath = generator.makeHtml(Style().getPageStyle(self.testPage))
        result = self.__readFile(htmlpath)

        self.assertTrue(u"source_utf8111.py" in result, result)
Пример #32
0
class PageTypeColor_ColorsListTest(unittest.TestCase, BaseOutWikerGUIMixin):
    def setUp(self):
        self.initApplication()
        plugins_dirs = ["plugins/pagetypecolor"]

        self.loader = PluginsLoader(self.application)
        self.loader.load(plugins_dirs)
        self._clearConfig()

    def tearDown(self):
        self._clearConfig()
        self.loader.clear()
        self.destroyApplication()

    def test_empty(self):
        from pagetypecolor.colorslist import ColorsList
        from pagetypecolor.config import PageTypeColorConfig

        pagetype = 'wiki'

        colorslist = ColorsList(self.application)

        color_param = StringOption(self.application.config,
                                   PageTypeColorConfig.SECTION, pagetype, None)
        self.assertIsNone(color_param.value)

        self.assertEqual(list(colorslist.getPageTypes()), [])

    def test_init(self):
        from pagetypecolor.colorslist import ColorsList

        colorslist = ColorsList(self.application)
        colorslist.load()

        pageTypeList = colorslist.getPageTypes()

        self.assertIn('wiki', pageTypeList)
        self.assertIn('html', pageTypeList)
        self.assertIn('text', pageTypeList)
        self.assertIn('search', pageTypeList)

    def test_init_markdown(self):
        self._loadMarkdownPlugin()

        from pagetypecolor.colorslist import ColorsList

        colorslist = ColorsList(self.application)
        colorslist.load()

        pageTypeList = colorslist.getPageTypes()

        self.assertIn('markdown', pageTypeList)

    def test_init_markdown_config(self):
        pagetype = 'markdown'
        self._loadMarkdownPlugin()

        from pagetypecolor.colorslist import ColorsList
        from pagetypecolor.config import PageTypeColorConfig

        colorslist = ColorsList(self.application)
        colorslist.load()

        color_param = StringOption(self.application.config,
                                   PageTypeColorConfig.SECTION, pagetype, None)
        self.assertIsNotNone(color_param.value)

    def test_setColor_manual(self):
        from pagetypecolor.colorslist import ColorsList
        from pagetypecolor.config import PageTypeColorConfig

        color = '#AABBCC'
        pagetype = 'wiki'

        color_param = StringOption(self.application.config,
                                   PageTypeColorConfig.SECTION, pagetype, None)
        color_param.value = color

        colorslist = ColorsList(self.application)
        colorslist.load()

        self.assertEqual(colorslist.getColor(pagetype), color)

    def test_setColor_01(self):
        from pagetypecolor.colorslist import ColorsList

        color = '#AABBCC'
        pagetype = 'wiki'

        colorslist = ColorsList(self.application)
        colorslist.load()
        colorslist.setColor(pagetype, color)

        self.assertEqual(colorslist.getColor(pagetype), color)

    def test_setColor_02(self):
        from pagetypecolor.colorslist import ColorsList

        color = '#AABBCC'
        pagetype = 'wiki'

        colorslist = ColorsList(self.application)
        colorslist.setColor(pagetype, color)

        self.assertEqual(colorslist.getColor(pagetype), color)

    def test_setColor_03(self):
        from pagetypecolor.colorslist import ColorsList

        color = '#AABBCC'
        pagetype = 'wiki'

        colorslist = ColorsList(self.application)
        colorslist.setColor(pagetype, color)

        colorslist_new = ColorsList(self.application)
        colorslist_new.load()

        self.assertEqual(colorslist_new.getColor(pagetype), color)

    def test_markdown_default(self):
        self._loadMarkdownPlugin()

        from pagetypecolor.colorslist import ColorsList

        pagetype = 'markdown'

        colorslist = ColorsList(self.application)
        colorslist.load()
        color_param = colorslist.getColor(pagetype)

        self.assertIsNotNone(color_param)
        self.assertNotEqual(color_param, 'white')

    def _clearConfig(self):
        from pagetypecolor.config import PageTypeColorConfig

        self.application.config.remove_section(PageTypeColorConfig.SECTION)

    def _loadMarkdownPlugin(self):
        self.loader.clear()

        plugins_dirs = [
            "plugins/pagetypecolor",
            "plugins/markdown",
        ]
        self.loader.load(plugins_dirs)
Пример #33
0
class SourceGuiPluginTest(unittest.TestCase):
    """
    Тесты интерфейса для плагина Source
    """
    def setUp(self):
        self.__pluginname = u"Source"

        self.__createWiki()

        dirlist = [u"../plugins/source"]
        self._stylesCount = 26

        self.loader = PluginsLoader(Application)
        self.loader.load(dirlist)

        self.config = self.loader[self.__pluginname].config
        self._clearConfig(self.config)

        from source.insertdialogcontroller import InsertDialogController
        self.dialog = FakeInsertDialog()
        self.controller = InsertDialogController(self.testPage, self.dialog,
                                                 self.config)

    def __createWiki(self):
        # Здесь будет создаваться вики
        self.path = mkdtemp(prefix=u'Абырвалг абыр')

        self.wikiroot = WikiDocument.create(self.path)

        WikiPageFactory().create(self.wikiroot, u"Страница 1", [])
        self.testPage = self.wikiroot[u"Страница 1"]

    def tearDown(self):
        self._clearConfig(self.config)
        removeDir(self.path)
        self.loader.clear()

    def _clearConfig(self, config):
        Application.config.remove_section(self.config.section)

    def testDialogController1(self):
        """
        Тест контроллера диалога для вставки команды (:source:)
        """
        self.dialog.SetReturnCode(wx.ID_CANCEL)
        result = self.controller.showDialog()

        self.assertEqual(result, wx.ID_CANCEL)

    def testDialogController2(self):
        """
        Тест контроллера диалога для вставки команды (:source:)
        """
        self.dialog.SetReturnCode(wx.ID_OK)
        result = self.controller.showDialog()

        self.assertEqual(result, wx.ID_OK)

    def testDialogControllerResult1(self):
        """
        Тест контроллера диалога для вставки команды (:source:)
        """
        self.config.languageList.value = [
            u"python", u"cpp", u"haskell", u"text"
        ]
        self.config.defaultLanguage.value = "text"

        self.dialog.SetReturnCode(wx.ID_OK)
        self.controller.showDialog()

        self.dialog.tabWidthSpin.SetValue(4)
        result = self.controller.getCommandStrings()

        self.assertEqual(
            result,
            (u'(:source lang="text" tabwidth="4":)\n', u'\n(:sourceend:)'))

    def testDialogControllerResult2(self):
        """
        Тест контроллера диалога для вставки команды (:source:)
        """
        self.config.defaultLanguage.value = "python"

        self.dialog.SetReturnCode(wx.ID_OK)
        self.controller.showDialog()

        self.dialog.tabWidthSpin.SetValue(8)
        result = self.controller.getCommandStrings()

        self.assertEqual(
            result,
            (u'(:source lang="python" tabwidth="8":)\n', u'\n(:sourceend:)'))

    def testDialogControllerResult3(self):
        """
        Тест контроллера диалога для вставки команды (:source:)
        """
        self.config.languageList.value = [
            u"python", u"cpp", u"haskell", u"text"
        ]
        self.config.defaultLanguage.value = "text"

        self.dialog.SetReturnCode(wx.ID_OK)
        self.controller.showDialog()

        self.dialog.tabWidthSpin.SetValue(4)
        result = self.controller.getCommandStrings()

        self.assertEqual(
            result,
            (u'(:source lang="text" tabwidth="4":)\n', u'\n(:sourceend:)'))

    def testDialogControllerResult4(self):
        """
        Тест контроллера диалога для вставки команды (:source:)
        """
        self.config.languageList.value = [
            u"python", u"cpp", u"haskell", u"text"
        ]
        self.config.defaultLanguage.value = "text"

        self.dialog.SetReturnCode(wx.ID_OK)
        self.controller.showDialog()

        self.dialog.tabWidthSpin.SetValue(0)
        result = self.controller.getCommandStrings()

        self.assertEqual(result,
                         (u'(:source lang="text":)\n', u'\n(:sourceend:)'))

    def testDialogControllerResult5(self):
        """
        Тест контроллера диалога для вставки команды (:source:)
        """
        self.config.languageList.value = [
            u"python", u"cpp", u"haskell", u"text"
        ]
        self.config.defaultLanguage.value = "text"

        self.dialog.SetReturnCode(wx.ID_OK)
        self.controller.showDialog()

        self.dialog.languageComboBox.SetSelection(0)
        self.dialog.tabWidthSpin.SetValue(0)
        result = self.controller.getCommandStrings()

        self.assertEqual(result,
                         (u'(:source lang="cpp":)\n', u'\n(:sourceend:)'))

    def testDialogControllerResult6(self):
        """
        Тест контроллера диалога для вставки команды (:source:)
        """
        self.config.languageList.value = [
            u"python", u"cpp", u"haskell", u"text"
        ]
        self.config.defaultLanguage.value = "text"

        self.dialog.SetReturnCode(wx.ID_OK)
        self.controller.showDialog()

        self.dialog.languageComboBox.SetSelection(1)
        self.dialog.tabWidthSpin.SetValue(0)
        result = self.controller.getCommandStrings()

        self.assertEqual(result,
                         (u'(:source lang="haskell":)\n', u'\n(:sourceend:)'))

    def testSourceConfig1(self):
        self.config.defaultLanguage.value = u"python"
        self.config.tabWidth.value = 8
        self.config.dialogWidth.value = 100
        self.config.dialogHeight.value = 200
        self.config.languageList.value = [u"python", u"cpp", u"haskell"]

        self.assertEqual(self.config.defaultLanguage.value, u"python")
        self.assertEqual(self.config.tabWidth.value, 8)
        self.assertEqual(self.config.dialogWidth.value, 100)
        self.assertEqual(self.config.dialogHeight.value, 200)
        self.assertEqual(self.config.languageList.value,
                         [u"python", u"cpp", u"haskell"])

    def testDialogLanguageValues1(self):
        self.config.languageList.value = [u"python", u"cpp", u"haskell"]
        self.config.defaultLanguage.value = u"haskell"

        self.controller.showDialog()

        self.assertEqual(self.dialog.languageComboBox.GetItems(),
                         [u"cpp", u"haskell", u"python"])

        self.assertEqual(self.dialog.languageComboBox.GetSelection(), 1)
        self.assertEqual(self.dialog.languageComboBox.GetValue(), u"haskell")

        self.assertEqual(self.dialog.tabWidthSpin.GetValue(), 0)

    def testDialogLanguageValues2(self):
        self.config.languageList.value = []
        self.config.defaultLanguage.value = u"haskell"

        self.controller.showDialog()

        self.assertEqual(self.dialog.languageComboBox.GetItems(), [u"text"])

        self.assertEqual(self.dialog.languageComboBox.GetSelection(), 0)
        self.assertEqual(self.dialog.languageComboBox.GetValue(), u"text")

    def testDialogLanguageValues3(self):
        self.config.languageList.value = [u"python", u"cpp", u"haskell"]
        self.config.defaultLanguage.value = u"c"

        self.controller.showDialog()

        self.assertEqual(self.dialog.languageComboBox.GetItems(),
                         [u"cpp", u"haskell", u"python"])

        self.assertEqual(self.dialog.languageComboBox.GetSelection(), 0)
        self.assertEqual(self.dialog.languageComboBox.GetValue(), u"cpp")

    def testDialogLanguageValues4(self):
        self.config.languageList.value = [u"python", u"cpp", u"haskell"]
        self.config.defaultLanguage.value = u"   haskell   "

        self.controller.showDialog()

        self.assertEqual(self.dialog.languageComboBox.GetItems(),
                         [u"cpp", u"haskell", u"python"])

        self.assertEqual(self.dialog.languageComboBox.GetSelection(), 1)
        self.assertEqual(self.dialog.languageComboBox.GetValue(), u"haskell")

        self.assertEqual(self.dialog.tabWidthSpin.GetValue(), 0)

    def testDialogStyleValues1(self):
        self.config.languageList.value = [u"python", u"cpp", u"haskell"]
        self.config.defaultLanguage.value = u"python"

        self.controller.showDialog()

        self.assertEqual(self.dialog.styleComboBox.GetCount(),
                         self._stylesCount)
        self.assertEqual(self.dialog.styleComboBox.GetValue(), "default")

        result = self.controller.getCommandStrings()

        self.assertEqual(result,
                         (u'(:source lang="python":)\n', u'\n(:sourceend:)'))

    def testDialogStyleValues2(self):
        self.config.defaultStyle.value = "blablabla"
        self.controller.showDialog()

        self.assertEqual(self.dialog.styleComboBox.GetCount(),
                         self._stylesCount)
        self.assertEqual(self.dialog.styleComboBox.GetValue(), "default")

    def testDialogStyleValues3(self):
        self.config.defaultStyle.value = ""
        self.controller.showDialog()

        self.assertEqual(self.dialog.styleComboBox.GetCount(),
                         self._stylesCount)
        self.assertEqual(self.dialog.styleComboBox.GetValue(), "default")

    def testDialogStyleValues4(self):
        self.config.defaultStyle.value = "vim"
        self.controller.showDialog()

        self.assertEqual(self.dialog.styleComboBox.GetCount(),
                         self._stylesCount)
        self.assertEqual(self.dialog.styleComboBox.GetValue(), "vim")

    def testDialogStyleValues5(self):
        self.config.defaultStyle.value = "emacs"
        self.controller.showDialog()

        self.assertEqual(self.dialog.styleComboBox.GetCount(),
                         self._stylesCount)
        self.assertEqual(self.dialog.styleComboBox.GetValue(), "emacs")

    def testDialogStyle1(self):
        self.config.languageList.value = [u"python", u"cpp", u"haskell"]
        self.config.defaultLanguage.value = u"python"
        self.config.defaultStyle.value = u"vim"
        self.config.style.value = u"vim"

        self.controller.showDialog()

        self.assertEqual(self.dialog.styleComboBox.GetCount(),
                         self._stylesCount)
        self.assertEqual(self.dialog.styleComboBox.GetValue(), "vim")

        result = self.controller.getCommandStrings()

        self.assertEqual(result,
                         (u'(:source lang="python":)\n', u'\n(:sourceend:)'))

    def testDialogStyle2(self):
        self.config.languageList.value = [u"python", u"cpp", u"haskell"]
        self.config.defaultLanguage.value = u"python"
        self.config.defaultStyle.value = u"vim"
        self.config.style.value = u"default"

        self.controller.showDialog()

        self.assertEqual(self.dialog.styleComboBox.GetCount(),
                         self._stylesCount)
        self.assertEqual(self.dialog.styleComboBox.GetValue(), "default")

        result = self.controller.getCommandStrings()

        self.assertEqual(result,
                         (u'(:source lang="python" style="default":)\n',
                          u'\n(:sourceend:)'))

    def testDialogStyleText(self):
        self.config.languageList.value = [u"python", u"cpp", u"haskell"]
        self.config.defaultLanguage.value = u"python"

        self.controller.showDialog()
        self.dialog.styleComboBox.SetSelection(0)

        self.assertEqual(self.dialog.styleComboBox.GetValue(), "algol")
        self.assertEqual(self.dialog.style, "algol")

        result = self.controller.getCommandStrings()

        self.assertEqual(
            result,
            (u'(:source lang="python" style="algol":)\n', u'\n(:sourceend:)'))

    def testDialogStyleFile(self):
        self.samplefilesPath = u"../test/samplefiles/sources"
        Attachment(self.testPage).attach(
            [os.path.join(self.samplefilesPath, u"source_utf8.py")])
        Attachment(self.testPage).attach(
            [os.path.join(self.samplefilesPath, u"source_cp1251.cs")])

        self.config.languageList.value = [u"python", u"cpp", u"haskell"]
        self.config.defaultLanguage.value = u"python"

        self.controller.showDialog()

        self.dialog.fileCheckBox.SetValue(True)
        self.dialog.styleComboBox.SetSelection(0)
        self.dialog.attachmentComboBox.SetSelection(0)

        self.assertEqual(self.dialog.styleComboBox.GetValue(), "algol")
        self.assertEqual(self.dialog.style, "algol")

        result = self.controller.getCommandStrings()

        self.assertEqual(result, (
            u'(:source file="Attach:source_cp1251.cs" lang="python" style="algol":)',
            u'(:sourceend:)'))

    def testDialogStyleFile2(self):
        self.samplefilesPath = u"../test/samplefiles/sources"
        Attachment(self.testPage).attach(
            [os.path.join(self.samplefilesPath, u"source_utf8.py")])
        Attachment(self.testPage).attach(
            [os.path.join(self.samplefilesPath, u"source_cp1251.cs")])

        self.config.languageList.value = [u"python", u"cpp", u"haskell"]
        self.config.defaultLanguage.value = u"python"

        self.controller.showDialog()

        self.dialog.fileCheckBox.SetValue(True)
        self.dialog.styleComboBox.SetSelection(0)
        self.dialog.attachmentComboBox.SetSelection(0)
        self.dialog.languageComboBox.SetSelection(0)

        self.assertEqual(self.dialog.styleComboBox.GetValue(), "algol")
        self.assertEqual(self.dialog.style, "algol")

        result = self.controller.getCommandStrings()

        self.assertEqual(
            result,
            (u'(:source file="Attach:source_cp1251.cs" style="algol":)',
             u'(:sourceend:)'))

    def testDialogStyleText2(self):
        self.config.languageList.value = [u"python", u"cpp", u"haskell"]
        self.config.defaultLanguage.value = u"python"

        self.controller.showDialog()
        self.dialog.styleComboBox.SetSelection(0)
        self.dialog.tabWidthSpin.SetValue(5)

        self.assertEqual(self.dialog.styleComboBox.GetValue(), "algol")
        self.assertEqual(self.dialog.style, "algol")

        result = self.controller.getCommandStrings()

        self.assertEqual(
            result, (u'(:source lang="python" tabwidth="5" style="algol":)\n',
                     u'\n(:sourceend:)'))

    def testStyleConfig1(self):
        self.config.style.value = "default"

        self.controller.showDialog()
        self.assertEqual(self.dialog.style, "default")

    def testStyleConfig2(self):
        self.config.style.value = "vim"

        self.controller.showDialog()
        self.assertEqual(self.dialog.style, "vim")

    def testStyleConfig3(self):
        self.config.style.value = "  vim   "

        self.controller.showDialog()
        self.assertEqual(self.dialog.style, "vim")

    def testStyleConfig4(self):
        self.config.style.value = "invalid_style"

        self.controller.showDialog()
        self.assertEqual(self.dialog.style, "default")

    def testStyleConfig5(self):
        self.controller.showDialog()
        self.assertEqual(self.dialog.style, "default")

    def testParentBgConfig1(self):
        self.config.parentbg.value = u"  False  "
        self.controller.showDialog()

        self.assertEqual(self.dialog.parentbg, False)

    def testParentBgConfig2(self):
        self.config.parentbg.value = u"  True  "
        self.controller.showDialog()

        self.assertEqual(self.dialog.parentbg, True)

    def testParentBgConfig3(self):
        self.config.parentbg.value = u"  блаблабла  "
        self.controller.showDialog()

        self.assertEqual(self.dialog.parentbg, False)

    def testParentBgConfig4(self):
        # Если нет вообще записей в файле настроек
        self.controller.showDialog()

        self.assertEqual(self.dialog.parentbg, False)

    def testLineNumConfig1(self):
        # Если нет вообще записей в файле настроек
        self.controller.showDialog()

        self.assertEqual(self.dialog.lineNum, False)

    def testLineNumConfig2(self):
        self.config.lineNum.value = u"  False  "
        self.controller.showDialog()

        self.assertEqual(self.dialog.lineNum, False)

    def testLineNumConfig3(self):
        self.config.lineNum.value = u"  блаблабла  "
        self.controller.showDialog()

        self.assertEqual(self.dialog.lineNum, False)

    def testLineNumConfig4(self):
        self.config.lineNum.value = u"True"
        self.controller.showDialog()

        self.assertEqual(self.dialog.lineNum, True)

    def testDialogParengBg(self):
        self.config.languageList.value = [u"python", u"cpp", u"haskell"]
        self.config.defaultLanguage.value = u"python"

        self.controller.showDialog()
        self.dialog.parentBgCheckBox.SetValue(True)

        result = self.controller.getCommandStrings()

        self.assertEqual(
            result,
            (u'(:source lang="python" parentbg:)\n', u'\n(:sourceend:)'))

    def testDialogLineNum(self):
        self.config.languageList.value = [u"python", u"cpp", u"haskell"]
        self.config.defaultLanguage.value = u"python"

        self.controller.showDialog()
        self.dialog.lineNumCheckBox.SetValue(True)

        result = self.controller.getCommandStrings()

        self.assertEqual(
            result,
            (u'(:source lang="python" linenum:)\n', u'\n(:sourceend:)'))

    def testDialogParentBgLineNum(self):
        self.config.languageList.value = [u"python", u"cpp", u"haskell"]
        self.config.defaultLanguage.value = u"python"

        self.controller.showDialog()
        self.dialog.parentBgCheckBox.SetValue(True)
        self.dialog.lineNumCheckBox.SetValue(True)

        result = self.controller.getCommandStrings()

        self.assertEqual(result,
                         (u'(:source lang="python" parentbg linenum:)\n',
                          u'\n(:sourceend:)'))

    def testDialogTabWidth(self):
        self.config.languageList.value = [u"python", u"cpp", u"haskell"]
        self.config.defaultLanguage.value = u"python"

        self.controller.showDialog()
        self.dialog.tabWidthSpin.SetValue(10)

        result = self.controller.getCommandStrings()

        self.assertEqual(
            result,
            (u'(:source lang="python" tabwidth="10":)\n', u'\n(:sourceend:)'))
Пример #34
0
class InsertNodeTest(unittest.TestCase, BaseOutWikerGUIMixin):
    def setUp(self):
        self.initApplication()
        self.wikiroot = self.createWiki()
        dirlist = ["../plugins/diagrammer"]

        self.loader = PluginsLoader(Application)
        self.loader.load(dirlist)

        from diagrammer.gui.insertnodedialog import (
            InsertNodeDialog,
            InsertNodeController
        )

        self._dlg = InsertNodeDialog(None)
        self._controller = InsertNodeController(self._dlg)
        Tester.dialogTester.clear()

    def tearDown(self):
        self._dlg.Destroy()
        self.loader.clear()
        self.destroyApplication()
        self.destroyWiki(self.wikiroot)

    def testDestroy(self):
        Application.wikiroot = None
        self.loader.clear()

    def testName_01(self):

        Tester.dialogTester.appendOk()
        self._dlg.name = "Абырвалг"

        result = self._controller.getResult()

        self.assertEqual(result, "Абырвалг")

    def testName_02(self):
        Tester.dialogTester.appendOk()
        self._dlg.name = "Абырвалг 111"

        result = self._controller.getResult()

        self.assertEqual(result, '"Абырвалг 111"')

    def testShapeSelection_01(self):
        Tester.dialogTester.appendOk()
        self._dlg.name = "Абырвалг"
        self._dlg.setShapeSelection(0)

        result = self._controller.getResult()

        self.assertEqual(result, "Абырвалг")

    def testShapeSelection_02(self):
        Tester.dialogTester.appendOk()
        self._dlg.name = "Абырвалг"
        self._dlg.setShapeSelection(1)

        result = self._controller.getResult()

        self.assertEqual(result, "Абырвалг [shape = actor];")

    def testShapeSelection_03(self):
        Tester.dialogTester.appendOk()
        self._dlg.name = "Абырвалг"

        self._dlg.setShapeSelection(10)

        result = self._controller.getResult()

        self.assertEqual(result, "Абырвалг [shape = flowchart.database];")

    def testBorderStyle_01(self):
        Tester.dialogTester.appendOk()
        self._dlg.name = "Абырвалг"

        self._dlg.setStyleIndex(0)

        result = self._controller.getResult()
        self.assertEqual(result, "Абырвалг")

    def testBorderStyle_02(self):
        Tester.dialogTester.appendOk()
        self._dlg.name = "Абырвалг"

        self._dlg.setStyleIndex(1)

        result = self._controller.getResult()
        self.assertEqual(result, "Абырвалг [style = solid];")

    def testBorderStyle_03(self):
        Tester.dialogTester.appendOk()
        self._dlg.name = "Абырвалг"

        self._dlg.setStyleIndex(2)

        result = self._controller.getResult()
        self.assertEqual(result, "Абырвалг [style = dotted];")

    def testBorderStyle_04(self):
        Tester.dialogTester.appendOk()
        self._dlg.name = "Абырвалг"

        self._dlg.style = ""

        result = self._controller.getResult()
        self.assertEqual(result, "Абырвалг")

    def testBorderStyle_05(self):
        Tester.dialogTester.appendOk()
        self._dlg.name = "Абырвалг"

        self._dlg.style = "solid"

        result = self._controller.getResult()
        self.assertEqual(result, "Абырвалг [style = solid];")

    def testBorderStyle_06(self):
        Tester.dialogTester.appendOk()
        self._dlg.name = "Абырвалг"

        self._dlg.style = "Solid"

        result = self._controller.getResult()
        self.assertEqual(result, "Абырвалг [style = solid];")

    def testBorderStyle_07(self):
        Tester.dialogTester.appendOk()
        self._dlg.name = "Абырвалг"

        self._dlg.style = " Solid "

        result = self._controller.getResult()
        self.assertEqual(result, "Абырвалг [style = solid];")

    def testBorderStyle_08(self):
        Tester.dialogTester.appendOk()
        self._dlg.name = "Абырвалг"

        self._dlg.style = "1,2,3"

        result = self._controller.getResult()
        self.assertEqual(result, 'Абырвалг [style = "1,2,3"];')

    def testBorderStyle_09(self):
        Tester.dialogTester.appendOk()
        self._dlg.name = "Абырвалг"

        self._dlg.style = "1, 2, 3"

        result = self._controller.getResult()
        self.assertEqual(result, 'Абырвалг [style = "1,2,3"];')

    def testBorderStyle_10(self):
        Tester.dialogTester.appendOk()
        self._dlg.name = "Абырвалг"

        self._dlg.style = " 1, 2, 3 "

        result = self._controller.getResult()
        self.assertEqual(result, 'Абырвалг [style = "1,2,3"];')

    def testBorderStyle_11(self):
        Tester.dialogTester.appendOk()
        self._dlg.name = "Абырвалг"

        self._dlg.style = '"1,2,3"'

        result = self._controller.getResult()
        self.assertEqual(result, 'Абырвалг [style = "1,2,3"];')

    def testBorderStyle_12(self):
        Tester.dialogTester.appendOk()
        self._dlg.name = "Абырвалг"

        self._dlg.setShapeSelection(1)
        self._dlg.style = "dotted"

        result = self._controller.getResult()
        self.assertEqual(result, "Абырвалг [shape = actor, style = dotted];")

    def testStacked_01(self):
        Tester.dialogTester.appendOk()
        self._dlg.name = "Абырвалг"
        self._dlg.stacked = True

        result = self._controller.getResult()
        self.assertEqual(result, "Абырвалг [stacked];")

    def testStacked_02(self):
        Tester.dialogTester.appendOk()
        self._dlg.name = "Абырвалг"
        self._dlg.stacked = True
        self._dlg.setShapeSelection(1)

        result = self._controller.getResult()
        self.assertEqual(result, "Абырвалг [shape = actor, stacked];")

    def testLabel_01(self):
        Tester.dialogTester.appendOk()
        self._dlg.name = "Абырвалг"
        self._dlg.label = "Превед"

        result = self._controller.getResult()
        self.assertEqual(result, 'Абырвалг [label = "Превед"];')

    def testLabel_02(self):
        Tester.dialogTester.appendOk()
        self._dlg.name = "Абырвалг"
        self._dlg.setShapeSelection(1)
        self._dlg.label = "Превед"

        result = self._controller.getResult()
        self.assertEqual(result, 'Абырвалг [shape = actor, label = "Превед"];')

    def testLabel_03(self):
        Tester.dialogTester.appendOk()
        self._dlg.name = "Абырвалг"
        self._dlg.label = "Абырвалг"

        result = self._controller.getResult()
        self.assertEqual(result, 'Абырвалг')

    def testColor_01(self):
        Tester.dialogTester.appendOk()
        self._dlg.name = "Абырвалг"
        self._dlg.isBackColorChanged = True
        self._dlg.backColor = "white"

        result = self._controller.getResult()
        self.assertEqual(result, 'Абырвалг [color = "white"];')

    def testColor_02(self):
        Tester.dialogTester.appendOk()
        self._dlg.name = "Абырвалг"
        self._dlg.isBackColorChanged = True
        self._dlg.backColor = "#AAAAAA"

        result = self._controller.getResult()
        self.assertEqual(result, 'Абырвалг [color = "#AAAAAA"];')

    def testColor_03(self):
        Tester.dialogTester.appendOk()
        self._dlg.name = "Абырвалг"
        self._dlg.isBackColorChanged = False
        self._dlg.backColor = "#AAAAAA"

        result = self._controller.getResult()
        self.assertEqual(result, 'Абырвалг')

    def testColor_04(self):
        Tester.dialogTester.appendOk()
        self._dlg.name = "Абырвалг"
        self._dlg.setShapeSelection(1)
        self._dlg.isBackColorChanged = True
        self._dlg.backColor = "#AAAAAA"

        result = self._controller.getResult()
        self.assertEqual(result,
                         'Абырвалг [shape = actor, color = "#AAAAAA"];')

    def testTextColor_01(self):
        Tester.dialogTester.appendOk()
        self._dlg.name = "Абырвалг"
        self._dlg.isTextColorChanged = True
        self._dlg.textColor = "black"

        result = self._controller.getResult()
        self.assertEqual(result, 'Абырвалг [textcolor = "black"];')

    def testTextColor_02(self):
        Tester.dialogTester.appendOk()
        self._dlg.name = "Абырвалг"
        self._dlg.isTextColorChanged = True
        self._dlg.textColor = "#AAAAAA"

        result = self._controller.getResult()
        self.assertEqual(result, 'Абырвалг [textcolor = "#AAAAAA"];')

    def testTextColor_03(self):
        Tester.dialogTester.appendOk()
        self._dlg.name = "Абырвалг"
        self._dlg.isTextColorChanged = False
        self._dlg.textColor = "#AAAAAA"

        result = self._controller.getResult()
        self.assertEqual(result, 'Абырвалг')

    def testTextColor_04(self):
        Tester.dialogTester.appendOk()
        self._dlg.name = "Абырвалг"
        self._dlg.setShapeSelection(1)
        self._dlg.isTextColorChanged = True
        self._dlg.textColor = "#AAAAAA"

        result = self._controller.getResult()
        self.assertEqual(result,
                         'Абырвалг [shape = actor, textcolor = "#AAAAAA"];')

    def testFontSize_01(self):
        Tester.dialogTester.appendOk()
        self._dlg.name = "Абырвалг"
        self._dlg.isFontSizeChanged = True
        self._dlg.fontSize = 20

        result = self._controller.getResult()
        self.assertEqual(result, 'Абырвалг [fontsize = 20];')

    def testFontSize_02(self):
        Tester.dialogTester.appendOk()
        self._dlg.name = "Абырвалг"
        self._dlg.isFontSizeChanged = False
        self._dlg.fontSize = 20

        result = self._controller.getResult()
        self.assertEqual(result, 'Абырвалг')

    def testFontSize_03(self):
        Tester.dialogTester.appendOk()
        self._dlg.name = "Абырвалг"
        self._dlg.setShapeSelection(1)
        self._dlg.isFontSizeChanged = True
        self._dlg.fontSize = 20

        result = self._controller.getResult()
        self.assertEqual(result, 'Абырвалг [shape = actor, fontsize = 20];')

    def testWidth_01(self):
        Tester.dialogTester.appendOk()
        self._dlg.name = "Абырвалг"
        self._dlg.isWidthChanged = True
        self._dlg.width = 200

        result = self._controller.getResult()
        self.assertEqual(result, 'Абырвалг [width = 200];')

    def testWidth_02(self):
        Tester.dialogTester.appendOk()
        self._dlg.name = "Абырвалг"
        self._dlg.isWidthChanged = False
        self._dlg.width = 200

        result = self._controller.getResult()
        self.assertEqual(result, 'Абырвалг')

    def testWidth_03(self):
        Tester.dialogTester.appendOk()
        self._dlg.name = "Абырвалг"
        self._dlg.setShapeSelection(1)
        self._dlg.isWidthChanged = True
        self._dlg.width = 200

        result = self._controller.getResult()
        self.assertEqual(result, 'Абырвалг [shape = actor, width = 200];')

    def testHeight_01(self):
        Tester.dialogTester.appendOk()
        self._dlg.name = "Абырвалг"
        self._dlg.isHeightChanged = True
        self._dlg.height = 200

        result = self._controller.getResult()
        self.assertEqual(result, 'Абырвалг [height = 200];')

    def testHeight_02(self):
        Tester.dialogTester.appendOk()
        self._dlg.name = "Абырвалг"
        self._dlg.isHeightChanged = False
        self._dlg.height = 200

        result = self._controller.getResult()
        self.assertEqual(result, 'Абырвалг')

    def testHeight_03(self):
        Tester.dialogTester.appendOk()
        self._dlg.name = "Абырвалг"
        self._dlg.setShapeSelection(1)
        self._dlg.isHeightChanged = True
        self._dlg.height = 200

        result = self._controller.getResult()
        self.assertEqual(result, 'Абырвалг [shape = actor, height = 200];')
Пример #35
0
class SourceStyleTest (unittest.TestCase, BaseOutWikerGUIMixin):
    def setUp(self):
        self.__pluginname = "Source"
        self.initApplication()
        self.wikiroot = self.createWiki()
        self.testPage = WikiPageFactory().create(self.wikiroot,
                                                 "Страница 1",
                                                 [])

        dirlist = ["plugins/source"]

        # Путь, где лежат примеры исходников в разных кодировках
        self.samplefilesPath = "testdata/samplefiles/sources"

        # Пример программы
        self.pythonSource = '''import os

# Комментарий
def hello (count):
	"""
	Hello world
	"""
	for i in range (10):
		print "Hello world!!!"
'''

        self.loader = PluginsLoader(self.application)
        self.loader.load(dirlist)

        self.config = self.loader[self.__pluginname].config
        self.config.tabWidth.value = 4
        self.config.defaultLanguage.remove_option()
        self.application.config.remove_section(self.config.section)

        self.factory = ParserFactory()
        self.parser = self.factory.make(self.testPage, self.application.config)

    def tearDown(self):
        self.config.tabWidth.value = 4
        self.application.config.remove_section(self.config.section)
        self.loader.clear()
        self.destroyApplication()
        self.destroyWiki(self.wikiroot)

    def testDefaultStyle(self):
        text = '(:source lang="python" tabwidth=4:){0}(:sourceend:)'.format(
            self.pythonSource)

        self.testPage.content = text

        generator = HtmlGenerator(self.testPage)
        result = generator.makeHtml(Style().getPageStyle(self.testPage))

        innerString1 = ".highlight-default .c"
        innerString2 = ".highlight-default .c { color: #3D7B7B; font-style: italic } /* Comment */"
        innerString3 = '        <span class="nb">print</span> <span class="s2">&quot;Hello world!!!&quot;</span>'
        innerString4 = '<span class="kn">import</span> <span class="nn">os</span>'

        self.assertTrue(innerString1 in result)
        self.assertTrue(innerString2 in result)
        self.assertTrue(innerString3 in result)
        self.assertTrue(innerString4 in result)

    def testDefaultInvalidStyle(self):
        text = '(:source lang="python" tabwidth=4:){0}(:sourceend:)'.format(
            self.pythonSource)

        self.testPage.content = text

        self.config.defaultStyle.value = "invalid_blablabla"

        generator = HtmlGenerator(self.testPage)
        result = generator.makeHtml(Style().getPageStyle(self.testPage))

        innerString1 = ".highlight-default .c"
        innerString2 = ".highlight-default .c { color: #3D7B7B; font-style: italic } /* Comment */"
        innerString3 = '        <span class="nb">print</span> <span class="s2">&quot;Hello world!!!&quot;</span>'
        innerString4 = '<span class="kn">import</span> <span class="nn">os</span>'

        self.assertTrue(innerString1 in result)
        self.assertTrue(innerString2 in result)
        self.assertTrue(innerString3 in result)
        self.assertTrue(innerString4 in result)

    def testDefaultEmptyStyle(self):
        text = '(:source lang="python" tabwidth=4:){0}(:sourceend:)'.format(
            self.pythonSource)

        self.testPage.content = text

        self.config.defaultStyle.value = ""

        generator = HtmlGenerator(self.testPage)
        result = generator.makeHtml(Style().getPageStyle(self.testPage))

        innerString1 = ".highlight-default .c"
        innerString2 = ".highlight-default .c { color: #3D7B7B; font-style: italic } /* Comment */"
        innerString3 = '        <span class="nb">print</span> <span class="s2">&quot;Hello world!!!&quot;</span>'
        innerString4 = '<span class="kn">import</span> <span class="nn">os</span>'

        self.assertTrue(innerString1 in result)
        self.assertTrue(innerString2 in result)
        self.assertTrue(innerString3 in result)
        self.assertTrue(innerString4 in result)

    def testDefaultStyleVim(self):
        text = '(:source lang="python" tabwidth=4:){0}(:sourceend:)'.format(
            self.pythonSource)

        self.testPage.content = text

        self.config.defaultStyle.value = "vim"

        generator = HtmlGenerator(self.testPage)
        result = generator.makeHtml(Style().getPageStyle(self.testPage))

        innerString1 = ".highlight-vim .c"
        innerString2 = ".highlight-vim .c { color: #000080 } /* Comment */"
        innerString3 = '        <span class="nb">print</span> <span class="s2">&quot;Hello world!!!&quot;</span>'
        innerString4 = '<span class="kn">import</span> <span class="nn">os</span>'

        self.assertTrue(innerString1 in result)
        self.assertTrue(innerString2 in result)
        self.assertTrue(innerString3 in result)
        self.assertTrue(innerString4 in result)

    def testInvalidStyle(self):
        text = '(:source lang="python" tabwidth=4 style="invalid_bla-bla-bla":){0}(:sourceend:)'.format(
            self.pythonSource)

        self.testPage.content = text

        generator = HtmlGenerator(self.testPage)
        result = generator.makeHtml(Style().getPageStyle(self.testPage))

        innerString1 = ".highlight-default .c"
        innerString2 = ".highlight-default .c { color: #3D7B7B; font-style: italic } /* Comment */"
        innerString3 = '        <span class="nb">print</span> <span class="s2">&quot;Hello world!!!&quot;</span>'
        innerString4 = '<span class="kn">import</span> <span class="nn">os</span>'

        self.assertTrue(innerString1 in result)
        self.assertTrue(innerString2 in result)
        self.assertTrue(innerString3 in result)
        self.assertTrue(innerString4 in result)

    def testStyleVim(self):
        text = '(:source lang="python" tabwidth=4 style="vim":){0}(:sourceend:)'.format(
            self.pythonSource)

        self.testPage.content = text

        generator = HtmlGenerator(self.testPage)
        result = generator.makeHtml(Style().getPageStyle(self.testPage))

        innerString1 = ".highlight-vim .c"
        innerString2 = ".highlight-vim .c { color: #000080 } /* Comment */"
        innerString3 = '        <span class="nb">print</span> <span class="s2">&quot;Hello world!!!&quot;</span>'
        innerString4 = '<span class="kn">import</span> <span class="nn">os</span>'

        self.assertTrue(innerString1 in result)
        self.assertTrue(innerString2 in result)
        self.assertTrue(innerString3 in result)
        self.assertTrue(innerString4 in result)

    def testSeveralStyles(self):
        text = '''(:source lang="python" tabwidth=4 style="vim":){0}(:sourceend:)

(:source lang="python" tabwidth=4:){0}(:sourceend:)'''.format(self.pythonSource)

        self.testPage.content = text

        generator = HtmlGenerator(self.testPage)
        result = generator.makeHtml(Style().getPageStyle(self.testPage))

        innerString1 = ".highlight-vim .c"
        innerString2 = ".highlight-vim .c { color: #000080 } /* Comment */"
        innerString3 = '        <span class="nb">print</span> <span class="s2">&quot;Hello world!!!&quot;</span>'
        innerString4 = '<span class="kn">import</span> <span class="nn">os</span>'
        innerString5 = ".highlight-default .c"
        innerString6 = ".highlight-default .c { color: #3D7B7B; font-style: italic } /* Comment */"
        innerString7 = '<div class="highlight-default">'
        innerString8 = '<div class="highlight-vim">'

        self.assertTrue(innerString1 in result)
        self.assertTrue(innerString2 in result)
        self.assertTrue(innerString3 in result)
        self.assertTrue(innerString4 in result)
        self.assertTrue(innerString5 in result)
        self.assertTrue(innerString6 in result)
        self.assertTrue(innerString7 in result)
        self.assertTrue(innerString8 in result)

    def testDefaultStyleFile(self):
        Attachment(self.testPage).attach(
            [os.path.join(self.samplefilesPath, "source_utf8.py")])
        text = '(:source lang="python" tabwidth=4 file="source_utf8.py":){0}(:sourceend:)'.format(
            self.pythonSource)

        self.testPage.content = text

        generator = HtmlGenerator(self.testPage)
        result = generator.makeHtml(Style().getPageStyle(self.testPage))

        innerString1 = ".highlight-default .c"
        innerString2 = ".highlight-default .c { color: #3D7B7B; font-style: italic } /* Comment */"

        self.assertTrue(innerString1 in result)
        self.assertTrue(innerString2 in result)

    def testDefaultInvalidStyleFile(self):
        Attachment(self.testPage).attach(
            [os.path.join(self.samplefilesPath, "source_utf8.py")])
        text = '(:source lang="python" tabwidth=4 file="source_utf8.py":){0}(:sourceend:)'.format(
            self.pythonSource)

        self.testPage.content = text

        self.config.defaultStyle.value = "invalid_blablabla"

        generator = HtmlGenerator(self.testPage)
        result = generator.makeHtml(Style().getPageStyle(self.testPage))

        innerString1 = ".highlight-default .c"
        innerString2 = ".highlight-default .c { color: #3D7B7B; font-style: italic } /* Comment */"

        self.assertTrue(innerString1 in result)
        self.assertTrue(innerString2 in result)

    def testDefaultEmptyStyleFile(self):
        Attachment(self.testPage).attach(
            [os.path.join(self.samplefilesPath, "source_utf8.py")])
        text = '(:source lang="python" tabwidth=4 file="source_utf8.py":){0}(:sourceend:)'.format(
            self.pythonSource)

        self.testPage.content = text

        self.config.defaultStyle.value = ""

        generator = HtmlGenerator(self.testPage)
        result = generator.makeHtml(Style().getPageStyle(self.testPage))

        innerString1 = ".highlight-default .c"
        innerString2 = ".highlight-default .c { color: #3D7B7B; font-style: italic } /* Comment */"

        self.assertTrue(innerString1 in result)
        self.assertTrue(innerString2 in result)

    def testDefaultStyleVimFile(self):
        text = '(:source lang="python" tabwidth=4:){0}(:sourceend:)'.format(
            self.pythonSource)

        self.testPage.content = text

        self.config.defaultStyle.value = "vim"

        generator = HtmlGenerator(self.testPage)
        result = generator.makeHtml(Style().getPageStyle(self.testPage))

        innerString1 = ".highlight-vim .c"
        innerString2 = ".highlight-vim .c { color: #000080 } /* Comment */"

        self.assertTrue(innerString1 in result)
        self.assertTrue(innerString2 in result)

    def testParentBg1(self):
        text = '(:source lang="python" tabwidth=4:){0}(:sourceend:)'.format(
            self.pythonSource)

        self.testPage.content = text
        self.config.defaultStyle.value = "vim"

        generator = HtmlGenerator(self.testPage)
        result = generator.makeHtml(Style().getPageStyle(self.testPage))

        innerString1 = ".highlight-vim pre {padding: 0px; border: none; color: inherit; background-color: inherit; margin:0px; }"
        innerString2 = ".highlight-vim {color: inherit; background-color: inherit }"

        self.assertTrue(innerString1 in result)
        self.assertTrue(innerString2 not in result)

    def testParentBg2(self):
        text = '(:source lang="python" tabwidth=4 parentbg:){0}(:sourceend:)'.format(
            self.pythonSource)

        self.testPage.content = text
        self.config.defaultStyle.value = "vim"

        generator = HtmlGenerator(self.testPage)
        result = generator.makeHtml(Style().getPageStyle(self.testPage))

        innerString1 = ".highlight-vim-parentbg pre {padding: 0px; border: none; color: inherit; background-color: inherit; margin:0px; }"
        innerString2 = ".highlight-vim-parentbg {color: inherit; background-color: inherit }"
        innerString3 = '<div class="highlight-vim-parentbg">'
        innerString4 = ".highlight-vim {color: inherit; background-color: inherit }"
        innerString5 = '<div class="highlight-vim">'

        self.assertTrue(innerString1 in result)
        self.assertTrue(innerString2 in result)
        self.assertTrue(innerString3 in result)
        self.assertTrue(innerString4 not in result)
        self.assertTrue(innerString5 not in result)

    def testParentBg3(self):
        text = '(:source lang="python" parentbg tabwidth=4:){0}(:sourceend:)'.format(
            self.pythonSource)

        self.testPage.content = text
        self.config.defaultStyle.value = "vim"

        generator = HtmlGenerator(self.testPage)
        result = generator.makeHtml(Style().getPageStyle(self.testPage))

        innerString1 = ".highlight-vim-parentbg pre {padding: 0px; border: none; color: inherit; background-color: inherit; margin:0px; }"
        innerString2 = ".highlight-vim-parentbg {color: inherit; background-color: inherit }"
        innerString3 = '<div class="highlight-vim-parentbg">'
        innerString4 = ".highlight-vim {color: inherit; background-color: inherit }"
        innerString5 = '<div class="highlight-vim">'

        self.assertTrue(innerString1 in result)
        self.assertTrue(innerString2 in result)
        self.assertTrue(innerString3 in result)
        self.assertTrue(innerString4 not in result)
        self.assertTrue(innerString5 not in result)

    def testParentBg4(self):
        text = '''(:source lang="python" tabwidth=4:){0}(:sourceend:)

        (:source lang="python" tabwidth=4 parentbg:){0}(:sourceend:)'''.format(self.pythonSource)

        self.testPage.content = text
        self.config.defaultStyle.value = "vim"

        generator = HtmlGenerator(self.testPage)
        result = generator.makeHtml(Style().getPageStyle(self.testPage))

        innerString1 = ".highlight-vim-parentbg pre {padding: 0px; border: none; color: inherit; background-color: inherit; margin:0px; }"
        innerString2 = ".highlight-vim-parentbg {color: inherit; background-color: inherit }"
        innerString3 = '<div class="highlight-vim-parentbg">'
        innerString4 = ".highlight-vim {color: inherit; background-color: inherit }"
        innerString5 = '<div class="highlight-vim">'

        self.assertTrue(innerString1 in result)
        self.assertTrue(innerString2 in result)
        self.assertTrue(innerString3 in result)
        self.assertTrue(innerString4 not in result)
        self.assertTrue(innerString5 in result)
Пример #36
0
class HtmlHeadsTest (unittest.TestCase):

    def setUp(self):
        self.maxDiff = None

        self.filesPath = u"../test/samplefiles/"
        self.__createWiki()
        self.testPage = self.wikiroot[u"Страница 1"]

        dirlist = [u"../plugins/htmlheads"]

        self.loader = PluginsLoader(Application)
        self.loader.load(dirlist)

        self.factory = ParserFactory()
        self.parser = self.factory.make (self.testPage, Application.config)


    def __createWiki (self):
        # Здесь будет создаваться вики
        self.path = mkdtemp (prefix=u'Абырвалг абыр')

        self.wikiroot = WikiDocument.create (self.path)

        WikiPageFactory().create (self.wikiroot, u"Страница 1", [])


    def tearDown(self):
        removeDir (self.path)
        self.loader.clear()


    def testPluginLoad (self):
        self.assertEqual (len (self.loader), 1)


    def testTitle_01 (self):
        text = u'(:title Бла-бла-бла:)'

        self.testPage.content = text

        generator = HtmlGenerator (self.testPage)
        result = generator.makeHtml (Style().getPageStyle (self.testPage))

        self.assertIn (u"<title>Бла-бла-бла</title>", result)


    def testTitle_02 (self):
        text = u'(:title    Бла-бла-бла бла-бла   :)'

        self.testPage.content = text

        generator = HtmlGenerator (self.testPage)
        result = generator.makeHtml (Style().getPageStyle (self.testPage))

        self.assertIn (u"<title>Бла-бла-бла бла-бла</title>", result)


    def testDescription_01 (self):
        text = u'(:description Бла-бла-бла абырвалг:)'

        self.testPage.content = text

        generator = HtmlGenerator (self.testPage)
        result = generator.makeHtml (Style().getPageStyle (self.testPage))

        self.assertIn (u'<meta name="description" content="Бла-бла-бла абырвалг"/>', result)


    def testDescription_02 (self):
        text = u'(:description    Бла-бла-бла абырвалг   :)'

        self.testPage.content = text

        generator = HtmlGenerator (self.testPage)
        result = generator.makeHtml (Style().getPageStyle (self.testPage))

        self.assertIn (u'<meta name="description" content="Бла-бла-бла абырвалг"/>', result)


    def testDescription_03 (self):
        text = u'(:description:)'

        self.testPage.content = text

        generator = HtmlGenerator (self.testPage)
        result = generator.makeHtml (Style().getPageStyle (self.testPage))

        self.assertIn (u'<meta name="description" content=""/>', result)


    def testKeywords_01 (self):
        text = u'(:keywords Бла-бла-бла, абырвалг:)'

        self.testPage.content = text

        generator = HtmlGenerator (self.testPage)
        result = generator.makeHtml (Style().getPageStyle (self.testPage))

        self.assertIn (u'<meta name="keywords" content="Бла-бла-бла, абырвалг"/>', result)


    def testKeywords_02 (self):
        text = u'(:keywords     Бла-бла-бла, абырвалг    :)'

        self.testPage.content = text

        generator = HtmlGenerator (self.testPage)
        result = generator.makeHtml (Style().getPageStyle (self.testPage))

        self.assertIn (u'<meta name="keywords" content="Бла-бла-бла, абырвалг"/>', result)


    def testKeywords_03 (self):
        text = u'(:keywords:)'

        self.testPage.content = text

        generator = HtmlGenerator (self.testPage)
        result = generator.makeHtml (Style().getPageStyle (self.testPage))

        self.assertIn (u'<meta name="keywords" content=""/>', result)


    def testHtmlHead_01 (self):
        text = u'''(:htmlhead:)<meta name="keywords" content="Бла-бла-бла, абырвалг"/>(:htmlheadend:)'''

        self.testPage.content = text

        generator = HtmlGenerator (self.testPage)
        result = generator.makeHtml (Style().getPageStyle (self.testPage))

        self.assertIn (u'<meta name="keywords" content="Бла-бла-бла, абырвалг"/>', result)
        self.assertNotIn ("(:htmlhead:)", result)


    def testHtmlHead_02 (self):
        text = u'''(:htmlhead:)
        <meta name="keywords" content="Бла-бла-бла, абырвалг"/>
        <meta name="description" content="Бла-бла-бла абырвалг"/>
(:htmlheadend:)'''

        self.testPage.content = text

        generator = HtmlGenerator (self.testPage)
        result = generator.makeHtml (Style().getPageStyle (self.testPage))

        self.assertIn (u'<meta name="keywords" content="Бла-бла-бла, абырвалг"/>', result)
        self.assertIn (u'<meta name="description" content="Бла-бла-бла абырвалг"/>', result)
        self.assertNotIn ("(:htmlhead:)", result)


    def testHtmlHead_03 (self):
        text = u'''(:htmlhead:)(:htmlheadend:)'''

        self.testPage.content = text

        generator = HtmlGenerator (self.testPage)
        result = generator.makeHtml (Style().getPageStyle (self.testPage))

        self.assertNotIn ("(:htmlhead:)", result)
Пример #37
0
class TexEquationToolsWindowTest(unittest.TestCase, BaseOutWikerGUIMixin):
    def setUp(self):
        self.initApplication()
        self.wikiroot = self.createWiki()
        self.testPage = WikiPageFactory().create(self.wikiroot,
                                                 "Страница 1",
                                                 [])

        self.filesPath = "../test/samplefiles/"
        dirlist = ["../plugins/texequation"]

        self.loader = PluginsLoader(self.application)
        self.loader.load(dirlist)

        self.testPage = self.wikiroot["Страница 1"]

    def tearDown(self):
        self.loader.clear()
        self.destroyApplication()
        self.destroyWiki(self.wikiroot)

    def test_equationExtract_empty(self):
        from texequation.toolswindowcontroller import ToolsWindowController

        text = ''
        position = 0

        equation, blockMode = ToolsWindowController.extractEquation(text,
                                                                    position)
        self.assertEqual(equation, '')
        self.assertFalse(blockMode)

    def test_equationExtract_miss_01(self):
        from texequation.toolswindowcontroller import ToolsWindowController

        text = '{$a=b$}'
        position = 0

        equation, blockMode = ToolsWindowController.extractEquation(text,
                                                                    position)
        self.assertEqual(equation, '')
        self.assertFalse(blockMode)

    def test_equationExtract_inline_01(self):
        from texequation.toolswindowcontroller import ToolsWindowController

        text = '{$a=b$}'
        position = 2

        equation, blockMode = ToolsWindowController.extractEquation(text,
                                                                    position)
        self.assertEqual(equation, 'a=b')
        self.assertFalse(blockMode)

    def test_equationExtract_block_01(self):
        from texequation.toolswindowcontroller import ToolsWindowController

        text = '{$$a=b$$}'
        position = 3

        equation, blockMode = ToolsWindowController.extractEquation(text,
                                                                    position)
        self.assertEqual(equation, 'a=b')
        self.assertTrue(blockMode)

    def test_equationExtract_block_02(self):
        from texequation.toolswindowcontroller import ToolsWindowController

        text = '{$$a=b$$}'
        position = 6

        equation, blockMode = ToolsWindowController.extractEquation(text,
                                                                    position)
        self.assertEqual(equation, 'a=b')
        self.assertTrue(blockMode)

    def test_equationExtract_block_03(self):
        from texequation.toolswindowcontroller import ToolsWindowController

        text = '{$$a=b$$}'
        position = 7

        equation, blockMode = ToolsWindowController.extractEquation(text,
                                                                    position)
        self.assertEqual(equation, 'a=b')
        self.assertTrue(blockMode)

    def test_equationExtract_block_miss_02(self):
        from texequation.toolswindowcontroller import ToolsWindowController

        text = '{$$a=b$$}'
        position = 9

        equation, blockMode = ToolsWindowController.extractEquation(text,
                                                                    position)
        self.assertEqual(equation, '')
        self.assertFalse(blockMode)

    def test_equationExtract_inline_02(self):
        from texequation.toolswindowcontroller import ToolsWindowController

        text = '{$...$} {$a=b$} {$...$}'
        position = 10

        equation, blockMode = ToolsWindowController.extractEquation(text,
                                                                    position)
        self.assertEqual(equation, 'a=b')
        self.assertFalse(blockMode)
Пример #38
0
class PageStatisticsTest (unittest.TestCase):
    """Тесты плагина Statistics применительно к статистике страницы"""
    def setUp (self):
        self.__pluginname = u"Statistics"

        self.__createWiki()

        dirlist = [u"../plugins/statistics"]

        self.loader = PluginsLoader(Application)
        self.loader.load (dirlist)

        filesPath = u"../test/samplefiles/"
        self.files = [u"accept.png", u"add.png", u"anchor.png", u"dir"]
        self.fullFilesPath = [os.path.join (filesPath, fname) for fname in self.files]


    def tearDown (self):
        removeDir (self.path)
        self.loader.clear()


    def __createWiki (self):
        # Здесь будет создаваться вики
        self.path = mkdtemp (prefix=u'Абырвалг абыр')

        self.wikiroot = WikiDocument.create (self.path)


    def testPluginLoad (self):
        self.assertEqual (len (self.loader), 1)


    def testSymbolsCountWiki (self):
        from statistics.pagestat import PageStat

        WikiPageFactory().create (self.wikiroot, u"Страница 1", [])
        testPage = self.wikiroot[u"Страница 1"]

        testPage.content = u"Бла бла бла"
        pageStat = PageStat (testPage)

        self.assertEqual (pageStat.symbols, 11)


    def testSymbolsCountHtml (self):
        from statistics.pagestat import PageStat

        HtmlPageFactory().create (self.wikiroot, u"Страница 1", [])
        testPage = self.wikiroot[u"Страница 1"]

        testPage.content = u"Бла бла бла"
        pageStat = PageStat (testPage)

        self.assertEqual (pageStat.symbols, 11)


    def testSymbolsCountText (self):
        from statistics.pagestat import PageStat

        TextPageFactory().create (self.wikiroot, u"Страница 1", [])
        testPage = self.wikiroot[u"Страница 1"]

        testPage.content = u"Бла бла бла"
        pageStat = PageStat (testPage)

        self.assertEqual (pageStat.symbols, 11)


    def testSymbolsCountSearch (self):
        def runTest ():
            from statistics.pagestat import PageStat

            SearchPageFactory().create (self.wikiroot, u"Страница 1", [])
            testPage = self.wikiroot[u"Страница 1"]

            pageStat = PageStat (testPage)
            pageStat.symbols

        self.assertRaises (TypeError, runTest)


    def testSymbolsNotWhiteSpacesWiki (self):
        from statistics.pagestat import PageStat

        WikiPageFactory().create (self.wikiroot, u"Страница 1", [])
        testPage = self.wikiroot[u"Страница 1"]

        testPage.content = u"Бла бла бла\r\n\t\t\tАбырвалг  "
        pageStat = PageStat (testPage)

        self.assertEqual (pageStat.symbolsNotWhiteSpaces, 17)


    def testSymbolsNotWhiteSpacesHtml (self):
        from statistics.pagestat import PageStat

        HtmlPageFactory().create (self.wikiroot, u"Страница 1", [])
        testPage = self.wikiroot[u"Страница 1"]

        testPage.content = u"Бла бла бла\r\n\t\t\tАбырвалг  "
        pageStat = PageStat (testPage)

        self.assertEqual (pageStat.symbolsNotWhiteSpaces, 17)


    def testSymbolsNotWhiteSpacesText (self):
        from statistics.pagestat import PageStat

        TextPageFactory().create (self.wikiroot, u"Страница 1", [])
        testPage = self.wikiroot[u"Страница 1"]

        testPage.content = u"Бла бла бла\r\n\t\t\tАбырвалг  "
        pageStat = PageStat (testPage)

        self.assertEqual (pageStat.symbolsNotWhiteSpaces, 17)


    def testSymbolsNotWhiteSpacesSearch (self):
        def runTest ():
            from statistics.pagestat import PageStat

            SearchPageFactory().create (self.wikiroot, u"Страница 1", [])
            testPage = self.wikiroot[u"Страница 1"]

            pageStat = PageStat (testPage)
            pageStat.symbolsNotWhiteSpaces

        self.assertRaises (TypeError, runTest)


    def testLinesWiki1 (self):
        from statistics.pagestat import PageStat

        WikiPageFactory().create (self.wikiroot, u"Страница 1", [])
        testPage = self.wikiroot[u"Страница 1"]

        testPage.content = u"""Бла бла бла
Еще одна строка
И еще строка
Последняя строка"""

        pageStat = PageStat (testPage)

        self.assertEqual (pageStat.lines, 4)


    def testLinesWiki2 (self):
        from statistics.pagestat import PageStat

        WikiPageFactory().create (self.wikiroot, u"Страница 1", [])
        testPage = self.wikiroot[u"Страница 1"]

        testPage.content = u"""Бла бла бла
Еще одна строка

И еще строка

Последняя строка

"""

        pageStat = PageStat (testPage)

        self.assertEqual (pageStat.lines, 4)


    def testLinesHtml1 (self):
        from statistics.pagestat import PageStat

        HtmlPageFactory().create (self.wikiroot, u"Страница 1", [])
        testPage = self.wikiroot[u"Страница 1"]

        testPage.content = u"""Бла бла бла
Еще одна строка
И еще строка
Последняя строка"""

        pageStat = PageStat (testPage)

        self.assertEqual (pageStat.lines, 4)


    def testLinesHtml2 (self):
        from statistics.pagestat import PageStat

        HtmlPageFactory().create (self.wikiroot, u"Страница 1", [])
        testPage = self.wikiroot[u"Страница 1"]

        testPage.content = u"""Бла бла бла
Еще одна строка

И еще строка

Последняя строка

"""

        pageStat = PageStat (testPage)

        self.assertEqual (pageStat.lines, 4)


    def testLinesText1 (self):
        from statistics.pagestat import PageStat

        TextPageFactory().create (self.wikiroot, u"Страница 1", [])
        testPage = self.wikiroot[u"Страница 1"]

        testPage.content = u"""Бла бла бла
Еще одна строка
И еще строка
Последняя строка"""

        pageStat = PageStat (testPage)

        self.assertEqual (pageStat.lines, 4)


    def testLinesText2 (self):
        from statistics.pagestat import PageStat

        TextPageFactory().create (self.wikiroot, u"Страница 1", [])
        testPage = self.wikiroot[u"Страница 1"]

        testPage.content = u"""Бла бла бла
Еще одна строка

И еще строка

Последняя строка

"""

        pageStat = PageStat (testPage)

        self.assertEqual (pageStat.lines, 4)


    def testWordsWiki1 (self):
        from statistics.pagestat import PageStat

        WikiPageFactory().create (self.wikiroot, u"Страница 1", [])
        testPage = self.wikiroot[u"Страница 1"]

        testPage.content = u"""Бла бла бла
Еще одна строка

И еще строка

Последняя строка

"""

        pageStat = PageStat (testPage)

        self.assertEqual (pageStat.words, 11)


    def testWordsWiki2 (self):
        from statistics.pagestat import PageStat

        WikiPageFactory().create (self.wikiroot, u"Страница 1", [])
        testPage = self.wikiroot[u"Страница 1"]

        testPage.content = u"""Бла бла бла.
Еще одна строка111 222 333

И еще строка ... ... ;;; @#$%#$

Последняя строка

"""

        pageStat = PageStat (testPage)

        self.assertEqual (pageStat.words, 13)


    def testWordsHtml1 (self):
        from statistics.pagestat import PageStat

        HtmlPageFactory().create (self.wikiroot, u"Страница 1", [])
        testPage = self.wikiroot[u"Страница 1"]

        testPage.content = u"""Бла бла бла
Еще одна строка

И еще строка

Последняя строка

"""

        pageStat = PageStat (testPage)

        self.assertEqual (pageStat.words, 11)


    def testWordsHtml2 (self):
        from statistics.pagestat import PageStat

        HtmlPageFactory().create (self.wikiroot, u"Страница 1", [])
        testPage = self.wikiroot[u"Страница 1"]

        testPage.content = u"""Бла бла бла.
Еще одна строка111 222 333

И еще строка ... ... ;;; @#$%#$

Последняя строка

"""

        pageStat = PageStat (testPage)

        self.assertEqual (pageStat.words, 13)


    def testWordsText1 (self):
        from statistics.pagestat import PageStat

        TextPageFactory().create (self.wikiroot, u"Страница 1", [])
        testPage = self.wikiroot[u"Страница 1"]

        testPage.content = u"""Бла бла бла
Еще одна строка

И еще строка

Последняя строка

"""

        pageStat = PageStat (testPage)

        self.assertEqual (pageStat.words, 11)


    def testWordsText2 (self):
        from statistics.pagestat import PageStat

        TextPageFactory().create (self.wikiroot, u"Страница 1", [])
        testPage = self.wikiroot[u"Страница 1"]

        testPage.content = u"""Бла бла бла.
Еще одна строка111 222 333

И еще строка ... ... ;;; @#$%#$

Последняя строка

"""

        pageStat = PageStat (testPage)

        self.assertEqual (pageStat.words, 13)


    def testWordsSearch (self):
        def runTest ():
            from statistics.pagestat import PageStat

            SearchPageFactory().create (self.wikiroot, u"Страница 1", [])
            testPage = self.wikiroot[u"Страница 1"]

            pageStat = PageStat (testPage)
            pageStat.words

        self.assertRaises (TypeError, runTest)


    def testAttachmentsCountWiki1 (self):
        from statistics.pagestat import PageStat

        WikiPageFactory().create (self.wikiroot, u"Страница 1", [])
        testPage = self.wikiroot[u"Страница 1"]

        pageStat = PageStat (testPage)

        self.assertEqual (pageStat.attachmentsCount, 0)


    def testAttachmentsCountWiki2 (self):
        from statistics.pagestat import PageStat

        WikiPageFactory().create (self.wikiroot, u"Страница 1", [])
        testPage = self.wikiroot[u"Страница 1"]
        Attachment (testPage).attach (self.fullFilesPath[0:1])

        pageStat = PageStat (testPage)

        self.assertEqual (pageStat.attachmentsCount, 1)


    def testAttachmentsCountWiki3 (self):
        from statistics.pagestat import PageStat

        WikiPageFactory().create (self.wikiroot, u"Страница 1", [])
        testPage = self.wikiroot[u"Страница 1"]
        Attachment (testPage).attach (self.fullFilesPath[0:3])

        pageStat = PageStat (testPage)

        self.assertEqual (pageStat.attachmentsCount, 3)


    def testAttachmentsCountWiki4 (self):
        from statistics.pagestat import PageStat

        WikiPageFactory().create (self.wikiroot, u"Страница 1", [])
        testPage = self.wikiroot[u"Страница 1"]
        Attachment (testPage).attach (self.fullFilesPath)

        pageStat = PageStat (testPage)

        self.assertEqual (pageStat.attachmentsCount, 6)


    def testAttachmentsCountSearch1 (self):
        from statistics.pagestat import PageStat

        SearchPageFactory().create (self.wikiroot, u"Страница 1", [])
        testPage = self.wikiroot[u"Страница 1"]
        Attachment (testPage).attach (self.fullFilesPath)

        pageStat = PageStat (testPage)

        self.assertEqual (pageStat.attachmentsCount, 6)


    def testAttachmentsSizeWiki1 (self):
        from statistics.pagestat import PageStat

        WikiPageFactory().create (self.wikiroot, u"Страница 1", [])
        testPage = self.wikiroot[u"Страница 1"]

        pageStat = PageStat (testPage)

        self.assertEqual (pageStat.attachmentsSize, 0)


    def testAttachmentsSizeWiki2 (self):
        from statistics.pagestat import PageStat

        WikiPageFactory().create (self.wikiroot, u"Страница 1", [])
        testPage = self.wikiroot[u"Страница 1"]
        Attachment (testPage).attach (self.fullFilesPath[0:1])

        pageStat = PageStat (testPage)

        self.assertEqual (pageStat.attachmentsSize, 781)


    def testAttachmentsSizeWiki3 (self):
        from statistics.pagestat import PageStat

        WikiPageFactory().create (self.wikiroot, u"Страница 1", [])
        testPage = self.wikiroot[u"Страница 1"]
        Attachment (testPage).attach (self.fullFilesPath[0:3])

        pageStat = PageStat (testPage)

        self.assertEqual (pageStat.attachmentsSize, 2037)


    def testAttachmentsSizeWiki4 (self):
        from statistics.pagestat import PageStat

        WikiPageFactory().create (self.wikiroot, u"Страница 1", [])
        testPage = self.wikiroot[u"Страница 1"]
        Attachment (testPage).attach (self.fullFilesPath)

        pageStat = PageStat (testPage)

        self.assertAlmostEqual (pageStat.attachmentsSize, 11771, delta=300)


    def testAttachmentsSizeSearch1 (self):
        from statistics.pagestat import PageStat

        SearchPageFactory().create (self.wikiroot, u"Страница 1", [])
        testPage = self.wikiroot[u"Страница 1"]
        Attachment (testPage).attach (self.fullFilesPath)

        pageStat = PageStat (testPage)

        self.assertAlmostEqual (pageStat.attachmentsSize, 11771, delta=300)
Пример #39
0
class SourceGuiPluginTest (unittest.TestCase, BaseOutWikerGUIMixin):
    """
    Тесты интерфейса для плагина Source
    """

    def setUp(self):
        self.__pluginname = "Source"
        self.initApplication()
        self.wikiroot = self.createWiki()
        self.testPage = WikiPageFactory().create(self.wikiroot,
                                                 "Страница 1",
                                                 [])

        dirlist = ["../plugins/source"]
        self._stylesCount = 35

        self.loader = PluginsLoader(self.application)
        self.loader.load(dirlist)

        self.config = self.loader[self.__pluginname].config
        self._clearConfig(self.config)

        from source.insertdialogcontroller import InsertDialogController
        self.dialog = FakeInsertDialog()
        self.controller = InsertDialogController(
            self.testPage, self.dialog, self.config)

    def tearDown(self):
        self._clearConfig(self.config)
        self.loader.clear()
        self.destroyApplication()
        self.destroyWiki(self.wikiroot)

    def _clearConfig(self, config):
        self.application.config.remove_section(self.config.section)

    def testDialogController1(self):
        """
        Тест контроллера диалога для вставки команды (:source:)
        """
        self.dialog.SetReturnCode(wx.ID_CANCEL)
        result = self.controller.showDialog()

        self.assertEqual(result, wx.ID_CANCEL)

    def testDialogController2(self):
        """
        Тест контроллера диалога для вставки команды (:source:)
        """
        self.dialog.SetReturnCode(wx.ID_OK)
        result = self.controller.showDialog()

        self.assertEqual(result, wx.ID_OK)

    def testDialogControllerResult1(self):
        """
        Тест контроллера диалога для вставки команды (:source:)
        """
        self.config.languageList.value = ["python", "cpp", "haskell", "text"]
        self.config.defaultLanguage.value = "text"

        self.dialog.SetReturnCode(wx.ID_OK)
        self.controller.showDialog()

        self.dialog.tabWidthSpin.SetValue(4)
        result = self.controller.getCommandStrings()

        self.assertEqual(
            result, ('(:source lang="text" tabwidth="4":)\n', '\n(:sourceend:)'))

    def testDialogControllerResult2(self):
        """
        Тест контроллера диалога для вставки команды (:source:)
        """
        self.config.defaultLanguage.value = "python"

        self.dialog.SetReturnCode(wx.ID_OK)
        self.controller.showDialog()

        self.dialog.tabWidthSpin.SetValue(8)
        result = self.controller.getCommandStrings()

        self.assertEqual(
            result, ('(:source lang="python" tabwidth="8":)\n', '\n(:sourceend:)'))

    def testDialogControllerResult3(self):
        """
        Тест контроллера диалога для вставки команды (:source:)
        """
        self.config.languageList.value = ["python", "cpp", "haskell", "text"]
        self.config.defaultLanguage.value = "text"

        self.dialog.SetReturnCode(wx.ID_OK)
        self.controller.showDialog()

        self.dialog.tabWidthSpin.SetValue(4)
        result = self.controller.getCommandStrings()

        self.assertEqual(
            result, ('(:source lang="text" tabwidth="4":)\n', '\n(:sourceend:)'))

    def testDialogControllerResult4(self):
        """
        Тест контроллера диалога для вставки команды (:source:)
        """
        self.config.languageList.value = ["python", "cpp", "haskell", "text"]
        self.config.defaultLanguage.value = "text"

        self.dialog.SetReturnCode(wx.ID_OK)
        self.controller.showDialog()

        self.dialog.tabWidthSpin.SetValue(0)
        result = self.controller.getCommandStrings()

        self.assertEqual(
            result, ('(:source lang="text":)\n', '\n(:sourceend:)'))

    def testDialogControllerResult5(self):
        """
        Тест контроллера диалога для вставки команды (:source:)
        """
        self.config.languageList.value = ["python", "cpp", "haskell", "text"]
        self.config.defaultLanguage.value = "text"

        self.dialog.SetReturnCode(wx.ID_OK)
        self.controller.showDialog()

        self.dialog.languageComboBox.SetSelection(0)
        self.dialog.tabWidthSpin.SetValue(0)
        result = self.controller.getCommandStrings()

        self.assertEqual(
            result, ('(:source lang="cpp":)\n', '\n(:sourceend:)'))

    def testDialogControllerResult6(self):
        """
        Тест контроллера диалога для вставки команды (:source:)
        """
        self.config.languageList.value = ["python", "cpp", "haskell", "text"]
        self.config.defaultLanguage.value = "text"

        self.dialog.SetReturnCode(wx.ID_OK)
        self.controller.showDialog()

        self.dialog.languageComboBox.SetSelection(1)
        self.dialog.tabWidthSpin.SetValue(0)
        result = self.controller.getCommandStrings()

        self.assertEqual(
            result, ('(:source lang="haskell":)\n', '\n(:sourceend:)'))

    def testSourceConfig1(self):
        self.config.defaultLanguage.value = "python"
        self.config.tabWidth.value = 8
        self.config.dialogWidth.value = 100
        self.config.dialogHeight.value = 200
        self.config.languageList.value = ["python", "cpp", "haskell"]

        self.assertEqual(self.config.defaultLanguage.value, "python")
        self.assertEqual(self.config.tabWidth.value, 8)
        self.assertEqual(self.config.dialogWidth.value, 100)
        self.assertEqual(self.config.dialogHeight.value, 200)
        self.assertEqual(self.config.languageList.value,
                         ["python", "cpp", "haskell"])

    def testDialogLanguageValues1(self):
        self.config.languageList.value = ["python", "cpp", "haskell"]
        self.config.defaultLanguage.value = "haskell"

        self.controller.showDialog()

        self.assertEqual(self.dialog.languageComboBox.GetItems(),
                         ["C++", "Haskell", "Python", "Other..."])

        self.assertEqual(self.dialog.languageComboBox.GetSelection(), 1)
        self.assertEqual(self.dialog.languageComboBox.GetValue(), "Haskell")

        self.assertEqual(self.dialog.tabWidthSpin.GetValue(), 0)

    def testDialogLanguageValues2(self):
        self.config.languageList.value = []
        self.config.defaultLanguage.value = "haskell"

        self.controller.showDialog()

        self.assertEqual(self.dialog.languageComboBox.GetItems(),
                         ["text", "Other..."])

        self.assertEqual(self.dialog.languageComboBox.GetSelection(), 0)
        self.assertEqual(self.dialog.languageComboBox.GetValue(), "text")

    def testDialogLanguageValues3(self):
        self.config.languageList.value = ["python", "cpp", "haskell"]
        self.config.defaultLanguage.value = "c"

        self.controller.showDialog()

        self.assertEqual(self.dialog.languageComboBox.GetItems(), [
                         "C++", "Haskell", "Python", "Other..."])

        self.assertEqual(self.dialog.languageComboBox.GetSelection(), 0)
        self.assertEqual(self.dialog.languageComboBox.GetValue(), "C++")

    def testDialogLanguageValues4(self):
        self.config.languageList.value = ["python", "cpp", "haskell"]
        self.config.defaultLanguage.value = "   haskell   "

        self.controller.showDialog()

        self.assertEqual(self.dialog.languageComboBox.GetItems(),
                         ["C++", "Haskell", "Python", "Other..."])

        self.assertEqual(self.dialog.languageComboBox.GetSelection(), 1)
        self.assertEqual(self.dialog.languageComboBox.GetValue(), "Haskell")

        self.assertEqual(self.dialog.tabWidthSpin.GetValue(), 0)

    def testDialogStyleValues1(self):
        self.config.languageList.value = ["python", "cpp", "haskell"]
        self.config.defaultLanguage.value = "python"

        self.controller.showDialog()

        self.assertEqual(self.dialog.styleComboBox.GetCount(),
                         self._stylesCount)
        self.assertEqual(self.dialog.styleComboBox.GetValue(), "default")

        result = self.controller.getCommandStrings()

        self.assertEqual(
            result, ('(:source lang="python":)\n', '\n(:sourceend:)'))

    def testDialogStyleValues2(self):
        self.config.defaultStyle.value = "blablabla"
        self.controller.showDialog()

        self.assertEqual(self.dialog.styleComboBox.GetCount(),
                         self._stylesCount)
        self.assertEqual(self.dialog.styleComboBox.GetValue(), "default")

    def testDialogStyleValues3(self):
        self.config.defaultStyle.value = ""
        self.controller.showDialog()

        self.assertEqual(self.dialog.styleComboBox.GetCount(),
                         self._stylesCount)
        self.assertEqual(self.dialog.styleComboBox.GetValue(), "default")

    def testDialogStyleValues4(self):
        self.config.defaultStyle.value = "vim"
        self.controller.showDialog()

        self.assertEqual(self.dialog.styleComboBox.GetCount(),
                         self._stylesCount)
        self.assertEqual(self.dialog.styleComboBox.GetValue(), "vim")

    def testDialogStyleValues5(self):
        self.config.defaultStyle.value = "emacs"
        self.controller.showDialog()

        self.assertEqual(self.dialog.styleComboBox.GetCount(),
                         self._stylesCount)
        self.assertEqual(self.dialog.styleComboBox.GetValue(), "emacs")

    def testDialogStyle1(self):
        self.config.languageList.value = ["python", "cpp", "haskell"]
        self.config.defaultLanguage.value = "python"
        self.config.defaultStyle.value = "vim"
        self.config.style.value = "vim"

        self.controller.showDialog()

        self.assertEqual(self.dialog.styleComboBox.GetCount(),
                         self._stylesCount)
        self.assertEqual(self.dialog.styleComboBox.GetValue(), "vim")

        result = self.controller.getCommandStrings()

        self.assertEqual(
            result, ('(:source lang="python":)\n', '\n(:sourceend:)'))

    def testDialogStyle2(self):
        self.config.languageList.value = ["python", "cpp", "haskell"]
        self.config.defaultLanguage.value = "python"
        self.config.defaultStyle.value = "vim"
        self.config.style.value = "default"

        self.controller.showDialog()

        self.assertEqual(self.dialog.styleComboBox.GetCount(),
                         self._stylesCount)
        self.assertEqual(self.dialog.styleComboBox.GetValue(), "default")

        result = self.controller.getCommandStrings()

        self.assertEqual(
            result, ('(:source lang="python" style="default":)\n', '\n(:sourceend:)'))

    def testDialogStyleText(self):
        self.config.languageList.value = ["python", "cpp", "haskell"]
        self.config.defaultLanguage.value = "python"

        self.controller.showDialog()
        self.dialog.styleComboBox.SetSelection(0)

        self.assertEqual(self.dialog.styleComboBox.GetValue(), "abap")
        self.assertEqual(self.dialog.style, "abap")

        result = self.controller.getCommandStrings()

        self.assertEqual(
            result, ('(:source lang="python" style="abap":)\n', '\n(:sourceend:)'))

    def testDialogStyleFile(self):
        self.samplefilesPath = "../test/samplefiles/sources"
        Attachment(self.testPage).attach(
            [os.path.join(self.samplefilesPath, "source_utf8.py")])
        Attachment(self.testPage).attach(
            [os.path.join(self.samplefilesPath, "source_cp1251.cs")])

        self.config.languageList.value = ["python", "cpp", "haskell"]
        self.config.defaultLanguage.value = "python"

        self.controller.showDialog()

        self.dialog.fileCheckBox.SetValue(True)
        self.dialog.styleComboBox.SetSelection(0)
        self.dialog.attachmentComboBox.SetSelection(0)

        self.assertEqual(self.dialog.styleComboBox.GetValue(), "abap")
        self.assertEqual(self.dialog.style, "abap")

        result = self.controller.getCommandStrings()

        self.assertEqual(
            result, ('(:source file="Attach:source_cp1251.cs" lang="python" style="abap":)', '(:sourceend:)'))

    def testDialogStyleFile2(self):
        self.samplefilesPath = "../test/samplefiles/sources"
        Attachment(self.testPage).attach(
            [os.path.join(self.samplefilesPath, "source_utf8.py")])
        Attachment(self.testPage).attach(
            [os.path.join(self.samplefilesPath, "source_cp1251.cs")])

        self.config.languageList.value = ["python", "cpp", "haskell"]
        self.config.defaultLanguage.value = "python"

        self.controller.showDialog()

        self.dialog.fileCheckBox.SetValue(True)
        self.dialog.styleComboBox.SetSelection(0)
        self.dialog.attachmentComboBox.SetSelection(0)
        self.dialog.languageComboBox.SetSelection(0)

        self.assertEqual(self.dialog.styleComboBox.GetValue(), "abap")
        self.assertEqual(self.dialog.style, "abap")

        result = self.controller.getCommandStrings()

        self.assertEqual(
            result, ('(:source file="Attach:source_cp1251.cs" style="abap":)', '(:sourceend:)'))

    def testDialogStyleText2(self):
        self.config.languageList.value = ["python", "cpp", "haskell"]
        self.config.defaultLanguage.value = "python"

        self.controller.showDialog()
        self.dialog.styleComboBox.SetSelection(0)
        self.dialog.tabWidthSpin.SetValue(5)

        self.assertEqual(self.dialog.styleComboBox.GetValue(), "abap")
        self.assertEqual(self.dialog.style, "abap")

        result = self.controller.getCommandStrings()

        self.assertEqual(
            result, ('(:source lang="python" tabwidth="5" style="abap":)\n', '\n(:sourceend:)'))

    def testStyleConfig1(self):
        self.config.style.value = "default"

        self.controller.showDialog()
        self.assertEqual(self.dialog.style, "default")

    def testStyleConfig2(self):
        self.config.style.value = "vim"

        self.controller.showDialog()
        self.assertEqual(self.dialog.style, "vim")

    def testStyleConfig3(self):
        self.config.style.value = "  vim   "

        self.controller.showDialog()
        self.assertEqual(self.dialog.style, "vim")

    def testStyleConfig4(self):
        self.config.style.value = "invalid_style"

        self.controller.showDialog()
        self.assertEqual(self.dialog.style, "default")

    def testStyleConfig5(self):
        self.controller.showDialog()
        self.assertEqual(self.dialog.style, "default")

    def testParentBgConfig1(self):
        self.config.parentbg.value = "  False  "
        self.controller.showDialog()

        self.assertEqual(self.dialog.parentbg, False)

    def testParentBgConfig2(self):
        self.config.parentbg.value = "  True  "
        self.controller.showDialog()

        self.assertEqual(self.dialog.parentbg, True)

    def testParentBgConfig3(self):
        self.config.parentbg.value = "  блаблабла  "
        self.controller.showDialog()

        self.assertEqual(self.dialog.parentbg, False)

    def testParentBgConfig4(self):
        # Если нет вообще записей в файле настроек
        self.controller.showDialog()

        self.assertEqual(self.dialog.parentbg, False)

    def testLineNumConfig1(self):
        # Если нет вообще записей в файле настроек
        self.controller.showDialog()

        self.assertEqual(self.dialog.lineNum, False)

    def testLineNumConfig2(self):
        self.config.lineNum.value = "  False  "
        self.controller.showDialog()

        self.assertEqual(self.dialog.lineNum, False)

    def testLineNumConfig3(self):
        self.config.lineNum.value = "  блаблабла  "
        self.controller.showDialog()

        self.assertEqual(self.dialog.lineNum, False)

    def testLineNumConfig4(self):
        self.config.lineNum.value = "True"
        self.controller.showDialog()

        self.assertEqual(self.dialog.lineNum, True)

    def testDialogParengBg(self):
        self.config.languageList.value = ["python", "cpp", "haskell"]
        self.config.defaultLanguage.value = "python"

        self.controller.showDialog()
        self.dialog.parentBgCheckBox.SetValue(True)

        result = self.controller.getCommandStrings()

        self.assertEqual(
            result, ('(:source lang="python" parentbg:)\n', '\n(:sourceend:)'))

    def testDialogLineNum(self):
        self.config.languageList.value = ["python", "cpp", "haskell"]
        self.config.defaultLanguage.value = "python"

        self.controller.showDialog()
        self.dialog.lineNumCheckBox.SetValue(True)

        result = self.controller.getCommandStrings()

        self.assertEqual(
            result, ('(:source lang="python" linenum:)\n', '\n(:sourceend:)'))

    def testDialogParentBgLineNum(self):
        self.config.languageList.value = ["python", "cpp", "haskell"]
        self.config.defaultLanguage.value = "python"

        self.controller.showDialog()
        self.dialog.parentBgCheckBox.SetValue(True)
        self.dialog.lineNumCheckBox.SetValue(True)

        result = self.controller.getCommandStrings()

        self.assertEqual(
            result, ('(:source lang="python" parentbg linenum:)\n', '\n(:sourceend:)'))

    def testDialogTabWidth(self):
        self.config.languageList.value = ["python", "cpp", "haskell"]
        self.config.defaultLanguage.value = "python"

        self.controller.showDialog()
        self.dialog.tabWidthSpin.SetValue(10)

        result = self.controller.getCommandStrings()

        self.assertEqual(
            result, ('(:source lang="python" tabwidth="10":)\n', '\n(:sourceend:)'))
Пример #40
0
class InsertGroupTest(unittest.TestCase, BaseOutWikerGUIMixin):
    def setUp(self):
        self.initApplication()
        self.wikiroot = self.createWiki()
        dirlist = ["../plugins/diagrammer"]

        self.loader = PluginsLoader(Application)
        self.loader.load(dirlist)

        from diagrammer.gui.insertgroupdialog import (
            InsertGroupDialog,
            InsertGroupController
        )

        self._dlg = InsertGroupDialog(None)
        self._controller = InsertGroupController(self._dlg)
        Tester.dialogTester.clear()

    def tearDown(self):
        self.loader.clear()
        self._dlg.Destroy()
        self.destroyApplication()
        self.destroyWiki(self.wikiroot)

    def testDefault(self):
        Tester.dialogTester.appendOk()

        begin, end = self._controller.getResult()

        valid_begin = '''group {
    '''

        self.assertEqual(begin, valid_begin)
        self.assertEqual(end, "\n}")

    def testName_01(self):
        Tester.dialogTester.appendOk()
        self._dlg.name = "Абырвалг"

        begin, end = self._controller.getResult()

        valid_begin = '''group Абырвалг {
    '''

        self.assertEqual(begin, valid_begin)
        self.assertEqual(end, "\n}")

    def testBackColor_01(self):
        Tester.dialogTester.appendOk()
        self._dlg.isBackColorChanged = True
        self._dlg.backColor = "blue"

        begin, end = self._controller.getResult()

        valid_begin = '''group {
    color = "blue";

    '''

        self.assertEqual(begin, valid_begin)
        self.assertEqual(end, "\n}")

    def testBackColor_02(self):
        Tester.dialogTester.appendOk()
        self._dlg.isBackColorChanged = False
        self._dlg.backColor = "blue"

        begin, end = self._controller.getResult()

        valid_begin = '''group {
    '''

        self.assertEqual(begin, valid_begin)
        self.assertEqual(end, "\n}")

    def testBackColor_03(self):
        Tester.dialogTester.appendOk()
        self._dlg.isBackColorChanged = True
        self._dlg.backColor = "#AAAAAA"

        begin, end = self._controller.getResult()

        valid_begin = '''group {
    color = "#AAAAAA";

    '''

        self.assertEqual(begin, valid_begin)
        self.assertEqual(end, "\n}")

    def testOrientation_01(self):
        Tester.dialogTester.appendOk()
        self._dlg.isOrientationChanged = True
        self._dlg.orientationIndex = 0

        begin, end = self._controller.getResult()

        valid_begin = '''group {
    orientation = landscape;

    '''

        self.assertEqual(begin, valid_begin)

    def testOrientation_02(self):
        Tester.dialogTester.appendOk()
        self._dlg.isOrientationChanged = True
        self._dlg.orientationIndex = 1

        begin, end = self._controller.getResult()

        valid_begin = '''group {
    orientation = portrait;

    '''

        self.assertEqual(begin, valid_begin)

    def testOrientation_03(self):
        Tester.dialogTester.appendOk()
        self._dlg.isOrientationChanged = False
        self._dlg.orientationIndex = 1

        begin, end = self._controller.getResult()

        valid_begin = '''group {
    '''

        self.assertEqual(begin, valid_begin)

    def testOrientation_04(self):
        Tester.dialogTester.appendOk()
        self._dlg.isOrientationChanged = True
        self._dlg.orientationIndex = 1
        self._dlg.isBackColorChanged = True
        self._dlg.backColor = "blue"

        begin, end = self._controller.getResult()

        valid_begin = '''group {
    color = "blue";
    orientation = portrait;

    '''

        self.assertEqual(begin, valid_begin)

    def testLabel_01(self):
        Tester.dialogTester.appendOk()
        self._dlg.label = "Абырвалг"

        begin, end = self._controller.getResult()

        valid_begin = '''group {
    label = "Абырвалг";

    '''

        self.assertEqual(begin, valid_begin)

    def testLabel_02(self):
        Tester.dialogTester.appendOk()
        self._dlg.label = ""

        begin, end = self._controller.getResult()

        valid_begin = '''group {
    '''

        self.assertEqual(begin, valid_begin)

    def testTextColor_01(self):
        Tester.dialogTester.appendOk()
        self._dlg.isTextColorChanged = True
        self._dlg.textColor = "blue"

        begin, end = self._controller.getResult()

        valid_begin = '''group {
    textcolor = "blue";

    '''

        self.assertEqual(begin, valid_begin)
        self.assertEqual(end, "\n}")

    def testTextColor_02(self):
        Tester.dialogTester.appendOk()
        self._dlg.isTextColorChanged = False
        self._dlg.textColor = "blue"

        begin, end = self._controller.getResult()

        valid_begin = '''group {
    '''

        self.assertEqual(begin, valid_begin)
        self.assertEqual(end, "\n}")

    def testTextColor_03(self):
        Tester.dialogTester.appendOk()
        self._dlg.isTextColorChanged = True
        self._dlg.textColor = "#AAAAAA"

        begin, end = self._controller.getResult()

        valid_begin = '''group {
    textcolor = "#AAAAAA";

    '''

        self.assertEqual(begin, valid_begin)
        self.assertEqual(end, "\n}")

    def testBorderShape_01(self):
        Tester.dialogTester.appendOk()
        self._dlg.isBorderShapeChanged = True
        self._dlg.borderShapeIndex = 0

        begin, end = self._controller.getResult()

        valid_begin = '''group {
    shape = box;

    '''

        self.assertEqual(begin, valid_begin)

    def testBorderShape_02(self):
        Tester.dialogTester.appendOk()
        self._dlg.isBorderShapeChanged = True
        self._dlg.borderShapeIndex = 1

        begin, end = self._controller.getResult()

        valid_begin = '''group {
    shape = line;

    '''

        self.assertEqual(begin, valid_begin)

    def testBorderShape_03(self):
        Tester.dialogTester.appendOk()
        self._dlg.isBorderShapeChanged = False
        self._dlg.borderShapeIndex = 1

        begin, end = self._controller.getResult()

        valid_begin = '''group {
    '''

        self.assertEqual(begin, valid_begin)

    def testBorderStyle_01(self):
        Tester.dialogTester.appendOk()
        self._dlg.isBorderShapeChanged = True
        self._dlg.borderShapeIndex = 1

        self._dlg.setStyleIndex(1)

        begin, end = self._controller.getResult()

        valid_begin = '''group {
    shape = line;
    style = solid;

    '''

        self.assertEqual(begin, valid_begin)

    def testBorderStyle_02(self):
        Tester.dialogTester.appendOk()
        self._dlg.isBorderShapeChanged = False
        self._dlg.borderShapeIndex = 1

        self._dlg.setStyleIndex(1)

        begin, end = self._controller.getResult()

        valid_begin = '''group {
    '''

        self.assertEqual(begin, valid_begin)

    def testBorderStyle_03(self):
        Tester.dialogTester.appendOk()
        self._dlg.isBorderShapeChanged = True
        self._dlg.borderShapeIndex = 0

        self._dlg.setStyleIndex(1)

        begin, end = self._controller.getResult()

        valid_begin = '''group {
    shape = box;

    '''

        self.assertEqual(begin, valid_begin)

    def testBorderStyle_04(self):
        Tester.dialogTester.appendOk()
        self._dlg.isBorderShapeChanged = True
        self._dlg.borderShapeIndex = 1

        self._dlg.setStyleIndex(2)

        begin, end = self._controller.getResult()

        valid_begin = '''group {
    shape = line;
    style = dotted;

    '''

        self.assertEqual(begin, valid_begin)

    def testBorderStyle_05(self):
        Tester.dialogTester.appendOk()
        self._dlg.isBorderShapeChanged = True
        self._dlg.borderShapeIndex = 1

        self._dlg.setStyleIndex(3)

        begin, end = self._controller.getResult()

        valid_begin = '''group {
    shape = line;
    style = dashed;

    '''

        self.assertEqual(begin, valid_begin)

    def testBorderStyle_06(self):
        Tester.dialogTester.appendOk()
        self._dlg.isBorderShapeChanged = True
        self._dlg.borderShapeIndex = 1

        self._dlg.style = "1,2,3,4"

        begin, end = self._controller.getResult()

        valid_begin = '''group {
    shape = line;
    style = "1,2,3,4";

    '''

        self.assertEqual(begin, valid_begin)

    def testBorderStyle_07(self):
        Tester.dialogTester.appendOk()
        self._dlg.isBorderShapeChanged = True
        self._dlg.borderShapeIndex = 1

        self._dlg.style = " 1, 2, 3, 4 "

        begin, end = self._controller.getResult()

        valid_begin = '''group {
    shape = line;
    style = "1,2,3,4";

    '''

        self.assertEqual(begin, valid_begin)
Пример #41
0
class DownloaderTest(unittest.TestCase):
    def setUp(self):
        self.plugindirlist = [u'../plugins/webpage']
        self._staticDirName = u'__download'
        self._tempDir = mkdtemp(prefix=u'Абырвалг абыр')

        self.loader = PluginsLoader(Application)
        self.loader.load(self.plugindirlist)

    def tearDown(self):
        self.loader.clear()
        removeDir(self._tempDir)

    def testContentImgExample1(self):
        from webpage.downloader import Downloader, DownloadController

        template = u'<img src="{path}"'

        controller = DownloadController(self._tempDir, self._staticDirName)
        downloader = Downloader()

        examplePath = u'../test/webpage/example1/'
        exampleHtmlPath = os.path.join(examplePath, u'example1.html')

        downloader.start(self._path2url(exampleHtmlPath), controller)

        self.assertIn(
            template.format(path=self._staticDirName + u'/image_01.png'),
            downloader.contentResult)

        self.assertIn(
            template.format(path=self._staticDirName + u'/картинка.png'),
            downloader.contentResult)

        self.assertIn(
            template.format(path=self._staticDirName + u'/image_01_1.png'),
            downloader.contentResult)

        self.assertIn(
            template.format(path=self._staticDirName + u'/image_02.png'),
            downloader.contentResult)

        self.assertNotIn(
            template.format(path=self._staticDirName + u'/image_02_1.png'),
            downloader.contentResult)

        self.assertIn(
            template.format(path=self._staticDirName + u'/image_03.png'),
            downloader.contentResult)

        self.assertNotIn(
            template.format(path=self._staticDirName + u'/image_03_1.png'),
            downloader.contentResult)

    def testContentCSSExample1_01(self):
        from webpage.downloader import Downloader, DownloadController

        template = u'<link href="{path}"'

        controller = DownloadController(self._tempDir, self._staticDirName)
        downloader = Downloader()

        examplePath = u'../test/webpage/example1/'
        exampleHtmlPath = os.path.join(examplePath, u'example1.html')

        downloader.start(self._path2url(exampleHtmlPath), controller)

        self.assertIn(
            template.format(path=self._staticDirName + u'/fname1.css'),
            downloader.contentResult)

        self.assertIn(
            template.format(path=self._staticDirName + u'/fname2.css'),
            downloader.contentResult)

        self.assertIn(
            template.format(path=self._staticDirName + u'/fname3.css'),
            downloader.contentResult)

        self.assertIn(
            template.format(path=self._staticDirName + u'/fname4.css'),
            downloader.contentResult)

        self.assertIn(
            template.format(path=self._staticDirName + u'/fname1_1.css'),
            downloader.contentResult)

        self.assertNotIn(
            template.format(path=self._staticDirName + u'/fname2_1.css'),
            downloader.contentResult)

    def testContentScriptExample1(self):
        from webpage.downloader import Downloader, DownloadController

        template = u'<script src="{path}"'

        controller = DownloadController(self._tempDir, self._staticDirName)
        downloader = Downloader()

        examplePath = u'../test/webpage/example1/'
        exampleHtmlPath = os.path.join(examplePath, u'example1.html')

        downloader.start(self._path2url(exampleHtmlPath), controller)

        self.assertIn(
            template.format(path=self._staticDirName + u'/fname1.js'),
            downloader.contentResult)

        self.assertIn(
            template.format(path=self._staticDirName + u'/fname2.js'),
            downloader.contentResult)

        self.assertIn(
            template.format(path=self._staticDirName + u'/fname2_1.js'),
            downloader.contentResult)

        self.assertIn(
            template.format(path=self._staticDirName + u'/fname3.js'),
            downloader.contentResult)

        self.assertIn(
            template.format(path=self._staticDirName + u'/fname4.js'),
            downloader.contentResult)

        self.assertNotIn(
            template.format(path=self._staticDirName + u'/fname1_1.js'),
            downloader.contentResult)

    def testTitleExample1(self):
        from webpage.downloader import Downloader, DownloadController

        controller = DownloadController(self._tempDir, self._staticDirName)
        downloader = Downloader()

        examplePath = u'../test/webpage/example1/'
        exampleHtmlPath = os.path.join(examplePath, u'example1.html')

        downloader.start(self._path2url(exampleHtmlPath), controller)

        self.assertTrue(downloader.success)
        self.assertEqual(downloader.pageTitle, u'Заголовок страницы')

    def testNoTitle(self):
        from webpage.downloader import Downloader, DownloadController

        controller = DownloadController(self._tempDir, self._staticDirName)
        downloader = Downloader()

        examplePath = u'../test/webpage/example_no_title/'
        exampleHtmlPath = os.path.join(examplePath, u'example_no_title.html')

        downloader.start(self._path2url(exampleHtmlPath), controller)

        self.assertTrue(downloader.success)
        self.assertIsNone(downloader.pageTitle)

    def testContentExample2(self):
        from webpage.downloader import Downloader, DownloadController

        template = u'<img src="{path}"'

        controller = DownloadController(self._tempDir, self._staticDirName)
        downloader = Downloader()

        examplePath = u'../test/webpage/example2/'
        exampleHtmlPath = os.path.join(examplePath, u'example2.html')

        downloader.start(self._path2url(exampleHtmlPath), controller)

        self.assertIn(
            template.format(path=self._staticDirName + u'/image_01.png'),
            downloader.contentResult)

        self.assertIn(
            template.format(path=self._staticDirName + u'/image_01_1.png'),
            downloader.contentResult)

        self.assertIn(
            template.format(path=self._staticDirName + u'/image_02.png'),
            downloader.contentResult)

        self.assertNotIn(
            template.format(path=self._staticDirName + u'/image_02_1.png'),
            downloader.contentResult)

    def testDownloading_img_01(self):
        from webpage.downloader import Downloader, DownloadController

        controller = DownloadController(self._tempDir, self._staticDirName)
        downloader = Downloader()

        examplePath = u'../test/webpage/example1/'
        exampleHtmlPath = os.path.join(examplePath, u'example1.html')

        downloader.start(self._path2url(exampleHtmlPath), controller)

        downloadDir = os.path.join(self._tempDir, self._staticDirName)

        fname1 = os.path.join(self._tempDir, self._staticDirName,
                              u'image_01.png')

        fname2 = os.path.join(self._tempDir, self._staticDirName,
                              u'image_02.png')

        fname3 = os.path.join(self._tempDir, self._staticDirName,
                              u'image_03.png')

        fname4 = os.path.join(self._tempDir, self._staticDirName,
                              u'image_01_1.png')

        self.assertTrue(os.path.exists(downloadDir))
        self.assertTrue(os.path.exists(fname1))
        self.assertTrue(os.path.exists(fname2))
        self.assertTrue(os.path.exists(fname3))
        self.assertTrue(os.path.exists(fname4))

    def testDownloading_img_02(self):
        from webpage.downloader import Downloader, DownloadController

        controller = DownloadController(self._tempDir, self._staticDirName)
        downloader = Downloader()

        examplePath = u'../test/webpage/example2/'
        exampleHtmlPath = os.path.join(examplePath, u'example2.html')

        downloader.start(self._path2url(exampleHtmlPath), controller)

        downloadDir = os.path.join(self._tempDir, self._staticDirName)

        fname1 = os.path.join(self._tempDir, self._staticDirName,
                              u'image_01.png')

        fname2 = os.path.join(self._tempDir, self._staticDirName,
                              u'image_02.png')

        fname3 = os.path.join(self._tempDir, self._staticDirName,
                              u'image_03.png')

        self.assertTrue(os.path.exists(downloadDir))
        self.assertTrue(os.path.exists(fname1))
        self.assertTrue(os.path.exists(fname2))
        self.assertTrue(os.path.exists(fname3))

    def testDownloading_css_01(self):
        from webpage.downloader import Downloader, DownloadController

        controller = DownloadController(self._tempDir, self._staticDirName)
        downloader = Downloader()

        examplePath = u'../test/webpage/example1/'
        exampleHtmlPath = os.path.join(examplePath, u'example1.html')

        downloader.start(self._path2url(exampleHtmlPath), controller)

        downloadDir = os.path.join(self._tempDir, self._staticDirName)

        fname1 = os.path.join(self._tempDir, self._staticDirName,
                              u'fname1.css')

        fname2 = os.path.join(self._tempDir, self._staticDirName,
                              u'fname2.css')

        fname3 = os.path.join(self._tempDir, self._staticDirName,
                              u'fname3.css')

        fname4 = os.path.join(self._tempDir, self._staticDirName,
                              u'fname4.css')

        fname5 = os.path.join(self._tempDir, self._staticDirName,
                              u'fname1_1.css')

        self.assertTrue(os.path.exists(downloadDir))
        self.assertTrue(os.path.exists(fname1))
        self.assertTrue(os.path.exists(fname2))
        self.assertTrue(os.path.exists(fname3))
        self.assertTrue(os.path.exists(fname4))
        self.assertTrue(os.path.exists(fname5))

    def testDownloading_css_import_01(self):
        from webpage.downloader import Downloader, DownloadController

        controller = DownloadController(self._tempDir, self._staticDirName)
        downloader = Downloader()

        examplePath = u'../test/webpage/example1/'
        exampleHtmlPath = os.path.join(examplePath, u'example1.html')

        downloader.start(self._path2url(exampleHtmlPath), controller)

        self.assertTrue(
            os.path.exists(
                os.path.join(self._tempDir, self._staticDirName,
                             u'import1.css')))

        self.assertTrue(
            os.path.exists(
                os.path.join(self._tempDir, self._staticDirName,
                             u'import2.css')))

        self.assertTrue(
            os.path.exists(
                os.path.join(self._tempDir, self._staticDirName,
                             u'import3.css')))

        self.assertTrue(
            os.path.exists(
                os.path.join(self._tempDir, self._staticDirName,
                             u'import4.css')))

        self.assertTrue(
            os.path.exists(
                os.path.join(self._tempDir, self._staticDirName,
                             u'basic2.css')))

        self.assertTrue(
            os.path.exists(
                os.path.join(self._tempDir, self._staticDirName,
                             u'basic3.css')))

        self.assertTrue(
            os.path.exists(
                os.path.join(self._tempDir, self._staticDirName,
                             u'basic4.css')))

        self.assertTrue(
            os.path.exists(
                os.path.join(self._tempDir, self._staticDirName,
                             u'basic5.css')))

        self.assertTrue(
            os.path.exists(
                os.path.join(self._tempDir, self._staticDirName,
                             u'basic5_1.css')))

        self.assertTrue(
            os.path.exists(
                os.path.join(self._tempDir, self._staticDirName,
                             u'basic6.css')))

    def testDownloading_css_back_img_01(self):
        from webpage.downloader import Downloader, DownloadController

        controller = DownloadController(self._tempDir, self._staticDirName)
        downloader = Downloader()

        examplePath = u'../test/webpage/example1/'
        exampleHtmlPath = os.path.join(examplePath, u'example1.html')

        downloader.start(self._path2url(exampleHtmlPath), controller)

        self.assertTrue(
            os.path.exists(
                os.path.join(self._tempDir, self._staticDirName,
                             u'back_img_01.png')))

        self.assertTrue(
            os.path.exists(
                os.path.join(self._tempDir, self._staticDirName,
                             u'back_img_02.png')))

        self.assertTrue(
            os.path.exists(
                os.path.join(self._tempDir, self._staticDirName,
                             u'back_img_03.png')))

        self.assertTrue(
            os.path.exists(
                os.path.join(self._tempDir, self._staticDirName,
                             u'back_img_04.png')))

        self.assertTrue(
            os.path.exists(
                os.path.join(self._tempDir, self._staticDirName,
                             u'back_img_05.png')))

        self.assertTrue(
            os.path.exists(
                os.path.join(self._tempDir, self._staticDirName,
                             u'back_img_06.png')))

    def testDownloading_css_url_01(self):
        from webpage.downloader import Downloader, DownloadController

        template = u'url("{url}")'

        controller = DownloadController(self._tempDir, self._staticDirName)
        downloader = Downloader()

        examplePath = u'../test/webpage/example1/'
        exampleHtmlPath = os.path.join(examplePath, u'example1.html')

        downloader.start(self._path2url(exampleHtmlPath), controller)

        fname1_text = readTextFile(
            os.path.join(self._tempDir, self._staticDirName, u'fname1.css'))

        self.assertIn(template.format(url=u'import1.css'), fname1_text)
        self.assertIn(template.format(url=u'back_img_01.png'), fname1_text)
        self.assertIn(template.format(url=u'back_img_02.png'), fname1_text)
        self.assertIn(template.format(url=u'back_img_03.png'), fname1_text)
        self.assertIn(template.format(url=u'back_img_04.png'), fname1_text)
        self.assertIn(template.format(url=u'back_img_05.png'), fname1_text)
        self.assertIn(template.format(url=u'back_img_06.png'), fname1_text)

    def testDownloading_css_url_02(self):
        from webpage.downloader import Downloader, DownloadController

        template = u'url("{url}")'

        controller = DownloadController(self._tempDir, self._staticDirName)
        downloader = Downloader()

        examplePath = u'../test/webpage/example1/'
        exampleHtmlPath = os.path.join(examplePath, u'example1.html')

        downloader.start(self._path2url(exampleHtmlPath), controller)

        fname2_text = readTextFile(
            os.path.join(self._tempDir, self._staticDirName, u'fname2.css'))

        self.assertIn(template.format(url=u'basic2.css'), fname2_text)
        self.assertIn(template.format(url=u'basic4.css'), fname2_text)
        self.assertIn(template.format(url=u'basic5.css'), fname2_text)
        self.assertIn(template.format(url=u'basic6.css'), fname2_text)
        self.assertIn('basic3.css', fname2_text)
        self.assertIn('basic5.css', fname2_text)

    def testDownloading_javascript_01(self):
        from webpage.downloader import Downloader, DownloadController

        controller = DownloadController(self._tempDir, self._staticDirName)
        downloader = Downloader()

        examplePath = u'../test/webpage/example1/'
        exampleHtmlPath = os.path.join(examplePath, u'example1.html')

        downloader.start(self._path2url(exampleHtmlPath), controller)

        downloadDir = os.path.join(self._tempDir, self._staticDirName)

        fname1 = os.path.join(self._tempDir, self._staticDirName, u'fname1.js')

        fname2 = os.path.join(self._tempDir, self._staticDirName, u'fname2.js')

        fname3 = os.path.join(self._tempDir, self._staticDirName, u'fname3.js')

        fname4 = os.path.join(self._tempDir, self._staticDirName, u'fname4.js')

        self.assertTrue(os.path.exists(downloadDir))
        self.assertTrue(os.path.exists(fname1))
        self.assertTrue(os.path.exists(fname2))
        self.assertTrue(os.path.exists(fname3))
        self.assertTrue(os.path.exists(fname4))

    @staticmethod
    def _path2url(path):
        path = os.path.abspath(path)
        path = path.encode('utf8')
        return 'file:' + urllib.pathname2url(path)
Пример #42
0
class SpoilerPluginTest(unittest.TestCase, BaseOutWikerGUIMixin):
    def setUp(self):
        self.__pluginname = "Spoiler"
        self.initApplication()
        self.wikiroot = self.createWiki()
        self.testPage = WikiPageFactory().create(self.wikiroot, "Страница 1",
                                                 [])

        dirlist = ["plugins/spoiler"]

        self.loader = PluginsLoader(self.application)
        self.loader.load(dirlist)

        self.factory = ParserFactory()
        self.parser = self.factory.make(self.testPage, self.application.config)

    def tearDown(self):
        self.loader.clear()
        self.destroyApplication()
        self.destroyWiki(self.wikiroot)

    def testPluginLoad(self):
        self.assertEqual(len(self.loader), 1)

    def testEmptyCommand(self):
        text = '''bla-bla-bla (:spoiler:) bla-bla-bla'''

        self.testPage.content = text

        generator = HtmlGenerator(self.testPage)
        result = generator.makeHtml(Style().getPageStyle(self.testPage))

        self.assertTrue("bla-bla-bla" in result)

    def testSimple(self):
        text = "бла-бла-бла (:spoiler:)Текст(:spoilerend:)"

        self.testPage.content = text

        generator = HtmlGenerator(self.testPage)
        result = generator.makeHtml(Style().getPageStyle(self.testPage))

        self.assertTrue("бла-бла-бла" in result)
        self.assertTrue("Текст</div></div></div>" in result)

    def testSimpleNumbers(self):
        for index in range(10):
            text = "бла-бла-бла (:spoiler{index}:)Текст(:spoiler{index}end:)".format(
                index=index)

            self.testPage.content = text

            generator = HtmlGenerator(self.testPage)
            result = generator.makeHtml(Style().getPageStyle(self.testPage))

            self.assertTrue("бла-бла-бла" in result)
            self.assertTrue("Текст</div></div></div>" in result)

    def testWikiBoldContent(self):
        text = "бла-бла-бла (:spoiler:)'''Текст'''(:spoilerend:)"

        self.testPage.content = text

        generator = HtmlGenerator(self.testPage)
        result = generator.makeHtml(Style().getPageStyle(self.testPage))

        self.assertTrue("бла-бла-бла" in result)
        self.assertTrue("<b>Текст</b></div></div></div>" in result)

    def testExpandText(self):
        text = """бла-бла-бла (:spoiler expandtext="Раскукожить":)Текст(:spoilerend:)"""

        self.testPage.content = text

        generator = HtmlGenerator(self.testPage)
        result = generator.makeHtml(Style().getPageStyle(self.testPage))

        self.assertTrue("бла-бла-бла" in result)
        self.assertTrue("Текст</div></div></div>" in result)
        self.assertTrue("Раскукожить</a></span></div>" in result)

    def testCollapseText(self):
        text = """бла-бла-бла (:spoiler collapsetext="Скукожить":)Текст(:spoilerend:)"""

        self.testPage.content = text

        generator = HtmlGenerator(self.testPage)
        result = generator.makeHtml(Style().getPageStyle(self.testPage))

        self.assertTrue("бла-бла-бла" in result)
        self.assertTrue("Текст</div></div></div>" in result)
        self.assertTrue("Скукожить</a>" in result)

    def testExpandCollapseText(self):
        text = """бла-бла-бла (:spoiler expandtext="Раскукожить" collapsetext="Скукожить":)Текст(:spoilerend:)"""

        self.testPage.content = text

        generator = HtmlGenerator(self.testPage)
        result = generator.makeHtml(Style().getPageStyle(self.testPage))

        self.assertTrue("бла-бла-бла" in result)
        self.assertTrue("Текст</div></div></div>" in result)
        self.assertTrue("Раскукожить</a></span></div>" in result)
        self.assertTrue("Скукожить</a>" in result)

    def testInline(self):
        text = "бла-бла-бла (:spoiler inline:)Текст(:spoilerend:)"

        self.testPage.content = text

        generator = HtmlGenerator(self.testPage)
        result = generator.makeHtml(Style().getPageStyle(self.testPage))

        self.assertTrue("бла-бла-бла" in result)
        self.assertFalse("Текст</div></div></div>" in result)
        self.assertTrue("<span><span" in result)

    def testInlineExpandText(self):
        text = """бла-бла-бла (:spoiler expandtext="Раскукожить" inline:)Текст(:spoilerend:)"""

        self.testPage.content = text

        generator = HtmlGenerator(self.testPage)
        result = generator.makeHtml(Style().getPageStyle(self.testPage))

        self.assertTrue("бла-бла-бла" in result)
        self.assertFalse("Текст</div></div></div>" in result)
        self.assertTrue("<span><span" in result)
        self.assertTrue("""<a href="#">Раскукожить</a>""" in result)
Пример #43
0
class ExecDialogTest(unittest.TestCase, BaseOutWikerGUIMixin):
    """
    Tests for ExecDialog and ExecDialogController
    """

    def setUp(self):
        self.initApplication()

        dirlist = ["plugins/externaltools"]

        self._loader = PluginsLoader(self.application)
        self._loader.load(dirlist)

        from externaltools.config import ExternalToolsConfig
        ExternalToolsConfig(self.application.config).clearAll()

        from externaltools.commandexec.execdialog import ExecDialog
        self._dlg = ExecDialog(self.application.mainWindow)
        Tester.dialogTester.clear()
        Tester.dialogTester.appendOk()

    def tearDown(self):
        self._dlg.Destroy()
        self._loader.clear()

        from externaltools.config import ExternalToolsConfig
        ExternalToolsConfig(self.application.config).clearAll()

        self.destroyApplication()

    def testDefault(self):
        from externaltools.commandexec.execdialogcontroller import ExecDialogController

        controller = ExecDialogController(
            self._dlg,
            self.application
        )

        result = controller.showDialog()
        begin, end = controller.getResult()

        self.assertEqual(result, wx.ID_OK)
        self.assertEqual(begin, '(:exec:)')
        self.assertEqual(end, '(:execend:)')

    def testTitle(self):
        from externaltools.commandexec.execdialogcontroller import ExecDialogController

        controller = ExecDialogController(
            self._dlg,
            self.application
        )

        self._dlg.title = 'Заголовок команды'

        result = controller.showDialog()
        begin, end = controller.getResult()

        self.assertEqual(result, wx.ID_OK)
        self.assertEqual(begin, '(:exec title="Заголовок команды":)')
        self.assertEqual(end, '(:execend:)')

    def testFormat(self):
        from externaltools.commandexec.execdialogcontroller import ExecDialogController

        controller = ExecDialogController(
            self._dlg,
            self.application
        )

        self._dlg.format = 1

        result = controller.showDialog()
        begin, end = controller.getResult()

        self.assertEqual(result, wx.ID_OK)
        self.assertEqual(begin, '(:exec format="button":)')
        self.assertEqual(end, '(:execend:)')

    def testTitleFormat(self):
        from externaltools.commandexec.execdialogcontroller import ExecDialogController

        controller = ExecDialogController(
            self._dlg,
            self.application
        )

        self._dlg.title = 'Заголовок команды'
        self._dlg.format = 1

        result = controller.showDialog()
        begin, end = controller.getResult()

        self.assertEqual(result, wx.ID_OK)
        self.assertEqual(
            begin, '(:exec title="Заголовок команды" format="button":)')
        self.assertEqual(end, '(:execend:)')
Пример #44
0
class ParagraphHtmlImproverTest(unittest.TestCase, BaseOutWikerMixin):
    def setUp(self):
        self.initApplication()
        dirlist = ["plugins/htmlformatter"]

        self.loader = PluginsLoader(self.application)
        self.loader.load(dirlist)

        factory = HtmlImproverFactory(self.application)
        self.improver = factory['pimprover']

    def tearDown(self):
        self.loader.clear()
        self.destroyApplication()

    def test_empty(self):
        src = ''
        expectedResult = ''

        result = self.improver.run(src)
        self.assertEqual(expectedResult, result)

    def test_text_single_line(self):
        src = 'Абырвалг'
        expectedResult = '<p>Абырвалг</p>'

        result = self.improver.run(src)
        self.assertEqual(expectedResult, result)

    def test_text_br(self):
        src = '''Абырвалг
Foo
Bar'''
        expectedResult = '''<p>Абырвалг<br/>
Foo<br/>
Bar</p>'''

        result = self.improver.run(src)

        self.assertEqual(expectedResult, result)

    def test_text_p_01(self):
        src = '''Абырвалг

Второй параграф'''

        expectedResult = '''<p>Абырвалг</p>
<p>Второй параграф</p>'''

        result = self.improver.run(src)

        self.assertEqual(expectedResult, result)

    def test_text_p_02(self):
        src = '''Абырвалг

Второй параграф




'''

        expectedResult = '''<p>Абырвалг</p>
<p>Второй параграф</p>'''

        result = self.improver.run(src)

        self.assertEqual(expectedResult, result)

    def test_improve_01(self):
        src = r"""<h2>Attach links</h2>Attach:file.odt<br/><a href="__attach/file.odt">file.odt</a><br/><a href="__attach/file.odt">alternative text</a><br/><a href="__attach/file with spaces.pdf">file with spaces.pdf</a><h2>Images</h2>"""

        expectedResult = r"""<h2>Attach links</h2>
<p>Attach:file.odt<br/>
<a href="__attach/file.odt">file.odt</a><br/>
<a href="__attach/file.odt">alternative text</a><br/>
<a href="__attach/file with spaces.pdf">file with spaces.pdf</a></p>
<h2>Images</h2>"""

        result = self.improver.run(src)

        self.assertEqual(expectedResult, result)

    def test_pre_01(self):
        src = r"""qweqweqw qweqwe
qwewqeqwe wqe

qweqweqw qwe qweqwe<pre>
аап ываыв ываываыываы ыва ыва
ываыва выа выа

ываыв фывфв фывфывыф ыфв
вапвапввап вапвапвап

вапвапвап вапваапва</pre>

sdfsdf sdfsdf
sdfsdf
sdf sdfsdf sdf"""

        expectedResult = r"""<p>qweqweqw qweqwe<br/>
qwewqeqwe wqe</p>
<p>qweqweqw qwe qweqwe</p>

<pre>
аап ываыв ываываыываы ыва ыва
ываыва выа выа

ываыв фывфв фывфывыф ыфв
вапвапввап вапвапвап

вапвапвап вапваапва</pre>

<p>sdfsdf sdfsdf<br/>
sdfsdf<br/>
sdf sdfsdf sdf</p>"""

        result = self.improver.run(src)
        self.assertEqual(expectedResult, result, result)

    def test_pre_02(self):
        src = r"""Абырвалг<pre><br/><h1>111</h1></pre>Абырвалг<pre><br/><h1>111</h1></pre>"""

        expectedResult = r"""<p>Абырвалг</p>

<pre><br/><h1>111</h1></pre>

<p>Абырвалг</p>

<pre><br/><h1>111</h1></pre>"""

        result = self.improver.run(src)
        self.assertEqual(expectedResult, result, result)

    def test_pre_03(self):
        src = r"""Абырвалг
<pre>111</pre>
Абырвалг
<pre>222</pre>"""

        expectedResult = r"""<p>Абырвалг</p>

<pre>111</pre>

<p>Абырвалг</p>

<pre>222</pre>"""

        result = self.improver.run(src)
        self.assertEqual(expectedResult, result, result)

    def test_pre_04(self):
        src = r"""Абырвалг
<   pre   >111
Абырвалг
йцукен</   pre   >
<pre>222</pre>"""

        expectedResult = r"""<p>Абырвалг</p>

<   pre   >111
Абырвалг
йцукен</   pre   >

<pre>222</pre>"""

        result = self.improver.run(src)
        self.assertEqual(expectedResult, result, result)

    def test_script_01(self):
        src = r"""Абырвалг

<script>Абырвалг
йцукен
qwerty
фыва
</script>"""

        expectedResult = r"""<p>Абырвалг</p>

<script>Абырвалг
йцукен
qwerty
фыва
</script>"""

        result = self.improver.run(src)
        self.assertEqual(expectedResult, result, result)

    def test_script_02(self):
        src = r"""Абырвалг
<script>Абырвалг
йцукен
qwerty
фыва
</script>"""

        expectedResult = r"""<p>Абырвалг</p>

<script>Абырвалг
йцукен
qwerty
фыва
</script>"""

        result = self.improver.run(src)
        self.assertEqual(expectedResult, result, result)

    def test_script_03(self):
        src = r"""Абырвалг
<   script   >111
Абырвалг
йцукен</   script   >
<script>222</script>"""

        expectedResult = r"""<p>Абырвалг</p>

<   script   >111
Абырвалг
йцукен</   script   >

<script>222</script>"""

        result = self.improver.run(src)

        self.assertEqual(expectedResult, result, result)

    def test_script_pre_01(self):
        src = r"""Абырвалг
<script>Абырвалг
<pre>
йцукен
qwerty
</pre>
фыва
</script>"""

        expectedResult = r"""<p>Абырвалг</p>

<script>Абырвалг
<pre>
йцукен
qwerty
</pre>
фыва
</script>"""

        result = self.improver.run(src)
        self.assertEqual(expectedResult, result, result)

    def test_script_pre_02(self):
        src = r"""Абырвалг
<script>Абырвалг
<pre>
йцукен
qwerty
</pre>
фыва
</script>Абырвалг"""

        expectedResult = r"""<p>Абырвалг</p>

<script>Абырвалг
<pre>
йцукен
qwerty
</pre>
фыва
</script>

<p>Абырвалг</p>"""

        result = self.improver.run(src)
        self.assertEqual(expectedResult, result, result)

    def test_blockquote_01(self):
        src = r"""<blockquote>Абырвалг</blockquote>"""

        expectedResult = r"""<blockquote>
<p>Абырвалг</p>
</blockquote>"""

        result = self.improver.run(src)
        self.assertEqual(expectedResult, result, result)

    def test_blockquote_02(self):
        src = r"""Абзац 1<blockquote>Абырвалг</blockquote>Абзац 2"""

        expectedResult = r"""<p>Абзац 1</p>
<blockquote>
<p>Абырвалг</p>
</blockquote>
<p>Абзац 2</p>"""

        result = self.improver.run(src)
        self.assertEqual(expectedResult, result, result)

    def test_blockquote_03(self):
        src = r"""Абзац 1

<blockquote>Абырвалг</blockquote>

Абзац 2"""

        expectedResult = r"""<p>Абзац 1</p>
<blockquote>
<p>Абырвалг</p>
</blockquote>
<p>Абзац 2</p>"""

        result = self.improver.run(src)
        self.assertEqual(expectedResult, result, result)

    def test_blockquote_04(self):
        src = r"""Абзац 1

<blockquote>
Абырвалг
</blockquote>

Абзац 2"""

        expectedResult = r"""<p>Абзац 1</p>
<blockquote>
<p>Абырвалг</p>
</blockquote>
<p>Абзац 2</p>"""

        result = self.improver.run(src)
        self.assertEqual(expectedResult, result, result)

    def test_table_01(self):
        src = r"""Абзац 1<table><tr><td>Ячейка таблицы</td></tr></table>Абзац 2"""

        expectedResult = r"""<p>Абзац 1
<table>
<tr>
<td>Ячейка таблицы</td>
</tr>
</table>
Абзац 2</p>"""

        result = self.improver.run(src)
        self.assertEqual(expectedResult, result, result)

    def test_table_02(self):
        src = r"""Абзац 1
<table><tr><td>Ячейка таблицы</td></tr></table>
Абзац 2"""

        expectedResult = r"""<p>Абзац 1
<table>
<tr>
<td>Ячейка таблицы</td>
</tr>
</table>
Абзац 2</p>"""

        result = self.improver.run(src)
        self.assertEqual(expectedResult, result, result)

    def test_table_03(self):
        src = r"""Абзац 1

<table><tr><td>Ячейка таблицы</td></tr></table>
Абзац 2"""

        expectedResult = r"""<p>Абзац 1</p>
<p>
<table>
<tr>
<td>Ячейка таблицы</td>
</tr>
</table>
Абзац 2</p>"""

        result = self.improver.run(src)
        self.assertEqual(expectedResult, result, result)
Пример #45
0
class BasePluginLoadingTest(BaseMainWndTest):
    __metaclass__ = ABCMeta

    @abstractmethod
    def getPluginDir(self):
        """
        Должен возвращать путь до папки с тестируемым плагином
        """
        pass

    @abstractmethod
    def getPluginName(self):
        """
        Должен возвращать имя плагина, по которому его можно найти в PluginsLoader
        """
        pass

    def setUp(self):
        BaseMainWndTest.setUp(self)
        self.__createWiki()

        dirlist = [self.getPluginDir()]

        self.loader = PluginsLoader(Application)
        self.loader.load(dirlist)

    def __createWiki(self):
        # Здесь будет создаваться вики
        WikiPageFactory().create(self.wikiroot, u"Викистраница", [])
        TextPageFactory().create(self.wikiroot, u"Текст", [])
        HtmlPageFactory().create(self.wikiroot, u"HTML", [])
        SearchPageFactory().create(self.wikiroot, u"Search", [])

    def tearDown(self):
        Application.selectedPage = None
        Application.wikiroot = None
        self.loader.clear()
        BaseMainWndTest.tearDown(self)

    def testPluginLoad(self):
        self.assertEqual(len(self.loader), 1)
        self.assertNotEqual(self.loader[self.getPluginName()], None)

    def testDestroy_01(self):
        Application.wikiroot = None
        self.loader.clear()

    def testDestroy_02(self):
        Application.wikiroot = self.wikiroot
        Application.selectedPage = None
        self.loader.clear()

    def testDestroy_03(self):
        Application.wikiroot = self.wikiroot
        Application.selectedPage = self.wikiroot[u"Викистраница"]
        self.loader.clear()

    def testDestroy_04(self):
        Application.wikiroot = self.wikiroot
        Application.selectedPage = self.wikiroot[u"Текст"]
        self.loader.clear()

    def testDestroy_05(self):
        Application.wikiroot = self.wikiroot
        Application.selectedPage = self.wikiroot[u"HTML"]
        self.loader.clear()

    def testDestroy_06(self):
        Application.wikiroot = self.wikiroot
        Application.selectedPage = self.wikiroot[u"Search"]
        self.loader.clear()
Пример #46
0
class SourceStyleTest (unittest.TestCase):
    def setUp(self):
        self.__pluginname = u"Source"

        self.__createWiki()

        dirlist = [u"../plugins/source"]

        # Путь, где лежат примеры исходников в разных кодировках
        self.samplefilesPath = u"../test/samplefiles/sources"

        # Пример программы
        self.pythonSource = u'''import os

# Комментарий
def hello (count):
	"""
	Hello world
	"""
	for i in range (10):
		print "Hello world!!!"
'''

        self.loader = PluginsLoader(Application)
        self.loader.load (dirlist)

        self.config = self.loader[self.__pluginname].config
        self.config.tabWidth.value = 4
        self.config.defaultLanguage.remove_option()
        Application.config.remove_section (self.config.section)

        self.factory = ParserFactory()
        self.parser = self.factory.make (self.testPage, Application.config)


    def __createWiki (self):
        # Здесь будет создаваться вики
        self.path = mkdtemp (prefix=u'Абырвалг абыр')

        self.wikiroot = WikiDocument.create (self.path)

        WikiPageFactory().create (self.wikiroot, u"Страница 1", [])
        self.testPage = self.wikiroot[u"Страница 1"]


    def tearDown(self):
        self.config.tabWidth.value = 4
        Application.config.remove_section (self.config.section)
        removeDir (self.path)
        self.loader.clear()


    def testDefaultStyle (self):
        text = u'(:source lang="python" tabwidth=4:){0}(:sourceend:)'.format (self.pythonSource)

        self.testPage.content = text

        generator = HtmlGenerator (self.testPage)
        result = generator.makeHtml (Style().getPageStyle (self.testPage))

        innerString1 = u".highlight-default .c"
        innerString2 = u".highlight-default .c { color: #408080; font-style: italic } /* Comment */"
        innerString3 = u'        <span class="k">print</span> <span class="s2">&quot;Hello world!!!&quot;</span>'
        innerString4 = u'<span class="kn">import</span> <span class="nn">os</span>'

        self.assertTrue (innerString1 in result)
        self.assertTrue (innerString2 in result)
        self.assertTrue (innerString3 in result)
        self.assertTrue (innerString4 in result)


    def testDefaultInvalidStyle (self):
        text = u'(:source lang="python" tabwidth=4:){0}(:sourceend:)'.format (self.pythonSource)

        self.testPage.content = text

        self.config.defaultStyle.value = "invalid_blablabla"

        generator = HtmlGenerator (self.testPage)
        result = generator.makeHtml (Style().getPageStyle (self.testPage))

        innerString1 = u".highlight-default .c"
        innerString2 = u".highlight-default .c { color: #408080; font-style: italic } /* Comment */"
        innerString3 = u'        <span class="k">print</span> <span class="s2">&quot;Hello world!!!&quot;</span>'
        innerString4 = u'<span class="kn">import</span> <span class="nn">os</span>'

        self.assertTrue (innerString1 in result)
        self.assertTrue (innerString2 in result)
        self.assertTrue (innerString3 in result)
        self.assertTrue (innerString4 in result)


    def testDefaultEmptyStyle (self):
        text = u'(:source lang="python" tabwidth=4:){0}(:sourceend:)'.format (self.pythonSource)

        self.testPage.content = text

        self.config.defaultStyle.value = ""

        generator = HtmlGenerator (self.testPage)
        result = generator.makeHtml (Style().getPageStyle (self.testPage))

        innerString1 = u".highlight-default .c"
        innerString2 = u".highlight-default .c { color: #408080; font-style: italic } /* Comment */"
        innerString3 = u'        <span class="k">print</span> <span class="s2">&quot;Hello world!!!&quot;</span>'
        innerString4 = u'<span class="kn">import</span> <span class="nn">os</span>'

        self.assertTrue (innerString1 in result)
        self.assertTrue (innerString2 in result)
        self.assertTrue (innerString3 in result)
        self.assertTrue (innerString4 in result)


    def testDefaultStyleVim (self):
        text = u'(:source lang="python" tabwidth=4:){0}(:sourceend:)'.format (self.pythonSource)

        self.testPage.content = text

        self.config.defaultStyle.value = "vim"

        generator = HtmlGenerator (self.testPage)
        result = generator.makeHtml (Style().getPageStyle (self.testPage))

        innerString1 = u".highlight-vim .c"
        innerString2 = u".highlight-vim .c { color: #000080 } /* Comment */"
        innerString3 = u'        <span class="k">print</span> <span class="s2">&quot;Hello world!!!&quot;</span>'
        innerString4 = u'<span class="kn">import</span> <span class="nn">os</span>'

        self.assertTrue (innerString1 in result)
        self.assertTrue (innerString2 in result)
        self.assertTrue (innerString3 in result)
        self.assertTrue (innerString4 in result)


    def testInvalidStyle (self):
        text = u'(:source lang="python" tabwidth=4 style="invalid_bla-bla-bla":){0}(:sourceend:)'.format (self.pythonSource)

        self.testPage.content = text

        generator = HtmlGenerator (self.testPage)
        result = generator.makeHtml (Style().getPageStyle (self.testPage))

        innerString1 = u".highlight-default .c"
        innerString2 = u".highlight-default .c { color: #408080; font-style: italic } /* Comment */"
        innerString3 = u'        <span class="k">print</span> <span class="s2">&quot;Hello world!!!&quot;</span>'
        innerString4 = u'<span class="kn">import</span> <span class="nn">os</span>'

        self.assertTrue (innerString1 in result)
        self.assertTrue (innerString2 in result)
        self.assertTrue (innerString3 in result)
        self.assertTrue (innerString4 in result)


    def testStyleVim (self):
        text = u'(:source lang="python" tabwidth=4 style="vim":){0}(:sourceend:)'.format (self.pythonSource)

        self.testPage.content = text

        generator = HtmlGenerator (self.testPage)
        result = generator.makeHtml (Style().getPageStyle (self.testPage))

        innerString1 = u".highlight-vim .c"
        innerString2 = u".highlight-vim .c { color: #000080 } /* Comment */"
        innerString3 = u'        <span class="k">print</span> <span class="s2">&quot;Hello world!!!&quot;</span>'
        innerString4 = u'<span class="kn">import</span> <span class="nn">os</span>'

        self.assertTrue (innerString1 in result)
        self.assertTrue (innerString2 in result)
        self.assertTrue (innerString3 in result)
        self.assertTrue (innerString4 in result)


    def testSeveralStyles (self):
        text = u'''(:source lang="python" tabwidth=4 style="vim":){0}(:sourceend:)

(:source lang="python" tabwidth=4:){0}(:sourceend:)'''.format (self.pythonSource)

        self.testPage.content = text

        generator = HtmlGenerator (self.testPage)
        result = generator.makeHtml (Style().getPageStyle (self.testPage))

        innerString1 = u".highlight-vim .c"
        innerString2 = u".highlight-vim .c { color: #000080 } /* Comment */"
        innerString3 = u'        <span class="k">print</span> <span class="s2">&quot;Hello world!!!&quot;</span>'
        innerString4 = u'<span class="kn">import</span> <span class="nn">os</span>'
        innerString5 = u".highlight-default .c"
        innerString6 = u".highlight-default .c { color: #408080; font-style: italic } /* Comment */"
        innerString7 = u'<div class="highlight-default">'
        innerString8 = u'<div class="highlight-vim">'

        self.assertTrue (innerString1 in result)
        self.assertTrue (innerString2 in result)
        self.assertTrue (innerString3 in result)
        self.assertTrue (innerString4 in result)
        self.assertTrue (innerString5 in result)
        self.assertTrue (innerString6 in result)
        self.assertTrue (innerString7 in result)
        self.assertTrue (innerString8 in result)


    def testDefaultStyleFile (self):
        Attachment(self.testPage).attach ([os.path.join (self.samplefilesPath, u"source_utf8.py")])
        text = u'(:source lang="python" tabwidth=4 file="source_utf8.py":){0}(:sourceend:)'.format (self.pythonSource)

        self.testPage.content = text

        generator = HtmlGenerator (self.testPage)
        result = generator.makeHtml (Style().getPageStyle (self.testPage))

        innerString1 = u".highlight-default .c"
        innerString2 = u".highlight-default .c { color: #408080; font-style: italic } /* Comment */"

        self.assertTrue (innerString1 in result)
        self.assertTrue (innerString2 in result)


    def testDefaultInvalidStyleFile (self):
        Attachment(self.testPage).attach ([os.path.join (self.samplefilesPath, u"source_utf8.py")])
        text = u'(:source lang="python" tabwidth=4 file="source_utf8.py":){0}(:sourceend:)'.format (self.pythonSource)

        self.testPage.content = text

        self.config.defaultStyle.value = "invalid_blablabla"

        generator = HtmlGenerator (self.testPage)
        result = generator.makeHtml (Style().getPageStyle (self.testPage))

        innerString1 = u".highlight-default .c"
        innerString2 = u".highlight-default .c { color: #408080; font-style: italic } /* Comment */"

        self.assertTrue (innerString1 in result)
        self.assertTrue (innerString2 in result)


    def testDefaultEmptyStyleFile (self):
        Attachment(self.testPage).attach ([os.path.join (self.samplefilesPath, u"source_utf8.py")])
        text = u'(:source lang="python" tabwidth=4 file="source_utf8.py":){0}(:sourceend:)'.format (self.pythonSource)

        self.testPage.content = text

        self.config.defaultStyle.value = ""

        generator = HtmlGenerator (self.testPage)
        result = generator.makeHtml (Style().getPageStyle (self.testPage))

        innerString1 = u".highlight-default .c"
        innerString2 = u".highlight-default .c { color: #408080; font-style: italic } /* Comment */"

        self.assertTrue (innerString1 in result)
        self.assertTrue (innerString2 in result)


    def testDefaultStyleVimFile (self):
        text = u'(:source lang="python" tabwidth=4:){0}(:sourceend:)'.format (self.pythonSource)

        self.testPage.content = text

        self.config.defaultStyle.value = "vim"

        generator = HtmlGenerator (self.testPage)
        result = generator.makeHtml (Style().getPageStyle (self.testPage))

        innerString1 = u".highlight-vim .c"
        innerString2 = u".highlight-vim .c { color: #000080 } /* Comment */"

        self.assertTrue (innerString1 in result)
        self.assertTrue (innerString2 in result)


    def testParentBg1 (self):
        text = u'(:source lang="python" tabwidth=4:){0}(:sourceend:)'.format (self.pythonSource)

        self.testPage.content = text
        self.config.defaultStyle.value = "vim"

        generator = HtmlGenerator (self.testPage)
        result = generator.makeHtml (Style().getPageStyle (self.testPage))

        innerString1 = u".highlight-vim pre {padding: 0px; border: none; color: inherit; background-color: inherit; margin:0px; }"
        innerString2 = u".highlight-vim {color: inherit; background-color: inherit }"

        self.assertTrue (innerString1 in result)
        self.assertTrue (innerString2 not in result)


    def testParentBg2 (self):
        text = u'(:source lang="python" tabwidth=4 parentbg:){0}(:sourceend:)'.format (self.pythonSource)

        self.testPage.content = text
        self.config.defaultStyle.value = "vim"

        generator = HtmlGenerator (self.testPage)
        result = generator.makeHtml (Style().getPageStyle (self.testPage))

        innerString1 = u".highlight-vim-parentbg pre {padding: 0px; border: none; color: inherit; background-color: inherit; margin:0px; }"
        innerString2 = u".highlight-vim-parentbg {color: inherit; background-color: inherit }"
        innerString3 = u'<div class="highlight-vim-parentbg">'
        innerString4 = u".highlight-vim {color: inherit; background-color: inherit }"
        innerString5 = u'<div class="highlight-vim">'

        self.assertTrue (innerString1 in result)
        self.assertTrue (innerString2 in result)
        self.assertTrue (innerString3 in result)
        self.assertTrue (innerString4 not in result)
        self.assertTrue (innerString5 not in result)


    def testParentBg3 (self):
        text = u'(:source lang="python" parentbg tabwidth=4:){0}(:sourceend:)'.format (self.pythonSource)

        self.testPage.content = text
        self.config.defaultStyle.value = "vim"

        generator = HtmlGenerator (self.testPage)
        result = generator.makeHtml (Style().getPageStyle (self.testPage))

        innerString1 = u".highlight-vim-parentbg pre {padding: 0px; border: none; color: inherit; background-color: inherit; margin:0px; }"
        innerString2 = u".highlight-vim-parentbg {color: inherit; background-color: inherit }"
        innerString3 = u'<div class="highlight-vim-parentbg">'
        innerString4 = u".highlight-vim {color: inherit; background-color: inherit }"
        innerString5 = u'<div class="highlight-vim">'

        self.assertTrue (innerString1 in result)
        self.assertTrue (innerString2 in result)
        self.assertTrue (innerString3 in result)
        self.assertTrue (innerString4 not in result)
        self.assertTrue (innerString5 not in result)


    def testParentBg4 (self):
        text = u'''(:source lang="python" tabwidth=4:){0}(:sourceend:)

        (:source lang="python" tabwidth=4 parentbg:){0}(:sourceend:)'''.format (self.pythonSource)

        self.testPage.content = text
        self.config.defaultStyle.value = "vim"

        generator = HtmlGenerator (self.testPage)
        result = generator.makeHtml (Style().getPageStyle (self.testPage))

        innerString1 = u".highlight-vim-parentbg pre {padding: 0px; border: none; color: inherit; background-color: inherit; margin:0px; }"
        innerString2 = u".highlight-vim-parentbg {color: inherit; background-color: inherit }"
        innerString3 = u'<div class="highlight-vim-parentbg">'
        innerString4 = u".highlight-vim {color: inherit; background-color: inherit }"
        innerString5 = u'<div class="highlight-vim">'

        self.assertTrue (innerString1 in result)
        self.assertTrue (innerString2 in result)
        self.assertTrue (innerString3 in result)
        self.assertTrue (innerString4 not in result)
        self.assertTrue (innerString5 in result)
Пример #47
0
class DiagrammerTest(unittest.TestCase):
    def setUp(self):
        self.maxDiff = None

        self.filesPath = u"../test/samplefiles/"
        self.__createWiki()

        dirlist = [u"../plugins/diagrammer"]

        self.loader = PluginsLoader(Application)
        self.loader.load(dirlist)

        self.factory = ParserFactory()
        self.parser = self.factory.make(self.testPage, Application.config)

        self.thumbDir = os.path.join(u"__attach", u"__thumb")
        self.thumbFullPath = os.path.join(self.testPage.path, self.thumbDir)

    def __createWiki(self):
        # Здесь будет создаваться вики
        self.path = mkdtemp(prefix=u'Абырвалг абыр')

        self.wikiroot = WikiDocument.create(self.path)

        WikiPageFactory().create(self.wikiroot, u"Страница 1", [])
        self.testPage = self.wikiroot[u"Страница 1"]

    def tearDown(self):
        removeDir(self.path)
        self.loader.clear()

    def testEmpty(self):
        text = u"(:diagram:)(:diagramend:)"
        validResult = u'<img src="{}/__diagram_'.format(self.thumbDir)

        result = self.parser.toHtml(text)
        self.assertIn(validResult, result)

        # Признак ошибки
        self.assertNotIn(u"<b>", result)

        self.assertTrue(os.path.exists(self.thumbFullPath))
        self.assertEqual(len(os.listdir(self.thumbFullPath)), 1)

    def test_simple(self):
        text = u"(:diagram:)Абырвалг -> Блаблабла(:diagramend:)"
        validResult = u'<img src="{}/__diagram_'.format(self.thumbDir)

        result = self.parser.toHtml(text)
        self.assertIn(validResult, result)

        # Признак ошибки
        self.assertNotIn(u"<b>", result)

        self.assertTrue(os.path.exists(self.thumbFullPath))
        self.assertEqual(len(os.listdir(self.thumbFullPath)), 1)

    def test_double(self):
        text = u"""(:diagram:)Абырвалг -> Блаблабла(:diagramend:)
(:diagram:)Абыр -> валг -> Блаблабла(:diagramend:)"""

        validResult = u'<img src="{}/__diagram_'.format(self.thumbDir)

        result = self.parser.toHtml(text)
        self.assertIn(validResult, result)

        # Признак ошибки
        self.assertNotIn(u"<b>", result)

        self.assertTrue(os.path.exists(self.thumbFullPath))
        self.assertEqual(len(os.listdir(self.thumbFullPath)), 2)

    def test_copy(self):
        text = u"""(:diagram:)Абырвалг -> Блаблабла(:diagramend:)
(:diagram:)Абырвалг -> Блаблабла(:diagramend:)"""

        validResult = u'<img src="{}/__diagram_'.format(self.thumbDir)

        result = self.parser.toHtml(text)
        self.assertIn(validResult, result)

        # Признак ошибки
        self.assertNotIn(u"<b>", result)

        self.assertTrue(os.path.exists(self.thumbFullPath))
        self.assertEqual(len(os.listdir(self.thumbFullPath)), 1)

    def testError(self):
        text = u"(:diagram:)a - b(:diagramend:)"
        validResult = u'<img src="{}/__diagram_'.format(self.thumbDir)

        result = self.parser.toHtml(text)
        self.assertNotIn(validResult, result)

        # Признак ошибки
        self.assertIn(u"<b>", result)

        # Папка для превьюшек все равно создается
        self.assertTrue(os.path.exists(self.thumbFullPath))

    def testShapes_01(self):
        template = u'a{n}[shape = {shape}]'
        shapes = [
            "actor",
            "beginpoint",
            "box",
            "circle",
            "cloud",
            "diamond",
            "dots",
            "ellipse",
            "endpoint",
            "mail",
            "minidiamond",
            "none",
            "note",
            "roundedbox",
            "square",
            "textbox",
            "flowchart.database",
            "flowchart.input",
            "flowchart.loopin",
            "flowchart.loopout",
            "flowchart.terminator",
        ]

        lines = [u"(:diagram:)"]

        for n, shape in zip(range(len(shapes)), shapes):
            lines.append(template.format(n=n, shape=shape))

        lines.append(u"(:diagramend:)")
        text = u"\n".join(lines)

        validResult = u'<img src="{}/__diagram_'.format(self.thumbDir)
        result = self.parser.toHtml(text)
        self.assertIn(validResult, result)

        # Признак ошибки
        self.assertNotIn(u"<b>", result)

    def testShapes_02(self):
        shapes = sorted([
            "actor",
            "beginpoint",
            "box",
            "circle",
            "cloud",
            "diamond",
            "dots",
            "ellipse",
            "endpoint",
            "mail",
            "minidiamond",
            "none",
            "note",
            "roundedbox",
            "square",
            "textbox",
            "flowchart.database",
            "flowchart.input",
            "flowchart.loopin",
            "flowchart.loopout",
            "flowchart.terminator",
        ])

        from diagrammer.diagramrender import DiagramRender
        diagramShapers = DiagramRender.shapes

        self.assertEqual(shapes, diagramShapers)
Пример #48
0
class HackPage_ChangePageUidTest(unittest.TestCase, BaseOutWikerGUIMixin):
    def setUp(self):
        self.initApplication()
        self.wikiroot = self.createWiki()

        self.__createWiki()
        self.testPage = self.wikiroot["Страница 1"]
        self.testPage2 = self.wikiroot["Страница 2"]

        dirlist = ["plugins/hackpage"]

        self._loader = PluginsLoader(self.application)
        self._loader.load(dirlist)

        Tester.dialogTester.clear()

    def tearDown(self):
        Tester.dialogTester.clear()
        self.application.wikiroot = None
        removeDir(self.wikiroot.path)
        self._loader.clear()
        self.destroyApplication()
        self.destroyWiki(self.wikiroot)

    def __createWiki(self):
        WikiPageFactory().create(self.wikiroot, "Страница 1", [])
        WikiPageFactory().create(self.wikiroot, "Страница 2", [])

    def _setValue(self, dialog, value):
        dialog.Value = value
        return wx.ID_OK

    def test_UidDefault(self):
        from hackpage.utils import changeUidWithDialog

        Tester.dialogTester.appendOk()
        uid_old = self.application.pageUidDepot.createUid(self.testPage)

        changeUidWithDialog(self.testPage, self.application)

        uid_new = self.application.pageUidDepot.createUid(self.testPage)

        self.assertEqual(uid_old, uid_new)
        self.assertEqual(Tester.dialogTester.count, 0)

    def test_change_uid_01(self):
        from hackpage.utils import changeUidWithDialog
        uid = 'dsfsfsfssg'

        Tester.dialogTester.append(self._setValue, uid)

        changeUidWithDialog(self.testPage, self.application)

        uid_new = self.application.pageUidDepot.createUid(self.testPage)

        self.assertEqual(Tester.dialogTester.count, 0)
        self.assertEqual(uid_new, uid)

    def test_change_uid_02(self):
        from hackpage.utils import changeUidWithDialog
        uid = '     dsfsfsfssg      '

        Tester.dialogTester.append(self._setValue, uid)

        changeUidWithDialog(self.testPage, self.application)

        uid_new = self.application.pageUidDepot.createUid(self.testPage)

        self.assertEqual(Tester.dialogTester.count, 0)
        self.assertEqual(uid_new, uid.strip())

    def test_uid_validate_simple(self):
        from hackpage.validators import ChangeUidValidator
        Tester.dialogTester.appendOk()

        uid = 'dofiads7f89qwhrj'
        uidvalidator = ChangeUidValidator(self.application, self.testPage)

        self.assertTrue(uidvalidator(uid))
        self.assertEqual(Tester.dialogTester.count, 1)

    def test_uid_validate_underline(self):
        from hackpage.validators import ChangeUidValidator
        Tester.dialogTester.appendOk()

        uid = '__dofiads7f89qwhrj__'
        uidvalidator = ChangeUidValidator(self.application, self.testPage)

        self.assertTrue(uidvalidator(uid))
        self.assertEqual(Tester.dialogTester.count, 1)

    def test_uid_validate_russian(self):
        from hackpage.validators import ChangeUidValidator
        Tester.dialogTester.appendOk()

        uid = 'ывдратфыщшатф4е6'
        uidvalidator = ChangeUidValidator(self.application, self.testPage)

        self.assertTrue(uidvalidator(uid))
        self.assertEqual(Tester.dialogTester.count, 1)

    def test_uid_validate_error_spaces(self):
        from hackpage.validators import ChangeUidValidator
        Tester.dialogTester.appendOk()

        uid = 'dsfsf sfssgs'
        uidvalidator = ChangeUidValidator(self.application, self.testPage)

        self.assertFalse(uidvalidator(uid))
        self.assertEqual(Tester.dialogTester.count, 0)

    def test_uid_validate_error_duplicate(self):
        from hackpage.validators import ChangeUidValidator
        Tester.dialogTester.appendOk()

        uid = self.application.pageUidDepot.createUid(self.testPage2)
        uidvalidator = ChangeUidValidator(self.application, self.testPage)

        self.assertFalse(uidvalidator(uid))
        self.assertEqual(Tester.dialogTester.count, 0)

    def test_uid_validate_spaces_begin_end(self):
        from hackpage.validators import ChangeUidValidator
        Tester.dialogTester.appendOk()

        uid = '  dsfsfsfssgs  '
        uidvalidator = ChangeUidValidator(self.application, self.testPage)

        self.assertTrue(uidvalidator(uid))
        self.assertEqual(Tester.dialogTester.count, 1)
Пример #49
0
class SnippetParserTest(unittest.TestCase, BaseOutWikerGUIMixin):
    def setUp(self):
        self.initApplication()
        self.wikiroot = self.createWiki()
        self.testPage = WikiPageFactory().create(self.wikiroot,
                                                 "Страница 1",
                                                 [])
        plugins_dir = ["plugins/snippets"]

        self.loader = PluginsLoader(self.application)
        self.loader.load(plugins_dir)

        self.application.wikiroot = self.wikiroot
        self.application.selectedPage = self.testPage

    def tearDown(self):
        self.application.wikiroot = None
        self.loader.clear()
        self.destroyApplication()
        self.destroyWiki(self.wikiroot)

    def test_empty(self):
        from snippets.snippetparser import SnippetParser
        template = ''
        selectedText = ''
        vars = {}

        right_result = ''
        right_variables = set()

        page = self.testPage
        parser = SnippetParser(template, '.', self.application)
        result = parser.process(selectedText, page, **vars)
        variables = parser.getVariables()

        self.assertEqual(result, right_result)
        self.assertEqual(variables, right_variables)

    def test_simple(self):
        from snippets.snippetparser import SnippetParser
        template = 'Проверка 123'
        selectedText = ''
        vars = {}

        right_result = 'Проверка 123'
        right_variables = set()

        page = self.testPage
        parser = SnippetParser(template, '.', self.application)
        result = parser.process(selectedText, page, **vars)
        variables = parser.getVariables()

        self.assertEqual(result, right_result)
        self.assertEqual(variables, right_variables)

    def test_vars_01(self):
        from snippets.snippetparser import SnippetParser
        template = '{{varname}}'
        selectedText = ''
        vars = {'varname': 'Проверка 123'}

        right_result = 'Проверка 123'
        right_variables = {'varname'}

        page = self.testPage
        parser = SnippetParser(template, '.', self.application)
        result = parser.process(selectedText, page, **vars)
        variables = parser.getVariables()

        self.assertEqual(result, right_result)
        self.assertEqual(variables, right_variables)

    def test_vars_02(self):
        from snippets.snippetparser import SnippetParser
        template = '{{varname}}'
        selectedText = ''
        vars = {
            'varname': 'Проверка 123',
            'varname_2': 'Абырвалг',
        }

        right_result = 'Проверка 123'
        right_variables = {'varname'}

        page = self.testPage
        parser = SnippetParser(template, '.', self.application)
        result = parser.process(selectedText, page, **vars)
        variables = parser.getVariables()

        self.assertEqual(result, right_result)
        self.assertEqual(variables, right_variables)

    def test_vars_03(self):
        from snippets.snippetparser import SnippetParser
        template = 'Проверка: {{varname}}'
        selectedText = ''
        vars = {}

        right_result = 'Проверка: '
        right_variables = {'varname'}

        page = self.testPage
        parser = SnippetParser(template, '.', self.application)
        result = parser.process(selectedText, page, **vars)
        variables = parser.getVariables()

        self.assertEqual(result, right_result)
        self.assertEqual(variables, right_variables)

    def test_include_01(self):
        from snippets.snippetparser import SnippetParser
        template = '{{varname}} {% include "included" %}'
        selectedText = ''
        vars = {
            'varname': 'Проверка 123',
            'var_inc': 'Абырвалг',
        }

        right_result = 'Проверка 123 Включенный шаблон Абырвалг'
        right_variables = {'varname', 'var_inc'}

        page = self.testPage
        parser = SnippetParser(template,
                               'testdata/snippets',
                               self.application)
        result = parser.process(selectedText, page, **vars)
        variables = parser.getVariables()

        self.assertEqual(result, right_result)
        self.assertEqual(variables, right_variables)

    def test_global_var_title(self):
        from snippets.snippetparser import SnippetParser
        page = self.testPage
        template = '{{__title}}'
        selectedText = ''
        vars = {}

        right_result = page.title

        parser = SnippetParser(template, '.', self.application)
        result = parser.process(selectedText, page, **vars)

        self.assertEqual(result, right_result)

    def test_global_var_text(self):
        from snippets.snippetparser import SnippetParser
        page = self.testPage
        template = '{{__text}}'
        selectedText = 'Проверка'
        vars = {}

        right_result = 'Проверка'

        parser = SnippetParser(template, '.', self.application)
        result = parser.process(selectedText, page, **vars)

        self.assertEqual(result, right_result)

    def test_global_var_subpath(self):
        from snippets.snippetparser import SnippetParser
        page = self.testPage
        template = '{{__subpath}}'
        selectedText = ''
        vars = {}

        right_result = page.subpath

        parser = SnippetParser(template, '.', self.application)
        result = parser.process(selectedText, page, **vars)

        self.assertEqual(result, right_result)

    def test_global_var_attach(self):
        from snippets.snippetparser import SnippetParser
        page = self.testPage
        template = '{{__attach}}'
        selectedText = ''
        vars = {}

        right_result = Attachment(page).getAttachPath(False)

        parser = SnippetParser(template, '.', self.application)
        result = parser.process(selectedText, page, **vars)

        self.assertEqual(result, right_result)
        self.assertTrue(os.path.exists(right_result))

    def test_global_var_folder(self):
        from snippets.snippetparser import SnippetParser
        page = self.testPage
        template = '{{__folder}}'
        selectedText = ''
        vars = {}

        right_result = page.path

        parser = SnippetParser(template, '.', self.application)
        result = parser.process(selectedText, page, **vars)

        self.assertEqual(result, right_result)

    def test_global_var_pageid(self):
        from snippets.snippetparser import SnippetParser
        page = self.testPage
        template = '{{__pageid}}'
        selectedText = ''
        vars = {}

        right_result = self.application.pageUidDepot.createUid(page)

        parser = SnippetParser(template, '.', self.application)
        result = parser.process(selectedText, page, **vars)

        self.assertEqual(result, right_result)

    def test_global_var_eddate(self):
        from snippets.snippetparser import SnippetParser
        date = datetime(2016, 12, 9, 14, 23)
        page = self.testPage
        page.datetime = date
        template = '{{__eddate}}'
        selectedText = ''
        vars = {}

        right_result = str(date)

        parser = SnippetParser(template, '.', self.application)
        result = parser.process(selectedText, page, **vars)

        self.assertEqual(result, right_result)

    def test_global_var_crdate(self):
        from snippets.snippetparser import SnippetParser
        date = datetime(2016, 12, 9, 14, 0)
        page = self.testPage
        page.creationdatetime = date
        template = '{{__crdate}}'
        selectedText = ''
        vars = {}

        right_result = str(date)

        parser = SnippetParser(template, '.', self.application)
        result = parser.process(selectedText, page, **vars)

        self.assertEqual(result, right_result)

    def test_global_var_tags_01(self):
        from snippets.snippetparser import SnippetParser
        page = self.testPage
        page.tags = ['проверка', 'test', 'тест']
        template = '{{__tags}}'
        selectedText = ''
        vars = {}

        right_result = 'test, проверка, тест'

        parser = SnippetParser(template, '.', self.application)
        result = parser.process(selectedText, page, **vars)

        self.assertEqual(result, right_result)

    def test_global_var_tags_02(self):
        from snippets.snippetparser import SnippetParser
        page = self.testPage
        page.tags = ['проверка', 'test', 'тест']
        template = '{% for tag in __tags %}{{tag}}---{% endfor %}'
        selectedText = ''
        vars = {}

        right_result = 'test---проверка---тест---'

        parser = SnippetParser(template, '.', self.application)
        result = parser.process(selectedText, page, **vars)

        self.assertEqual(result, right_result)

    def test_global_var_tags_03_empty(self):
        from snippets.snippetparser import SnippetParser
        page = self.testPage
        page.tags = []
        template = '{{__tags}}'
        selectedText = ''
        vars = {}

        right_result = ''

        parser = SnippetParser(template, '.', self.application)
        result = parser.process(selectedText, page, **vars)

        self.assertEqual(result, right_result)

    def test_global_var_childlist_01(self):
        from snippets.snippetparser import SnippetParser
        page = self.testPage
        WikiPageFactory().create(page, "Страница 1", [])
        WikiPageFactory().create(page, "Страница 2", [])
        WikiPageFactory().create(page, "Страница 3", [])

        template = '{{__childlist}}'
        selectedText = ''
        vars = {}

        right_result = 'Страница 1, Страница 2, Страница 3'

        parser = SnippetParser(template, '.', self.application)
        result = parser.process(selectedText, page, **vars)

        self.assertEqual(result, right_result)

    def test_global_var_childlist_02(self):
        from snippets.snippetparser import SnippetParser
        page = self.testPage
        subpage1 = WikiPageFactory().create(page, "Страница 1", [])
        subpage2 = WikiPageFactory().create(page, "Страница 2", [])
        subpage3 = WikiPageFactory().create(page, "Страница 3", [])

        subpage2.order = 1
        subpage3.order = 4
        subpage1.order = 10

        template = '{{__childlist}}'
        selectedText = ''
        vars = {}

        right_result = 'Страница 2, Страница 3, Страница 1'

        parser = SnippetParser(template, '.', self.application)
        result = parser.process(selectedText, page, **vars)

        self.assertEqual(result, right_result)

    def test_global_var_type(self):
        from snippets.snippetparser import SnippetParser
        page = self.testPage
        template = '{{__type}}'
        selectedText = ''
        vars = {}

        right_result = 'wiki'

        parser = SnippetParser(template, '.', self.application)
        result = parser.process(selectedText, page, **vars)

        self.assertEqual(result, right_result)

    def test_global_var_attachilist(self):
        from snippets.snippetparser import SnippetParser
        fnames = ['ccc.png', 'aaa.tmp', 'zzz.doc']
        page = self.testPage
        attachdir = Attachment(page).getAttachPath(True)
        for fname in fnames:
            fullpath = os.path.join(attachdir, fname)
            with open(fullpath, 'w'):
                pass

        page = self.testPage
        template = '{{__attachlist}}'
        selectedText = ''
        vars = {}

        right_result = 'aaa.tmp, ccc.png, zzz.doc'

        parser = SnippetParser(template, '.', self.application)
        result = parser.process(selectedText, page, **vars)

        self.assertEqual(result, right_result)

    def test_unicode_01(self):
        from snippets.snippetparser import SnippetParser

        page = self.testPage
        template = 'Переменная = {{переменная}}'
        selectedText = ''
        vars = {'переменная': 'Проверка 123'}
        right_result = 'Переменная = Проверка 123'

        parser = SnippetParser(template, '.', self.application)
        result = parser.process(selectedText, page, **vars)
        self.assertEqual(result, right_result)

    def test_unicode_02(self):
        from snippets.snippetparser import SnippetParser
        template = 'Переменная = {{переменная}}'
        right_result = 'Переменная = '
        selectedText = ''
        page = self.testPage
        vars = {}

        parser = SnippetParser(template, '.', self.application)
        result = parser.process(selectedText, page, **vars)
        self.assertEqual(result, right_result)
Пример #50
0
class SourceEncodingPluginTest(unittest.TestCase, BaseOutWikerGUIMixin):
    """
    Тесты на работу с разными кодировками в плагине Source
    """

    def setUp(self):
        self.__pluginname = "Source"
        self.initApplication()
        self.wikiroot = self.createWiki()
        self.testPage = WikiPageFactory().create(self.wikiroot,
                                                 "Страница 1",
                                                 [])

        dirlist = ["plugins/source"]

        # Путь, где лежат примеры исходников в разных кодировках
        self.samplefilesPath = "testdata/samplefiles/sources"

        self.loader = PluginsLoader(self.application)
        self.loader.load(dirlist)

        self.config = self.loader[self.__pluginname].config
        self.config.tabWidth.value = 4
        self.config.defaultLanguage.remove_option()

        self.factory = ParserFactory()
        self.parser = self.factory.make(self.testPage, self.application.config)

    def tearDown(self):
        self.loader.clear()
        self.destroyApplication()
        self.destroyWiki(self.wikiroot)

    def testHighlightFileEncoding1(self):
        """
        Явное задание кодировки
        """
        Attachment(self.testPage).attach(
            [os.path.join(self.samplefilesPath, "source_cp1251.cs")])
        content = '(:source file="source_cp1251.cs"  encoding="cp1251":)'
        self.testPage.content = content

        generator = HtmlGenerator(self.testPage)
        result = generator.makeHtml(Style().getPageStyle(self.testPage))

        self.assertTrue(
            '<span class="k">using</span><span class="w"> </span><span class="nn">System.Collections.Generic</span><span class="p">;</span><span class="w"></span' in result)
        self.assertTrue('Ошибка соединения с сервером' in result)

    def testHighlightFileEncoding2(self):
        """
        Явное задание неправильной кодировки
        """
        Attachment(self.testPage).attach(
            [os.path.join(self.samplefilesPath, "source_cp1251.cs")])
        content = '(:source file="source_cp1251.cs"  encoding="utf8":)'
        self.testPage.content = content

        generator = HtmlGenerator(self.testPage)
        result = generator.makeHtml(Style().getPageStyle(self.testPage))

        self.assertTrue(
            '<span class="k">using</span> <span class="nn">System.Collections.Generic</span><span class="p">;</span>' not in result)
        self.assertTrue('Ошибка соединения с сервером' not in result)

        self.assertTrue('Source' in result)

    def testHighlightFileEncoding3(self):
        """
        Явное задание неправильной кодировки(которой нет в списке кодировок)
        """
        Attachment(self.testPage).attach(
            [os.path.join(self.samplefilesPath, "source_cp1251.cs")])
        content = '(:source file="source_cp1251.cs"  encoding="blablabla":)'
        self.testPage.content = content

        generator = HtmlGenerator(self.testPage)
        result = generator.makeHtml(Style().getPageStyle(self.testPage))

        self.assertTrue(
            '<span class="k">using</span> <span class="nn">System.Collections.Generic</span><span class="p">;</span>' not in result)
        self.assertTrue('Ошибка соединения с сервером' not in result)

        self.assertTrue('Source' in result)

    def testHighlightFileEncoding4(self):
        """
        Явное задание неправильной кодировки(которой нет в списке кодировок)
        """
        Attachment(self.testPage).attach(
            [os.path.join(self.samplefilesPath, "source_utf8.py")])
        content = '(:source file="source_utf8.py"  encoding="blablabla":)'
        self.testPage.content = content

        generator = HtmlGenerator(self.testPage)
        result = generator.makeHtml(Style().getPageStyle(self.testPage))

        self.assertTrue(
            '<span class="kn">import</span> <span class="nn">os.path</span>' not in result)

        self.assertTrue(
            '<span class="bp">self</span><span class="o">.</span><span class="n">__correctSysPath</span><span class="p">()</span>' not in result)

        self.assertTrue('Уничтожение(выгрузка) плагина.' not in result)

        self.assertTrue('Source' in result)
Пример #51
0
class SnippetsLoaderTest(unittest.TestCase, BaseOutWikerGUIMixin):
    def setUp(self):
        self.initApplication()
        dirlist = ["../plugins/snippets"]

        self.loader = PluginsLoader(Application)
        self.loader.load(dirlist)
        self._dir_snippets = mkdtemp('outwiker_snippets')

    def tearDown(self):
        self.loader.clear()
        removeDir(self._dir_snippets)
        self.destroyApplication()

    def _create(self, fname):
        with open(fname, 'w'):
            pass

    def test_empty_01(self):
        from snippets.snippetsloader import SnippetsLoader
        loader = SnippetsLoader(self._dir_snippets)
        snippets = loader.getSnippets()

        self.assertEqual(snippets.name, os.path.basename(self._dir_snippets))
        self.assertEqual(len(snippets), 0)
        self.assertEqual(snippets.dirs, [])
        self.assertEqual(snippets.snippets, [])

    def test_empty_02_invalid(self):
        from snippets.snippetsloader import SnippetsLoader
        loader = SnippetsLoader('Invalid dir')
        snippets = loader.getSnippets()

        self.assertEqual(snippets.name, 'Invalid dir')
        self.assertEqual(len(snippets), 0)
        self.assertEqual(snippets.dirs, [])
        self.assertEqual(snippets.snippets, [])

    def test_snippets_01(self):
        from snippets.snippetsloader import SnippetsLoader
        files = ['Шаблон']
        for fname in files:
            self._create(os.path.join(self._dir_snippets, fname))

        loader = SnippetsLoader(self._dir_snippets)
        snippets = loader.getSnippets()
        self.assertEqual(snippets.dirs, [])
        self.assertEqual(snippets.snippets,
                         [os.path.join(self._dir_snippets, 'Шаблон')])
        self.assertEqual(len(snippets), 1)

    def test_snippets_02(self):
        from snippets.snippetsloader import SnippetsLoader
        files = ['Шаблон 01', 'Шаблон 02', 'Шаблон 03.txt']
        for fname in files:
            self._create(os.path.join(self._dir_snippets, fname))

        loader = SnippetsLoader(self._dir_snippets)
        snippets = loader.getSnippets()
        self.assertEqual(snippets.dirs, [])

        self.assertIn(
            os.path.join(self._dir_snippets, 'Шаблон 01'),
            snippets.snippets)

        self.assertIn(
            os.path.join(self._dir_snippets, 'Шаблон 02'),
            snippets.snippets)

        self.assertIn(
            os.path.join(self._dir_snippets, 'Шаблон 03.txt'),
            snippets.snippets)

        self.assertEqual(len(snippets), 3)

    def test_subdir_01(self):
        from snippets.snippetsloader import SnippetsLoader
        subdir = os.path.join(self._dir_snippets, 'Поддиректория 01')
        os.mkdir(subdir)

        loader = SnippetsLoader(self._dir_snippets)
        snippets = loader.getSnippets()
        self.assertEqual(len(snippets.dirs), 1)

        subdir = snippets.dirs[0]
        self.assertEqual(len(subdir), 0)
        self.assertEqual(subdir.name, 'Поддиректория 01')

    def test_subdir_02(self):
        from snippets.snippetsloader import SnippetsLoader
        subdir_1 = os.path.join(self._dir_snippets, 'Поддиректория 01')
        subdir_2 = os.path.join(self._dir_snippets, 'Поддиректория 02')
        os.mkdir(subdir_1)
        os.mkdir(subdir_2)

        loader = SnippetsLoader(self._dir_snippets)
        snippets = loader.getSnippets()

        self.assertEqual(len(snippets), 2)
        self.assertEqual(len(snippets.dirs), 2)

        self.assertEqual(len(snippets.dirs[0]), 0)
        self.assertEqual(len(snippets.dirs[1]), 0)

    def test_subdir_03(self):
        from snippets.snippetsloader import SnippetsLoader
        subdir_1 = os.path.join(self._dir_snippets, 'Поддиректория 01')
        subdir_2 = os.path.join(subdir_1, 'Поддиректория 02')
        os.mkdir(subdir_1)
        os.mkdir(subdir_2)

        loader = SnippetsLoader(self._dir_snippets)
        snippets = loader.getSnippets()

        self.assertEqual(len(snippets), 1)
        self.assertEqual(len(snippets.dirs), 1)

        self.assertEqual(len(snippets.dirs[0]), 1)
        self.assertEqual(len(snippets.dirs[0].dirs[0]), 0)

    def test_full_01(self):
        from snippets.snippetsloader import SnippetsLoader
        subdir_1 = os.path.join(self._dir_snippets, 'Поддиректория 01')
        subdir_2 = os.path.join(subdir_1, 'Поддиректория 02')
        os.mkdir(subdir_1)
        os.mkdir(subdir_2)

        files = [os.path.join(self._dir_snippets, 'root_01'),
                 os.path.join(self._dir_snippets, 'root_02'),
                 os.path.join(subdir_1, 'dir_01_01'),
                 os.path.join(subdir_1, 'dir_01_02'),
                 os.path.join(subdir_2, 'dir_02_01'),
                 os.path.join(subdir_2, 'dir_02_02'),
                 ]

        list([self._create(fname) for fname in files])
        loader = SnippetsLoader(self._dir_snippets)
        snippets = loader.getSnippets()

        self.assertEqual(len(snippets.snippets), 2)
        self.assertEqual(len(snippets.dirs), 1)
        self.assertEqual(len(snippets), 3)

        self.assertEqual(len(snippets.dirs[0].snippets), 2)
        self.assertEqual(len(snippets.dirs[0].dirs), 1)
        self.assertEqual(len(snippets.dirs[0]), 3)

        self.assertEqual(len(snippets.dirs[0].dirs[0].snippets), 2)
        self.assertEqual(len(snippets.dirs[0].dirs[0].dirs), 0)
        self.assertEqual(len(snippets.dirs[0].dirs[0]), 2)
Пример #52
0
class PluginLoadingMixin(BaseOutWikerGUIMixin, metaclass=ABCMeta):
    @abstractmethod
    def getPluginDir(self):
        """
        Должен возвращать путь до папки с тестируемым плагином
        """
        pass

    @abstractmethod
    def getPluginName(self):
        """
        Должен возвращать имя плагина,
        по которому его можно найти в PluginsLoader
        """
        pass

    def setUp(self):
        self.initApplication()
        self.wikiroot = self.createWiki()
        self.__createWiki()

        dirlist = [self.getPluginDir()]

        self.loader = PluginsLoader(self.application)
        self.loader.load(dirlist)

    def __createWiki(self):
        # Здесь будет создаваться вики
        WikiPageFactory().create(self.wikiroot, "Викистраница", [])
        TextPageFactory().create(self.wikiroot, "Текст", [])
        HtmlPageFactory().create(self.wikiroot, "HTML", [])
        SearchPageFactory().create(self.wikiroot, "Search", [])

    def tearDown(self):
        self.application.selectedPage = None
        self.application.wikiroot = None
        self.loader.clear()
        self.destroyApplication()
        self.destroyWiki(self.wikiroot)

    def testPluginLoad(self):
        self.assertEqual(len(self.loader), 1)
        self.assertNotEqual(self.loader[self.getPluginName()], None)

    def testDestroy_01(self):
        self.application.wikiroot = None
        self.loader.clear()

    def testDestroy_02(self):
        self.application.wikiroot = self.wikiroot
        self.application.selectedPage = None
        self.loader.clear()

    def testDestroy_03(self):
        self.application.wikiroot = self.wikiroot
        self.application.selectedPage = self.wikiroot["Викистраница"]
        self.loader.clear()

    def testDestroy_04(self):
        self.application.wikiroot = self.wikiroot
        self.application.selectedPage = self.wikiroot["Текст"]
        self.loader.clear()

    def testDestroy_05(self):
        self.application.wikiroot = self.wikiroot
        self.application.selectedPage = self.wikiroot["HTML"]
        self.loader.clear()

    def testDestroy_06(self):
        self.application.wikiroot = self.wikiroot
        self.application.selectedPage = self.wikiroot["Search"]
        self.loader.clear()

    def testDestroy_07(self):
        self.application.wikiroot = self.wikiroot
        self.application.selectedPage = self.wikiroot["Викистраница"]
        self.loader.disable(self.getPluginName())

        action = self.application.actionController.getAction(SwitchCodeResultAction.stringId)
        action.run(None)
        self.loader.clear()

    def testDestroy_08(self):
        self.application.wikiroot = self.wikiroot
        self.application.selectedPage = self.wikiroot["HTML"]
        self.loader.disable(self.getPluginName())

        action = self.application.actionController.getAction(SwitchCodeResultAction.stringId)
        action.run(None)
        self.loader.clear()

    def testDestroy_09(self):
        self.application.wikiroot = self.wikiroot
        self.application.selectedPage = self.wikiroot["Викистраница"]
        self.loader.clear()

        action = self.application.actionController.getAction(SwitchCodeResultAction.stringId)
        action.run(None)

    def testDestroy_10(self):
        self.application.wikiroot = self.wikiroot
        self.application.selectedPage = self.wikiroot["HTML"]
        self.loader.clear()

        action = self.application.actionController.getAction(SwitchCodeResultAction.stringId)
        action.run(None)
Пример #53
0
class CommandExecParserTest (unittest.TestCase):
    def setUp(self):
        self.maxDiff = None

        self.__createWiki()
        self.testPage = self.wikiroot['Страница 1']
        self.testPageTextPath = os.path.join(self.testPage.path, '__page.text')
        self.testPageHtmlPath = os.path.join(
            self.testPage.path, PAGE_RESULT_HTML)
        self.testPageAttachPath = Attachment(
            self.testPage).getAttachPath(False)

        dirlist = ['../plugins/externaltools']

        self.loader = PluginsLoader(Application)
        self.loader.load(dirlist)

        self.factory = ParserFactory()
        self.parser = self.factory.make(self.testPage, Application.config)

    def __createWiki(self):
        # Здесь будет создаваться вики
        self.path = mkdtemp(prefix='Абырвалг абыр')
        self.wikiroot = WikiDocument.create(self.path)
        WikiPageFactory().create(self.wikiroot, 'Страница 1', [])

    def tearDown(self):
        removeDir(self.path)
        self.loader.clear()

    def testPluginLoad(self):
        self.assertEqual(len(self.loader), 1)

    def testEmpty(self):
        text = '(:exec:)(:execend:)'
        validResult = ''

        result = self.parser.toHtml(text)
        self.assertEqual(result, validResult)

    def testCommandExecParser_01_empty(self):
        from externaltools.commandexec.commandexecparser import CommandExecParser
        text = ''

        parser = CommandExecParser(self.testPage)
        result = parser.parse(text)

        self.assertEqual(len(result), 0)

    def testCommandExecParser_02(self):
        from externaltools.commandexec.commandexecparser import CommandExecParser
        text = 'gvim'

        parser = CommandExecParser(self.testPage)
        result = parser.parse(text)

        self.assertEqual(len(result), 1)
        self.assertEqual(result[0].command, 'gvim')
        self.assertEqual(len(result[0].params), 0)

    def testCommandExecParser_03(self):
        from externaltools.commandexec.commandexecparser import CommandExecParser
        text = '''gvim
krusader'''

        parser = CommandExecParser(self.testPage)
        result = parser.parse(text)

        self.assertEqual(len(result), 2)

        self.assertEqual(result[0].command, 'gvim')
        self.assertEqual(len(result[0].params), 0)

        self.assertEqual(result[1].command, 'krusader')
        self.assertEqual(len(result[1].params), 0)

    def testCommandExecParser_04(self):
        from externaltools.commandexec.commandexecparser import CommandExecParser
        text = '''

    gvim


      krusader

'''

        parser = CommandExecParser(self.testPage)
        result = parser.parse(text)

        self.assertEqual(len(result), 2)

        self.assertEqual(result[0].command, 'gvim')
        self.assertEqual(len(result[0].params), 0)

        self.assertEqual(result[1].command, 'krusader')
        self.assertEqual(len(result[1].params), 0)

    def testCommandExecParser_05_params(self):
        from externaltools.commandexec.commandexecparser import CommandExecParser
        text = 'gvim -d файл1.txt файл2.txt'

        parser = CommandExecParser(self.testPage)
        result = parser.parse(text)

        self.assertEqual(len(result), 1)
        self.assertEqual(result[0].command, 'gvim')
        self.assertEqual(result[0].params, ['-d', 'файл1.txt', 'файл2.txt'])

    def testCommandExecParser_06_params(self):
        from externaltools.commandexec.commandexecparser import CommandExecParser
        text = '  gvim   -d   файл1.txt   файл2.txt   '

        parser = CommandExecParser(self.testPage)
        result = parser.parse(text)

        self.assertEqual(len(result), 1)
        self.assertEqual(result[0].command, 'gvim')
        self.assertEqual(result[0].params, ['-d', 'файл1.txt', 'файл2.txt'])

    def testCommandExecParser_07_params(self):
        from externaltools.commandexec.commandexecparser import CommandExecParser
        text = '  gvim   -d   "Имя файла 1.txt"   "Имя файла 2.txt"   '

        parser = CommandExecParser(self.testPage)
        result = parser.parse(text)

        self.assertEqual(len(result), 1)
        self.assertEqual(result[0].command, 'gvim')
        self.assertEqual(
            result[0].params, [
                '-d', 'Имя файла 1.txt', 'Имя файла 2.txt'])

    def testCommandExecParser_08_params(self):
        from externaltools.commandexec.commandexecparser import CommandExecParser
        text = r'  gvim   -d   "Имя файла 1\".txt"   "Имя файла 2.txt"   '

        parser = CommandExecParser(self.testPage)
        result = parser.parse(text)

        self.assertEqual(len(result), 1)
        self.assertEqual(result[0].command, 'gvim')
        self.assertEqual(
            result[0].params, [
                '-d', 'Имя файла 1".txt', 'Имя файла 2.txt'])

    def testCommandExecParser_09_params(self):
        from externaltools.commandexec.commandexecparser import CommandExecParser
        text = '''
        gvim   -d   "Имя файла 1.txt"   "Имя файла 2.txt"


        krusader Параметр1 "Параметр 2 с пробелом"

        '''

        parser = CommandExecParser(self.testPage)
        result = parser.parse(text)

        self.assertEqual(len(result), 2)

        self.assertEqual(result[0].command, 'gvim')
        self.assertEqual(
            result[0].params, [
                '-d', 'Имя файла 1.txt', 'Имя файла 2.txt'])

        self.assertEqual(result[1].command, 'krusader')
        self.assertEqual(
            result[1].params, [
                'Параметр1', 'Параметр 2 с пробелом'])

    def testCommandExecParser_10_join(self):
        from externaltools.commandexec.commandexecparser import CommandExecParser
        text = r'''gvim \
"Имя файла"
'''

        parser = CommandExecParser(self.testPage)
        result = parser.parse(text)

        self.assertEqual(len(result), 1)

        self.assertEqual(result[0].command, 'gvim')
        self.assertEqual(result[0].params, ['Имя файла'])

    def testCommandExecParser_11_join(self):
        from externaltools.commandexec.commandexecparser import CommandExecParser
        text = r'''gvim \
   "Имя файла"
'''

        parser = CommandExecParser(self.testPage)
        result = parser.parse(text)

        self.assertEqual(len(result), 1)

        self.assertEqual(result[0].command, 'gvim')
        self.assertEqual(result[0].params, ['Имя файла'])

    def testCommandExecParser_join_01(self):
        from externaltools.commandexec.commandexecparser import CommandExecParser
        text = r'''gvim \


"Имя файла"
'''

        parser = CommandExecParser(self.testPage)
        result = parser.parse(text)

        self.assertEqual(len(result), 1)

        self.assertEqual(result[0].command, 'gvim')
        self.assertEqual(result[0].params, ['Имя файла'])

    def testCommandExecParser_13_invalid(self):
        from externaltools.commandexec.commandexecparser import CommandExecParser
        text = r'''gvim \ asdfadsf'''

        parser = CommandExecParser(self.testPage)
        parser.parse(text)

    def testCommandExecParser_14_params(self):
        from externaltools.commandexec.commandexecparser import CommandExecParser
        text = 'gvim -d'

        parser = CommandExecParser(self.testPage)
        result = parser.parse(text)

        self.assertEqual(len(result), 1)
        self.assertEqual(result[0].command, 'gvim')
        self.assertEqual(result[0].params, ['-d'])

    def testCommandExecParser_15_params(self):
        from externaltools.commandexec.commandexecparser import CommandExecParser
        text = 'gvim "c:\\temp\\abyrvalg\\rrr\\nnn"'

        parser = CommandExecParser(self.testPage)
        result = parser.parse(text)

        self.assertEqual(len(result), 1)
        self.assertEqual(result[0].command, 'gvim')
        self.assertEqual(result[0].params, ['c:\\temp\\abyrvalg\\rrr\\nnn'])

    def testMacrosPage_01(self):
        from externaltools.commandexec.commandexecparser import CommandExecParser

        text = '''gvim %page%'''

        parser = CommandExecParser(self.testPage)
        result = parser.parse(text)

        self.assertEqual(len(result), 1)
        self.assertEqual(result[0].command, 'gvim')
        self.assertEqual(result[0].params, [self.testPageTextPath])

    def testMacrosPage_02(self):
        from externaltools.commandexec.commandexecparser import CommandExecParser

        text = '''gvim %PAGE%'''

        parser = CommandExecParser(self.testPage)
        result = parser.parse(text)

        self.assertEqual(len(result), 1)
        self.assertEqual(result[0].command, 'gvim')
        self.assertEqual(result[0].params, ['%PAGE%'])

    def testMacrosPage_03(self):
        from externaltools.commandexec.commandexecparser import CommandExecParser

        text = '''gvim \\
%page%'''

        parser = CommandExecParser(self.testPage)
        result = parser.parse(text)

        self.assertEqual(len(result), 1)
        self.assertEqual(result[0].command, 'gvim')
        self.assertEqual(result[0].params, [self.testPageTextPath])

    def testMacrosHtml_01(self):
        from externaltools.commandexec.commandexecparser import CommandExecParser

        text = '''gvim %html%'''

        parser = CommandExecParser(self.testPage)
        result = parser.parse(text)

        self.assertEqual(len(result), 1)
        self.assertEqual(result[0].command, 'gvim')
        self.assertEqual(result[0].params, [self.testPageHtmlPath])

    def testMacrosFolder_01(self):
        from externaltools.commandexec.commandexecparser import CommandExecParser

        text = '''gvim %folder%'''

        parser = CommandExecParser(self.testPage)
        result = parser.parse(text)

        self.assertEqual(len(result), 1)
        self.assertEqual(result[0].command, 'gvim')
        self.assertEqual(result[0].params, [self.testPage.path])

    def testMacrosFolder_02(self):
        from externaltools.commandexec.commandexecparser import CommandExecParser

        text = '''gvim %folder%/111.txt'''

        parser = CommandExecParser(self.testPage)
        result = parser.parse(text)

        self.assertEqual(len(result), 1)
        self.assertEqual(result[0].command, 'gvim')
        self.assertEqual(result[0].params, [self.testPage.path + '/111.txt'])

    def testMacrosFolder_03(self):
        from externaltools.commandexec.commandexecparser import CommandExecParser

        text = '''gvim %FOLDER%'''

        parser = CommandExecParser(self.testPage)
        result = parser.parse(text)

        self.assertEqual(len(result), 1)
        self.assertEqual(result[0].command, 'gvim')
        self.assertEqual(result[0].params, ['%FOLDER%'])

    def testMacrosAttach_01(self):
        from externaltools.commandexec.commandexecparser import CommandExecParser

        text = '''gvim %attach%'''

        parser = CommandExecParser(self.testPage)
        result = parser.parse(text)

        self.assertEqual(len(result), 1)
        self.assertEqual(result[0].command, 'gvim')
        self.assertEqual(result[0].params, [self.testPageAttachPath])

    def testMacrosAttach_02(self):
        from externaltools.commandexec.commandexecparser import CommandExecParser

        text = '''gvim %ATTACH%'''

        parser = CommandExecParser(self.testPage)
        result = parser.parse(text)

        self.assertEqual(len(result), 1)
        self.assertEqual(result[0].command, 'gvim')
        self.assertEqual(result[0].params, ['%ATTACH%'])

    def testMacrosAttach_03(self):
        from externaltools.commandexec.commandexecparser import CommandExecParser

        text = '''gvim Attach:абырвалг.txt'''

        attachPath = os.path.join(self.testPageAttachPath, 'абырвалг.txt')

        parser = CommandExecParser(self.testPage)
        result = parser.parse(text)

        self.assertEqual(len(result), 1)
        self.assertEqual(result[0].command, 'gvim')
        self.assertEqual(result[0].params, [attachPath])

    def testMacrosAttach_04(self):
        from externaltools.commandexec.commandexecparser import CommandExecParser

        text = '''gvim "Attach:абырвалг главрыба.txt"'''

        attachPath = os.path.join(
            self.testPageAttachPath,
            'абырвалг главрыба.txt')

        parser = CommandExecParser(self.testPage)
        result = parser.parse(text)

        self.assertEqual(len(result), 1)
        self.assertEqual(result[0].command, 'gvim')
        self.assertEqual(result[0].params, [attachPath])

    def testMacrosAttach_05(self):
        from externaltools.commandexec.commandexecparser import CommandExecParser

        text = '''gvim xAttach:абырвалг.txt'''

        parser = CommandExecParser(self.testPage)
        result = parser.parse(text)

        self.assertEqual(len(result), 1)
        self.assertEqual(result[0].command, 'gvim')
        self.assertEqual(result[0].params, ['xAttach:абырвалг.txt'])

    def testMacrosAttach_06(self):
        from externaltools.commandexec.commandexecparser import CommandExecParser

        text = '''gvim attach:абырвалг.txt'''

        parser = CommandExecParser(self.testPage)
        result = parser.parse(text)

        self.assertEqual(len(result), 1)
        self.assertEqual(result[0].command, 'gvim')
        self.assertEqual(result[0].params, ['attach:абырвалг.txt'])

    def testMacrosApp_01(self):
        from externaltools.commandexec.commandexecparser import CommandExecParser

        text = '''%folder%/gvim'''

        parser = CommandExecParser(self.testPage)
        result = parser.parse(text)

        self.assertEqual(len(result), 1)
        self.assertEqual(result[0].command,
                         self.testPage.path + '/gvim')

    def testMacrosApp_02(self):
        from externaltools.commandexec.commandexecparser import CommandExecParser

        text = '''%attach%/gvim'''

        parser = CommandExecParser(self.testPage)
        result = parser.parse(text)

        self.assertEqual(len(result), 1)
        self.assertEqual(result[0].command,
                         self.testPageAttachPath + '/gvim')

    def testComments_01(self):
        from externaltools.commandexec.commandexecparser import CommandExecParser

        text = '''gvim fname
# Комментарий'''

        parser = CommandExecParser(self.testPage)
        result = parser.parse(text)

        self.assertEqual(len(result), 1)
        self.assertEqual(result[0].command, 'gvim')
        self.assertEqual(result[0].params, ['fname'])

    def testComments_02(self):
        from externaltools.commandexec.commandexecparser import CommandExecParser

        text = '''gvim fname

# Комментарий


'''

        parser = CommandExecParser(self.testPage)
        result = parser.parse(text)

        self.assertEqual(len(result), 1)
        self.assertEqual(result[0].command, 'gvim')
        self.assertEqual(result[0].params, ['fname'])

    def testComments_03(self):
        from externaltools.commandexec.commandexecparser import CommandExecParser

        text = '''# Комментарий

gvim fname'''

        parser = CommandExecParser(self.testPage)
        result = parser.parse(text)

        self.assertEqual(len(result), 1)
        self.assertEqual(result[0].command, 'gvim')
        self.assertEqual(result[0].params, ['fname'])

    def testComments_04(self):
        from externaltools.commandexec.commandexecparser import CommandExecParser

        text = '''gvim fname # Комментарий'''

        parser = CommandExecParser(self.testPage)
        result = parser.parse(text)

        self.assertEqual(len(result), 1)
        self.assertEqual(result[0].command, 'gvim')
        self.assertEqual(result[0].params, ['fname', '#', 'Комментарий'])

    def testComments_05(self):
        from externaltools.commandexec.commandexecparser import CommandExecParser

        text = '''gvim fname
#Комментарий'''

        parser = CommandExecParser(self.testPage)
        result = parser.parse(text)

        self.assertEqual(len(result), 1)
        self.assertEqual(result[0].command, 'gvim')
        self.assertEqual(result[0].params, ['fname'])

    def testComments_06(self):
        from externaltools.commandexec.commandexecparser import CommandExecParser

        text = '''gvim fname \\
#Комментарий'''

        parser = CommandExecParser(self.testPage)
        result = parser.parse(text)

        self.assertEqual(len(result), 1)
        self.assertEqual(result[0].command, 'gvim')
        self.assertEqual(result[0].params, ['fname'])

    def testComments_07(self):
        from externaltools.commandexec.commandexecparser import CommandExecParser

        text = '''gvim \\
#Комментарий
fname'''

        parser = CommandExecParser(self.testPage)
        result = parser.parse(text)

        self.assertEqual(len(result), 1)
        self.assertEqual(result[0].command, 'gvim')
        self.assertEqual(result[0].params, ['fname'])

    def testComments_08(self):
        from externaltools.commandexec.commandexecparser import CommandExecParser

        text = '''gvim \\
 #Комментарий'''

        parser = CommandExecParser(self.testPage)
        result = parser.parse(text)

        self.assertEqual(len(result), 1)
        self.assertEqual(result[0].command, 'gvim')
        self.assertEqual(result[0].params, ['#Комментарий'])

    def testComments_09(self):
        from externaltools.commandexec.commandexecparser import CommandExecParser

        text = '''gvim \\
 #Комментарий

'''

        parser = CommandExecParser(self.testPage)
        result = parser.parse(text)

        self.assertEqual(len(result), 1)
        self.assertEqual(result[0].command, 'gvim')
        self.assertEqual(result[0].params, ['#Комментарий'])

    def testComments_10(self):
        from externaltools.commandexec.commandexecparser import CommandExecParser

        text = '''gvim
# Комментарий
krusader
# Комментарий 2
'''

        parser = CommandExecParser(self.testPage)
        result = parser.parse(text)

        self.assertEqual(len(result), 2)

        self.assertEqual(result[0].command, 'gvim')
        self.assertEqual(result[0].params, [])

        self.assertEqual(result[1].command, 'krusader')
        self.assertEqual(result[1].params, [])
Пример #54
0
class ParagraphHtmlImproverTest(unittest.TestCase):
    def setUp(self):
        dirlist = [u"../plugins/htmlformatter"]

        self.loader = PluginsLoader(Application)
        self.loader.load(dirlist)

        factory = HtmlImproverFactory(Application)
        self.improver = factory["pimprover"]

    def tearDown(self):
        self.loader.clear()

    def test_empty(self):
        src = u""
        expectedResult = u""

        result = self.improver.run(src)
        self.assertEqual(expectedResult, result)

    def test_text_single_line(self):
        src = u"Абырвалг"
        expectedResult = u"<p>Абырвалг</p>"

        result = self.improver.run(src)
        self.assertEqual(expectedResult, result)

    def test_text_br(self):
        src = u"""Абырвалг
Foo
Bar"""
        expectedResult = u"""<p>Абырвалг<br/>
Foo<br/>
Bar</p>"""

        result = self.improver.run(src)

        self.assertEqual(expectedResult, result)

    def test_text_p_01(self):
        src = u"""Абырвалг

Второй параграф"""

        expectedResult = u"""<p>Абырвалг</p>
<p>Второй параграф</p>"""

        result = self.improver.run(src)

        self.assertEqual(expectedResult, result)

    def test_text_p_02(self):
        src = u"""Абырвалг

Второй параграф




"""

        expectedResult = u"""<p>Абырвалг</p>
<p>Второй параграф</p>"""

        result = self.improver.run(src)

        self.assertEqual(expectedResult, result)

    def test_improve_01(self):
        src = ur"""<h2>Attach links</h2>Attach:file.odt<br/><a href="__attach/file.odt">file.odt</a><br/><a href="__attach/file.odt">alternative text</a><br/><a href="__attach/file with spaces.pdf">file with spaces.pdf</a><h2>Images</h2>"""

        expectedResult = ur"""<h2>Attach links</h2>
<p>Attach:file.odt<br/>
<a href="__attach/file.odt">file.odt</a><br/>
<a href="__attach/file.odt">alternative text</a><br/>
<a href="__attach/file with spaces.pdf">file with spaces.pdf</a></p>
<h2>Images</h2>"""

        result = self.improver.run(src)

        self.assertEqual(expectedResult, result)

    def test_pre_01(self):
        src = ur"""qweqweqw qweqwe
qwewqeqwe wqe

qweqweqw qwe qweqwe<pre>
аап ываыв ываываыываы ыва ыва
ываыва выа выа

ываыв фывфв фывфывыф ыфв
вапвапввап вапвапвап

вапвапвап вапваапва</pre>

sdfsdf sdfsdf
sdfsdf
sdf sdfsdf sdf"""

        expectedResult = ur"""<p>qweqweqw qweqwe<br/>
qwewqeqwe wqe</p>
<p>qweqweqw qwe qweqwe</p>

<pre>
аап ываыв ываываыываы ыва ыва
ываыва выа выа

ываыв фывфв фывфывыф ыфв
вапвапввап вапвапвап

вапвапвап вапваапва</pre>

<p>sdfsdf sdfsdf<br/>
sdfsdf<br/>
sdf sdfsdf sdf</p>"""

        result = self.improver.run(src)
        self.assertEqual(expectedResult, result, result)

    def test_pre_02(self):
        src = ur"""Абырвалг<pre><br/><h1>111</h1></pre>Абырвалг<pre><br/><h1>111</h1></pre>"""

        expectedResult = ur"""<p>Абырвалг</p>

<pre><br/><h1>111</h1></pre>

<p>Абырвалг</p>

<pre><br/><h1>111</h1></pre>"""

        result = self.improver.run(src)
        self.assertEqual(expectedResult, result, result)

    def test_pre_03(self):
        src = ur"""Абырвалг
<pre>111</pre>
Абырвалг
<pre>222</pre>"""

        expectedResult = ur"""<p>Абырвалг</p>

<pre>111</pre>

<p>Абырвалг</p>

<pre>222</pre>"""

        result = self.improver.run(src)
        self.assertEqual(expectedResult, result, result)

    def test_pre_04(self):
        src = ur"""Абырвалг
<   pre   >111
Абырвалг
йцукен</   pre   >
<pre>222</pre>"""

        expectedResult = ur"""<p>Абырвалг</p>

<   pre   >111
Абырвалг
йцукен</   pre   >

<pre>222</pre>"""

        result = self.improver.run(src)
        self.assertEqual(expectedResult, result, result)

    def test_script_01(self):
        src = ur"""Абырвалг

<script>Абырвалг
йцукен
qwerty
фыва
</script>"""

        expectedResult = ur"""<p>Абырвалг</p>

<script>Абырвалг
йцукен
qwerty
фыва
</script>"""

        result = self.improver.run(src)
        self.assertEqual(expectedResult, result, result)

    def test_script_02(self):
        src = ur"""Абырвалг
<script>Абырвалг
йцукен
qwerty
фыва
</script>"""

        expectedResult = ur"""<p>Абырвалг</p>

<script>Абырвалг
йцукен
qwerty
фыва
</script>"""

        result = self.improver.run(src)
        self.assertEqual(expectedResult, result, result)

    def test_script_03(self):
        src = ur"""Абырвалг
<   script   >111
Абырвалг
йцукен</   script   >
<script>222</script>"""

        expectedResult = ur"""<p>Абырвалг</p>

<   script   >111
Абырвалг
йцукен</   script   >

<script>222</script>"""

        result = self.improver.run(src)

        self.assertEqual(expectedResult, result, result)

    def test_script_pre_01(self):
        src = ur"""Абырвалг
<script>Абырвалг
<pre>
йцукен
qwerty
</pre>
фыва
</script>"""

        expectedResult = ur"""<p>Абырвалг</p>

<script>Абырвалг
<pre>
йцукен
qwerty
</pre>
фыва
</script>"""

        result = self.improver.run(src)
        self.assertEqual(expectedResult, result, result)

    def test_script_pre_02(self):
        src = ur"""Абырвалг
<script>Абырвалг
<pre>
йцукен
qwerty
</pre>
фыва
</script>Абырвалг"""

        expectedResult = ur"""<p>Абырвалг</p>

<script>Абырвалг
<pre>
йцукен
qwerty
</pre>
фыва
</script>

<p>Абырвалг</p>"""

        result = self.improver.run(src)
        self.assertEqual(expectedResult, result, result)

    def test_blockquote_01(self):
        src = ur"""<blockquote>Абырвалг</blockquote>"""

        expectedResult = ur"""<blockquote>
<p>Абырвалг</p>
</blockquote>"""

        result = self.improver.run(src)
        self.assertEqual(expectedResult, result, result)

    def test_blockquote_02(self):
        src = ur"""Абзац 1<blockquote>Абырвалг</blockquote>Абзац 2"""

        expectedResult = ur"""<p>Абзац 1</p>
<blockquote>
<p>Абырвалг</p>
</blockquote>
<p>Абзац 2</p>"""

        result = self.improver.run(src)
        self.assertEqual(expectedResult, result, result)

    def test_blockquote_03(self):
        src = ur"""Абзац 1

<blockquote>Абырвалг</blockquote>

Абзац 2"""

        expectedResult = ur"""<p>Абзац 1</p>
<blockquote>
<p>Абырвалг</p>
</blockquote>
<p>Абзац 2</p>"""

        result = self.improver.run(src)
        self.assertEqual(expectedResult, result, result)

    def test_blockquote_04(self):
        src = ur"""Абзац 1

<blockquote>
Абырвалг
</blockquote>

Абзац 2"""

        expectedResult = ur"""<p>Абзац 1</p>
<blockquote>
<p>Абырвалг</p>
</blockquote>
<p>Абзац 2</p>"""

        result = self.improver.run(src)
        self.assertEqual(expectedResult, result, result)

    def test_table_01(self):
        src = ur"""Абзац 1<table><tr><td>Ячейка таблицы</td></tr></table>Абзац 2"""

        expectedResult = ur"""<p>Абзац 1
<table>
<tr>
<td>Ячейка таблицы</td>
</tr>
</table>
Абзац 2</p>"""

        result = self.improver.run(src)
        self.assertEqual(expectedResult, result, result)

    def test_table_02(self):
        src = ur"""Абзац 1
<table><tr><td>Ячейка таблицы</td></tr></table>
Абзац 2"""

        expectedResult = ur"""<p>Абзац 1
<table>
<tr>
<td>Ячейка таблицы</td>
</tr>
</table>
Абзац 2</p>"""

        result = self.improver.run(src)
        self.assertEqual(expectedResult, result, result)

    def test_table_03(self):
        src = ur"""Абзац 1

<table><tr><td>Ячейка таблицы</td></tr></table>
Абзац 2"""

        expectedResult = ur"""<p>Абзац 1</p>
<p>
<table>
<tr>
<td>Ячейка таблицы</td>
</tr>
</table>
Абзац 2</p>"""

        result = self.improver.run(src)
        self.assertEqual(expectedResult, result, result)
Пример #55
0
class SourceGuiPluginTest (unittest.TestCase):
    """
    Тесты интерфейса для плагина Source
    """
    def setUp(self):
        self.__pluginname = u"Source"

        self.__createWiki()

        dirlist = [u"../plugins/source"]
        self._stylesCount = 19

        self.loader = PluginsLoader(Application)
        self.loader.load (dirlist)

        self.config = self.loader[self.__pluginname].config
        self._clearConfig (self.config)

        self.dialog = FakeInsertDialog ()
        self.controller = self.loader[self.__pluginname].insertDialogControllerClass(self.testPage, self.dialog, self.config)
        

    def __readFile (self, path):
        with open (path) as fp:
            result = unicode (fp.read(), "utf8")

        return result
    

    def __createWiki (self):
        # Здесь будет создаваться вики
        self.path = u"../test/testwiki"
        removeWiki (self.path)

        self.rootwiki = WikiDocument.create (self.path)

        WikiPageFactory.create (self.rootwiki, u"Страница 1", [])
        self.testPage = self.rootwiki[u"Страница 1"]
        

    def tearDown(self):
        self._clearConfig (self.config)
        removeWiki (self.path)
        self.loader.clear()


    def _clearConfig (self, config):
        Application.config.remove_section (self.config.section)


    def testDialogController1 (self):
        """
        Тест контроллера диалога для вставки команды (:source:)
        """
        self.dialog.SetReturnCode (wx.ID_CANCEL)
        result = self.controller.showDialog()

        self.assertEqual (result, wx.ID_CANCEL)


    def testDialogController2 (self):
        """
        Тест контроллера диалога для вставки команды (:source:)
        """
        self.dialog.SetReturnCode (wx.ID_OK)
        result = self.controller.showDialog()

        self.assertEqual (result, wx.ID_OK)


    def testDialogControllerResult1 (self):
        """
        Тест контроллера диалога для вставки команды (:source:)
        """
        self.config.languageList.value = [u"python", u"cpp", u"haskell", u"text"]
        self.config.defaultLanguage.value = "text"

        self.dialog.SetReturnCode (wx.ID_OK)
        self.controller.showDialog()

        self.dialog.tabWidthSpin.SetValue (4)
        result = self.controller.getCommandStrings()

        self.assertEqual (result, (u'(:source lang="text" tabwidth="4":)\n', u'\n(:sourceend:)'))


    def testDialogControllerResult2 (self):
        """
        Тест контроллера диалога для вставки команды (:source:)
        """
        self.config.defaultLanguage.value = "python"

        self.dialog.SetReturnCode (wx.ID_OK)
        self.controller.showDialog()

        self.dialog.tabWidthSpin.SetValue (8)
        result = self.controller.getCommandStrings()

        self.assertEqual (result, (u'(:source lang="python" tabwidth="8":)\n', u'\n(:sourceend:)'))


    def testDialogControllerResult3 (self):
        """
        Тест контроллера диалога для вставки команды (:source:)
        """
        self.config.languageList.value = [u"python", u"cpp", u"haskell", u"text"]
        self.config.defaultLanguage.value = "text"

        self.dialog.SetReturnCode (wx.ID_OK)
        self.controller.showDialog()

        self.dialog.tabWidthSpin.SetValue (4)
        result = self.controller.getCommandStrings()

        self.assertEqual (result, (u'(:source lang="text" tabwidth="4":)\n', u'\n(:sourceend:)'))


    def testDialogControllerResult4 (self):
        """
        Тест контроллера диалога для вставки команды (:source:)
        """
        self.config.languageList.value = [u"python", u"cpp", u"haskell", u"text"]
        self.config.defaultLanguage.value = "text"

        self.dialog.SetReturnCode (wx.ID_OK)
        self.controller.showDialog()

        self.dialog.tabWidthSpin.SetValue (0)
        result = self.controller.getCommandStrings()

        self.assertEqual (result, (u'(:source lang="text":)\n', u'\n(:sourceend:)'))


    def testDialogControllerResult5 (self):
        """
        Тест контроллера диалога для вставки команды (:source:)
        """
        self.config.languageList.value = [u"python", u"cpp", u"haskell", u"text"]
        self.config.defaultLanguage.value = "text"

        self.dialog.SetReturnCode (wx.ID_OK)
        self.controller.showDialog()

        self.dialog.languageComboBox.SetSelection (0)
        self.dialog.tabWidthSpin.SetValue (0)
        result = self.controller.getCommandStrings()

        self.assertEqual (result, (u'(:source lang="cpp":)\n', u'\n(:sourceend:)'))


    def testDialogControllerResult6 (self):
        """
        Тест контроллера диалога для вставки команды (:source:)
        """
        self.config.languageList.value = [u"python", u"cpp", u"haskell", u"text"]
        self.config.defaultLanguage.value = "text"

        self.dialog.SetReturnCode (wx.ID_OK)
        self.controller.showDialog()

        self.dialog.languageComboBox.SetSelection (1)
        self.dialog.tabWidthSpin.SetValue (0)
        result = self.controller.getCommandStrings()

        self.assertEqual (result, (u'(:source lang="haskell":)\n', u'\n(:sourceend:)'))


    def testSourceConfig1 (self):
        self.config.defaultLanguage.value = u"python"
        self.config.tabWidth.value = 8
        self.config.dialogWidth.value = 100
        self.config.dialogHeight.value = 200
        self.config.languageList.value = [u"python", u"cpp", u"haskell"]

        self.assertEqual (self.config.defaultLanguage.value, u"python")
        self.assertEqual (self.config.tabWidth.value, 8)
        self.assertEqual (self.config.dialogWidth.value, 100)
        self.assertEqual (self.config.dialogHeight.value, 200)
        self.assertEqual (self.config.languageList.value, 
                [u"python", u"cpp", u"haskell"])


    def testDialogLanguageValues1 (self):
        self.config.languageList.value = [u"python", u"cpp", u"haskell"]
        self.config.defaultLanguage.value = u"haskell"

        self.controller.showDialog()

        self.assertEqual (self.dialog.languageComboBox.GetItems(), 
                [u"cpp", u"haskell", u"python"])

        self.assertEqual (self.dialog.languageComboBox.GetSelection(), 1)
        self.assertEqual (self.dialog.languageComboBox.GetValue(), u"haskell")

        self.assertEqual (self.dialog.tabWidthSpin.GetValue(), 0)


    def testDialogLanguageValues2 (self):
        self.config.languageList.value = []
        self.config.defaultLanguage.value = u"haskell"

        self.controller.showDialog()

        self.assertEqual (self.dialog.languageComboBox.GetItems(), [u"text"])

        self.assertEqual (self.dialog.languageComboBox.GetSelection(), 0)
        self.assertEqual (self.dialog.languageComboBox.GetValue(), u"text")


    def testDialogLanguageValues3 (self):
        self.config.languageList.value = [u"python", u"cpp", u"haskell"]
        self.config.defaultLanguage.value = u"c"

        self.controller.showDialog()

        self.assertEqual (self.dialog.languageComboBox.GetItems(), [u"cpp", u"haskell", u"python"])

        self.assertEqual (self.dialog.languageComboBox.GetSelection(), 0)
        self.assertEqual (self.dialog.languageComboBox.GetValue(), u"cpp")


    def testDialogLanguageValues4 (self):
        self.config.languageList.value = [u"python", u"cpp", u"haskell"]
        self.config.defaultLanguage.value = u"   haskell   "

        self.controller.showDialog()

        self.assertEqual (self.dialog.languageComboBox.GetItems(), 
                [u"cpp", u"haskell", u"python"])

        self.assertEqual (self.dialog.languageComboBox.GetSelection(), 1)
        self.assertEqual (self.dialog.languageComboBox.GetValue(), u"haskell")

        self.assertEqual (self.dialog.tabWidthSpin.GetValue(), 0)


    def testDialogStyleValues1 (self):
        self.config.languageList.value = [u"python", u"cpp", u"haskell"]
        self.config.defaultLanguage.value = u"python"

        self.controller.showDialog()

        self.assertEqual (self.dialog.styleComboBox.GetCount(), self._stylesCount)
        self.assertEqual (self.dialog.styleComboBox.GetValue(), "default")

        result = self.controller.getCommandStrings()

        self.assertEqual (result, (u'(:source lang="python":)\n', u'\n(:sourceend:)'))


    def testDialogStyleValues2 (self):
        self.config.defaultStyle.value = "blablabla"
        self.controller.showDialog()

        self.assertEqual (self.dialog.styleComboBox.GetCount(), self._stylesCount)
        self.assertEqual (self.dialog.styleComboBox.GetValue(), "default")


    def testDialogStyleValues3 (self):
        self.config.defaultStyle.value = ""
        self.controller.showDialog()

        self.assertEqual (self.dialog.styleComboBox.GetCount(), self._stylesCount)
        self.assertEqual (self.dialog.styleComboBox.GetValue(), "default")


    def testDialogStyleValues4 (self):
        self.config.defaultStyle.value = "vim"
        self.controller.showDialog()

        self.assertEqual (self.dialog.styleComboBox.GetCount(), self._stylesCount)
        self.assertEqual (self.dialog.styleComboBox.GetValue(), "vim")


    def testDialogStyleValues5 (self):
        self.config.defaultStyle.value = "emacs"
        self.controller.showDialog()

        self.assertEqual (self.dialog.styleComboBox.GetCount(), self._stylesCount)
        self.assertEqual (self.dialog.styleComboBox.GetValue(), "emacs")


    def testDialogStyle1 (self):
        self.config.languageList.value = [u"python", u"cpp", u"haskell"]
        self.config.defaultLanguage.value = u"python"
        self.config.defaultStyle.value = u"vim"
        self.config.style.value = u"vim"

        self.controller.showDialog()

        self.assertEqual (self.dialog.styleComboBox.GetCount(), self._stylesCount)
        self.assertEqual (self.dialog.styleComboBox.GetValue(), "vim")

        result = self.controller.getCommandStrings()

        self.assertEqual (result, (u'(:source lang="python":)\n', u'\n(:sourceend:)'))


    def testDialogStyle2 (self):
        self.config.languageList.value = [u"python", u"cpp", u"haskell"]
        self.config.defaultLanguage.value = u"python"
        self.config.defaultStyle.value = u"vim"
        self.config.style.value = u"default"

        self.controller.showDialog()

        self.assertEqual (self.dialog.styleComboBox.GetCount(), self._stylesCount)
        self.assertEqual (self.dialog.styleComboBox.GetValue(), "default")

        result = self.controller.getCommandStrings()

        self.assertEqual (result, (u'(:source lang="python" style="default":)\n', u'\n(:sourceend:)'))


    def testDialogStyleText (self):
        self.config.languageList.value = [u"python", u"cpp", u"haskell"]
        self.config.defaultLanguage.value = u"python"

        self.controller.showDialog()
        self.dialog.styleComboBox.SetSelection (0)

        self.assertEqual (self.dialog.styleComboBox.GetValue(), "autumn")
        self.assertEqual (self.dialog.style, "autumn")

        result = self.controller.getCommandStrings()

        self.assertEqual (result, (u'(:source lang="python" style="autumn":)\n', u'\n(:sourceend:)'))


    def testDialogStyleFile (self):
        self.samplefilesPath = u"../test/samplefiles/sources"
        Attachment(self.testPage).attach ([os.path.join (self.samplefilesPath, u"source_utf8.py")])
        Attachment(self.testPage).attach ([os.path.join (self.samplefilesPath, u"source_cp1251.cs")])

        self.config.languageList.value = [u"python", u"cpp", u"haskell"]
        self.config.defaultLanguage.value = u"python"

        self.controller.showDialog()

        self.dialog.fileCheckBox.SetValue(True)
        self.dialog.styleComboBox.SetSelection (0)
        self.dialog.attachmentComboBox.SetSelection (0)

        self.assertEqual (self.dialog.styleComboBox.GetValue(), "autumn")
        self.assertEqual (self.dialog.style, "autumn")

        result = self.controller.getCommandStrings()

        self.assertEqual (result, (u'(:source file="Attach:source_cp1251.cs" lang="python" style="autumn":)', u'(:sourceend:)'))


    def testDialogStyleFile2 (self):
        self.samplefilesPath = u"../test/samplefiles/sources"
        Attachment(self.testPage).attach ([os.path.join (self.samplefilesPath, u"source_utf8.py")])
        Attachment(self.testPage).attach ([os.path.join (self.samplefilesPath, u"source_cp1251.cs")])

        self.config.languageList.value = [u"python", u"cpp", u"haskell"]
        self.config.defaultLanguage.value = u"python"

        self.controller.showDialog()

        self.dialog.fileCheckBox.SetValue(True)
        self.dialog.styleComboBox.SetSelection (0)
        self.dialog.attachmentComboBox.SetSelection (0)
        self.dialog.languageComboBox.SetSelection (0)

        self.assertEqual (self.dialog.styleComboBox.GetValue(), "autumn")
        self.assertEqual (self.dialog.style, "autumn")

        result = self.controller.getCommandStrings()

        self.assertEqual (result, (u'(:source file="Attach:source_cp1251.cs" style="autumn":)', u'(:sourceend:)'))


    def testDialogStyleText2 (self):
        self.config.languageList.value = [u"python", u"cpp", u"haskell"]
        self.config.defaultLanguage.value = u"python"

        self.controller.showDialog()
        self.dialog.styleComboBox.SetSelection (0)
        self.dialog.tabWidthSpin.SetValue (5)

        self.assertEqual (self.dialog.styleComboBox.GetValue(), "autumn")
        self.assertEqual (self.dialog.style, "autumn")

        result = self.controller.getCommandStrings()

        self.assertEqual (result, (u'(:source lang="python" tabwidth="5" style="autumn":)\n', u'\n(:sourceend:)'))


    def testStyleConfig1 (self):
        self.config.style.value = "default"

        self.controller.showDialog ()
        self.assertEqual (self.dialog.style, "default")


    def testStyleConfig2 (self):
        self.config.style.value = "vim"

        self.controller.showDialog ()
        self.assertEqual (self.dialog.style, "vim")


    def testStyleConfig3 (self):
        self.config.style.value = "  vim   "

        self.controller.showDialog ()
        self.assertEqual (self.dialog.style, "vim")


    def testStyleConfig4 (self):
        self.config.style.value = "invalid_style"

        self.controller.showDialog ()
        self.assertEqual (self.dialog.style, "default")


    def testStyleConfig5 (self):
        self.controller.showDialog ()
        self.assertEqual (self.dialog.style, "default")


    def testParentBgConfig1 (self):
        self.config.parentbg.value = u"  False  "
        self.controller.showDialog ()

        self.assertEqual (self.dialog.parentbg, False)


    def testParentBgConfig2 (self):
        self.config.parentbg.value = u"  True  "
        self.controller.showDialog ()

        self.assertEqual (self.dialog.parentbg, True)


    def testParentBgConfig3 (self):
        self.config.parentbg.value = u"  блаблабла  "
        self.controller.showDialog ()

        self.assertEqual (self.dialog.parentbg, False)


    def testParentBgConfig4 (self):
        # Если нет вообще записей в файле настроек
        self.controller.showDialog ()

        self.assertEqual (self.dialog.parentbg, False)


    def testLineNumConfig1 (self):
        # Если нет вообще записей в файле настроек
        self.controller.showDialog ()

        self.assertEqual (self.dialog.lineNum, False)


    def testLineNumConfig2 (self):
        self.config.lineNum.value = u"  False  "
        self.controller.showDialog ()

        self.assertEqual (self.dialog.lineNum, False)


    def testLineNumConfig3 (self):
        self.config.lineNum.value = u"  блаблабла  "
        self.controller.showDialog ()

        self.assertEqual (self.dialog.lineNum, False)


    def testLineNumConfig4 (self):
        self.config.lineNum.value = u"True"
        self.controller.showDialog ()

        self.assertEqual (self.dialog.lineNum, True)


    def testDialogParengBg (self):
        self.config.languageList.value = [u"python", u"cpp", u"haskell"]
        self.config.defaultLanguage.value = u"python"

        self.controller.showDialog()
        self.dialog.parentBgCheckBox.SetValue (True)

        result = self.controller.getCommandStrings()

        self.assertEqual (result, (u'(:source lang="python" parentbg:)\n', u'\n(:sourceend:)'))


    def testDialogLineNum (self):
        self.config.languageList.value = [u"python", u"cpp", u"haskell"]
        self.config.defaultLanguage.value = u"python"

        self.controller.showDialog()
        self.dialog.lineNumCheckBox.SetValue (True)

        result = self.controller.getCommandStrings()

        self.assertEqual (result, (u'(:source lang="python" linenum:)\n', u'\n(:sourceend:)'))


    def testDialogParentBgLineNum (self):
        self.config.languageList.value = [u"python", u"cpp", u"haskell"]
        self.config.defaultLanguage.value = u"python"

        self.controller.showDialog()
        self.dialog.parentBgCheckBox.SetValue (True)
        self.dialog.lineNumCheckBox.SetValue (True)

        result = self.controller.getCommandStrings()

        self.assertEqual (result, (u'(:source lang="python" parentbg linenum:)\n', u'\n(:sourceend:)'))


    def testDialogTabWidth (self):
        self.config.languageList.value = [u"python", u"cpp", u"haskell"]
        self.config.defaultLanguage.value = u"python"

        self.controller.showDialog()
        self.dialog.tabWidthSpin.SetValue (10)

        result = self.controller.getCommandStrings()

        self.assertEqual (result, (u'(:source lang="python" tabwidth="10":)\n', u'\n(:sourceend:)'))
Пример #56
0
class ThumbListPluginTest(unittest.TestCase, BaseOutWikerGUIMixin):
    def setUp(self):
        self.initApplication()
        self.wikiroot = self.createWiki()
        self.testPage = WikiPageFactory().create(self.wikiroot, "Страница 1",
                                                 [])

        self.maxDiff = None
        self.filesPath = "../test/samplefiles/"

        dirlist = ["../plugins/thumbgallery"]

        self.loader = PluginsLoader(self.application)
        self.loader.load(dirlist)

        self.factory = ParserFactory()
        self.parser = self.factory.make(self.testPage, self.application.config)

    def tearDown(self):
        self.loader.clear()
        self.destroyApplication()
        self.destroyWiki(self.wikiroot)

    def testPluginLoad(self):
        self.assertEqual(len(self.loader), 1)

    def testContentParseEmpty(self):
        text = """Бла-бла-бла (:thumblist:) бла-бла-бла"""

        validResult = """Бла-бла-бла <div class="thumblist"></div> бла-бла-бла"""

        result = self.parser.toHtml(text)
        self.assertEqual(validResult, result)
        self.assertTrue("<table" not in result)

    def testAttachFull1(self):
        text = """Бла-бла-бла
        (:thumblist:)
        бла-бла-бла"""

        files = ["first.jpg"]
        fullpath = [os.path.join(self.filesPath, fname) for fname in files]
        Attachment(self.testPage).attach(fullpath)

        result = self.parser.toHtml(text)

        self.assertTrue('<A HREF="__attach/first.jpg">' in result)
        self.assertTrue("__thumb" in result)
        self.assertTrue("_first.jpg" in result)

        self.assertTrue(
            os.path.exists(
                os.path.join(self.testPage.path, "__attach", "__thumb")))
        self.assertTrue("<table" not in result)

    def testAttachThumbListFull2(self):
        text = """Бла-бла-бла
        (:thumblist:)
        бла-бла-бла"""

        files = ["first.jpg", "image_01.JPG", "html.txt"]
        fullpath = [os.path.join(self.filesPath, fname) for fname in files]
        Attachment(self.testPage).attach(fullpath)

        result = self.parser.toHtml(text)

        self.assertTrue('<A HREF="__attach/first.jpg">' in result)
        self.assertTrue("__thumb" in result)
        self.assertTrue("_first.jpg" in result)

        self.assertTrue('<A HREF="__attach/image_01.JPG">' in result)
        self.assertTrue("_image_01.JPG" in result)

        self.assertFalse("html.txt" in result)
        self.assertTrue("<table" not in result)

    def testAttachGalleryFull2(self):
        text = """Бла-бла-бла
        (:thumbgallery:)
        бла-бла-бла"""

        files = ["first.jpg", "image_01.JPG", "html.txt"]
        fullpath = [os.path.join(self.filesPath, fname) for fname in files]
        Attachment(self.testPage).attach(fullpath)

        result = self.parser.toHtml(text)

        self.assertTrue('<A HREF="__attach/first.jpg">' in result)
        self.assertTrue("__thumb" in result)
        self.assertTrue("_first.jpg" in result)

        self.assertTrue('<A HREF="__attach/image_01.JPG">' in result)
        self.assertTrue("_image_01.JPG" in result)

        self.assertFalse("html.txt" in result)
        self.assertTrue("<table" not in result)

    def testAttachEmpty1(self):
        text = """Бла-бла-бла
        (:thumblist:)
        (:thumblistend:)
        бла-бла-бла"""

        files = ["first.jpg", "image_01.JPG", "html.txt"]
        fullpath = [os.path.join(self.filesPath, fname) for fname in files]
        Attachment(self.testPage).attach(fullpath)

        result = self.parser.toHtml(text)

        self.assertFalse('<A HREF="__attach/first.jpg">' in result)
        self.assertFalse("__thumb" in result)
        self.assertFalse("_first.jpg" in result)

        self.assertFalse('<A HREF="__attach/image_01.JPG">' in result)
        self.assertFalse("_image_01.JPG" in result)

        self.assertFalse("html.txt" in result)
        self.assertTrue("<table" not in result)

    def testAttachGalleryEmpty1(self):
        text = """Бла-бла-бла
        (:thumbgallery:)
        (:thumbgalleryend:)
        бла-бла-бла"""

        files = ["first.jpg", "image_01.JPG", "html.txt"]
        fullpath = [os.path.join(self.filesPath, fname) for fname in files]
        Attachment(self.testPage).attach(fullpath)

        result = self.parser.toHtml(text)

        self.assertFalse('<A HREF="__attach/first.jpg">' in result)
        self.assertFalse("__thumb" in result)
        self.assertFalse("_first.jpg" in result)

        self.assertFalse('<A HREF="__attach/image_01.JPG">' in result)
        self.assertFalse("_image_01.JPG" in result)

        self.assertFalse("html.txt" in result)
        self.assertTrue("<table" not in result)

    def testAttachList1(self):
        text = """Бла-бла-бла
        (:thumblist:)
            first.jpg
            particle_01.PNG
        (:thumblistend:)
        бла-бла-бла"""

        files = [
            "first.jpg", "image_01.JPG", "particle_01.PNG", "image.png",
            "html.txt"
        ]
        fullpath = [os.path.join(self.filesPath, fname) for fname in files]
        Attachment(self.testPage).attach(fullpath)

        result = self.parser.toHtml(text)

        self.assertTrue('<A HREF="__attach/first.jpg">' in result)
        self.assertTrue("_first.jpg" in result)
        self.assertTrue("__thumb" in result)

        self.assertTrue('<A HREF="__attach/particle_01.PNG">' in result)
        self.assertTrue("_particle_01.PNG" in result)

        self.assertFalse('<A HREF="__attach/image_01.JPG">' in result)
        self.assertFalse("_image_01.JPG" in result)

        self.assertFalse("html.txt" in result)
        self.assertTrue("<table" not in result)

    def testAttachList2(self):
        text = """Бла-бла-бла
        (:thumblist:)
            Attach:first.jpg
            Attach:particle_01.PNG
        (:thumblistend:)
        бла-бла-бла"""

        files = [
            "first.jpg", "image_01.JPG", "particle_01.PNG", "image.png",
            "html.txt"
        ]
        fullpath = [os.path.join(self.filesPath, fname) for fname in files]
        Attachment(self.testPage).attach(fullpath)

        result = self.parser.toHtml(text)

        self.assertTrue('<A HREF="__attach/first.jpg">' in result)
        self.assertTrue("_first.jpg" in result)
        self.assertTrue("__thumb" in result)

        self.assertTrue('<A HREF="__attach/particle_01.PNG">' in result)
        self.assertTrue("_particle_01.PNG" in result)

        self.assertFalse('<A HREF="__attach/image_01.JPG">' in result)
        self.assertFalse("_image_01.JPG" in result)

        self.assertFalse("html.txt" in result)
        self.assertTrue("<table" not in result)

    def testAttachGalleryList2(self):
        text = """Бла-бла-бла
        (:thumbgallery:)
            Attach:first.jpg
            Attach:particle_01.PNG
        (:thumbgalleryend:)
        бла-бла-бла"""

        files = [
            "first.jpg", "image_01.JPG", "particle_01.PNG", "image.png",
            "html.txt"
        ]
        fullpath = [os.path.join(self.filesPath, fname) for fname in files]
        Attachment(self.testPage).attach(fullpath)

        result = self.parser.toHtml(text)

        self.assertTrue('<A HREF="__attach/first.jpg">' in result)
        self.assertTrue("_first.jpg" in result)
        self.assertTrue("__thumb" in result)

        self.assertTrue('<A HREF="__attach/particle_01.PNG">' in result)
        self.assertTrue("_particle_01.PNG" in result)

        self.assertFalse('<A HREF="__attach/image_01.JPG">' in result)
        self.assertFalse("_image_01.JPG" in result)

        self.assertFalse("html.txt" in result)
        self.assertTrue("<table" not in result)

    def testAttachList3(self):
        text = """Бла-бла-бла
        (:thumblist:)

            Attach:first.jpg


            Attach:particle_01.PNG


        (:thumblistend:)
        бла-бла-бла"""

        files = [
            "first.jpg", "image_01.JPG", "particle_01.PNG", "image.png",
            "html.txt"
        ]
        fullpath = [os.path.join(self.filesPath, fname) for fname in files]
        Attachment(self.testPage).attach(fullpath)

        result = self.parser.toHtml(text)

        self.assertTrue('<A HREF="__attach/first.jpg">' in result)
        self.assertTrue("_first.jpg" in result)
        self.assertTrue("__thumb" in result)

        self.assertTrue('<A HREF="__attach/particle_01.PNG">' in result)
        self.assertTrue("_particle_01.PNG" in result)

        self.assertFalse('<A HREF="__attach/image_01.JPG">' in result)
        self.assertFalse("_image_01.JPG" in result)

        self.assertFalse("html.txt" in result)
        self.assertTrue("<table" not in result)

    def testAttachGallery3(self):
        text = """Бла-бла-бла
        (:thumbgallery:)

            Attach:first.jpg


            Attach:particle_01.PNG


        (:thumbgalleryend:)
        бла-бла-бла"""

        files = [
            "first.jpg", "image_01.JPG", "particle_01.PNG", "image.png",
            "html.txt"
        ]
        fullpath = [os.path.join(self.filesPath, fname) for fname in files]
        Attachment(self.testPage).attach(fullpath)

        result = self.parser.toHtml(text)

        self.assertTrue('<A HREF="__attach/first.jpg">' in result)
        self.assertTrue("_first.jpg" in result)
        self.assertTrue("__thumb" in result)

        self.assertTrue('<A HREF="__attach/particle_01.PNG">' in result)
        self.assertTrue("_particle_01.PNG" in result)

        self.assertFalse('<A HREF="__attach/image_01.JPG">' in result)
        self.assertFalse("_image_01.JPG" in result)

        self.assertFalse("html.txt" in result)
        self.assertTrue("<table" not in result)

    def testAttachGallerySpaces1(self):
        text = """Бла-бла-бла
        (:thumbgallery:)

            Attach:first.jpg


            Attach:картинка с пробелами.png


        (:thumbgalleryend:)
        бла-бла-бла"""

        files = [
            "first.jpg", "image_01.JPG", "particle_01.PNG", "image.png",
            "html.txt", "картинка с пробелами.png"
        ]
        fullpath = [os.path.join(self.filesPath, fname) for fname in files]
        Attachment(self.testPage).attach(fullpath)

        result = self.parser.toHtml(text)

        self.assertTrue('<A HREF="__attach/first.jpg">' in result)
        self.assertTrue("_first.jpg" in result)
        self.assertTrue("__thumb" in result)

        self.assertTrue("картинка с пробелами.png" in result)
        self.assertTrue("_картинка с пробелами.png" in result)

        self.assertFalse('<A HREF="__attach/image_01.JPG">' in result)
        self.assertFalse("_image_01.JPG" in result)

        self.assertFalse("html.txt" in result)
        self.assertTrue("<table" not in result)

    def testAttachGallerySpaces2(self):
        text = """Бла-бла-бла
        (:thumbgallery:)

            Attach:first.jpg


            картинка с пробелами.png


        (:thumbgalleryend:)
        бла-бла-бла"""

        files = [
            "first.jpg", "image_01.JPG", "particle_01.PNG", "image.png",
            "html.txt", "картинка с пробелами.png"
        ]
        fullpath = [os.path.join(self.filesPath, fname) for fname in files]
        Attachment(self.testPage).attach(fullpath)

        result = self.parser.toHtml(text)

        self.assertTrue('<A HREF="__attach/first.jpg">' in result)
        self.assertTrue("_first.jpg" in result)
        self.assertTrue("__thumb" in result)

        self.assertTrue("картинка с пробелами.png" in result)
        self.assertTrue("_картинка с пробелами.png" in result)

        self.assertFalse('<A HREF="__attach/image_01.JPG">' in result)
        self.assertFalse("_image_01.JPG" in result)

        self.assertFalse("html.txt" in result)
        self.assertTrue("<table" not in result)

    def testAttachGallerySize1(self):
        text = """Бла-бла-бла
        (:thumbgallery maxsize=100:)

            Attach:first.jpg


            Attach:particle_01.PNG
            Attach:картинка с пробелами.png

        (:thumbgalleryend:)
        бла-бла-бла"""

        files = [
            "first.jpg", "image_01.JPG", "particle_01.PNG", "image.png",
            "html.txt", "картинка с пробелами.png"
        ]
        fullpath = [os.path.join(self.filesPath, fname) for fname in files]
        Attachment(self.testPage).attach(fullpath)

        result = self.parser.toHtml(text)

        self.assertTrue('<A HREF="__attach/first.jpg">' in result)
        self.assertTrue("maxsize_100_first.jpg" in result)
        self.assertTrue("__thumb" in result)

        self.assertTrue('<A HREF="__attach/particle_01.PNG">' in result)
        self.assertTrue("maxsize_100_particle_01.PNG" in result)

        self.assertTrue("картинка с пробелами.png" in result)
        self.assertTrue("maxsize_100_картинка с пробелами.png" in result)

        self.assertFalse('<A HREF="__attach/image_01.JPG">' in result)
        self.assertFalse("maxsize_100_image_01.JPG" in result)

        self.assertFalse("html.txt" in result)
        self.assertTrue("<table" not in result)

    def testAttachGallerySize2(self):
        text = """Бла-бла-бла
        (:thumbgallery px=100:)

            Attach:first.jpg


            Attach:particle_01.PNG


        (:thumbgalleryend:)
        бла-бла-бла"""

        files = [
            "first.jpg", "image_01.JPG", "particle_01.PNG", "image.png",
            "html.txt"
        ]
        fullpath = [os.path.join(self.filesPath, fname) for fname in files]
        Attachment(self.testPage).attach(fullpath)

        result = self.parser.toHtml(text)

        self.assertTrue('<A HREF="__attach/first.jpg">' in result)
        self.assertTrue("maxsize_100_first.jpg" in result)
        self.assertTrue("__thumb" in result)

        self.assertTrue('<A HREF="__attach/particle_01.PNG">' in result)
        self.assertTrue("maxsize_100_particle_01.PNG" in result)

        self.assertFalse('<A HREF="__attach/image_01.JPG">' in result)
        self.assertFalse("maxsize_100_image_01.JPG" in result)

        self.assertFalse("html.txt" in result)
        self.assertTrue("<table" not in result)

    def testAttachListSize1(self):
        text = """Бла-бла-бла
        (:thumblist maxsize=100:)

            Attach:first.jpg


            Attach:particle_01.PNG


        (:thumblistend:)
        бла-бла-бла"""

        files = [
            "first.jpg", "image_01.JPG", "particle_01.PNG", "image.png",
            "html.txt"
        ]
        fullpath = [os.path.join(self.filesPath, fname) for fname in files]
        Attachment(self.testPage).attach(fullpath)

        result = self.parser.toHtml(text)

        self.assertTrue('<A HREF="__attach/first.jpg">' in result)
        self.assertTrue("maxsize_100_first.jpg" in result)
        self.assertTrue("__thumb" in result)

        self.assertTrue('<A HREF="__attach/particle_01.PNG">' in result)
        self.assertTrue("maxsize_100_particle_01.PNG" in result)

        self.assertFalse('<A HREF="__attach/image_01.JPG">' in result)
        self.assertFalse("maxsize_100_image_01.JPG" in result)

        self.assertFalse("html.txt" in result)
        self.assertTrue("<table" not in result)

    def testAttachListSize2(self):
        text = """Бла-бла-бла
        (:thumblist px=100:)

            Attach:first.jpg


            Attach:particle_01.PNG


        (:thumblistend:)
        бла-бла-бла"""

        files = [
            "first.jpg", "image_01.JPG", "particle_01.PNG", "image.png",
            "html.txt"
        ]
        fullpath = [os.path.join(self.filesPath, fname) for fname in files]
        Attachment(self.testPage).attach(fullpath)

        result = self.parser.toHtml(text)

        self.assertTrue('<A HREF="__attach/first.jpg">' in result)
        self.assertTrue("maxsize_100_first.jpg" in result)
        self.assertTrue("__thumb" in result)

        self.assertTrue('<A HREF="__attach/particle_01.PNG">' in result)
        self.assertTrue("maxsize_100_particle_01.PNG" in result)

        self.assertFalse('<A HREF="__attach/image_01.JPG">' in result)
        self.assertFalse("maxsize_100_image_01.JPG" in result)

        self.assertFalse("html.txt" in result)
        self.assertTrue("<table" not in result)

    def testAttachListComments1(self):
        text = """Бла-бла-бла
        (:thumblist px=100:)

            Attach:first.jpg    | Первый


            Attach:particle_01.PNG|Комментарий к картинке


        (:thumblistend:)
        бла-бла-бла"""

        files = [
            "first.jpg", "image_01.JPG", "particle_01.PNG", "image.png",
            "html.txt"
        ]
        fullpath = [os.path.join(self.filesPath, fname) for fname in files]
        Attachment(self.testPage).attach(fullpath)

        result = self.parser.toHtml(text)

        self.assertTrue('<A HREF="__attach/first.jpg">' in result)
        self.assertTrue("maxsize_100_first.jpg" in result)
        self.assertTrue("__thumb" in result)

        self.assertTrue('<A HREF="__attach/particle_01.PNG">' in result)
        self.assertTrue("maxsize_100_particle_01.PNG" in result)

        self.assertFalse('<A HREF="__attach/image_01.JPG">' in result)
        self.assertFalse("maxsize_100_image_01.JPG" in result)

        self.assertFalse("html.txt" in result)
        self.assertTrue("<table" not in result)

    def testAttachListComments2(self):
        text = """Бла-бла-бла
        (:thumblist:)
            Attach:first.jpg    | Первый
            Attach:particle_01.PNG|Комментарий к картинке
        (:thumblistend:)
        бла-бла-бла"""

        files = [
            "first.jpg", "image_01.JPG", "particle_01.PNG", "image.png",
            "html.txt"
        ]
        fullpath = [os.path.join(self.filesPath, fname) for fname in files]
        Attachment(self.testPage).attach(fullpath)

        result = self.parser.toHtml(text)

        self.assertTrue('<A HREF="__attach/first.jpg">' in result)
        self.assertTrue("__thumb" in result)

        self.assertTrue('<A HREF="__attach/particle_01.PNG">' in result)
        self.assertFalse('<A HREF="__attach/image_01.JPG">' in result)

        self.assertFalse("html.txt" in result)
        self.assertTrue("<table" not in result)

    def testTable1(self):
        text = """Бла-бла-бла
        (:thumblist cols=2:)
        бла-бла-бла"""

        files = [
            "first.jpg", "image_01.JPG", "particle_01.PNG", "image.png",
            "html.txt"
        ]
        fullpath = [os.path.join(self.filesPath, fname) for fname in files]
        Attachment(self.testPage).attach(fullpath)

        result = self.parser.toHtml(text)

        self.assertTrue('<A HREF="__attach/first.jpg">' in result)
        self.assertTrue("__thumb" in result)

        self.assertTrue('<A HREF="__attach/particle_01.PNG">' in result)
        self.assertTrue('<A HREF="__attach/image_01.JPG">' in result)

        self.assertFalse("html.txt" in result)

        self.assertTrue("<table" in result)

        # В таблице две строки
        self.assertEqual(len(result.split("<tr")), 2 + 1)

    def testTable2(self):
        text = """Бла-бла-бла
        (:thumblist cols=1:)
        бла-бла-бла"""

        files = [
            "first.jpg", "image_01.JPG", "particle_01.PNG", "image.png",
            "html.txt"
        ]
        fullpath = [os.path.join(self.filesPath, fname) for fname in files]
        Attachment(self.testPage).attach(fullpath)

        result = self.parser.toHtml(text)

        self.assertTrue('<A HREF="__attach/first.jpg">' in result)
        self.assertTrue("__thumb" in result)

        self.assertTrue('<A HREF="__attach/particle_01.PNG">' in result)
        self.assertTrue('<A HREF="__attach/image_01.JPG">' in result)

        self.assertFalse("html.txt" in result)

        self.assertTrue("<table" in result)

        # В таблице две строки
        self.assertEqual(len(result.split("<tr")), 4 + 1)

    def testInvalidCols1(self):
        text = """Бла-бла-бла
        (:thumblist cols:)
        бла-бла-бла"""

        files = ["first.jpg", "image_01.JPG", "html.txt"]
        fullpath = [os.path.join(self.filesPath, fname) for fname in files]
        Attachment(self.testPage).attach(fullpath)

        result = self.parser.toHtml(text)

        self.assertTrue('<A HREF="__attach/first.jpg">' in result)
        self.assertTrue("__thumb" in result)
        self.assertTrue("_first.jpg" in result)

        self.assertTrue('<A HREF="__attach/image_01.JPG">' in result)
        self.assertTrue("_image_01.JPG" in result)

        self.assertFalse("html.txt" in result)
        self.assertTrue("<table" not in result)

    def testInvalidCols2(self):
        text = """Бла-бла-бла
        (:thumblist cols=:)
        бла-бла-бла"""

        files = ["first.jpg", "image_01.JPG", "html.txt"]
        fullpath = [os.path.join(self.filesPath, fname) for fname in files]
        Attachment(self.testPage).attach(fullpath)

        result = self.parser.toHtml(text)

        self.assertTrue('<A HREF="__attach/first.jpg">' in result)
        self.assertTrue("__thumb" in result)
        self.assertTrue("_first.jpg" in result)

        self.assertTrue('<A HREF="__attach/image_01.JPG">' in result)
        self.assertTrue("_image_01.JPG" in result)

        self.assertFalse("html.txt" in result)
        self.assertTrue("<table" not in result)

    def testInvalidCols3(self):
        text = """Бла-бла-бла
        (:thumblist cols=abyrvalg:)
        бла-бла-бла"""

        files = ["first.jpg", "image_01.JPG", "html.txt"]
        fullpath = [os.path.join(self.filesPath, fname) for fname in files]
        Attachment(self.testPage).attach(fullpath)

        result = self.parser.toHtml(text)

        self.assertTrue('<A HREF="__attach/first.jpg">' in result)
        self.assertTrue("__thumb" in result)
        self.assertTrue("_first.jpg" in result)

        self.assertTrue('<A HREF="__attach/image_01.JPG">' in result)
        self.assertTrue("_image_01.JPG" in result)

        self.assertFalse("html.txt" in result)
        self.assertTrue("<table" not in result)

    def testInvalidThumbSizeStream(self):
        text = """Абырвалг
        (:thumblist px=abyrvalg:)
        бла-бла-бла"""

        files = ["first.jpg", "image_01.JPG", "html.txt"]
        fullpath = [os.path.join(self.filesPath, fname) for fname in files]
        Attachment(self.testPage).attach(fullpath)

        result = self.parser.toHtml(text)
        self.assertTrue("бла-бла-бла" in result)

        self.assertTrue('<A HREF="__attach/first.jpg">' in result)
        self.assertTrue("__thumb" in result)
        self.assertTrue("_first.jpg" in result)

        self.assertTrue('<A HREF="__attach/image_01.JPG">' in result)
        self.assertTrue("_image_01.JPG" in result)

    def testInvalidThumbSizeTable(self):
        text = """Абырвалг
        (:thumblist px=abyrvalg сщды=3:)
        бла-бла-бла"""

        files = ["first.jpg", "image_01.JPG", "html.txt"]
        fullpath = [os.path.join(self.filesPath, fname) for fname in files]
        Attachment(self.testPage).attach(fullpath)

        result = self.parser.toHtml(text)
        self.assertTrue("бла-бла-бла" in result)

        self.assertTrue('<A HREF="__attach/first.jpg">' in result)
        self.assertTrue("__thumb" in result)
        self.assertTrue("_first.jpg" in result)

        self.assertTrue('<A HREF="__attach/image_01.JPG">' in result)
        self.assertTrue("_image_01.JPG" in result)
Пример #57
0
class DownloaderTest(unittest.TestCase):
    def setUp(self):
        self.plugindirlist = ['plugins/webpage']
        self._staticDirName = '__download'
        self._tempDir = mkdtemp(prefix='Абырвалг абыр')

        self.loader = PluginsLoader(Application)
        self.loader.load(self.plugindirlist)

    def tearDown(self):
        self.loader.clear()
        removeDir(self._tempDir)

    def testContentImgExample1(self):
        from webpage.downloader import Downloader, DownloadController

        template = '<img src="{path}"'

        controller = DownloadController(self._tempDir, self._staticDirName)
        downloader = Downloader()

        examplePath = 'testdata/webpage/example1/'
        exampleHtmlPath = os.path.join(examplePath, 'example1.html')

        downloader.start(self._path2url(exampleHtmlPath), controller)

        self.assertIn(
            template.format(path=self._staticDirName + '/image_01.png'),
            downloader.contentResult)

        self.assertIn(
            template.format(path=self._staticDirName + '/картинка.png'),
            downloader.contentResult)

        self.assertIn(
            template.format(path=self._staticDirName + '/image_01_1.png'),
            downloader.contentResult)

        self.assertIn(
            template.format(path=self._staticDirName + '/image_02.png'),
            downloader.contentResult)

        self.assertNotIn(
            template.format(path=self._staticDirName + '/image_02_1.png'),
            downloader.contentResult)

        self.assertIn(
            template.format(path=self._staticDirName + '/image_03.png'),
            downloader.contentResult)

        self.assertNotIn(
            template.format(path=self._staticDirName + '/image_03_1.png'),
            downloader.contentResult)

    def testContentCSSExample1_01(self):
        from webpage.downloader import Downloader, DownloadController

        template = '<link href="{path}"'

        controller = DownloadController(self._tempDir, self._staticDirName)
        downloader = Downloader()

        examplePath = 'testdata/webpage/example1/'
        exampleHtmlPath = os.path.join(examplePath, 'example1.html')

        downloader.start(self._path2url(exampleHtmlPath), controller)

        self.assertIn(
            template.format(path=self._staticDirName + '/fname1.css'),
            downloader.contentResult)

        self.assertIn(
            template.format(path=self._staticDirName + '/fname2.css'),
            downloader.contentResult)

        self.assertIn(
            template.format(path=self._staticDirName + '/fname3.css'),
            downloader.contentResult)

        self.assertIn(
            template.format(path=self._staticDirName + '/fname4.css'),
            downloader.contentResult)

        self.assertIn(
            template.format(path=self._staticDirName + '/fname1_1.css'),
            downloader.contentResult)

        self.assertNotIn(
            template.format(path=self._staticDirName + '/fname2_1.css'),
            downloader.contentResult)

    def testContentScriptExample1(self):
        from webpage.downloader import Downloader, DownloadController

        template = '<script src="{path}"'

        controller = DownloadController(self._tempDir, self._staticDirName)
        downloader = Downloader()

        examplePath = 'testdata/webpage/example1/'
        exampleHtmlPath = os.path.join(examplePath, 'example1.html')

        downloader.start(self._path2url(exampleHtmlPath), controller)

        self.assertIn(template.format(path=self._staticDirName + '/fname1.js'),
                      downloader.contentResult)

        self.assertIn(template.format(path=self._staticDirName + '/fname2.js'),
                      downloader.contentResult)

        self.assertIn(
            template.format(path=self._staticDirName + '/fname2_1.js'),
            downloader.contentResult)

        self.assertIn(template.format(path=self._staticDirName + '/fname3.js'),
                      downloader.contentResult)

        self.assertIn(template.format(path=self._staticDirName + '/fname4.js'),
                      downloader.contentResult)

        self.assertNotIn(
            template.format(path=self._staticDirName + '/fname1_1.js'),
            downloader.contentResult)

    def testTitleExample1(self):
        from webpage.downloader import Downloader, DownloadController

        controller = DownloadController(self._tempDir, self._staticDirName)
        downloader = Downloader()

        examplePath = 'testdata/webpage/example1/'
        exampleHtmlPath = os.path.join(examplePath, 'example1.html')

        downloader.start(self._path2url(exampleHtmlPath), controller)

        self.assertTrue(downloader.success)
        self.assertEqual(downloader.pageTitle, 'Заголовок страницы')

    def testNoTitle(self):
        from webpage.downloader import Downloader, DownloadController

        controller = DownloadController(self._tempDir, self._staticDirName)
        downloader = Downloader()

        examplePath = 'testdata/webpage/example_no_title/'
        exampleHtmlPath = os.path.join(examplePath, 'example_no_title.html')

        downloader.start(self._path2url(exampleHtmlPath), controller)

        self.assertTrue(downloader.success)
        self.assertIsNone(downloader.pageTitle)

    def testContentExample2(self):
        from webpage.downloader import Downloader, DownloadController

        template = '<img src="{path}"'

        controller = DownloadController(self._tempDir, self._staticDirName)
        downloader = Downloader()

        examplePath = 'testdata/webpage/example2/'
        exampleHtmlPath = os.path.join(examplePath, 'example2.html')

        downloader.start(self._path2url(exampleHtmlPath), controller)

        self.assertIn(
            template.format(path=self._staticDirName + '/image_01.png'),
            downloader.contentResult)

        self.assertIn(
            template.format(path=self._staticDirName + '/image_01_1.png'),
            downloader.contentResult)

        self.assertIn(
            template.format(path=self._staticDirName + '/image_02.png'),
            downloader.contentResult)

        self.assertNotIn(
            template.format(path=self._staticDirName + '/image_02_1.png'),
            downloader.contentResult)

    def testDownloading_img_01(self):
        from webpage.downloader import Downloader, DownloadController

        controller = DownloadController(self._tempDir, self._staticDirName)
        downloader = Downloader()

        examplePath = 'testdata/webpage/example1/'
        exampleHtmlPath = os.path.join(examplePath, 'example1.html')

        downloader.start(self._path2url(exampleHtmlPath), controller)

        downloadDir = os.path.join(self._tempDir, self._staticDirName)

        fname1 = os.path.join(self._tempDir, self._staticDirName,
                              'image_01.png')

        fname2 = os.path.join(self._tempDir, self._staticDirName,
                              'image_02.png')

        fname3 = os.path.join(self._tempDir, self._staticDirName,
                              'image_03.png')

        fname4 = os.path.join(self._tempDir, self._staticDirName,
                              'image_01_1.png')

        self.assertTrue(os.path.exists(downloadDir))
        self.assertTrue(os.path.exists(fname1))
        self.assertTrue(os.path.exists(fname2))
        self.assertTrue(os.path.exists(fname3))
        self.assertTrue(os.path.exists(fname4))

    def testDownloading_img_02(self):
        from webpage.downloader import Downloader, DownloadController

        controller = DownloadController(self._tempDir, self._staticDirName)
        downloader = Downloader()

        examplePath = 'testdata/webpage/example2/'
        exampleHtmlPath = os.path.join(examplePath, 'example2.html')

        downloader.start(self._path2url(exampleHtmlPath), controller)

        downloadDir = os.path.join(self._tempDir, self._staticDirName)

        fname1 = os.path.join(self._tempDir, self._staticDirName,
                              'image_01.png')

        fname2 = os.path.join(self._tempDir, self._staticDirName,
                              'image_02.png')

        fname3 = os.path.join(self._tempDir, self._staticDirName,
                              'image_03.png')

        self.assertTrue(os.path.exists(downloadDir))
        self.assertTrue(os.path.exists(fname1))
        self.assertTrue(os.path.exists(fname2))
        self.assertTrue(os.path.exists(fname3))

    def testDownloading_img_03(self):
        from webpage.downloader import Downloader, DownloadController

        controller = DownloadController(self._tempDir, self._staticDirName)
        downloader = Downloader()

        examplePath = 'testdata/webpage/Пример 3/'
        exampleHtmlPath = os.path.join(examplePath, 'пример 3.html')

        downloader.start(self._path2url(exampleHtmlPath), controller)

        downloadDir = os.path.join(self._tempDir, self._staticDirName)

        fname1 = os.path.join(self._tempDir, self._staticDirName,
                              'image_01.png')

        fname2 = os.path.join(self._tempDir, self._staticDirName,
                              'image_02.png')

        fname3 = os.path.join(self._tempDir, self._staticDirName,
                              'image_03.png')

        fname4 = os.path.join(self._tempDir, self._staticDirName,
                              'image_01_1.png')

        self.assertTrue(os.path.exists(downloadDir))
        self.assertTrue(os.path.exists(fname1))
        self.assertTrue(os.path.exists(fname2))
        self.assertTrue(os.path.exists(fname3))
        self.assertTrue(os.path.exists(fname4))

    def testDownloading_img_urlquote(self):
        from webpage.downloader import Downloader, DownloadController

        template = '<img src="{path}"'

        controller = DownloadController(self._tempDir, self._staticDirName)
        downloader = Downloader()

        examplePath = 'testdata/webpage/example_urlquote/'
        exampleHtmlPath = os.path.join(examplePath, 'example_urlquote.html')

        downloader.start(self._path2url(exampleHtmlPath), controller)

        downloadDir = os.path.join(self._tempDir, self._staticDirName)

        fname = os.path.join(self._tempDir, self._staticDirName, 'рисунок.png')

        self.assertTrue(os.path.exists(downloadDir))
        self.assertTrue(os.path.exists(fname))

        self.assertIn(
            template.format(path=self._staticDirName + '/рисунок.png'),
            downloader.contentResult)

    def testDownloading_favicon(self):
        from webpage.downloader import Downloader, DownloadController

        template = 'href="{path}"'
        downloadDir = os.path.join(self._tempDir, self._staticDirName)

        controller = DownloadController(self._tempDir, self._staticDirName)
        downloader = Downloader()

        examplePath = 'testdata/webpage/example_favicon/'
        exampleHtmlPath = os.path.join(examplePath, 'example.html')

        downloader.start(self._path2url(exampleHtmlPath), controller)

        fname_1 = os.path.join(self._tempDir, self._staticDirName,
                               'favicon_1.png')
        fname_2 = os.path.join(self._tempDir, self._staticDirName,
                               'favicon_2.png')

        self.assertTrue(os.path.exists(downloadDir))
        self.assertTrue(os.path.exists(fname_1))
        self.assertTrue(os.path.exists(fname_2))

        self.assertIn(
            template.format(path=self._staticDirName + '/favicon_1.png'),
            downloader.contentResult)

        self.assertIn(
            template.format(path=self._staticDirName + '/favicon_2.png'),
            downloader.contentResult)

    def testDownloading_css_rename(self):
        from webpage.downloader import Downloader, DownloadController

        template = 'href="{path}"'
        downloadDir = os.path.join(self._tempDir, self._staticDirName)

        controller = DownloadController(self._tempDir, self._staticDirName)
        downloader = Downloader()

        examplePath = 'testdata/webpage/example_css_rename/'
        exampleHtmlPath = os.path.join(examplePath, 'example.html')

        downloader.start(self._path2url(exampleHtmlPath), controller)

        fname = os.path.join(self._tempDir, self._staticDirName,
                             'style.php.css')

        self.assertTrue(os.path.exists(downloadDir))
        self.assertTrue(os.path.exists(fname))

        self.assertIn(
            template.format(path=self._staticDirName + '/style.php.css'),
            downloader.contentResult)

    def testDownloading_img_srcset_files(self):
        from webpage.downloader import Downloader, DownloadController

        controller = DownloadController(self._tempDir, self._staticDirName)
        downloader = Downloader()

        examplePath = 'testdata/webpage/example3/'
        exampleHtmlPath = os.path.join(examplePath, 'example3.html')

        downloader.start(self._path2url(exampleHtmlPath), controller)

        downloadDir = os.path.join(self._tempDir, self._staticDirName)

        fname1 = os.path.join(self._tempDir, self._staticDirName,
                              'image_01.png')

        fname2 = os.path.join(self._tempDir, self._staticDirName,
                              'image_02.png')

        fname3 = os.path.join(self._tempDir, self._staticDirName,
                              'image_03.png')

        fname4 = os.path.join(self._tempDir, self._staticDirName,
                              'image_04.png')

        self.assertTrue(os.path.exists(downloadDir))
        self.assertTrue(os.path.exists(fname1))
        self.assertTrue(os.path.exists(fname2))
        self.assertTrue(os.path.exists(fname3))
        self.assertTrue(os.path.exists(fname4))

    def testDownloading_img_srcset_content(self):
        from webpage.downloader import Downloader, DownloadController

        controller = DownloadController(self._tempDir, self._staticDirName)
        downloader = Downloader()

        examplePath = 'testdata/webpage/example3/'
        exampleHtmlPath = os.path.join(examplePath, 'example3.html')

        downloader.start(self._path2url(exampleHtmlPath), controller)
        downloadDir = os.path.join(self._tempDir, self._staticDirName)
        content = downloader.contentResult

        sample = 'srcset="{path}/image_02.png 2x, {path}/image_03.png w600, {path}/image_04.png"'.format(
            path=self._staticDirName)

        self.assertIn(sample, content)

    def testDownloading_css_01(self):
        from webpage.downloader import Downloader, DownloadController

        controller = DownloadController(self._tempDir, self._staticDirName)
        downloader = Downloader()

        examplePath = 'testdata/webpage/example1/'
        exampleHtmlPath = os.path.join(examplePath, 'example1.html')

        downloader.start(self._path2url(exampleHtmlPath), controller)

        downloadDir = os.path.join(self._tempDir, self._staticDirName)

        fname1 = os.path.join(self._tempDir, self._staticDirName, 'fname1.css')

        fname2 = os.path.join(self._tempDir, self._staticDirName, 'fname2.css')

        fname3 = os.path.join(self._tempDir, self._staticDirName, 'fname3.css')

        fname4 = os.path.join(self._tempDir, self._staticDirName, 'fname4.css')

        fname5 = os.path.join(self._tempDir, self._staticDirName,
                              'fname1_1.css')

        self.assertTrue(os.path.exists(downloadDir))
        self.assertTrue(os.path.exists(fname1))
        self.assertTrue(os.path.exists(fname2))
        self.assertTrue(os.path.exists(fname3))
        self.assertTrue(os.path.exists(fname4))
        self.assertTrue(os.path.exists(fname5))

    def testDownloading_css_import_01(self):
        from webpage.downloader import Downloader, DownloadController

        controller = DownloadController(self._tempDir, self._staticDirName)
        downloader = Downloader()

        examplePath = 'testdata/webpage/example1/'
        exampleHtmlPath = os.path.join(examplePath, 'example1.html')

        downloader.start(self._path2url(exampleHtmlPath), controller)

        self.assertTrue(
            os.path.exists(
                os.path.join(self._tempDir, self._staticDirName,
                             'import1.css')))

        self.assertTrue(
            os.path.exists(
                os.path.join(self._tempDir, self._staticDirName,
                             'import2.css')))

        self.assertTrue(
            os.path.exists(
                os.path.join(self._tempDir, self._staticDirName,
                             'import3.css')))

        self.assertTrue(
            os.path.exists(
                os.path.join(self._tempDir, self._staticDirName,
                             'import4.css')))

        self.assertTrue(
            os.path.exists(
                os.path.join(self._tempDir, self._staticDirName,
                             'basic2.css')))

        self.assertTrue(
            os.path.exists(
                os.path.join(self._tempDir, self._staticDirName,
                             'basic3.css')))

        self.assertTrue(
            os.path.exists(
                os.path.join(self._tempDir, self._staticDirName,
                             'basic4.css')))

        self.assertTrue(
            os.path.exists(
                os.path.join(self._tempDir, self._staticDirName,
                             'basic5.css')))

        self.assertTrue(
            os.path.exists(
                os.path.join(self._tempDir, self._staticDirName,
                             'basic5_1.css')))

        self.assertTrue(
            os.path.exists(
                os.path.join(self._tempDir, self._staticDirName,
                             'basic6.css')))

    def testDownloading_css_back_img_01(self):
        from webpage.downloader import Downloader, DownloadController

        controller = DownloadController(self._tempDir, self._staticDirName)
        downloader = Downloader()

        examplePath = 'testdata/webpage/example1/'
        exampleHtmlPath = os.path.join(examplePath, 'example1.html')

        downloader.start(self._path2url(exampleHtmlPath), controller)

        self.assertTrue(
            os.path.exists(
                os.path.join(self._tempDir, self._staticDirName,
                             'back_img_01.png')))

        self.assertTrue(
            os.path.exists(
                os.path.join(self._tempDir, self._staticDirName,
                             'back_img_02.png')))

        self.assertTrue(
            os.path.exists(
                os.path.join(self._tempDir, self._staticDirName,
                             'back_img_03.png')))

        self.assertTrue(
            os.path.exists(
                os.path.join(self._tempDir, self._staticDirName,
                             'back_img_04.png')))

        self.assertTrue(
            os.path.exists(
                os.path.join(self._tempDir, self._staticDirName,
                             'back_img_05.png')))

        self.assertTrue(
            os.path.exists(
                os.path.join(self._tempDir, self._staticDirName,
                             'back_img_06.png')))

    def testDownloading_css_url_01(self):
        from webpage.downloader import Downloader, DownloadController

        template = 'url("{url}")'

        controller = DownloadController(self._tempDir, self._staticDirName)
        downloader = Downloader()

        examplePath = 'testdata/webpage/example1/'
        exampleHtmlPath = os.path.join(examplePath, 'example1.html')

        downloader.start(self._path2url(exampleHtmlPath), controller)

        fname1_text = readTextFile(
            os.path.join(self._tempDir, self._staticDirName, 'fname1.css'))

        self.assertIn(template.format(url='import1.css'), fname1_text)
        self.assertIn(template.format(url='back_img_01.png'), fname1_text)
        self.assertIn(template.format(url='back_img_02.png'), fname1_text)
        self.assertIn(template.format(url='back_img_03.png'), fname1_text)
        self.assertIn(template.format(url='back_img_04.png'), fname1_text)
        self.assertIn(template.format(url='back_img_05.png'), fname1_text)
        self.assertIn(template.format(url='back_img_06.png'), fname1_text)

    def testDownloading_css_url_02(self):
        from webpage.downloader import Downloader, DownloadController

        template = 'url("{url}")'

        controller = DownloadController(self._tempDir, self._staticDirName)
        downloader = Downloader()

        examplePath = 'testdata/webpage/example1/'
        exampleHtmlPath = os.path.join(examplePath, 'example1.html')

        downloader.start(self._path2url(exampleHtmlPath), controller)

        fname2_text = readTextFile(
            os.path.join(self._tempDir, self._staticDirName, 'fname2.css'))

        self.assertIn(template.format(url='basic2.css'), fname2_text)
        self.assertIn(template.format(url='basic4.css'), fname2_text)
        self.assertIn(template.format(url='basic5.css'), fname2_text)
        self.assertIn(template.format(url='basic6.css'), fname2_text)
        self.assertIn('basic3.css', fname2_text)
        self.assertIn('basic5.css', fname2_text)

    def testDownloading_css_03(self):
        from webpage.downloader import Downloader, DownloadController

        controller = DownloadController(self._tempDir, self._staticDirName)
        downloader = Downloader()

        examplePath = 'testdata/webpage/Пример 3/'
        exampleHtmlPath = os.path.join(examplePath, 'пример 3.html')

        downloader.start(self._path2url(exampleHtmlPath), controller)

        downloadDir = os.path.join(self._tempDir, self._staticDirName)

        fname1 = os.path.join(self._tempDir, self._staticDirName, 'fname1.css')

        fname2 = os.path.join(self._tempDir, self._staticDirName, 'fname2.css')

        fname3 = os.path.join(self._tempDir, self._staticDirName, 'fname3.css')

        fname4 = os.path.join(self._tempDir, self._staticDirName, 'fname4.css')

        fname5 = os.path.join(self._tempDir, self._staticDirName,
                              'fname1_1.css')

        self.assertTrue(os.path.exists(downloadDir))
        self.assertTrue(os.path.exists(fname1))
        self.assertTrue(os.path.exists(fname2))
        self.assertTrue(os.path.exists(fname3))
        self.assertTrue(os.path.exists(fname4))
        self.assertTrue(os.path.exists(fname5))

    def testDownloading_javascript_01(self):
        from webpage.downloader import Downloader, DownloadController

        controller = DownloadController(self._tempDir, self._staticDirName)
        downloader = Downloader()

        examplePath = 'testdata/webpage/example1/'
        exampleHtmlPath = os.path.join(examplePath, 'example1.html')

        downloader.start(self._path2url(exampleHtmlPath), controller)

        downloadDir = os.path.join(self._tempDir, self._staticDirName)

        fname1 = os.path.join(self._tempDir, self._staticDirName, 'fname1.js')

        fname2 = os.path.join(self._tempDir, self._staticDirName, 'fname2.js')

        fname3 = os.path.join(self._tempDir, self._staticDirName, 'fname3.js')

        fname4 = os.path.join(self._tempDir, self._staticDirName, 'fname4.js')

        self.assertTrue(os.path.exists(downloadDir))
        self.assertTrue(os.path.exists(fname1))
        self.assertTrue(os.path.exists(fname2))
        self.assertTrue(os.path.exists(fname3))
        self.assertTrue(os.path.exists(fname4))

    @staticmethod
    def _path2url(path):
        path = os.path.abspath(path)
        return 'file:' + urllib.request.pathname2url(path)