Exemplo n.º 1
0
    def runTest(self):
        # First test some paths
        for input, uri in (
            ('file:///foo/bar', 'file:///foo/bar'),
            ('~/bar', Dir('~/bar').uri),
        ):
            if os.name == 'nt':
                input = input.replace('///', '///C:/')
                if not '///C:/' in uri:
                    uri = uri.replace('///', '///C:/')
            info = resolve_notebook(input)
            self.assertEqual(info.uri, uri)

        # Then test with (empty) notebook list
        info = resolve_notebook('foobar')
        self.assertIsNone(info)

        # add an entry and show we get it
        dir = Dir(self.create_tmp_dir()).subdir('foo')
        init_notebook(dir, name='foo')

        list = get_notebook_list()
        list.append(NotebookInfo(dir.uri, name='foo'))
        list.write()

        info = resolve_notebook('foo')
        self.assertIsNotNone(info)
        self.assertEqual(info.uri, dir.uri)
Exemplo n.º 2
0
	def runTest(self):
		for creator in self.creators:
			thumbdir = Dir(self.create_tmp_dir(creator.__name__))

			dir = Dir('./data/pixmaps')
			for i, basename in enumerate(dir.list()):
				file = dir.file(basename)
				thumbfile = thumbdir.file('thumb--' + basename)

				self.assertFalse(thumbfile.exists())
				pixbuf = creator(file, thumbfile, THUMB_SIZE_NORMAL)
				self.assertIsInstance(pixbuf, gtk.gdk.Pixbuf)
				self.assertTrue(thumbfile.exists())

				pixbuf = gtk.gdk.pixbuf_new_from_file(thumbfile.encodedpath)
				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, File('./README.txt'), thumbfile, THUMB_SIZE_NORMAL
			)
Exemplo n.º 3
0
    def parse_options(self, *args):
        self.opts['option'] = []  # allow list

        if all(not a.startswith('-') for a in args):
            # Backward compartibility for options not prefixed by "--"
            # used "=" as separator for values
            # template options came as "option:KEY=VALUE"
            for arg in args:
                if arg.startswith('option:'):
                    self.opts['option'].append(arg[7:])
                elif arg == 'help':
                    self.opts['help'] = True
                else:
                    key, value = arg.split('=', 1)
                    self.opts[key] = value
        else:
            GtkCommand.parse_options(self, *args)

        self.template_options = {}
        for arg in self.opts['option']:
            key, value = arg.split('=', 1)
            self.template_options[key] = value

        if 'append' in self.opts:
            self.opts['append'] = \
             self.opts['append'].lower() == 'true'

        if self.opts.get('attachments', None):
            if isabs(self.opts['attachments']):
                self.opts['attachments'] = Dir(self.opts['attachments'])
            else:
                self.opts['attachments'] = Dir(
                    (self.pwd, self.opts['attachments']))
Exemplo n.º 4
0
    def testUIInterface(self):
        # test ui.new_page_from_text()

        name = 'foo:new page quicknote'
        text = '''\
======= New Page =======
Test 1 2 3

attachment {{./zim16.png}}
'''
        wanted = '''\
<?xml version='1.0' encoding='utf-8'?>
<zim-tree><h level="1">New Page</h>
<p>Test 1 2 3
</p>
<p>attachment <img src="./zim16.png" />
</p></zim-tree>'''

        dirname = self.create_tmp_dir(name='import_source')
        File('./icons/zim16.png').copyto(Dir(dirname))

        ui = setupGtkInterface(self)
        path = ui.new_page_from_text(text, name, attachments=dirname)
        page = ui.notebook.get_page(path)
        attachments = ui.notebook.get_attachments_dir(path)

        self.assertEqual(page.get_parsetree().tostring(), wanted)
        self.assertIn('zim16.png', Dir(attachments.path).list())
