def generateHtml (self, page): resultFileName = self.getHtmlPath() cache = self._getCacher (page, self._application) # Проверим, можно ли прочитать уже готовый HTML if (cache.canReadFromCache() and os.path.exists (resultFileName)) or page.readonly: try: return readTextFile (resultFileName) except IOError: MessageBox (_(u"Can't read file {}".format (resultFileName)), _(u"Error"), wx.ICON_ERROR | wx.OK) return u"" style = Style() stylepath = style.getPageStyle (page) generator = self._getHtmlGenerator (page) try: html = generator.makeHtml(stylepath) cache.saveHash() except IOError: MessageBox (_(u"Can't create HTML file"), _(u"Error"), wx.ICON_ERROR | wx.OK) return html
def generateHtml (self, page): path = self.getHtmlPath (page) if page.readonly and os.path.exists (path): # Если страница открыта только для чтения и html-файл уже существует, то покажем его return path style = Style() stylepath = style.getPageStyle (page) try: tpl = HtmlTemplate (stylepath) except: MessageBox (_(u"Page style Error. Style by default is used"), _(u"Error"), wx.ICON_ERROR | wx.OK) tpl = HtmlTemplate (style.getDefaultStyle()) if page.autoLineWrap: text = HtmlImprover.run (page.content) text = re.sub ("\n<br>\n(<li>)|(<li>)", "\n<LI>", text) else: text = page.content result = tpl.substitute (content=text) with open (path, "wb") as fp: fp.write (result.encode ("utf-8")) return path
def testDefault(self): """ Проверка того, что возвращается правильный путь до шаблона по умолчанию """ style = Style() defaultStyle = style.getDefaultStyle() self.assertEqual(os.path.abspath(defaultStyle), os.path.abspath("styles/__default/__style.html"))
def _makeHtml(self, page): style = Style() stylepath = style.getPageStyle(page) try: tpl = HtmlTemplate(readTextFile(stylepath)) except EnvironmentError: tpl = HtmlTemplate(readTextFile(style.getDefaultStyle())) content = self._changeContentByEvent( page, PreprocessingParams(page.content), self._application.onPreprocessing) if page.autoLineWrap: content = self._changeContentByEvent( page, PreHtmlImprovingParams(content), self._application.onPreHtmlImproving) config = HtmlRenderConfig(self._application.config) improverFactory = HtmlImproverFactory(self._application) text = improverFactory[config.HTMLImprover.value].run(content) else: text = content result = tpl.substitute(content=text, title=page.display_title) result = self._changeContentByEvent(page, PostprocessingParams(result), self._application.onPostprocessing) return result
def testStylePage2(self): style = Style() page = self.rootwiki[u"Html-страница 2"] shutil.copy(self._testStylePath, page.path) validStyle = os.path.abspath(os.path.join(page.path, self._styleFname)) pageStyle = os.path.abspath(style.getPageStyle(page)) self.assertEqual(pageStyle, validStyle)
def testStylePage1(self): style = Style() page = self.wikiroot[u"Викистраница 1"] shutil.copy(self._testStylePath, page.path) validStyle = os.path.abspath(os.path.join(page.path, self._styleFname)) pageStyle = os.path.abspath(style.getPageStyle(page)) self.assertEqual(pageStyle, validStyle)
def testFakeStyle(self): style = Style() page = self.rootwiki[u"Викистраница 1"] os.mkdir(os.path.join(page.path, self._styleFname)) validStyle = os.path.abspath(style.getDefaultStyle()) pageStyle = os.path.abspath(style.getPageStyle(page)) self.assertEqual(pageStyle, validStyle)
def testInvalidPage(self): style = Style() style.setPageStyle(None, self._exampleStyleDir) style.setPageStyleDefault(None) style.setPageStyle(self.rootwiki, self._exampleStyleDir) style.setPageStyleDefault(self.rootwiki)
def testCacheStyle (self): """ Проверка на то, что изменение стиля страницы сбрасывает кэш """ style = Style() hashCalculator = WikiHashCalculator (Application) hash_src = hashCalculator.getHash (self.testPage) exampleStyleDir = u"../test/styles/example_jblog/example_jblog" exampleStyleDir2 = u"../test/styles/example_jnet/example_jnet" # Изменим стиль страницы style.setPageStyle (self.testPage, exampleStyleDir) hash2 = hashCalculator.getHash (self.testPage) self.assertNotEqual (hash2, hash_src) # Еще раз изменим стиль style.setPageStyle (self.testPage, exampleStyleDir2) hash3 = hashCalculator.getHash (self.testPage) self.assertNotEqual (hash2, hash3) self.assertNotEqual (hash3, hash_src) # Изменим стиль на тот же style.setPageStyle (self.testPage, exampleStyleDir2) hash4 = hashCalculator.getHash (self.testPage) self.assertEqual (hash4, hash3) # Установим стиль по умолчанию style.setPageStyleDefault (self.testPage) hash5 = hashCalculator.getHash (self.testPage) self.assertEqual (hash5, hash_src)
def testStylePageDefault(self): """ Проверка на то, что если у страницы нет файла стиля, то возвращается стиль по умолчанию """ style = Style() defaultStyle = style.getDefaultStyle() style_page1 = style.getPageStyle(self.rootwiki[u"Викистраница 1"]) style_page2 = style.getPageStyle(self.rootwiki[u"Html-страница 2"]) self.assertEqual(style_page1, defaultStyle) self.assertEqual(style_page2, defaultStyle)
def testChangeStyle(self): exampleStyleDir = u"../test/styles/example_jblog/example_jblog" newdate = datetime.datetime(2012, 8, 24) HtmlPageFactory().create(self.wikiroot, u"Страница 1", []) self.wikiroot[u"Страница 1"].datetime = newdate style = Style() style.setPageStyle(self.wikiroot[u"Страница 1"], exampleStyleDir) delta = datetime.datetime.now() - self.wikiroot[u"Страница 1"].datetime self.assertLess(delta, self._maxDelta)
def __getStyleContent(self, page): """ Возвращает содержимое шаблона """ style = Style() try: stylecontent = readTextFile(style.getPageStyle(page)) except (IOError, UnicodeDecodeError): stylecontent = "" return stylecontent
def __getStyleContent (self, page): """ Возвращает содержимое шаблона """ style = Style () try: with open (style.getPageStyle (page)) as fp: stylecontent = unicode (fp.read(), "utf8") except IOError: stylecontent = u"" except UnicodeDecodeError: stylecontent = u"" return stylecontent.encode (self._unicodeEncoding)
def _updatePage(self, page): path = page.getHtmlPath() cache = HtmlCache(page, self._application) # Проверим, можно ли прочитать уже готовый HTML if cache.canReadFromCache() and os.path.exists(path): return style = Style() stylepath = style.getPageStyle(page) generator = HtmlGenerator(page) html = generator.makeHtml(stylepath) writeTextFile(path, html) cache.saveHash()
def generateHtml (self, page): style = Style() stylepath = style.getPageStyle (page) generator = HtmlGenerator (page) try: html = generator.makeHtml(stylepath) except: MessageBox (_(u"Page style Error. Style by default is used"), _(u"Error"), wx.ICON_ERROR | wx.OK) html = generator.makeHtml (style.getDefaultStyle()) return html
def testSetStyleAsDir(self): style = Style() page = self.rootwiki[u"Викистраница 1"] pageStyleFname = os.path.join(page.path, self._styleFname) pageStyleDir = os.path.join(page.path, self._styleDir) self.assertFalse(os.path.exists(pageStyleDir)) self.assertFalse(os.path.exists(pageStyleFname)) style.setPageStyle(page, self._exampleStyleDir) self.assertTrue(os.path.exists(pageStyleDir)) self.assertTrue(os.path.exists(pageStyleFname)) style.setPageStyleDefault(page) self.assertFalse(os.path.exists(pageStyleDir)) self.assertFalse(os.path.exists(pageStyleFname))
def generateHtml (self, page): path = self.getHtmlPath () if page.readonly and os.path.exists (path): # Если страница открыта только для чтения и html-файл уже существует, то покажем его return readTextFile (path) style = Style() stylepath = style.getPageStyle (page) try: tpl = HtmlTemplate (readTextFile (stylepath)) except: MessageBox (_(u"Page style Error. Style by default is used"), _(u"Error"), wx.ICON_ERROR | wx.OK) tpl = HtmlTemplate (readTextFile (style.getDefaultStyle())) content = self._changeContentByEvent (self.page, PreprocessingParams (page.content), Application.onPreprocessing) if page.autoLineWrap: content = self._changeContentByEvent (self.page, PreHtmlImprovingParams (content), Application.onPreHtmlImproving) config = HtmlRenderConfig (Application.config) improverFactory = HtmlImproverFactory (Application) text = improverFactory[config.HTMLImprover.value].run (content) else: text = content userhead = u"<title>{}</title>".format (page.title) result = tpl.substitute (content = text, userhead = userhead) result = self._changeContentByEvent (self.page, PostprocessingParams (result), Application.onPostprocessing) return result
def testSelfDefault(self): style = Style() page = self.rootwiki[u"Викистраница 1"] style.setPageStyle(page, style.getPageStyle(page)) self.assertEqual(os.path.abspath(style.getPageStyle(page)), os.path.abspath(style.getDefaultStyle()))
def testEvent(self): """ Вызов событий при изменении стиля страницы """ style = Style() page = self.rootwiki[u"Викистраница 1"] self.assertEqual(self._pageUpdateCount, 0) style.setPageStyle(page, self._exampleStyleDir) self.assertEqual(self._pageUpdateCount, 1) style.setPageStyleDefault(page) self.assertEqual(self._pageUpdateCount, 2) style.setPageStyle(page, self._exampleStyleDir2) self.assertEqual(self._pageUpdateCount, 3)
def testAxisMinMax_01(self): text = '''(:plot x.min=-2 x.max="5" y.min="-10" y.max="20":) 10 20 30 40 (:plotend:)''' self.page.content = text generator = HtmlGenerator(self.page) result = generator.makeHtml(Style().getPageStyle(self.page)) text1 = '"min": -2.0' text2 = '"max": 5.0' text3 = '"min": -10.0' text4 = '"max": 20.0' self.assertIn(text1, result) self.assertIn(text2, result) self.assertIn(text3, result) self.assertIn(text4, result)
def test1S(self): text = u'''(:source lang="1s":) Функция УстановитьФизическиеЛица(Выборка) Пока Выборка.Следующий() Цикл //УстановитьФизическоеЛицо ФизическоеЛицо = Справочники.ФизическиеЛица.НайтиПоНаименованию(Выборка.Ссылка); Пользователь = Выборка.Ссылка.ПолучитьОбъект(); Пользователь.ФизическоеЛицо = ФизическоеЛицо; Пользователь.Записать(); Сообщить("" + Пользователь + " " + Пользователь.ФизическоеЛицо + "-[ОК!]"); КонецЦикла; КонецФункции (:sourceend:)''' self.testPage.content = text generator = HtmlGenerator(self.testPage) result = generator.makeHtml(Style().getPageStyle(self.testPage)) self.assertIn(u'<span class="c">//УстановитьФизическоеЛицо</span>', result) self.assertIn(u'<span class="k">КонецФункции</span>', result)
def test_add_tags_07(self): text = '''(:org:) Description: бла-бла-бла Tags: тег 1, тег 2, тег 3 Description: бла-бла-бла Tags: тег 4 Описание: бла-бла-бла Теги: тег 5 (:orgend:)''' self.testPage.content = text generator = HtmlGenerator(self.testPage) generator.makeHtml(Style().getPageStyle(self.testPage)) self.assertIn('тег 1', self.testPage.tags) self.assertIn('тег 2', self.testPage.tags) self.assertIn('тег 3', self.testPage.tags) self.assertIn('тег 4', self.testPage.tags) self.assertIn('тег 5', self.testPage.tags)
def testHighlightFileEncoding4(self): """ Явное задание неправильной кодировки (которой нет в списке кодировок) """ Attachment(self.testPage).attach( [os.path.join(self.samplefilesPath, u"source_utf8.py")]) content = u'(:source file="source_utf8.py" encoding="blablabla":)' self.testPage.content = content generator = HtmlGenerator(self.testPage) result = generator.makeHtml(Style().getPageStyle(self.testPage)) self.assertTrue( u'<span class="kn">import</span> <span class="nn">os.path</span>' not 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'Уничтожение (выгрузка) плагина.' not in result) self.assertTrue(u'Source' 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)
def testHeads_04(self): text = '''(:htmlhead:) excanvas.min.js jquery.min.js highcharts.js (:htmlheadend:) (:plot:)''' self.page.content = text generator = HtmlGenerator(self.page) result = generator.makeHtml(Style().getPageStyle(self.page)) attachpath = Attachment(self.page).getAttachPath() self.assertIn( '<div id="graph-0" style="width:700px; height:300px;"></div>', result) self.assertNotIn('excanvas.min.js">', result) self.assertNotIn('jquery.min.js">', result) self.assertNotIn('highcharts.js">', result) self.assertIn("$('#graph-0').highcharts({", result) self.assertFalse( os.path.exists( os.path.join(attachpath, '__thumb', '__js', 'excanvas.min.js'))) self.assertFalse( os.path.exists( os.path.join(attachpath, '__thumb', '__js', 'jquery.min.js'))) self.assertFalse( os.path.exists( os.path.join(attachpath, '__thumb', '__js', 'highcharts.js')))
def testCacheStyle(self): """ Проверка на то, что изменение стиля страницы сбрасывает кэш """ style = Style() # Только создали страницу, кешировать нельзя cache = HtmlCache(self.testPage, self.application) self.assertFalse(cache.canReadFromCache()) cache.saveHash() self.assertTrue(cache.canReadFromCache()) exampleStyleDir = "../test/styles/example_jblog/example_jblog" exampleStyleDir2 = "../test/styles/example_jnet/example_jnet" # Изменим стиль страницы style.setPageStyle(self.testPage, exampleStyleDir) self.assertFalse(cache.canReadFromCache()) cache.saveHash() self.assertTrue(cache.canReadFromCache()) # Еще раз изменим стиль style.setPageStyle(self.testPage, exampleStyleDir2) self.assertFalse(cache.canReadFromCache()) cache.saveHash() self.assertTrue(cache.canReadFromCache()) # Установим стиль по умолчанию style.setPageStyleDefault(self.testPage) self.assertFalse(cache.canReadFromCache()) cache.saveHash() self.assertTrue(cache.canReadFromCache())
def testFullHtml2(self): text = u"""Бла-бла-бла (:style:) body {font-size: 33px} (:styleend:) sdfsdf sdf (:style:) body {font-size: 10px} (:styleend:) бла-бла-бла """ self.testPage.content = text generator = HtmlGenerator(self.testPage) result = generator.makeHtml(Style().getPageStyle(self.testPage)) validStyle1 = u"<STYLE>body {font-size: 33px}</STYLE>" validStyle2 = u"<STYLE>body {font-size: 10px}</STYLE>" self.assertTrue(validStyle1 in result, result) self.assertTrue(validStyle2 in result, result)
def testColSep_02(self): text = '''(:plot curve.data.colsep="," :) 1, 10, 20, 30, 40 2, 11, 22, 31, 41 3, 13, 24, 33, 42 4, 15, 25, 35, 43 5, 16, 26, 36, 44 6, 18, 27, 37, 45 7, 20, 30, 38, 46 8, 20, 30, 38, 46 9, 20, 30, 38, 46 10, 20, 30, 38, 46 (:plotend:)''' self.page.content = text generator = HtmlGenerator(self.page) result = generator.makeHtml(Style().getPageStyle(self.page)) self.assertIn('10.0', result) self.assertIn('18.0', result) self.assertIn('20.0', result)
def testSetStyleAsDir(self): style = Style() page = self.wikiroot["Викистраница 1"] pageStyleFname = os.path.join(page.path, self._styleFname) pageStyleDir = os.path.join(page.path, self._styleDir) self.assertFalse(os.path.exists(pageStyleDir)) self.assertFalse(os.path.exists(pageStyleFname)) style.setPageStyle(page, self._exampleStyleDir) self.assertTrue(os.path.exists(pageStyleDir)) self.assertTrue(os.path.exists(pageStyleFname)) style.setPageStyleDefault(page) self.assertFalse(os.path.exists(pageStyleDir)) self.assertFalse(os.path.exists(pageStyleFname))
def testCacheStyle (self): """ Проверка на то, что изменение стиля страницы сбрасывает кэш """ style = Style() # Только создали страницу, кешировать нельзя generator = HtmlGenerator (self.testPage) self.assertFalse (generator.canReadFromCache()) generator.makeHtml (Style().getPageStyle (self.testPage)) self.assertTrue (generator.canReadFromCache()) exampleStyleDir = u"../test/styles/example_jblog/example_jblog" exampleStyleDir2 = u"../test/styles/example_jnet/example_jnet" # Изменим стиль страницы style.setPageStyle (self.testPage, exampleStyleDir) self.assertFalse (generator.canReadFromCache()) generator.makeHtml (Style().getPageStyle (self.testPage)) self.assertTrue (generator.canReadFromCache()) # Еще раз изменим стиль style.setPageStyle (self.testPage, exampleStyleDir2) self.assertFalse (generator.canReadFromCache()) generator.makeHtml (Style().getPageStyle (self.testPage)) self.assertTrue (generator.canReadFromCache()) # Установим стиль по умолчанию style.setPageStyleDefault (self.testPage) self.assertFalse (generator.canReadFromCache()) generator.makeHtml (Style().getPageStyle (self.testPage)) self.assertTrue (generator.canReadFromCache())
def testInvalidPath(self): style = Style() page = self.wikiroot["Викистраница 1"] self.assertRaises(IOError, style.setPageStyle, page, self._invalidStyleDir)
def testChangeStyle2(self): style = Style() self.assertRaises(ReadonlyException, style.setPageStyleDefault, self.wiki[u"Страница 1"])
def testChangeStyle1(self): style = Style() self.assertRaises(ReadonlyException, style.setPageStyle, self.wiki[u"Страница 1"], self._exampleStyleDir)
def _getStyleByCreation(self): selItem = self._appearancePanel.styleCombo.GetSelection() if selItem == 0: return Style().getDefaultStyle() return self._stylesList[selItem - 1]
def __applyStyle(self, page, style): if page.parent is not None and not page.readonly: # Если это не корень вики и страница открыта не только для чтения Style().setPageStyle(page, style) map(lambda child: self.__applyStyle(child, style), page.children)
def testSelfSpecial(self): style = Style() page = self.wikiroot["Викистраница 1"] style.setPageStyle(page, self._exampleStyleDir) style.setPageStyle(page, style.getPageStyle(page))
def testSelfSpecial(self): style = Style() page = self.rootwiki[u"Викистраница 1"] style.setPageStyle(page, self._exampleStyleDir) style.setPageStyle(page, style.getPageStyle(page))
def style(self): selItem = self.stylesCombo.GetSelection() if selItem == 0: return Style().getDefaultStyle() return self.__stylesList[selItem - 1]