def runTest(self): for creator in self.creators: thumbdir = LocalFolder(self.create_tmp_dir(creator.__name__)) dir = self.SRC_DIR.folder('data/pixmaps') for i, basename in enumerate(dir.list_names()): if basename.endswith('.svg'): continue # fails on windows in some cases file = dir.file(basename) thumbfile = thumbdir.file('thumb--' + basename) self.assertFalse(thumbfile.exists()) pixbuf = creator(file, thumbfile, THUMB_SIZE_NORMAL) self.assertIsInstance(pixbuf, GdkPixbuf.Pixbuf) self.assertTrue(thumbfile.exists()) pixbuf = GdkPixbuf.Pixbuf.new_from_file(thumbfile.path) self.assertEqual(pixbuf.get_option('tEXt::Thumb::URI'), file.uri) self.assertTrue( pixbuf.get_option('tEXt::Thumb::URI').startswith( 'file:///')) # Specific requirement of spec to use file:/// and not file://localhost/ self.assertEqual(int(pixbuf.get_option('tEXt::Thumb::MTime')), int(file.mtime())) self.assertTrue(i > 3) thumbfile = thumbdir.file('thumb-test.txt') self.assertRaises(ThumbnailCreatorFailure, creator, self.SRC_DIR.file('README.txt'), thumbfile, THUMB_SIZE_NORMAL)
def testCreateThumbnail(self): manager = ThumbnailManager() dir = LocalFolder(self.create_tmp_dir()) file = dir.file('zim.png') self.SRC_DIR.file('data/zim.png').copyto(file) self.assertTrue(file.exists()) self.assertTrue(file.isimage()) self.removeThumbnail(manager, file) # Thumbfile does not exist thumbfile, pixbuf = manager.get_thumbnail(file, 64, create=False) self.assertEqual((thumbfile, pixbuf), (None, None)) thumbfile, pixbuf = manager.get_thumbnail(file, 64) self.assertTrue(thumbfile.exists()) self.assertIsInstance(pixbuf, GdkPixbuf.Pixbuf) thumbfile, pixbuf = manager.get_thumbnail(file, 64) self.assertTrue(thumbfile.exists()) self.assertIsInstance(pixbuf, GdkPixbuf.Pixbuf) if os.name != 'nt': # Windows support chmod() is limitted import stat mode = os.stat(thumbfile.path).st_mode self.assertEqual(stat.S_IMODE(mode), 0o600) mode = os.stat( thumbfile.parent().parent().path).st_mode # thumnails dir self.assertEqual(stat.S_IMODE(mode), 0o700) # Change mtime to make thumbfile invalid oldmtime = file.mtime() os.utime(file.path, None) self.assertNotEqual(file.mtime(), oldmtime) thumbfile, pixbuf = manager.get_thumbnail(file, 64, create=False) self.assertEqual((thumbfile, pixbuf), (None, None)) thumbfile, pixbuf = manager.get_thumbnail(file, 64) self.assertTrue(thumbfile.exists()) self.assertIsInstance(pixbuf, GdkPixbuf.Pixbuf) # ensure next call to get_thumbnail cannot call create_thumbnail manager.create_thumbnail = None thumbfile, pixbuf = manager.get_thumbnail(file, 64) self.assertTrue(thumbfile.exists()) self.assertIsInstance(pixbuf, GdkPixbuf.Pixbuf) # Test remove self.removeThumbnail(manager, file)
def _iswritable(dir): if os.name == 'nt': # Test access - (iswritable turns out to be unreliable for folders on windows..) if isinstance(dir, Dir): dir = LocalFolder(dir.path) # only newfs supports cleanup=False f = dir.file('.zim.tmp') try: f.write('Test') f.remove(cleanup=False) except: return False else: return True else: return dir.iswritable()
def export_attachments_iter(self, notebook, page): # XXX FIXME remove need for notebook here # XXX what to do with folders that do not map to a page ? source = notebook.get_attachments_dir(page) target = self.layout.attachments_dir(page) assert isinstance(target, Dir) target = LocalFolder(target.path) # XXX convert try: for file in source.list_files(): yield file targetfile = target.file(file.basename) if targetfile.exists(): targetfile.remove() # Export does overwrite by default file.copyto(targetfile) except FileNotFoundError: pass
def testQueue(self): queue = ThumbnailQueue() self.assertTrue(queue.queue_empty()) # Test input / output src_file = self.setUpFolder(mock=tests.MOCK_ALWAYS_REAL).file('test.txt') src_file.write('Test 123\n') queue.queue_thumbnail_request(src_file, 64) # put an error in the queue dir = LocalFolder(tests.ZIM_DATADIR).folder('pixmaps') pixmaps = set() for basename in dir.list_names(): if not basename.endswith('.svg'): file = dir.file(basename) pixmaps.add(file.path) queue.queue_thumbnail_request(file, 64) self.assertFalse(queue.queue_empty()) with tests.LoggingFilter('zim.plugins.attachmentbrowser', 'Exception'): queue.start() seen = set() i = len(pixmaps) while i > 0: i -= 1 file, size, thumbfile, pixbuf, mtime = queue.get_ready_thumbnail(block=True) seen.add(file.path) self.assertEqual(size, 64) self.assertTrue(thumbfile.exists()) self.assertIsInstance(pixbuf, GdkPixbuf.Pixbuf) self.assertEqual(mtime, file.mtime()) self.assertEqual(seen, pixmaps) # Test clear self.assertTrue(queue.queue_empty()) for path in pixmaps: file = LocalFile(path) queue.queue_thumbnail_request(file, 64) self.assertFalse(queue.queue_empty()) queue.start() time.sleep(0.1) queue.clear_queue() self.assertTrue(queue.queue_empty())
def adapt_from_oldfs(file): from zim.newfs import LocalFile, LocalFolder if isinstance(file, File): return LocalFile(file.path) elif isinstance(file, Dir): return LocalFolder(file.path) else: return file
def export_resources(self): dir = self.layout.resources_dir() # Copy icons -- TODO should we define default resources somewhere ? #~ for name in ('checked-box', 'unchecked-box', 'xchecked-box'): #~ icon = data_file('pixmaps/%s.png' % name) #~ file = dir.file(name + '.png') #~ icon.copyto(file) # Copy template resources (can overwrite icons) if self.template.resources_dir \ and self.template.resources_dir.exists(): if dir.exists(): # Export does overwrite by default dir.remove_children() dir.remove() resources = self.template.resources_dir if isinstance(resources, Dir): resources = LocalFolder(resources.path) resources.copyto(dir)
def testThumbnailFile(self): manager = ThumbnailManager() folder = LocalFolder(self.get_tmp_name('empty')) file = folder.file(u'./foo-\u00e8\u00e1\u00f1.png' ) # non-existing path with unicode name self.assertTrue('%C3%A8%C3%A1%C3%B1' in file.uri) # utf encoded! basename = hashlib.md5(file.uri).hexdigest() + '.png' for file, size, wanted in ( (file, 28, LOCAL_THUMB_STORAGE_NORMAL.file(basename)), (file, 64, LOCAL_THUMB_STORAGE_NORMAL.file(basename)), (file, 128, LOCAL_THUMB_STORAGE_NORMAL.file(basename)), (file, 200, LOCAL_THUMB_STORAGE_LARGE.file(basename)), (file, 500, LOCAL_THUMB_STORAGE_LARGE.file(basename)), ): thumbfile = manager.get_thumbnail_file(file, size) self.assertEqual(thumbfile, wanted) self.assertTrue(len(thumbfile.basename) == 32 + 4) # lenght hexdigest according to spec + ".png"
def runTest(self): # During application init it is important that changes in # environment take effect immediately iter = XDGConfigDirsIter() path = os_native_path('/non-existing/dir') zimdir = LocalFolder(path + '/zim') self.assertNotIn(zimdir, list(map(adapt_from_oldfs, iter))) with EnvironmentConfigContext({'XDG_CONFIG_HOME': path}): self.assertIn(zimdir, list(map(adapt_from_oldfs, iter)))
def testDumpWiki(self): attachment_dir = self.setUpFolder(mock=tests.MOCK_ALWAYS_REAL) LocalFolder(tests.ZIM_DATADIR).file('zim.png').copyto(attachment_dir.file('test.png')) notebook = self.setUpNotebook() notebook.get_attachments_dir = lambda *a: attachment_dir pageview = setUpPageView(notebook, text='{{./test.png?type=equation}}') pageview.textview.get_buffer().set_modified(True) tree = pageview.get_parsetree() text = WikiDumper().dump(tree) self.assertEquals(text, ['{{./test.png?type=equation}}\n'])
def setUp(self): folder = LocalFolder(XDG_DATA_HOME.subdir('zim/templates').path) assert 'tests/tmp' in folder.path.replace('\\', '/') if folder.exists(): folder.remove_children() for name, content in ( ('html/foo_test.html', 'Test 123\n'), ('html/bar_test.html', 'Test 123\n'), ): folder.file(name).write(content)
def testError(self): def creator_with_failure(*a): raise ThumbnailCreatorFailure def creator_with_error(*a): raise ValueError file = LocalFolder(tests.ZIM_DATADIR).file('zim.png') self.assertTrue(file.exists()) self.assertTrue(file.isimage()) for creator in creator_with_failure, creator_with_error: #~ print(">>", creator.__name__) queue = ThumbnailQueue(creator) queue.queue_thumbnail_request(file, 64) with tests.LoggingFilter('zim.plugins.attachmentbrowser', 'Exception'): queue.start() while not queue.queue_empty(): r = queue.get_ready_thumbnail() self.assertIsNone(r[0], None)
def __init__(self, dir, ext, namespace=None): '''Constructor @param dir: a L{Dir} object @param ext: the file extension to be used, e.g. 'html' @param namespace: optional namespace prefix to strip from page names ''' if isinstance(dir, OldDir): dir = LocalFolder(dir.path) self.dir = dir self.ext = ext self.namespace = namespace self.relative_root = self.dir
def build_notebook_exporter(dir, format, template, **opts): '''Returns an L{Exporter} that is suitable for exporting a whole notebook to a folder with one file per page ''' from zim.export.layouts import MultiFileLayout from zim.export.exporters.files import MultiFileExporter if isinstance(dir, Dir): dir = LocalFolder(dir.path) template = get_template(format, template) ext = get_format(format).info['extension'] layout = MultiFileLayout(dir, ext) return MultiFileExporter(layout, template, format, **opts)
def export_iter(self, pages): basename = encode_filename(pages.name) folder = LocalFolder(get_tmpdir().subdir('mhtml_export_tmp_dir').path) # XXX if folder.exists(): folder.remove_children() else: folder.touch() file = folder.file(basename + '.html') layout = SingleFileLayout(file, pages.prefix) exporter = SingleFileExporter(layout, self.template, 'html', document_root_url=self.document_root_url) for p in exporter.export_iter(pages): yield p encoder = MHTMLEncoder() linker = ExportLinker(pages.notebook, layout, output=file, usebase=True) self.file.write(encoder(layout, linker))
def setUpFolder(cls, name=None, mock=MOCK_DEFAULT_MOCK): '''Convenience method to create a temporary folder for testing Default use of "C{MOCK_DEFAULT_MOCK}" means that about 20% of the cases will use real filesystem at random while the rest will mock. (Thus giving a balance between overall test speed and the whish to detect cases where mock and real filesystem give different results.) This behavior is overruled by "--fast" and "--full" in the test script. @param name: basename for the folder, use class name if C{None} @param mock: mock level for this test, one of C{MOCK_ALWAYS_MOCK}, C{MOCK_DEFAULT_MOCK}, C{MOCK_DEFAULT_REAL} or C{MOCK_ALWAYS_REAL}. @returns: a L{Folder} object (either L{LocalFolder} or L{MockFolder}) that is guarenteed non-existing ''' path = cls._get_tmp_name(name) if mock == MOCK_ALWAYS_MOCK: use_mock = True elif mock == MOCK_ALWAYS_REAL: use_mock = False elif mock == MOCK_DEFAULT_REAL: if FAST_TEST: use_mock = True else: use_mock = False else: # MOCK_DEFAULT_MOCK: if FULL_TEST: use_mock = False elif FAST_TEST: use_mock = True elif random.random() < 0.2: logger.info("Random dice throw: use real file system") use_mock = False else: use_mock = True if use_mock: from zim.newfs.mock import MockFolder folder = MockFolder(path) else: from zim.newfs import LocalFolder if os.path.exists(path): logger.debug('Clear tmp folder: %s', path) shutil.rmtree(path) assert not os.path.exists(path) # make real sure folder = LocalFolder(path) assert not folder.exists() return folder
def setUp(self): folder = LocalFolder(XDG_DATA_HOME.subdir('zim/templates').path) assert 'tests/tmp' in folder.path.replace('\\', '/') if folder.exists(): folder.remove_children() for name, content in ( ('html/foo_test.html', 'Test 123\n'), ('html/bar_test.html', 'Test 123\n'), ): folder.file(name).write(content) manager = ApplicationManager() entry = manager.create('text/plain', 'test', 'test') manager.set_default_application('text/plain', entry)
def runTest(self): opener = tests.MockObject() iconview = FileBrowserIconView(opener) dir = LocalFolder(tests.ZIM_DATADIR).folder('pixmaps') iconview.set_folder(dir) # simulate idle events while not iconview._thumbnailer.queue_empty(): iconview._on_check_thumbnail_queue() # refresh while nothing changed iconview.refresh() while not iconview._thumbnailer.queue_empty(): iconview._on_check_thumbnail_queue() iconview.teardown_folder()
def new_from_dir(klass, dir): '''Constructor to create a notebook based on a specific file system location. Since the file system is an external resource, this method will return unique objects per location and keep (weak) references for re-use. @param dir: a L{Dir} object @returns: a L{Notebook} object ''' dir = adapt_from_newfs(dir) assert isinstance(dir, Dir) nb = _NOTEBOOK_CACHE.get(dir.uri) if nb: return nb from .index import Index from .layout import FilesLayout config = NotebookConfig(dir.file('notebook.zim')) if config['Notebook']['shared']: cache_dir = _cache_dir_for_dir(dir) else: cache_dir = dir.subdir('.zim') cache_dir.touch() if not (cache_dir.exists() and _iswritable(cache_dir)): cache_dir = _cache_dir_for_dir(dir) folder = LocalFolder(dir.path) if config['Notebook']['notebook_layout'] == 'files': layout = FilesLayout(folder, config['Notebook']['endofline'], config['Notebook']['default_file_format'], config['Notebook']['default_file_extension']) else: raise ValueError('Unkonwn notebook layout: %s' % config['Notebook']['notebook_layout']) cache_dir.touch() # must exist for index to work index = Index(cache_dir.file('index.db').path, layout) nb = klass(cache_dir, config, folder, layout, index) _NOTEBOOK_CACHE[dir.uri] = nb return nb
def runTest(self): '''Test config environment setup of test''' zim.config.log_basedirs() for k, v in (('XDG_DATA_HOME', os.path.join(tests.TMPDIR, 'data_home')), ('XDG_CONFIG_HOME', os.path.join(tests.TMPDIR, 'config_home')), ('XDG_CACHE_HOME', os.path.join(tests.TMPDIR, 'cache_home'))): self.assertEqual(adapt_from_oldfs(getattr(zim.config, k)), LocalFolder(v)) for k, v in ( #~ ('XDG_DATA_DIRS', os.path.join(tests.TMPDIR, 'data_dir')), ('XDG_CONFIG_DIRS', os.path.join(tests.TMPDIR, 'config_dir')), ): self.assertEqual( list(map(adapt_from_oldfs, getattr(zim.config, k))), list(map(LocalFolder, v.split(os.pathsep))))
def testEditObjectDialog(self): attachment_dir = self.setUpFolder(mock=tests.MOCK_ALWAYS_REAL) LocalFolder(tests.ZIM_DATADIR).file('zim.png').copyto(attachment_dir.file('test.png')) notebook = self.setUpNotebook() notebook.get_attachments_dir = lambda *a: attachment_dir pageview = setUpPageView(notebook, text='{{./test.png?type=equation}}') def edit_dialog(dialog): self.assertIsInstance(dialog, ImageGeneratorDialog) dialog.set_text(r'c = \sqrt{ a^2 + b^2 }') dialog.update_image() dialog.assert_response_ok() with tests.DialogContext(edit_dialog): pageview.edit_object() self.assertEquals(attachment_dir.file('test.tex').read(), r'c = \sqrt{ a^2 + b^2 }') assertIsPNG(attachment_dir.file('test.png'))
def setUpFolder(self, name=None, mock=MOCK_DEFAULT_MOCK): '''Convenience method to create a temporary folder for testing @param name: basename for the folder, uses test name if C{None} @param mock: mock level for this test, one of C{MOCK_ALWAYS_MOCK}, C{MOCK_DEFAULT_MOCK}, C{MOCK_DEFAULT_REAL} or C{MOCK_ALWAYS_REAL}. The C{MOCK_ALWAYS_*} arguments force the use of a real folder or a mock object. The C{MOCK_DEFAULT_*} arguments give a preference but for these the behavior is overruled by "--fast" and "--full" in the test script. @returns: a L{Folder} object (either L{LocalFolder} or L{MockFolder}) that is guarenteed non-existing ''' if name is None and self._testMethodName != 'runTest': name = self._testMethodName path = self._get_tmp_name(name) if mock == MOCK_ALWAYS_MOCK: use_mock = True elif mock == MOCK_ALWAYS_REAL: use_mock = False else: if FULL_TEST: use_mock = False elif FAST_TEST: use_mock = True else: use_mock = (mock == MOCK_DEFAULT_MOCK) if use_mock: from zim.newfs.mock import MockFolder folder = MockFolder(path) else: from zim.newfs import LocalFolder if os.path.exists(path): logger.debug('Clear tmp folder: %s', path) shutil.rmtree(path) assert not os.path.exists(path) # make real sure folder = LocalFolder(path) assert not folder.exists() return folder
def new_from_dir(klass, dir): '''Constructor to create a notebook based on a specific file system location. Since the file system is an external resource, this method will return unique objects per location and keep (weak) references for re-use. @param dir: a L{Dir} object @returns: a L{Notebook} object ''' assert isinstance(dir, Dir) nb = _NOTEBOOK_CACHE.get(dir.uri) if nb: return nb from .index import Index from .layout import FilesLayout config = NotebookConfig(dir.file('notebook.zim')) endofline = config['Notebook']['endofline'] shared = config['Notebook']['shared'] subdir = dir.subdir('.zim') if not shared: subdir.touch() if not shared and subdir.exists() and _iswritable(subdir): cache_dir = subdir else: cache_dir = _cache_dir_for_dir(dir) folder = LocalFolder(dir.path) layout = FilesLayout(folder, endofline) cache_dir.touch() # must exist for index to work index = Index(cache_dir.file('index.db').path, layout) nb = klass(cache_dir, config, folder, layout, index) _NOTEBOOK_CACHE[dir.uri] = nb return nb
def testDefaults(self): '''Test default basedir paths''' with EnvironmentConfigContext({ 'XDG_DATA_HOME': None, 'XDG_DATA_DIRS': ' ', 'XDG_CONFIG_HOME': None, 'XDG_CONFIG_DIRS': '', 'XDG_CACHE_HOME': None, }): for k, v in (('XDG_DATA_HOME', '~/.local/share'), ('XDG_CONFIG_HOME', '~/.config'), ('XDG_CACHE_HOME', '~/.cache')): self.assertEqual( adapt_from_oldfs(getattr(zim.config.basedirs, k)), LocalFolder(v)) for k, v in ( ('XDG_DATA_DIRS', '/usr/share:/usr/local/share'), ('XDG_CONFIG_DIRS', '/etc/xdg'), ): self.assertEqual( list(map(adapt_from_oldfs, getattr(zim.config.basedirs, k))), list(map(LocalFolder, v.split(':'))))
def testDetectVCS(self): root = LocalFolder(self.create_tmp_dir()) root.folder('.bzr').touch() self.assertEqual(VCS._detect_in_folder(root), ('bzr', root)) folder = root.folder('Foo/Bar') folder.touch() self.assertEqual(VCS._detect_in_folder(folder), ('bzr', root)) subroot = root.folder('subroot') subroot.folder('.git').touch() self.assertEqual(VCS._detect_in_folder(subroot), ('git', subroot)) folder = subroot.folder('Foo/Bar') folder.touch() self.assertEqual(VCS._detect_in_folder(folder), ('git', subroot)) subroot = root.folder('subfold') subroot.file('.fslckout').touch() self.assertEqual(VCS._detect_in_folder(subroot), ('fossil', subroot)) folder = subroot.folder('Foo/Bar') folder.touch() self.assertEqual(VCS._detect_in_folder(folder), ('fossil', subroot))
def relative_filepath(self, file, path=None): '''Get a file path relative to the notebook or page Intended as the counter part of L{resolve_file()}. Typically this function is used to present the user with readable paths or to shorten the paths inserted in the wiki code. It is advised to use file URIs for links that can not be made relative with this method. The link can be relative: - to the I{document root} (link will start with "/") - the attachments dir (if a C{path} is given) or the notebook (links starting with "./" or "../") - or the users home dir (link like "~/user/") Relative file paths are always given with Unix path semantics (so "/" even on windows). But a leading "/" does not mean the path is absolute, but rather that it is relative to the X{document root}. @param file: L{File} object we want to link @keyword path: L{Path} object for the page where we want to link this file @returns: relative file path as string, or C{None} when no relative path was found ''' from zim.newfs import LocalFile, LocalFolder file = LocalFile(file.path) # XXX notebook_root = self.layout.root document_root = LocalFolder(self.document_root.path) if self.document_root else None# XXX rootdir = '/' mydir = '.' + SEP updir = '..' + SEP # Look within the notebook if path: attachments_dir = self.get_attachments_dir(path) if file.ischild(attachments_dir): return mydir + file.relpath(attachments_dir) elif document_root and notebook_root \ and document_root.ischild(notebook_root) \ and file.ischild(document_root) \ and not attachments_dir.ischild(document_root): # special case when document root is below notebook root # the case where document_root == attachment_folder is # already caught by above if clause return rootdir + file.relpath(document_root) elif notebook_root \ and file.ischild(notebook_root) \ and attachments_dir.ischild(notebook_root): parent = file.commonparent(attachments_dir) uppath = attachments_dir.relpath(parent) downpath = file.relpath(parent) up = 1 + uppath.replace('\\', '/').count('/') return updir * up + downpath else: if document_root and notebook_root \ and document_root.ischild(notebook_root) \ and file.ischild(document_root): # special case when document root is below notebook root return rootdir + file.relpath(document_root) elif notebook_root and file.ischild(notebook_root): return mydir + file.relpath(notebook_root) # If that fails look for global folders if document_root and file.ischild(document_root): return rootdir + file.relpath(document_root) # Finally check HOME or give up path = file.userpath return path if path.startswith('~') else None
logger = logging.getLogger('zim.plugins.attachmentbrowser') import zim from zim.config import XDG_CACHE_HOME from zim.gui.widgets import rotate_pixbuf from zim.newfs import LocalFile, LocalFolder LOCAL_THUMB_STORAGE_NORMAL = XDG_CACHE_HOME.subdir('thumbnails/normal') LOCAL_THUMB_STORAGE_LARGE = XDG_CACHE_HOME.subdir('thumbnails/large') LOCAL_THUMB_STORAGE_FAIL = XDG_CACHE_HOME.subdir('thumbnails/fail/zim-%s' % zim.__version__) ## XXX zim.fs --> zim.newfs LOCAL_THUMB_STORAGE_NORMAL = LocalFolder(LOCAL_THUMB_STORAGE_NORMAL.path) LOCAL_THUMB_STORAGE_LARGE = LocalFolder(LOCAL_THUMB_STORAGE_LARGE.path) LOCAL_THUMB_STORAGE_FAIL = LocalFolder(LOCAL_THUMB_STORAGE_FAIL.path) ## THUMB_SIZE_NORMAL = 128 THUMB_SIZE_LARGE = 256 class ThumbnailCreatorFailure(ValueError): pass from zim.newfs.local import _replace_file as _atomic_rename
def runTest(self): plugin = VersionControlPlugin() dir = get_tmp_dir('versioncontrol_TestMainWindowExtension') notebook = self.setUpNotebook(mock=tests.MOCK_ALWAYS_REAL, content=('Test', ), folder=LocalFolder(dir.path)) mainwindow = setUpMainWindow(notebook) plugin.extend(notebook) plugin.extend(mainwindow) notebook_ext = find_extension(notebook, NotebookExtension) window_ext = find_extension(mainwindow, VersionControlMainWindowExtension) op = ongoing_operation(notebook) assert op is None # check no opperation ongoing ## init & save version self.assertIsNone(notebook_ext.vcs) def init(dialog): self.assertIsInstance(dialog, VersionControlInitDialog) choice = dialog.combobox.get_active_text() self.assertTrue(choice and not choice.isspace()) dialog.answer_yes() with tests.DialogContext(init, SaveVersionDialog): window_ext.save_version() self.assertIsNotNone(notebook_ext.vcs) self.assertFalse(notebook_ext.vcs.is_modified()) ## save version again page = notebook.get_page(Path('Foo')) page.parse('wiki', 'foo!') notebook.store_page(page) self.assertTrue(notebook_ext.vcs.is_modified()) with tests.DialogContext(SaveVersionDialog): window_ext.save_version() self.assertFalse(notebook_ext.vcs.is_modified()) ## show versions with tests.DialogContext(VersionsDialog): window_ext.show_versions() ## auto-save plugin.preferences['autosave'] = True page = notebook.get_page(Path('Fooooo')) page.parse('wiki', 'foo!') notebook.store_page(page) self.assertTrue(notebook_ext.vcs.is_modified()) mainwindow.emit('close') self.assertFalse(notebook_ext.vcs.is_modified()) tests.gtk_process_events() assert ongoing_operation(notebook) is None
def get_tmp_dir(name): if 'REAL_TMP' in os.environ: # Set in tests/__init__.py dir = LocalFolder(os.environ['REAL_TMP']) else: dir = LocalFolder(tempfile.gettempdir()) #~ print("TMPDIR:", dir) dir = dir.folder('test_versioncontrol').folder(name) if dir.exists(): dir.remove_children() dir.remove() assert not dir.exists() dir.touch() return dir
def open_folder(args): got = LocalFolder(args[-1]) want = LocalFolder(XDG_DATA_HOME.subdir('zim/templates').path) self.assertEqual(got, want)