Exemplo n.º 5
0
    def testPropertiesDialog(self):
        '''Test PropertiesDialog'''
        from zim.gui.propertiesdialog import PropertiesDialog
        self.ui.readonly = True
        dialog = PropertiesDialog(self.ui)
        dialog.assert_response_ok()

        from zim.config import INIConfigFile
        notebook = self.ui.notebook
        file = notebook.dir.file('notebook.zim')
        notebook.config = NotebookConfig(file)
        self.ui.readonly = False

        config1 = {
            'name': 'Notebook Foo',
            'interwiki': None,
            'home': Path('Home'),
            'icon': './icon.png',
            'document_root': File('/foo').path,  # win32 save test
            'shared': False,
            'profile': None,
        }
        config2 = {
            'name': 'Notebook Bar',
            'interwiki': 'FooBar',
            'home': Path('HomeSweetHome'),
            'icon': './picture.png',
            'document_root': File('/bar').path,  # win32 save test
            'shared': True,
            'profile': 'foo',
        }
        notebook.save_properties(**config1)
        for key in config1:
            self.assertEqual(notebook.config['Notebook'][key], config1[key])

        dialog = PropertiesDialog(self.ui)
        dialog.assert_response_ok()

        for key in config1:
            self.assertEqual(notebook.config['Notebook'][key], config1[key])
        self.assertEqual(notebook.name, config1['name'])
        self.assertEqual(notebook.get_home_page(), config1['home'])
        self.assertEqual(notebook.icon,
                         notebook.dir.file(config1['icon']).path)
        self.assertEqual(notebook.document_root, Dir(config1['document_root']))

        dialog = PropertiesDialog(self.ui)
        dialog.form.update(config2)
        dialog.assert_response_ok()

        for key in config1:
            self.assertEqual(notebook.config['Notebook'][key], config2[key])
        self.assertEqual(notebook.name, config2['name'])
        self.assertEqual(notebook.get_home_page(), config2['home'])
        self.assertEqual(notebook.icon,
                         notebook.dir.file(config2['icon']).path)
        self.assertEqual(notebook.document_root, Dir(config2['document_root']))
Exemplo n.º 6
0
    def runTest(self):
        '''Test FileEntry widget'''
        from zim.fs import adapt_from_newfs, Dir
        dir = Dir(self.notebook.folder)  # XXX

        path = Path('Foo:Bar')
        entry = self.entry
        entry.set_use_relative_paths(self.notebook, path)

        home = Dir('~')
        for file, text in (
            (home.file('zim-test.txt'), '~/zim-test.txt'),
            (dir.file('Foo/Bar/test.txt'), './test.txt'),
            (File('/test.txt'), File('/test.txt').path),  # win32 save
        ):
            entry.set_file(file)
            self.assertEqual(entry.get_text(), os_native_path(text))
            self.assertEqual(entry.get_file(), file)

        self.notebook.config['Notebook'][
            'document_root'] = './notebook_document_root'
        doc_root = self.notebook.document_root
        self.assertEqual(doc_root, dir.subdir('notebook_document_root'))

        for file, text in (
            (home.file('zim-test.txt'), os_native_path('~/zim-test.txt')),
            (dir.file('Foo/Bar/test.txt'), os_native_path('./test.txt')),
            (File('/test.txt'), File('/test.txt').uri),  # win32 save
            (doc_root.file('test.txt'), '/test.txt'),
        ):
            entry.set_file(file)
            self.assertEqual(entry.get_text(), text)
            self.assertEqual(entry.get_file(), file)

        entry.set_use_relative_paths(self.notebook, None)

        for file, text in (
            (home.file('zim-test.txt'), os_native_path('~/zim-test.txt')),
            (dir.file('Foo/Bar/test.txt'),
             os_native_path('./Foo/Bar/test.txt')),
            (File('/test.txt'), File('/test.txt').uri),  # win32 save
            (doc_root.file('test.txt'), '/test.txt'),
        ):
            entry.set_file(file)
            self.assertEqual(entry.get_text(), text)
            self.assertEqual(entry.get_file(), file)

        entry.set_use_relative_paths(notebook=None)

        for file, text in (
            (home.file('zim-test.txt'), '~/zim-test.txt'),
                #~ (dir.file('Foo/Bar/test.txt'), './test.txt'),
            (File('/test.txt'), File('/test.txt').path),  # win32 save
        ):
            entry.set_file(file)
            self.assertEqual(entry.get_text(), text)
            self.assertEqual(entry.get_file(), file)
Exemplo n.º 7
0
	def testHomeAndUser(self):
		user = environ.get('USER')
		self.assertIsNotNone(user)

		home = environ.get('HOME')
		self.assertIsNotNone(home)
		self.assertTrue(Dir(home).exists())

		if os.name == 'nt':
			appdata = environ.get('APPDATA')
			self.assertIsNotNone(appdata)
			self.assertTrue(Dir(appdata).exists())
