def _sortFiles (self, names, params_dict): """ Отсортировать дочерние страницы, если нужно """ attach = Attachment (self.parser.page) names_full = [os.path.join (attach.getAttachPath(), name) for name in names] if u"sort" not in params_dict: names.sort (Attachment.sortByName) return sort = params_dict["sort"].lower() if sort == u"name": names.sort (Attachment.sortByName) elif sort == u"descendname": names.sort (Attachment.sortByName, reverse=True) elif sort == u"ext": names.sort (Attachment.sortByExt) elif sort == u"descendext": names.sort (Attachment.sortByExt, reverse=True) elif sort == u"size": names.sort (attach.sortBySizeRelative) elif sort == u"descendsize": names.sort (attach.sortBySizeRelative, reverse=True) elif sort == u"date": names.sort (attach.sortByDateRelative) elif sort == u"descenddate": names.sort (attach.sortByDateRelative, reverse=True) else: names.sort (Attachment.sortByName)
def _getAttach (self, params): """ Возвращает имя прикрепленного файла, который хотим вставить на страницу и хвост параметров после имени файла """ attach_begin = "Attach:" params_end = None params_tail = params # Выделим конец строки после Attach: if params.startswith (attach_begin): params_end = params[len (attach_begin) :] else: return (None, params_tail) attaches = Attachment (self.parser.page).attachmentFull attaches.sort (IncludeCommand.sortByLength, reverse=True) path = None for fname in attaches: if params_end.startswith (os.path.basename (fname)): path = fname params_tail = params_end[len (os.path.basename (fname)) :] break return (path, params_tail)
def testCacheSubdir (self): attach = Attachment (self.testPage) # Только создали страницу, кешировать нельзя generator = HtmlGenerator (self.testPage) self.assertFalse (generator.canReadFromCache()) generator.makeHtml (Style().getPageStyle (self.testPage)) # После того, как один раз сгенерили страницу, если ничего не изменилось, можно кешировать self.assertTrue (generator.canReadFromCache()) # Добавим файл в dir with open (os.path.join (attach.getAttachPath(), "dir", "temp.tmp"), "w" ) as fp: fp.write ("bla-bla-bla") self.assertFalse (generator.canReadFromCache()) # Добавим еще одну вложенную директорию subdir = os.path.join (attach.getAttachPath(), "dir", "subdir_2") os.mkdir (subdir) self.assertFalse (generator.canReadFromCache()) generator.makeHtml (Style().getPageStyle (self.testPage)) # Добавим файл в dir/subdir_2 with open (os.path.join (subdir, "temp2.tmp"), "w" ) as fp: fp.write ("bla-bla-bla") self.assertFalse (generator.canReadFromCache())
def testAttachPath4 (self): attach = Attachment (self.page) # Получить путь до прикрепленных файлов, создав ее path = attach.getAttachPath(create=True) # Вложенных файлов еще нет, поэтому нет и папки self.assertTrue (os.path.exists (path))
def testCacheSubdir (self): attach = Attachment (self.testPage) hashCalculator = WikiHashCalculator (Application) hash_src = hashCalculator.getHash (self.testPage) # Добавим файл в dir with open (os.path.join (attach.getAttachPath(), "dir", "temp.tmp"), "w") as fp: fp.write ("bla-bla-bla") hash2 = hashCalculator.getHash (self.testPage) self.assertNotEqual (hash_src, hash2) # Добавим еще одну вложенную директорию subdir = os.path.join (attach.getAttachPath(), "dir", "subdir_2") os.mkdir (subdir) hash3 = hashCalculator.getHash (self.testPage) self.assertNotEqual (hash2, hash3) self.assertNotEqual (hash_src, hash3) # Добавим файл в dir/subdir_2 with open (os.path.join (subdir, "temp2.tmp"), "w") as fp: fp.write ("bla-bla-bla") hash4 = hashCalculator.getHash (self.testPage) self.assertNotEqual (hash3, hash4) self.assertNotEqual (hash2, hash4) self.assertNotEqual (hash_src, hash4)
def testCacheSubdir(self): attach = Attachment(self.testPage) # Только создали страницу, кешировать нельзя cache = HtmlCache(self.testPage, self.application) self.assertFalse(cache.canReadFromCache()) cache.saveHash() # После того, как один раз сгенерили страницу, если ничего не # изменилось, можно кешировать self.assertTrue(cache.canReadFromCache()) # Добавим файл в dir with open(os.path.join(attach.getAttachPath(), "dir", "temp.tmp"), "w") as fp: fp.write("bla-bla-bla") self.assertFalse(cache.canReadFromCache()) cache.saveHash() # Добавим еще одну вложенную директорию subdir = os.path.join(attach.getAttachPath(), "dir", "subdir_2") os.mkdir(subdir) self.assertFalse(cache.canReadFromCache()) cache.saveHash() # Добавим файл в dir/subdir_2 with open(os.path.join(subdir, "temp2.tmp"), "w") as fp: fp.write("bla-bla-bla") self.assertFalse(cache.canReadFromCache())
def testCache1(self): # Только создали страницу, кешировать нельзя cache = HtmlCache(self.testPage, self.application) self.assertFalse(cache.canReadFromCache()) # После того, как один раз сгенерили страницу, если ничего не # изменилось, можно кешировать cache.saveHash() self.assertTrue(cache.canReadFromCache()) self.testPage.content = "бла-бла-бла" # Изменили содержимое страницы, опять нельзя кешировать self.assertFalse(cache.canReadFromCache()) cache.saveHash() self.assertTrue(cache.canReadFromCache()) # Добавим файл attach = Attachment(self.testPage) attach.attach([os.path.join(self.filesPath, "add.png")]) self.assertFalse(cache.canReadFromCache()) cache.saveHash() self.assertTrue(cache.canReadFromCache())
def testAttachPath2 (self): attach = Attachment (self.page) # Получить путь до прикрепленных файлов, не создавая ее path = attach.getAttachPath() # Вложенных файлов еще нет, поэтому нет и папки self.assertFalse (os.path.exists (path))
def __getDirContent (self, page, filescontent, dirname="."): """ Сформировать строку для расчета хеша по данным вложенной поддиректории dirname (путь относительно __attach) page - страница, для которой собираем список вложений filescontent - список, содержащий строки, описывающие вложенные файлы """ attach = Attachment (page) attachroot = attach.getAttachPath() attachlist = attach.getAttachRelative (dirname) attachlist.sort (Attachment.sortByName) for fname in attachlist: fullpath = os.path.join (attachroot, dirname, fname) # Пропустим директории, которые начинаются с __ if not os.path.isdir (fname) or not fname.startswith ("__"): try: filescontent.write (fname.encode (self._unicodeEncoding)) filescontent.write (unicode (os.stat (fullpath).st_mtime)) if os.path.isdir (fullpath): self.__getDirContent (page, filescontent, os.path.join (dirname, fname)) except OSError: # Если есть проблемы с доступом к файлу, то здесь на это не будем обращать внимания pass
def testSortByDate (self): files = [u"add.png", u"Anchor.png", u"image2.png", u"image.png", u"add.png2", u"файл с пробелами.tmp", u"filename"] fullFilesPath = [os.path.join (u"../test/samplefiles/for_sort", fname) for fname in files] attach = Attachment (self.page) attach.attach (fullFilesPath) files_list = attach.attachmentFull files_list.sort (Attachment.sortByName) os.utime (files_list[3], (1000000000, 1000000000)) os.utime (files_list[0], (1000000000, 1100000000)) os.utime (files_list[2], (1000000000, 1200000000)) os.utime (files_list[6], (1000000000, 1300000000)) os.utime (files_list[4], (1000000000, 1400000000)) os.utime (files_list[5], (1000000000, 1500000000)) os.utime (files_list[1], (1000000000, 1600000000)) Attachment (self.page) files_list2 = attach.attachmentFull files_list2.sort (Attachment.sortByDate) for n in range (1, len (files)): self.assertTrue (os.stat (files_list2[n - 1]).st_mtime <= os.stat (files_list2[n]).st_mtime)
def testRemoveError2(self): page1 = self.wikiroot["Страница 2"] page2 = self.wikiroot["Страница 2/Страница 3"] pagepath = page1.path attach2 = Attachment(page2) attachname = "add.png" attach2.attach([os.path.join("../test/samplefiles", attachname)]) with open(attach2.getFullPath("111.txt", True), "w"): try: page1.remove() except IOError: self.assertTrue(os.path.exists(pagepath)) self.assertNotEqual(self.wikiroot["Страница 2"], None) self.assertTrue( os.path.exists(self.wikiroot["Страница 2"].path) ) self.assertEqual(len(self.wikiroot), 3) self.assertNotEqual(self.wikiroot["Страница 2/Страница 3"], None) self.assertNotEqual( self.wikiroot["Страница 2/Страница 3/Страница 4"], None) else: self.assertEqual(self.wikiroot["Страница 2"], None) self.assertFalse(os.path.exists(pagepath))
def testMoveInvalid (self): """ А что, если кто-то блокирует папку с заметкой? """ page = self.wiki[u"Страница 1"] attachname = u"add.png" attach = Attachment (page) attach.attach ([os.path.join (u"../test/samplefiles", attachname)]) # Откроем на запись файл в папке с вложениями, чтобы нельзя было переместить папку with open (attach.getFullPath (u"lock.tmp", True), "w"): try: page.moveTo (self.wiki[u"Страница 2/Страница 3"]) except TreeException: # Если не удалось переместить страницу self.assertEqual (self.wiki[u"Страница 2/Страница 3/Страница 1"], None) self.assertNotEqual (self.wiki[u"Страница 1"], None) self.assertEqual (len (self.wiki[u"Страница 2/Страница 3"]), 1) self.assertTrue (os.path.exists (page.path)) self.assertFalse (os.path.exists (os.path.join (self.wiki[u"Страница 2/Страница 3"].path, u"Страница 1"))) self.assertTrue (os.path.exists (attach.getFullPath (attachname))) else: # А если страницу переместить удалось, то проверим, что она действительно перенеслась self.assertEqual (self.wiki[u"Страница 1"], None) self.assertTrue (os.path.exists (os.path.join (self.wiki[u"Страница 2/Страница 3"].path, u"Страница 1"))) self.assertEqual (len (self.wiki[u"Страница 2/Страница 3"]), 2) self.assertEqual (len (self.wiki), 3) self.assertEqual (self.wiki[u"Страница 2/Страница 3/Страница 1"].title, u"Страница 1") self.assertEqual (self.wiki[u"Страница 2/Страница 3/Страница 1/Страница 5"].title, u"Страница 5") self.assertEqual (self.wiki[u"Страница 2/Страница 3/Страница 1"].subpath, u"Страница 2/Страница 3/Страница 1") self.assertEqual (self.wiki[u"Страница 2/Страница 3/Страница 1/Страница 5"].subpath, u"Страница 2/Страница 3/Страница 1/Страница 5")
def _getGlobalVariables(self, selectedText, page): globals = { defines.VAR_DATE: datetime.now(), } if page is not None: attach = Attachment(page) attachList = VarList([fname for fname in sorted(attach.getAttachRelative()) if not fname.startswith(u'__')]) globals_page = { defines.VAR_SEL_TEXT: selectedText, defines.VAR_TITLE: page.display_title, defines.VAR_SUBPATH: page.subpath, defines.VAR_ATTACH: attach.getAttachPath(True), defines.VAR_FOLDER: page.path, defines.VAR_PAGE_ID: self._application.pageUidDepot.createUid(page), defines.VAR_DATE_CREATING: page.creationdatetime, defines.VAR_DATE_EDITIND: page.datetime, defines.VAR_TAGS: VarList(sorted(page.tags)), defines.VAR_PAGE_TYPE: page.getTypeString(), defines.VAR_CHILDLIST: VarList([subpage.title for subpage in page.children]), defines.VAR_ATTACHLIST: attachList, } globals.update(globals_page) return globals
def updateAttachments (self): """ Обновить список прикрепленных файлов """ self.__attachList.Freeze() self.__attachList.ClearAll() if Application.selectedPage is not None: files = Attachment (Application.selectedPage).attachmentFull files.sort(Attachment.sortByName, reverse=True) for fname in files: if not os.path.basename(fname).startswith("__") or not os.path.isdir (fname): # Отключим уведомления об ошибках во всплывающих окнах # иначе они появляются при попытке прочитать испорченные иконки # На результат работы это не сказывается, все-равно бракованные # иконки отлавливаются. wx.Log_EnableLogging(False) imageIndex = self.__fileIcons.getFileImage (fname) # Вернем всплывающие окна с ошибками wx.Log_EnableLogging(True) self.__attachList.InsertImageStringItem (0, os.path.basename (fname), imageIndex) self.__attachList.Thaw()
def testGetAttachRelative4 (self): attach = Attachment (self.page) attach.attach (self.fullFilesPath) attach_right = set ([u"attach.png", u"dir.xxx", u"subdir"]) attach_names = set (attach.getAttachRelative(u"dir")) self.assertEqual (attach_right, attach_names)
def testGetAttachRelative3 (self): attach = Attachment (self.page) attach.attach (self.fullFilesPath) attach_right = set (self.files) attach_names = set (attach.getAttachRelative()) self.assertEqual (attach_right, attach_names)
def testRemoveAttachDir1 (self): attach = Attachment (self.page) attach.attach (self.fullFilesPath) attach.removeAttach ([u"dir"]) self.assertEqual (len (attach.attachmentFull), len (self.fullFilesPath[1:]))
def _start_watch(self): if self._application.selectedPage is None: return self._watchedPage = self._application.selectedPage attach = Attachment(self._watchedPage) self._oldFilesList = attach.getAttachRelative() self._timer.Start(self._period)
def testAttach2 (self): Application.wikiroot = self.wikiroot Application.wikiroot.selectedPage = self.page attach = Attachment (self.page) attach.attach (self.fullFilesPath) self.assertEqual (self.wnd.attachPanel.panel.attachList.GetItemCount(), len (self.fullFilesPath))
def testAttach8 (self): # Не подключаем к Application созданную вики. Панель не должна реагировать на прикрепленные файлы self.wikiroot.selectedPage = self.page attach = Attachment (self.page) attach.attach (self.fullFilesPath) self.assertEqual (self.wnd.attachPanel.panel.attachList.GetItemCount(), 0)
def _fillAttaches (self): attach = Attachment (self._page) allFiles = attach.getAttachRelative() imagesFiles = [fname for fname in allFiles if isImage (fname)] imagesFiles.sort(Attachment.sortByName) self.attachFiles.Clear() self.attachFiles.AppendItems (imagesFiles)
def _loadAttachmentState(self): attach = Attachment(self._page) files = sorted(attach.getAttachRelative()) self._dialog.attachmentComboBox.Clear() self._dialog.attachmentComboBox.AppendItems(files) if len(files) > 0: self._dialog.attachmentComboBox.SetSelection(0)
def test_drop_several_attach(self): attach = Attachment(self.testpage) attach.attach(['../test/images/icon.png', '../test/images/first.png']) files = sorted(attach.attachmentFull) self.dropTarget.OnDropFiles(0, 0, files) expected_text = 'first.png icon.png' self.assertEqual(self.editor.GetText(), expected_text)
def testGetFullPath3 (self): attach = Attachment (self.page) fname = u"Имя файла.ext" path_full = attach.getFullPath (fname, create=True) path_right = os.path.join (attach.getAttachPath(), fname) self.assertTrue (os.path.exists (attach.getAttachPath())) self.assertEqual (path_full, path_right)
def testAttachBasename (self): attach = Attachment (self.page) attach.attach (self.fullFilesPath) self.assertEqual (len (attach.getAttachRelative()), len (self.files)) attachBasenames = attach.getAttachRelative() for fname in self.files: self.assertTrue (fname in attachBasenames, fname)
def testAttach6(self): attach = Attachment(self.page) attach.attach(self.fullFilesPath) self.application.wikiroot = self.wikiroot self.application.wikiroot.selectedPage = self.page self.assertEqual(self.mainWindow.attachPanel.panel.attachList.GetItemCount(), len(self.fullFilesPath)) self.application.wikiroot.selectedPage = None self.assertEqual(self.mainWindow.attachPanel.panel.attachList.GetItemCount(), 0)
def testAttach4 (self): attach = Attachment (self.page) attach.attach (self.fullFilesPath) Application.wikiroot = self.wikiroot Application.wikiroot.selectedPage = self.page self.assertEqual (self.wnd.attachPanel.panel.attachList.GetItemCount(), len (self.fullFilesPath)) Application.wikiroot.selectedPage = self.wikiroot[u"Страница 1"] self.assertEqual (self.wnd.attachPanel.panel.attachList.GetItemCount(), 0)
def testAttach1 (self): attach = Attachment (self.page) attach.attach (self.fullFilesPath) Application.wikiroot = self.wikiroot Application.wikiroot.selectedPage = self.page self.assertEqual (self.wnd.attachPanel.panel.attachList.GetItemCount(), len (self.fullFilesPath)) attach.removeAttach ([self.files[0]]) self.assertEqual (self.wnd.attachPanel.panel.attachList.GetItemCount(), len (self.fullFilesPath) - 1)
def test_drop_several_mixed(self): attach = Attachment(self.testpage) attach.attach(['../test/images/first.png']) files = (attach.attachmentFull + [os.path.abspath('../test/images/icon.png')]) self.dropTarget.OnDropFiles(0, 0, files) expected_text = ('first.png ' + os.path.abspath('../test/images/icon.png')) self.assertEqual(self.editor.GetText(), expected_text)
def _substituteAttach (self, paramText): attachPath = Attachment (self._page).getAttachPath (True) if attachPath.endswith (u'/') or attachPath.endswith (u'\\'): attachPath = attachPath[:-1] # Substitute %attach% result = paramText.replace (commandparams.MACROS_ATTACH, attachPath) # Substitute Attach: result = self._substituteAttachWiki (result) return result
def testAttachFull1(self): text = u"""Бла-бла-бла (:thumblist:) бла-бла-бла""" files = [u"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(u'<A HREF="__attach/first.jpg">' in result) self.assertTrue(u"__thumb" in result) self.assertTrue(u"_first.jpg" in result) self.assertTrue( os.path.exists( os.path.join(self.testPage.path, "__attach", "__thumb"))) self.assertTrue(u"<table" not in result)
def __onRemove(self, event): if self._application.selectedPage is not None: files = self.__getSelectedFiles() if len(files) == 0: MessageBox(_(u"You did not select a file to remove"), _(u"Error"), wx.OK | wx.ICON_ERROR) return if MessageBox(_(u"Remove selected files?"), _(u"Remove files?"), wx.YES_NO | wx.ICON_QUESTION) == wx.YES: try: Attachment(self._application.selectedPage).removeAttach(files) except IOError as e: MessageBox(str(e), _(u"Error"), wx.ICON_ERROR | wx.OK) self.updateAttachments()
def testAttach3(self): self.application.wikiroot = self.wikiroot self.application.wikiroot.selectedPage = self.page attach = Attachment(self.page) attach.attach(self.fullFilesPath[:1]) self.assertEqual( self.mainWindow.attachPanel.panel.attachList.GetItemCount(), 1) attach.attach(self.fullFilesPath[1:]) self.assertEqual( self.mainWindow.attachPanel.panel.attachList.GetItemCount(), len(self.fullFilesPath))
def testAttach1(self): attach = Attachment(self.page) attach.attach(self.fullFilesPath) self.application.wikiroot = self.wikiroot self.application.wikiroot.selectedPage = self.page self.assertEqual( self.mainWindow.attachPanel.panel.attachList.GetItemCount(), len(self.fullFilesPath)) attach.removeAttach([self.files[0]]) self.assertEqual( self.mainWindow.attachPanel.panel.attachList.GetItemCount(), len(self.fullFilesPath) - 1)
def testMoveInvalid(self): """ А что, если кто-то блокирует папку с заметкой? """ page = self.wiki[u"Страница 1"] attachname = u"add.png" attach = Attachment(page) attach.attach([os.path.join(u"../test/samplefiles", attachname)]) # Откроем на запись файл в папке с вложениями, чтобы нельзя было переместить папку with open(attach.getFullPath(u"lock.tmp", True), "w"): try: page.moveTo(self.wiki[u"Страница 2/Страница 3"]) except TreeException: # Если не удалось переместить страницу self.assertEqual( self.wiki[u"Страница 2/Страница 3/Страница 1"], None) self.assertNotEqual(self.wiki[u"Страница 1"], None) self.assertEqual(len(self.wiki[u"Страница 2/Страница 3"]), 1) self.assertTrue(os.path.exists(page.path)) self.assertFalse( os.path.exists( os.path.join(self.wiki[u"Страница 2/Страница 3"].path, u"Страница 1"))) self.assertTrue(os.path.exists(attach.getFullPath(attachname))) else: # А если страницу переместить удалось, то проверим, что она действительно перенеслась self.assertEqual(self.wiki[u"Страница 1"], None) self.assertTrue( os.path.exists( os.path.join(self.wiki[u"Страница 2/Страница 3"].path, u"Страница 1"))) self.assertEqual(len(self.wiki[u"Страница 2/Страница 3"]), 2) self.assertEqual(len(self.wiki), 3) self.assertEqual( self.wiki[u"Страница 2/Страница 3/Страница 1"].title, u"Страница 1") self.assertEqual( self.wiki[u"Страница 2/Страница 3/Страница 1/Страница 5"]. title, u"Страница 5") self.assertEqual( self.wiki[u"Страница 2/Страница 3/Страница 1"].subpath, u"Страница 2/Страница 3/Страница 1") self.assertEqual( self.wiki[u"Страница 2/Страница 3/Страница 1/Страница 5"]. subpath, u"Страница 2/Страница 3/Страница 1/Страница 5")
def testSortBySize (self): files = [u"add.png", u"Anchor.png", u"image2.png", u"image.png", u"add.png2", u"файл с пробелами.tmp", u"filename"] fullFilesPath = [os.path.join (u"../test/samplefiles/for_sort", fname) for fname in files] attach = Attachment (self.page) attach.attach (fullFilesPath) attach.attach ([os.path.join (u"../test/samplefiles", "dir")]) attach2 = Attachment (self.page) files_list = attach2.attachmentFull files_list.sort (Attachment.sortBySize) for n in range (1, len (files_list)): self.assertTrue (os.stat (files_list[n - 1]).st_size <= os.stat (files_list[n]).st_size)
def testThumbByWidthPng(self): images_dir = "testdata/images" fname_in = "outwiker_1.1.0_02.png" page = self.wikiroot["Страница 1"] Attachment(page).attach([os.path.join(images_dir, fname_in)]) newwidth = 250 newheight = 215 thumb_fname = self.thumbmaker.createThumbByWidth( page, fname_in, newwidth) thumb_path = os.path.join(page.path, thumb_fname) (width, height) = getImageSize(thumb_path) self.assertTrue(os.path.exists(thumb_path), thumb_path) self.assertEqual(width, newwidth) self.assertEqual(height, newheight)
def testInvalidCols3(self): text = u"""Бла-бла-бла (:thumblist cols=abyrvalg:) бла-бла-бла""" files = [u"first.jpg", u"image_01.JPG", u"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(u'<A HREF="__attach/first.jpg">' in result) self.assertTrue(u"__thumb" in result) self.assertTrue(u"_first.jpg" in result) self.assertTrue(u'<A HREF="__attach/image_01.JPG">' in result) self.assertTrue(u"_image_01.JPG" in result) self.assertFalse(u"html.txt" in result) self.assertTrue(u"<table" not in result)
def testRemoveAttachesEvent(self): attach = Attachment(self.page) attach.attach(self.fullFilesPath) Application.onPageUpdate += self.onPageUpdate attach.removeAttach([self.files[0]]) self.assertEqual(len(attach.attachmentFull), len(self.fullFilesPath) - 1) self.assertEqual(self.pageUpdateCount, 1) self.assertEqual(self.pageUpdateSender, self.page) attach.removeAttach([self.files[1], self.files[2]]) self.assertEqual(len(attach.attachmentFull), len(self.fullFilesPath) - 3) self.assertEqual(self.pageUpdateCount, 2) self.assertEqual(self.pageUpdateSender, self.page) Application.onPageUpdate -= self.onPageUpdate
def setUp(self): self.initApplication() self.wikiroot = self.createWiki() self._dialog = IncludeDialog(self.application.mainWindow) WikiPageFactory().create(self.wikiroot, "Викистраница", []) self.testedPage = self.wikiroot["Викистраница"] filesPath = "testdata/samplefiles/" self.files = [ "accept.png", "add.png", "anchor.png", "файл с пробелами.tmp", "dir" ] self.fullFilesPath = [ os.path.join(filesPath, fname) for fname in self.files ] Attachment(self.testedPage).attach(self.fullFilesPath) Tester.dialogTester.clear()
def __createWiki(self): # Здесь будет создаваться вики self.path = mkdtemp(prefix='Абырвалг абыр') self.wikiroot = WikiDocument.create(self.path) WikiPageFactory().create(self.wikiroot, "Страница 2", []) self.testPage = self.wikiroot["Страница 2"] files = [ "text_utf8.txt", "text_utf8.txt2", "image.gif", "текст_utf8.txt", "text_1251.txt", "html.txt", "html_1251.txt", "wiki.txt" ] fullFilesPath = [ os.path.join(self.filesPath, fname) for fname in files ] # Прикрепим к двум страницам файлы Attachment(self.testPage).attach(fullFilesPath)
def showDialog(self): filesList = list( filter(isImage, Attachment(self._page).getAttachRelative())) filesList.sort(key=lambda a: a.lower()) if (self._selectedText.startswith(u"Attach:") and self._selectedText[len(u"Attach:"):] in filesList): selectedFile = self._selectedText[len(u"Attach:"):] else: selectedFile = u"" dlg = self._createDialog(self._parent, filesList, selectedFile) resultDlg = dlg.ShowModal() self.result = self.__generateText(dlg) dlg.Destroy() return resultDlg
def testThumbByHeightJpeg(self): images_dir = "testdata/images" fname_in = "first.jpg" page = self.wikiroot["Страница 1"] Attachment(page).attach([os.path.join(images_dir, fname_in)]) newwidth = 249 newheight = 182 thumb_fname = self.thumbmaker.createThumbByHeight( page, fname_in, newheight) thumb_path = os.path.join(page.path, thumb_fname) (width, height) = getImageSize(thumb_path) self.assertTrue(os.path.exists(thumb_path), thumb_path) self.assertEqual(width, newwidth) self.assertEqual(height, newheight)
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 testSelectedAttach_wiki (self): Attachment (self._testpage).attach (self.files) parent = LinkDialog (self.wnd) Tester.dialogTester.appendOk() selectedString = u'Attach:add.png' controller = WikiLinkDialogController (Application, self._testpage, parent, selectedString) controller.showDialog() self.assertIn (u'Attach:accept.png', parent.linkText.GetItems()) self.assertIn (u'Attach:add.png', parent.linkText.GetItems()) self.assertIn (u'Attach:html.txt', parent.linkText.GetItems()) self.assertEqual (controller.link, u'Attach:add.png') self.assertEqual (controller.comment, u'Attach:add.png') self.assertEqual (controller.linkResult, u'[[Attach:add.png]]') self.assertEqual (parent.linkText.GetValue(), u'Attach:add.png')
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)
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 testHighlightFile9(self): """ Явное задание языка, не соответствующее расширению файла """ Attachment(self.testPage).attach( [os.path.join(self.samplefilesPath, "source_utf8.py")]) content = '(:source file="source_utf8.py" lang="text":)' 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('import os.path' 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("__correctSysPath()" 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 testThumbByMaxSizeJpeg2(self): images_dir = "testdata/images" fname_in = "first_vertical.jpeg" page = self.wikiroot["Страница 1"] Attachment(page).attach([os.path.join(images_dir, fname_in)]) maxsize = 250 newwidth = 182 newheight = 250 thumb_fname = self.thumbmaker.createThumbByMaxSize( page, fname_in, maxsize) thumb_path = os.path.join(page.path, thumb_fname) (width, height) = getImageSize(thumb_path) self.assertTrue(os.path.exists(thumb_path), thumb_path) self.assertEqual(width, newwidth) self.assertEqual(height, newheight)
def testRemoveAttaches1 (self): attach = Attachment (self.page) attach.attach (self.fullFilesPath) attach.removeAttach ([self.files[0]]) self.assertEqual (len (attach.attachmentFull), len (self.fullFilesPath[1:])) attachBasenames = [os.path.basename (path) for path in attach.attachmentFull] for path in self.fullFilesPath [1:]: self.assertTrue (os.path.basename (path) in attachBasenames, path) for path in attach.attachmentFull: self.assertTrue (os.path.exists (path))
def testReloading(self): attach = Attachment(self.page) attach.attach(self.fullFilesPath) self.wikiroot.selectedPage = self.page self.application.wikiroot = self.wikiroot self.assertEqual( self.mainWindow.attachPanel.panel.attachList.GetItemCount(), len(self.fullFilesPath)) # Создадим другую независимую вики newpath = mkdtemp(prefix='Абыр Абырвалг') newwikiroot = WikiDocument.create(newpath) TextPageFactory().create(newwikiroot, "Новая страница 1", []) TextPageFactory().create(newwikiroot, "Новая страница 2", []) filesPath = "testdata/samplefiles/" newfiles = ["accept.png", "add.png", "anchor.png"] newfullFilesPath = [ os.path.join(filesPath, fname) for fname in newfiles ] newattach = Attachment(newwikiroot["Новая страница 1"]) newattach.attach(newfullFilesPath) newwikiroot.selectedPage = newwikiroot["Новая страница 1"] self.application.wikiroot = newwikiroot self.assertEqual( self.mainWindow.attachPanel.panel.attachList.GetItemCount(), len(newfullFilesPath)) self.application.wikiroot.selectedPage = None self.application.wikiroot = None removeDir(newpath)
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 __createWiki(self): # Здесь будет создаваться вики self.path = mkdtemp(prefix='Абырвалг абыр') self.wikiroot = WikiDocument.create(self.path) factory = WikiPageFactory() factory.create(self.wikiroot, "Страница 2", []) factory.create(self.wikiroot["Страница 2"], "Страница3", []) factory.create(self.wikiroot["Страница 2"], "Страница 4", []) self.testPage = self.wikiroot["Страница 2"] files = ["accept.png", "add.png", "anchor.png", "filename.tmp", "файл с пробелами.tmp", "картинка с пробелами.png", "image.jpg", "image.jpeg", "image.png", "image.tif", "image.tiff", "image.gif", "image_01.JPG", "dir", "dir.xxx", "dir.png"] fullFilesPath = [ os.path.join( self.filesPath, fname) for fname in files] # Прикрепим к двум страницам файлы Attachment(self.testPage).attach(fullFilesPath)
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 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 _setDataSources(self, curvenames, page, content): """ Set data sources(StringSource or FileSource) for all curves """ for name in curvenames: curve = self._graph.getObject(name) assert curve is not None data = curve.getObject(defines.CURVE_DATA_OBJECT_NAME) assert data is not None colsep = data.getProperty(defines.DATA_COLUMNS_SEPARATOR_NAME, defines.DATA_COLUMNS_SEPARATOR_DEFAULT) try: skiprows = int( data.getProperty(defines.DATA_SKIP_ROWS_NAME, '0')) except ValueError: skiprows = 0 attachName = curve.getProperty(defines.CURVE_DATA_NAME, None) if attachName is None: data.setSource( StringSource(content.strip(), colsep=colsep, skiprows=skiprows)) else: # Remove prefix "Attach:" attachPrefix = u'Attach:' if attachName.startswith(attachPrefix): attachName = attachName[len(attachPrefix):] # Get full path to the attached file path = Attachment(page).getFullPath(attachName) data.setSource( FileSource(path, colsep=colsep, skiprows=skiprows))
def __createWiki(self): # Здесь будет создаваться вики self.filesPath = u"../test/samplefiles/" self.wikiroot = WikiDocument.create(self.path) WikiPageFactory().create(self.wikiroot, u"Страница 2", []) self.testPage = self.wikiroot[u"Страница 2"] files = [ u"accept.png", u"add.png", u"anchor.png", u"filename.tmp", u"файл с пробелами.tmp", u"картинка с пробелами.png", u"image.jpg", u"image.jpeg", u"image.png", u"image.tif", u"image.tiff", u"image.gif", u"image_01.JPG", u"dir", u"dir.xxx", u"dir.png" ] fullFilesPath = [ os.path.join(self.filesPath, fname) for fname in files ] # Прикрепим к двум страницам файлы Attachment(self.testPage).attach(fullFilesPath) factory = ParserFactory() self.parser = factory.make(self.testPage, Application.config)
def testEvent(self): self.pageUpdateCount = 0 Application.onAttachListChanged += self.onAttachListChanged attach = Attachment(self.page) # Прикрепим к двум страницам файлы attach.attach(self.fullFilesPath[: 2]) self.assertEqual(self.pageUpdateCount, 1) self.assertEqual(self.pageUpdateSender, self.page) attach.attach(self.fullFilesPath[2:]) self.assertEqual(self.pageUpdateCount, 2) self.assertEqual(self.pageUpdateSender, self.page) Application.onAttachListChanged -= self.onAttachListChanged
def testEvent (self): self.pageUpdateCount = 0 Application.onPageUpdate += self.onPageUpdate attach = Attachment (self.page) # Прикрепим к двум страницам файлы attach.attach (self.fullFilesPath [: 2]) self.assertEqual (self.pageUpdateCount, 1) self.assertEqual (self.pageUpdateSender, self.page) self.assertEqual (self.prev_kwargs['change'], PAGE_UPDATE_ATTACHMENT) attach.attach (self.fullFilesPath [2:]) self.assertEqual (self.pageUpdateCount, 2) self.assertEqual (self.pageUpdateSender, self.page) Application.onPageUpdate -= self.onPageUpdate