Exemplo n.º 8
0
    def resolve_file(self, filename, path=None):
        '''Resolve a file or directory path relative to a page or
		Notebook

		This method is intended to lookup file links found in pages and
		turn resolve the absolute path of those files.

		File URIs and paths that start with '~/' or '~user/' are
		considered absolute paths. Also windows path names like
		'C:\\user' are recognized as absolute paths.

		Paths that starts with a '/' are taken relative to the
		to the I{document root} - this can e.g. be a parent directory
		of the notebook. Defaults to the filesystem root when no document
		root is set. (So can be relative or absolute depending on the
		notebook settings.)

		Paths starting with any other character are considered
		attachments. If C{path} is given they are resolved relative to
		the I{attachment folder} of that page, otherwise they are
		resolved relative to the I{notebook folder} - if any.

		The file is resolved purely based on the path, it does not have
		to exist at all.

		@param filename: the (relative) file path or uri as string
		@param path: a L{Path} object for the page
		@returns: a L{File} object.
		'''
        assert isinstance(filename, str)
        filename = filename.replace('\\', '/')
        if filename.startswith('~') or filename.startswith('file:/'):
            return File(filename)
        elif filename.startswith('/'):
            dir = self.document_root or Dir('/')
            return dir.file(filename)
        elif is_win32_path_re.match(filename):
            if not filename.startswith('/'):
                filename = '/' + filename
                # make absolute on Unix
            return File(filename)
        else:
            if path:
                dir = self.get_attachments_dir(path)
                return File(
                    (dir.path, filename)
                )  # XXX LocalDir --> File -- will need get_abspath to resolve
            else:
                dir = Dir(self.layout.root.path)  # XXX
                return File((dir, filename))
Exemplo n.º 9
0
def get_tmp_dir(name):
    if 'REAL_TMP' in os.environ:  # Set in tests/__init__.py
        dir = Dir(os.environ['REAL_TMP'])
    else:
        dir = Dir(tempfile.gettempdir())
    #~ print "TMPDIR:", dir

    dir = dir.subdir('test_versioncontrol').subdir(name)
    if dir.exists():
        dir.remove_children()
        dir.remove()
    assert not dir.exists()

    return dir
Exemplo n.º 10
0
 def do_add_notebook(self, *a):
     fields = AddNotebookDialog(self).run()
     if fields:
         dir = Dir(fields['folder'])
         init_notebook(dir, name=fields['name'])
         model = self.treeview.get_model()
         model.append_notebook(dir.uri, name=fields['name'])
Exemplo n.º 11
0
    def setUp(self):
        self.tmpdir = Dir(self.get_tmp_name())
        self.notebookdir = self.tmpdir.subdir('notebook')

        script = self.tmpdir.file('mount.py')
        script.write('''\
import os
import sys
notebook = sys.argv[1]
os.mkdir(notebook)
os.mkdir(notebook + '/foo')
for path in (
	notebook + "/notebook.zim",
	notebook + "/foo/bar.txt"
):
	fh = open(path, 'w')
	fh.write("")
	fh.close()
''')

        automount = XDG_CONFIG_HOME.file('zim/automount.conf')
        assert not automount.exists(), "Exists: %s" % automount
        automount.write('''\
[Path %s]
mount=%s %s
''' % (self.notebookdir.path, script.path, self.notebookdir.path))
Exemplo n.º 12
0
	def runTest(self):
		'''Test if included notebooks are up to date'''
		from zim.fs import Dir
		from zim.notebook import Notebook
		for path in ('data/manual', 'HACKING'):
			notebook = Notebook(dir=Dir(path))
			self.assertTrue(not notebook.needs_upgrade)
Exemplo n.º 13
0
    def runTest(self):
        '''Test proper linking of files in export'''
        notebook = tests.new_notebook(fakedir='/source/dir/')

        linker = StaticLinker('html', notebook)
        linker.set_usebase(True)  # normally set by html format module
        linker.set_path(Path('foo:bar'))  # normally set by exporter
        linker.set_base(Dir('/source/dir/foo'))  # normally set by exporter

        self.assertEqual(linker.link_page('+dus'), './bar/dus.html')
        self.assertEqual(linker.link_page('dus'), './dus.html')
        self.assertEqual(linker.link_file('./dus.pdf'), './bar/dus.pdf')
        self.assertEqual(linker.link_file('../dus.pdf'), './dus.pdf')
        self.assertEqual(linker.link_file('../../dus.pdf'), '../dus.pdf')

        ## setup environment for interwiki link
        if os.name == 'nt':
            uri = 'file:///C:/foo'
        else:
            uri = 'file:///foo'

        list = get_notebook_list()
        list.append(NotebookInfo(uri, interwiki='foo'))
        list.write()
        ##

        href = interwiki_link('foo?Ideas:Task List')
        self.assertIsNotNone(href)
        self.assertEqual(linker.link('foo?Ideas:Task List'),
                         uri + '/Ideas/Task_List.txt')
Exemplo n.º 14
0
def new_files_notebook(dir):
    '''Returns a new Notebook object with a file store

	Uses data from L{WikiTestData}

	@param path: a folder path, e.g. created by L{TestCase.create_tmp_dir()}
	'''
    from zim.fs import Dir
    from zim.notebook import init_notebook, Notebook, Path
    from zim.index import Index

    dir = Dir(dir)
    init_notebook(dir)
    notebook = Notebook(dir=dir)
    store = notebook.get_store(':')
    manifest = []
    for name, text in WikiTestData:
        manifest.append(name)
        page = store.get_page(Path(name))
        page.parse('wiki', text)
        store.store_page(page)
    notebook.testdata_manifest = _expand_manifest(manifest)
    notebook.index.update()

    return notebook
Exemplo n.º 15
0
def new_notebook(fakedir=None):
    '''Returns a new Notebook object with all data in memory

	Uses data from L{WikiTestData}

	@param fakedir: optional parameter to set the 'dir' attribute for
	the notebook and the main store which allows you to resolve file
	paths etc. It will not automatically touch the dir
	(hence it being 'fake').
	'''
    from zim.fs import Dir
    from zim.notebook import Notebook, Path
    from zim.index import Index

    notebook = Notebook(index=Index(dbfile=':memory:'))
    store = notebook.add_store(Path(':'), 'memory')
    manifest = []
    for name, text in WikiTestData:
        manifest.append(name)
        store.set_node(Path(name), text)
    notebook.testdata_manifest = _expand_manifest(manifest)
    notebook.index.update()

    if fakedir:
        dir = Dir(fakedir)
        notebook.dir = dir
        store.dir = dir

    return notebook
Exemplo n.º 16
0
    def runTest(self):
        from zim.gui.mainwindow import MainWindow

        ## Without argument should prompt
        def testAddNotebookDialog(dialog):
            self.assertIn(dialog.__class__.__name__,
                          ('AddNotebookDialog', 'NotebookDialog'))

        cmd = GuiCommand('gui')
        with tests.DialogContext(testAddNotebookDialog):
            cmd.run(
            )  # Exits without running due to no notebook given in dialog

        ### Try again with argument
        dir = self.create_tmp_dir()
        cmd = GuiCommand('gui')
        cmd.parse_options(dir)
        with tests.WindowContext(MainWindow):
            with tests.LoggingFilter('zim', 'Exception while loading plugin:'):
                window = cmd.run()
                self.addCleanup(window.destroy)

        self.assertEqual(window.__class__.__name__, 'MainWindow')
        self.assertEqual(window.notebook.uri, Dir(dir).uri)  # XXX
        self.assertGreaterEqual(
            len(ConfigManager.preferences['General']['plugins']), 3)
        self.assertGreaterEqual(len(window.pageview.__zim_extension_objects__),
                                3)

        with tests.WindowContext(MainWindow):
            window2 = cmd.run()
        self.assertIs(window2, window)
Exemplo n.º 17
0
def list_plugins():
	'''List available plugin module names

	@returns: a set of available plugin names that can be loaded
	using L{get_plugin_class()}.
	'''
	# Only listing folders in __path__ because this parameter determines
	# what folders will considered when importing sub-modules of the
	# this package once this module is loaded.

	plugins = set()

	for dir in __path__:
		dir = Dir(dir)
		for candidate in dir.list(): # returns [] if dir does not exist
			if candidate.startswith('_') or candidate == 'base':
				continue
			elif candidate.endswith('.py'):
				#~ print '>> FOUND %s.py in %s' % (candidate, dir.path)
				plugins.add(candidate[:-3])
			elif zim.fs.isdir(dir.path+'/'+candidate) \
			and os.path.exists(dir.path+'/'+candidate+'/__init__.py'):
				#~ print '>> FOUND %s/__init__.py in %s' % (candidate, dir.path)
				plugins.add(candidate)
			else:
				pass

	return sorted(plugins)
Exemplo n.º 18
0
	def update(self):
		'''Check if info is still up to date and update this object

		This method will check the X{notebook.zim} file for notebook
		folders and read it if it changed. It uses the C{mtime}
		attribute to keep track of changes.

		@returns: C{True} when data was updated, C{False} otherwise
		'''
		# TODO support for paths that turn out to be files
		dir = Dir(self.uri)
		file = dir.file('notebook.zim')
		if file.exists() and file.mtime() != self.mtime:
			config = NotebookConfig(file)
			section = config['Notebook']

			self.name = section['name']
			self.interwiki = section['interwiki']
			self.icon_path = section['icon']
			icon, document_root = _resolve_relative_config(dir, section)
			if icon:
				self.icon = icon.uri
			else:
				self.icon = None

			self.mtime = file.mtime()
			return True
		else:
			return False
Exemplo n.º 19
0
    def runTest(self):
        dir = Dir(self.get_tmp_name())
        rdir = dir.subdir('_resources')

        layout = MultiFileLayout(dir, 'html')
        self.assertEqual(layout.relative_root, dir)
        self.assertEqual(layout.resources_dir(), rdir)

        for path, file, adir in (
            (Path('Foo'), dir.file('Foo.html'), dir.subdir('Foo')),
            (Path('Foo:Bar'), dir.file('Foo/Bar.html'), dir.subdir('Foo/Bar')),
        ):
            self.assertEqual(layout.page_file(path), file)
            self.assertEqual(layout.attachments_dir(path), adir)

        self.assertRaises(PathLookupError, layout.page_file, Path(':'))

        layout = MultiFileLayout(dir, 'html', namespace=Path('Test'))
        self.assertEqual(layout.relative_root, dir)
        self.assertEqual(layout.resources_dir(), rdir)

        for path, file, adir in (
            (Path('Test:Foo'), dir.file('Foo.html'), dir.subdir('Foo')),
            (Path('Test:Foo:Bar'), dir.file('Foo/Bar.html'),
             dir.subdir('Foo/Bar')),
        ):
            self.assertEqual(layout.page_file(path), file)
            self.assertEqual(layout.attachments_dir(path), adir)

        self.assertRaises(PathLookupError, layout.page_file, Path(':'))
        self.assertRaises(PathLookupError, layout.page_file, Path('Foo'))
Exemplo n.º 20
0
    def runTest(self):
        dir = Dir(self.create_tmp_dir())
        #~ dir =  VirtualDir('/test')

        i = 0
        print ''
        for template, file in list_templates(self.format):
            print 'Testing template: %s' % template
            notebook = tests.new_notebook(fakedir='/foo')
            pages = AllPages(notebook)  # TODO - sub-section ?
            exporter = build_notebook_exporter(dir.subdir(template),
                                               self.format, template)
            self.assertIsInstance(exporter, MultiFileExporter)

            with tests.LoggingFilter('zim.formats.latex',
                                     'Could not find latex equation'):
                exporter.export(pages)

            file = exporter.layout.page_file(Path('roundtrip'))
            text = file.read()
            self.assertIn('Lorem ipsum dolor sit amet', text)

            i += 1

        if self.format in ('html', 'latex'):
            self.assertTrue(i >= 3)
Exemplo n.º 21
0
    def setUp(self):
        tmpdir = self.get_tmp_name()
        notebook = tests.new_notebook(tmpdir + '/notebook')
        layout = MultiFileLayout(Dir(tmpdir + '/export'), 'html')
        linker_factory = partial(ExportLinker,
                                 notebook=notebook,
                                 layout=layout,
                                 output=layout.page_file(Path('test')),
                                 usebase=True)
        dumper_factory = get_format('html').Dumper

        title = 'Test Export'
        self.content = [notebook.get_page(Path('Test:foo'))]
        self.context = ExportTemplateContext(
            notebook,
            linker_factory,
            dumper_factory,
            title,
            self.content,
            special=None,
            home=None,
            up=None,
            prevpage=None,
            nextpage=None,
            links=None,
        )
Exemplo n.º 22
0
    def testCorrect(self):
        '''Test config environemnt with non-default basedir paths'''
        my_environ = {
            'XDG_DATA_HOME': '/foo/data/home',
            'XDG_DATA_DIRS': '/foo/data/dir1:/foo/data/dir2',
            'XDG_CONFIG_HOME': '/foo/config/home',
            'XDG_CONFIG_DIRS': '/foo/config/dir1:/foo/config/dir2',
            'XDG_CACHE_HOME': '/foo/cache',
        }
        if os.name == 'nt':
            my_environ['XDG_DATA_DIRS'] = '/foo/data/dir1;/foo/data/dir2'
            my_environ['XDG_CONFIG_DIRS'] = '/foo/config/dir1;/foo/config/dir2'

        with EnvironmentConfigContext(my_environ):
            for k, v in (('XDG_DATA_HOME', '/foo/data/home'),
                         ('XDG_CONFIG_HOME', '/foo/config/home'),
                         ('XDG_CACHE_HOME', '/foo/cache')):
                self.assertEqual(getattr(zim.config.basedirs, k), Dir(v))

            for k, v in (
                ('XDG_DATA_DIRS', '/foo/data/dir1:/foo/data/dir2'),
                ('XDG_CONFIG_DIRS', '/foo/config/dir1:/foo/config/dir2'),
            ):
                self.assertEqual(getattr(zim.config.basedirs, k),
                                 map(Dir, v.split(':')))
Exemplo n.º 23
0
	def runTest(self):

		## Without argument should prompt
		def testAddNotebookDialog(dialog):
			self.assertIn(dialog.__class__.__name__,
				('AddNotebookDialog', 'NotebookDialog')
			)

		cmd = GuiCommand('gui')
		with tests.DialogContext(testAddNotebookDialog):
			cmd.run() # Exist without running due to no notebook given in dialog

		### Try again with argument
		dir = self.create_tmp_dir()
		cmd = GuiCommand('gui')
		cmd.parse_options(dir)
		with tests.LoggingFilter('zim', 'Exception while loading plugin:'):
			window = cmd.run()
		self.addCleanup(window.destroy)

		self.assertEqual(window.__class__.__name__, 'MainWindow')
		self.assertEqual(window.ui.notebook.uri, Dir(dir).uri) # XXX

		window2 = cmd.run()
		self.assertIs(window2, window)
Exemplo n.º 24
0
 def import_attachments(self, notebook, path, dir):
     attachments = notebook.get_attachments_dir(path)
     attachments = Dir(attachments.path)  # XXX
     for name in dir.list():
         # FIXME could use list objects, or list_files()
         file = dir.file(name)
         if not file.isdir():
             file.copyto(attachments)
Exemplo n.º 25
0
	def do_add_notebook(self, *a):
		fields = AddNotebookDialog(self).run()
		if fields:
			if fields['type'] == 'local':
				dir = Dir(fields['folder'])
				init_notebook(dir, name=fields['name'])
				model = self.treeview.get_model()
				model.append_notebook(dir.uri, name=fields['name'])
			elif fields['type'] == 'google-drive':
				#TODO set client secret here somehow
				#make sure we are authenticated
				virtual.get_credentials()
				dir = Dir(fields['folder'])
				init_notebook(dir, name=fields['name'])
				model = self.treeview.get_model()
				model.append_notebook(dir.uri, name=fields['name'])
			else:
				raise NotImplemented
Exemplo n.º 26
0
    def runTest(self):
        from pprint import pprint

        from zim.fs import File
        file = File('./tests/data/TestTemplate.html')

        templ = Template(file)
        #~ pprint(templ.parts) # parser output

        output = []
        templ.process(output, {
         'title': 'THIS IS THE TITLE',
         'generator': {
          'name': 'ZIM VERSION',
         },
         'navigation': {
          'prev': None,
          'next': None,
         },
         'links': {},
         'pages': [
          { # page
           'name': 'page',
           'heading': 'HEAD',
           'body': 'BODY',
           'properties': {
            'type': 'PAGE',
           },
           'backlinks': [
            {'name': 'LINK1'},
            {'name': 'LINK2'},
            {'name': 'LINK3'},
           ],
           'attachments': [
            {'name': 'FILE1', 'basename': 'FILE1', 'size': '1k'},
            {'name': 'FILE2', 'basename': 'FILE2', 'size': '1k'},
           ],
          },
         ],
         'uri': ExpressionFunction(lambda l: "URL:%s" % l['name']),
         'anchor': ExpressionFunction(lambda l: "ANCHOR:%s" % l['name']),
        })
        #~ print ''.join(output)

        # TODO assert something

        ### Test empty template OK as well
        dir = Dir(self.create_tmp_dir())
        file = dir.file('empty.html')

        self.assertRaises(FileNotFoundError, Template, file)

        file.touch()
        templ = Template(file)
        output = []
        templ.process(output, {})
        self.assertEqual(output, [])
Exemplo n.º 27
0
    def runTest(self):
        '''Test FileEntry widget'''
        path = Path('Foo:Bar')
        entry = self.entry
        entry.set_use_relative_paths(self.notebook, path)

        home = Dir('~')
        dir = self.notebook.dir
        for file, text in (
            (home.file('zim-test.txt'), '~/zim-test.txt'),
            (dir.file('Foo/Bar/test.txt'), './test.txt'),
            (File('/test.txt'), File('/test.txt').path),  # win32 save
        ):
            entry.set_file(file)
            self.assertEqual(entry.get_text(), os_native_path(text))
            self.assertEqual(entry.get_file(), file)

        self.notebook.config['Notebook'][
            'document_root'] = './notebook_document_root'
        self.notebook.do_properties_changed()  # parse config
        doc_root = self.notebook.document_root
        self.assertEqual(doc_root, dir.subdir('notebook_document_root'))

        for file, text in (
            (home.file('zim-test.txt'), os_native_path('~/zim-test.txt')),
            (dir.file('Foo/Bar/test.txt'), os_native_path('./test.txt')),
            (File('/test.txt'), File('/test.txt').uri),  # win32 save
            (doc_root.file('test.txt'), '/test.txt'),
        ):
            entry.set_file(file)
            self.assertEqual(entry.get_text(), text)
            self.assertEqual(entry.get_file(), file)

        entry.set_use_relative_paths(self.notebook, None)

        for file, text in (
            (home.file('zim-test.txt'), os_native_path('~/zim-test.txt')),
            (dir.file('Foo/Bar/test.txt'),
             os_native_path('./Foo/Bar/test.txt')),
            (File('/test.txt'), File('/test.txt').uri),  # win32 save
            (doc_root.file('test.txt'), '/test.txt'),
        ):
            entry.set_file(file)
            self.assertEqual(entry.get_text(), text)
            self.assertEqual(entry.get_file(), file)

        entry.set_use_relative_paths(notebook=None)

        for file, text in (
            (home.file('zim-test.txt'), '~/zim-test.txt'),
                #~ (dir.file('Foo/Bar/test.txt'), './test.txt'),
            (File('/test.txt'), File('/test.txt').path),  # win32 save
        ):
            entry.set_file(file)
            self.assertEqual(entry.get_text(), text)
            self.assertEqual(entry.get_file(), file)
Exemplo n.º 28
0
def _get_path_object(path):
	if isinstance(path, str):
		file = File(path)
		if file.exists(): # exists and is a file
			path = file
		else:
			path = Dir(path)
	else:
		assert isinstance(path, (File, Dir))
	return path
Exemplo n.º 29
0
	def on_properties_changed(self, properties):
		dir = Dir(self.layout.root.path) # XXX

		self.name = properties['name'] or self.folder.basename
		icon, document_root = _resolve_relative_config(dir, properties)
		if icon:
			self.icon = icon.path # FIXME rewrite to use File object
		else:
			self.icon = None
		self.document_root = document_root
Exemplo n.º 30
0
	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(getattr(zim.config, k), Dir(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(getattr(zim.config, k), map(Dir, v.split(os.pathsep)))

		self.assertEqual(
			zim.config.XDG_DATA_DIRS[0],
			Dir(os.path.join(tests.TMPDIR, 'data_dir'))
		)