コード例 #1
0
ファイル: export.py プロジェクト: Jam71/Zim-QDA
class TestExport(tests.TestCase):

	options = {'format': 'html', 'template': 'Default'}

	def setUp(self):
		self.dir = Dir(self.create_tmp_dir('exported_files'))

	def export(self):
		notebook = tests.new_notebook(fakedir='/foo/bar')

		exporter = Exporter(notebook, **self.options)
		exporter.export_all(self.dir)

	def runTest(self):
		'''Test export notebook to html'''
		self.export()

		file = self.dir.file('Test/foo.html')
		self.assertTrue(file.exists())
		text = file.read()
		self.assertTrue('<!-- Wiki content -->' in text, 'template used')
		self.assertTrue('<h1>Foo</h1>' in text)

		for icon in ('checked-box',): #'unchecked-box', 'xchecked-box'):
			# Default template doesn't have its own checkboxes
			self.assertTrue(self.dir.file('_resources/%s.png' % icon).exists())
			self.assertEqual(
				md5(self.dir.file('_resources/%s.png' % icon)),
				md5(data_file('pixmaps/%s.png' % icon))
			)
コード例 #2
0
ファイル: notebook.py プロジェクト: timckuhn/zim-desktop-wiki
    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))
コード例 #3
0
ファイル: notebook.py プロジェクト: timckuhn/zim-desktop-wiki
    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)
コード例 #4
0
ファイル: export.py プロジェクト: zrf1/zim-desktop-wiki
    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)
コード例 #5
0
ファイル: __init__.py プロジェクト: pombredanne/zim
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)
コード例 #6
0
ファイル: quicknote.py プロジェクト: zrf1/zim-desktop-wiki
    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())
コード例 #7
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']))
コード例 #8
0
class TestExport(tests.TestCase):

    options = {'format': 'html', 'template': 'Default'}

    def setUp(self):
        self.dir = Dir(self.create_tmp_dir('exported_files'))

    def export(self):
        notebook = tests.new_notebook(fakedir='/foo/bar')

        exporter = Exporter(notebook, **self.options)
        exporter.export_all(self.dir)

    def runTest(self):
        '''Test export notebook to html'''
        self.export()

        file = self.dir.file('Test/foo.html')
        self.assertTrue(file.exists())
        text = file.read()
        self.assertTrue('<!-- Wiki content -->' in text, 'template used')
        self.assertTrue('<h1>Foo</h1>' in text)

        for icon in ('checked-box', ):  #'unchecked-box', 'xchecked-box'):
            # Default template doesn't have its own checkboxes
            self.assertTrue(self.dir.file('_resources/%s.png' % icon).exists())
            self.assertEqual(md5(self.dir.file('_resources/%s.png' % icon)),
                             md5(data_file('pixmaps/%s.png' % icon)))
コード例 #9
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
コード例 #10
0
ファイル: notebook.py プロジェクト: timckuhn/zim-desktop-wiki
class TestBuildNotebook(tests.TestCase):
    # Test including automount and uniqueness !

    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))

    #~ def tearDown(self):
    #~ automount = XDG_CONFIG_HOME.file('zim/automount.conf')
    #~ automount.remove()

    def runTest(self):
        def mockconstructor(dir):
            return dir

        nbid = None
        for uri, path in (
            (self.notebookdir.uri, None),
            (self.notebookdir.uri, None),  # repeat to check uniqueness
            (self.notebookdir.file('notebook.zim').uri, None),
            (self.notebookdir.file('foo/bar.txt').uri, Path('foo:bar')),
                #~ ('zim+' + tmpdir.uri + '?aaa:bbb:ccc', Path('aaa:bbb:ccc')),
        ):
            #~ print ">>", uri
            info = NotebookInfo(uri)
            nb, p = build_notebook(info)
            self.assertEqual(nb.dir, self.notebookdir)
            self.assertEqual(p, path)
            if nbid is None:
                nbid = id(nb)
            else:
                self.assertEqual(id(nb), nbid, 'Check uniqueness')

        info = NotebookInfo(self.notebookdir.file('nonexistingfile.txt'))
        self.assertRaises(FileNotFoundError, build_notebook, info)
コード例 #11
0
ファイル: templates.py プロジェクト: fabricehong/zim-desktop
	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, [])
コード例 #12
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, [])
コード例 #13
0
ファイル: gui.py プロジェクト: pombredanne/zim
    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']))
コード例 #14
0
    def runTest(self):
        dir = Dir(self.get_tmp_name())
        notebook = tests.new_notebook(fakedir=dir.subdir('notebook'))
        for name in (
                'foo',
                'bar',
                'foo:bar',
        ):
            p = notebook.get_page(Path(name))
            p.parse('wiki', "test 123")
            notebook.store_page(p)

        layout = MultiFileLayout(dir.subdir('layout'), 'html')
        source = Path('foo:bar')
        output = layout.page_file(source)

        linker = ExportLinker(notebook,
                              layout,
                              source=source,
                              output=output,
                              usebase=True)

        self.assertEqual(linker.link('+dus'), './bar/dus.html')
        self.assertEqual(linker.link('dus'), './dus.html')
        self.assertEqual(linker.link('./dus.pdf'), './bar/dus.pdf')
        self.assertEqual(linker.link('../dus.pdf'), './dus.pdf')
        self.assertEqual(linker.link('../../dus.pdf'), '../dus.pdf')
        self.assertEqual(linker.link('/dus.pdf'), File('/dus.pdf').uri)

        # TODO:
        # 	img
        # 	icon
        # 	resource
        # 	resolve_source_file
        # 	page_object
        # 	file_object
        #
        #	document_root_url

        ## 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')
コード例 #15
0
	def runTest(self):
		dir = Dir('./data/pixmaps')
		for i, filename in enumerate(dir.list()):
			file = dir.file(filename)
			icon = get_mime_icon(file, 128)
			self.assertIsInstance(icon, GdkPixbuf.Pixbuf)
			desc = get_mime_description(file.get_mimetype())
			self.assertIsInstance(desc, str)
			self.assertTrue(len(desc) > 5)

		self.assertTrue(i > 3)
コード例 #16
0
ファイル: applications.py プロジェクト: hjq300/zim-wiki
    def runTest(self):
        dir = Dir('./data/pixmaps')
        for i, filename in enumerate(dir.list()):
            file = dir.file(filename)
            icon = get_mime_icon(file, THUMB_SIZE_NORMAL)
            self.assertIsInstance(icon, gtk.gdk.Pixbuf)
            desc = get_mime_description(file.get_mimetype())
            self.assertIsInstance(desc, basestring)
            self.assertTrue(len(desc) > 5)

        self.assertTrue(i > 3)
コード例 #17
0
ファイル: widgets.py プロジェクト: fabricehong/zim-desktop
	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(), 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'), '~/zim-test.txt'),
			(dir.file('Foo/Bar/test.txt'), './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'), '~/zim-test.txt'),
			(dir.file('Foo/Bar/test.txt'), './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)
コード例 #18
0
ファイル: environ.py プロジェクト: hjq300/zim-wiki
	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())
コード例 #19
0
    def runTest(self):
        os.makedirs('tests/tmp/data_dir/mime/image/')
        shutil.copyfile('./tests/data/png.xml',
                        'tests/tmp/data_dir/mime/image/png.xml')

        dir = Dir('./data')
        file = dir.file('zim.png')
        icon = get_mime_icon(file, 128)
        self.assertIsInstance(icon, GdkPixbuf.Pixbuf)
        desc = get_mime_description(file.get_mimetype())
        self.assertIsInstance(desc, str)
        self.assertTrue(len(desc) > 5)
コード例 #20
0
ファイル: notebook.py プロジェクト: fabricehong/zim-desktop
class TestBuildNotebook(tests.TestCase):
	# Test including automount !

	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()
		automount.write('''\
[Path %s]
mount=%s %s
''' % (self.notebookdir.path, script.path, self.notebookdir.path))

	#~ def tearDown(self):
		#~ automount = XDG_CONFIG_HOME.file('zim/automount.conf')
		#~ automount.remove()

	def runTest(self):
		def mockconstructor(dir):
			return dir

		for uri, path in (
			(self.notebookdir.uri, None),
			(self.notebookdir.file('notebook.zim').uri, None),
			(self.notebookdir.file('foo/bar.txt').uri, Path('foo:bar')),
			#~ ('zim+' + tmpdir.uri + '?aaa:bbb:ccc', Path('aaa:bbb:ccc')),
		):
			#~ print ">>", uri
			info = NotebookInfo(uri)
			nb, p = build_notebook(info, notebookclass=mockconstructor)
			self.assertEqual(nb, self.notebookdir)
			self.assertEqual(p, path)

		info = NotebookInfo(self.notebookdir.file('nonexistingfile.txt'))
		self.assertRaises(FileNotFoundError, build_notebook, info)
コード例 #21
0
	def runTest(self):
		dir =  Dir(self.create_tmp_dir())
		file = dir.file('test.tex')
		page = Path('roundtrip')
		exporter = build_page_exporter(file, 'latex', 'Article', page)

		notebook = tests.new_notebook(fakedir='/foo')
		selection = SinglePage(notebook, page)

		exporter.export(selection)
		result = file.read()
		#~ print result
		self.assertIn('\section{Head1}', result) # this implies that document_type "article" was indeed used
コード例 #22
0
ファイル: exportdialog.py プロジェクト: thorhans/zimt
	def get_folder(self):
		dir = Dir(self.uistate['output_folder'])
		if dir.exists() and len(dir.list()) > 0:
			ok = QuestionDialog(self, (
				_('Folder exists: %s') % dir.path, # T: message heading
				_('Folder already exists and has content, '
				  'exporting to this folder may overwrite '
				  'existing files. '
				  'Do you want to continue?') # T: detailed message, answers are Yes and No
			)).run()
			if not ok:
				return None
		return dir
コード例 #23
0
ファイル: export.py プロジェクト: Jam71/Zim-QDA
	def export(self):
		dir = Dir(self.create_tmp_dir('source_files'))
		init_notebook(dir)
		notebook = Notebook(dir=dir)
		for name, text in tests.WikiTestData:
			page = notebook.get_page(Path(name))
			page.parse('wiki', text)
			notebook.store_page(page)
		file = dir.file('Test/foo.txt')
		self.assertTrue(file.exists())

		zim = Application(('./zim.py', '--export', '--template=Default', dir.path, '--output', self.dir.path, '--index-page', 'index'))
		zim.run()
コード例 #24
0
ファイル: export.py プロジェクト: zrf1/zim-desktop-wiki
    def runTest(self):
        dir = Dir(self.create_tmp_dir())
        #~ dir =  VirtualDir('/test')
        file = dir.file('export.mht')
        notebook = tests.new_notebook(fakedir='/foo')
        pages = AllPages(notebook)

        exporter = build_mhtml_file_exporter(file, 'Default')
        self.assertIsInstance(exporter, MHTMLExporter)
        exporter.export(pages)

        text = file.read()
        self.assertIn('Lorem ipsum dolor sit amet', text)
コード例 #25
0
	def get_folder(self):
		dir = Dir(self.uistate['output_folder'])
		if dir.exists() and len(dir.list()) > 0:
			ok = QuestionDialog(self, (
				_('Folder exists: %s') % dir.path, # T: message heading
				_('Folder already exists and has content, '
				  'exporting to this folder may overwrite '
				  'existing files. '
				  'Do you want to continue?' ) # T: detailed message, answers are Yes and No
			) ).run()
			if not ok:
				return None
		return dir
コード例 #26
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
			)
コード例 #27
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))
コード例 #28
0
	def testCreateThumbnail(self):
		manager = ThumbnailManager()

		dir = Dir(self.create_tmp_dir())
		file = dir.file('zim.png')
		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, gtk.gdk.Pixbuf)

		thumbfile, pixbuf = manager.get_thumbnail(file, 64)
		self.assertTrue(thumbfile.exists())
		self.assertIsInstance(pixbuf, gtk.gdk.Pixbuf)

		import stat
		mode = os.stat(thumbfile.encodedpath).st_mode
		self.assertEqual(stat.S_IMODE(mode), 0600)
		mode = os.stat(thumbfile.dir.dir.encodedpath).st_mode # thumnails dir
		self.assertEqual(stat.S_IMODE(mode), 0700)

		# Change mtime to make thumbfile invalid
		oldmtime = file.mtime()
		os.utime(file.encodedpath, 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, gtk.gdk.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, gtk.gdk.Pixbuf)

		# Test remove
		self.removeThumbnail(manager, file)
コード例 #29
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'])
コード例 #30
0
ファイル: main.py プロジェクト: thorhans/zimt
    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)
コード例 #31
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)
コード例 #32
0
ファイル: versioncontrol.py プロジェクト: gdw2/zim
	def testDetectVCS(self):
		root = Dir(self.create_tmp_dir())
		root.subdir('.bzr').touch()
		self.assertEqual(VCS._detect_in_folder(root), ('bzr', root))

		subdir = root.subdir('Foo/Bar')
		subdir.touch()
		self.assertEqual(VCS._detect_in_folder(subdir), ('bzr', root))

		subroot = root.subdir('subroot')
		subroot.subdir('.git').touch()
		self.assertEqual(VCS._detect_in_folder(subroot), ('git', subroot))

		subdir = subroot.subdir('Foo/Bar')
		subdir.touch()
		self.assertEqual(VCS._detect_in_folder(subdir), ('git', subroot))
コード例 #33
0
ファイル: notebook.py プロジェクト: fabricehong/zim-desktop
	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()
		automount.write('''\
[Path %s]
mount=%s %s
''' % (self.notebookdir.path, script.path, self.notebookdir.path))
コード例 #34
0
ファイル: __init__.py プロジェクト: gdw2/zim
class StubLinker(BaseLinker):
	'''Linker used for testing - just gives back the link as it was
	parsed. DO NOT USE outside of testing.
	'''

	def __init__(self):
		BaseLinker.__init__(self)
		self.path = '<PATH>'
		self.base = Dir('<NOBASE>')

	def resolve_file(self, link):
		return self.base.file(link)
			# Very simple stub, allows finding files be rel path for testing

	def icon(self, name):
		return 'icon:' + name

	def resource(self, path):
		return path

	def link_page(self, link):
		return link

	def link_file(self, path):
		return path
コード例 #35
0
ファイル: main.py プロジェクト: zrf1/zim-desktop-wiki
	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)
コード例 #36
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(':')))
コード例 #37
0
ファイル: export.py プロジェクト: zrf1/zim-desktop-wiki
    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,
        )
コード例 #38
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')
コード例 #39
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
コード例 #40
0
ファイル: versioncontrol.py プロジェクト: gdw2/zim
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
コード例 #41
0
ファイル: attachmentbrowser.py プロジェクト: hjq300/zim-wiki
	def testQueue(self):
		queue = ThumbnailQueue()
		self.assertTrue(queue.queue_empty())

		# Test input / output
		queue.queue_thumbnail_request(File('./README.txt'), 64)
			# put an error in the queue

		dir = Dir('./data/pixmaps')
		pixmaps = set()
		for basename in dir.list():
			file = dir.file(basename)
			pixmaps.add(file)
			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)
				self.assertEqual(size, 64)
				self.assertTrue(thumbfile.exists())
				self.assertIsInstance(pixbuf, gtk.gdk.Pixbuf)
				self.assertEqual(mtime, file.mtime())

		self.assertEqual(seen, pixmaps)

		# Test clear
		self.assertTrue(queue.queue_empty())
		for file in pixmaps:
			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())
コード例 #42
0
ファイル: versioncontrol.py プロジェクト: Jam71/Zim-QDA
def get_tmp_dir(name):
	testtmp = os.environ['TMP']
	del os.environ['TMP']
	dir = Dir(tempfile.gettempdir())
	os.environ['TMP'] = testtmp

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

	return dir
コード例 #43
0
ファイル: __init__.py プロジェクト: damiansimanuk/texslide
def list_plugins():
	'''Returns a set of available plugin names'''
	# FIXME how should this work for e.g. for python eggs ??
	plugins = set()
	for dir in sys.path:
		dir = Dir((dir, 'zim', 'plugins'))
		if not dir.exists():
			continue
		for candidate in dir.list():
			if candidate.startswith('_'):
				continue
			elif candidate.endswith('.py'):
				plugins.add(candidate[:-3])
			elif os.path.isdir(dir.path+'/'+candidate) \
			and os.path.exists(dir.path+'/'+candidate+'/__init__.py'):
				plugins.add(candidate)
			else:
				pass

	return plugins
コード例 #44
0
ファイル: notebook.py プロジェクト: fabricehong/zim-desktop
	def runTest(self):
		root = Dir(self.create_tmp_dir(u'some_utf8_here_\u0421\u0430\u0439'))

		# Start empty - see this is no issue
		list = get_notebook_list()
		self.assertTrue(isinstance(list, NotebookInfoList))
		self.assertTrue(len(list) == 0)

		info = list.get_by_name('foo')
		self.assertIsNone(info)

		# Now create it
		dir = root.subdir('/notebook')
		init_notebook(dir, name='foo')

		# And put it in the list and resolve it by name
		list = get_notebook_list()
		list.append(NotebookInfo(dir.uri, name='foo'))
		list.write()

		self.assertTrue(len(list) == 1)
		self.assertTrue(isinstance(list[0], NotebookInfo))

		info = list.get_by_name('foo')
		self.assertEqual(info.uri, dir.uri)
		self.assertEqual(info.name, 'foo')

		newlist = get_notebook_list() # just to be sure re-laoding works..
		self.assertTrue(len(list) == 1)
		info = newlist.get_by_name('foo')
		self.assertEqual(info.uri, dir.uri)
		self.assertEqual(info.name, 'foo')

		# Add a second entry
		if os.name == 'nt':
			uri1 = 'file:///C:/foo/bar'
		else:
			uri1 = 'file:///foo/bar'

		list = get_notebook_list()
		self.assertTrue(len(list) == 1)
		list.append(NotebookInfo(uri1, interwiki='foobar'))
			# on purpose do not set name, should default to basename
		list.write()

		self.assertTrue(len(list) == 2)
		self.assertEqual(list[:], [NotebookInfo(dir.uri), NotebookInfo(uri1)])

		# And check all works OK
		info = list.get_by_name('foo')
		self.assertEqual(info.uri, dir.uri)
		nb, path = build_notebook(info)
		self.assertIsInstance(nb, Notebook)
		self.assertIsNone(path)

		for name in ('bar', 'Bar'):
			info = list.get_by_name(name)
			self.assertEqual(info.uri, uri1)
			self.assertRaises(FileNotFoundError, build_notebook, info)
				# path should not exist

		# Test default
		list.set_default(uri1)
		list.write()
		list = get_notebook_list()
		self.assertIsNotNone(list.default)
		self.assertEqual(list.default.uri, uri1)

		# Check interwiki parsing - included here since it interacts with the notebook list
		self.assertEqual(interwiki_link('wp?Foo'), 'http://en.wikipedia.org/wiki/Foo')
		self.assertEqual(interwiki_link('foo?Foo'), 'zim+' + dir.uri + '?Foo')
		self.assertEqual(interwiki_link('foobar?Foo'), 'zim+' + uri1 + '?Foo') # interwiki key
		self.assertEqual(interwiki_link('FooBar?Foo'), 'zim+' + uri1 + '?Foo') # interwiki key
		self.assertEqual(interwiki_link('bar?Foo'), 'zim+' + uri1 + '?Foo') # name
		self.assertEqual(interwiki_link('Bar?Foo'), 'zim+' + uri1 + '?Foo') # name

		# Check backward compatibility
		file = File('tests/data/notebook-list-old-format.list')
		list = NotebookInfoList(file)
		self.assertEqual(list[:], [
			NotebookInfo(Dir(path).uri) for path in
				('~/Notes', '/home/user/code/zim.debug', '/home/user/Foo Bar')
		])
		self.assertEqual(list.default,
			NotebookInfo(Dir('/home/user/code/zim.debug').uri) )
コード例 #45
0
ファイル: notebook.py プロジェクト: Jam71/Zim-QDA
	def runTest(self):
		root = Dir(self.create_tmp_dir(u'some_utf8_here_\u0421\u0430\u0439'))

		# Start empty - see this is no issue
		list = get_notebook_list()
		self.assertTrue(isinstance(list, NotebookInfoList))
		self.assertTrue(len(list) == 0)

		nb, page = resolve_notebook('foo')
		self.assertTrue(nb is None)
		nb = _get_default_or_only_notebook()
		self.assertTrue(nb is None)

		# Non-existing dir
		dir = root.subdir('/notebook')
		nb, page = resolve_notebook(dir.path)
		self.assertEqual(nb, dir)

		# Now create it
		init_notebook(dir, name='foo')
		file = dir.file('notebook.zim')
		nb, page = resolve_notebook(dir.path)
		self.assertEqual(nb, dir)
		nb, page = resolve_notebook(file.uri)
		self.assertEqual(nb, dir)
		file = dir.file('foo/bar/baz.txt')
		file.touch()
		nb, page = resolve_notebook(file.path)
		self.assertEqual(nb, dir)
		self.assertEqual(page, Path('foo:bar:baz'))

		# And put it in the list and resolve it by name
		list = get_notebook_list()
		list.append(NotebookInfo(dir.uri, name='foo'))
		list.write()

		self.assertTrue(len(list) == 1)
		self.assertTrue(isinstance(list[0], NotebookInfo))

		info = list.get_by_name('foo')
		self.assertEqual(info.uri, dir.uri)
		self.assertEqual(info.name, 'foo')

		newlist = get_notebook_list() # just to be sure re-laoding works..
		info = newlist.get_by_name('foo')
		self.assertEqual(info.uri, dir.uri)
		self.assertEqual(info.name, 'foo')

		nb, page = resolve_notebook('foo')
		self.assertEqual(nb, dir)

		# Single notebook is automatically the default
		nb = _get_default_or_only_notebook()
		self.assertEqual(nb, dir.uri)

		# But not anymore after adding second notebook
		if os.name == 'nt':
			uri1 = 'file:///C:/foo/bar'
		else:
			uri1 = 'file:///foo/bar'

		list = get_notebook_list()
		list.append(NotebookInfo(uri1, interwiki='foobar'))
			# on purpose do not set name, should default to basename
		list.write()
		self.assertTrue(len(list) == 2)
		self.assertEqual(list[:],
			[NotebookInfo(dir.uri), NotebookInfo(uri1)])

		nb, page = resolve_notebook('foo')
		self.assertEqual(nb, dir)
		self.assertTrue(isinstance(get_notebook(nb), Notebook))

		nb, page = resolve_notebook('bar')
			# Check name defaults to dir basename
		self.assertEqual(nb, Dir(uri1))
		self.assertIs(get_notebook(nb), None) # path should not exist

		nb, page = resolve_notebook('Bar')
		self.assertEqual(nb, Dir(uri1))

		nb = _get_default_or_only_notebook()
		self.assertTrue(nb is None)

		list = get_notebook_list()
		list.set_default(uri1)
		list.write()
		nb = _get_default_or_only_notebook()
		self.assertEqual(nb, uri1)
		nb, p = resolve_notebook(nb)
		self.assertEqual(nb, Dir(uri1))
		self.assertEqual(get_notebook(nb), None)

		# Check interwiki parsing
		self.assertEqual(interwiki_link('wp?Foo'), 'http://en.wikipedia.org/wiki/Foo')
		self.assertEqual(interwiki_link('foo?Foo'), 'zim+' + dir.uri + '?Foo')
		nb, page = resolve_notebook(dir.uri + '?Foo')
		self.assertEqual(nb, dir)
		self.assertEqual(page, Path('Foo'))

		self.assertEqual(interwiki_link('foobar?Foo'), 'zim+' + uri1 + '?Foo') # interwiki key
		self.assertEqual(interwiki_link('FooBar?Foo'), 'zim+' + uri1 + '?Foo') # interwiki key
		self.assertEqual(interwiki_link('bar?Foo'), 'zim+' + uri1 + '?Foo') # name
		self.assertEqual(interwiki_link('Bar?Foo'), 'zim+' + uri1 + '?Foo') # name

		# Check backward compatibility
		file = File('tests/data/notebook-list-old-format.list')
		list = NotebookInfoList(file)
		self.assertEqual(list[:], [
			NotebookInfo(Dir(path).uri) for path in
				('~/Notes', '/home/user/code/zim.debug', '/home/user/Foo Bar')
		])
		self.assertEqual(list.default,
			NotebookInfo(Dir('/home/user/code/zim.debug').uri) )
コード例 #46
0
ファイル: main.py プロジェクト: fabricehong/zim-desktop
	def get_exporter(self, page):
		from zim.fs import File, Dir
		from zim.export import \
			build_mhtml_file_exporter, \
			build_single_file_exporter, \
			build_page_exporter, \
			build_notebook_exporter

		format = self.opts.get('format', 'html')
		if not 'output' in self.opts:
			raise UsageError, _('Output location needed for export') # T: error in export command
		output = Dir(self.opts['output'])
		if not output.isdir():
			output = File(self.opts.get('output'))
		template = self.opts.get('template', 'Default')

		if output.exists() and not self.opts.get('overwrite'):
			if output.isdir():
				if len(output.list()) > 0:
					raise Error, _('Output folder exists and not empty, specify "--overwrite" to force export')  # T: error message for export
				else:
					pass
			else:
				raise Error, _('Output file exists, specify "--overwrite" to force export')  # T: error message for export

		if format == 'mhtml':
			self.ignore_options('index-page')
			if output.isdir():
				raise UsageError, _('Need output file to export MHTML') # T: error message for export

			exporter = build_mhtml_file_exporter(
				output, template,
				document_root_url=self.opts.get('root-url'),
			)
		elif page:
			self.ignore_options('index-page')
			if output.exists() and output.isdir():
				ext = 'html'
				output = output.file(page.basename) + '.' + ext

			if self.opts.get('singlefile'):
				exporter = build_single_file_exporter(
					output, format, template, namespace=page,
					document_root_url=self.opts.get('root-url'),
				)
			else:
				exporter = build_page_exporter(
					output, format, template, page,
					document_root_url=self.opts.get('root-url'),
				)
		else:
			if not output.exists():
				output = Dir(output.path)
			elif not output.isdir():
				raise UsageError, _('Need output folder to export full notebook') # T: error message for export

			exporter = build_notebook_exporter(
				output, format, template,
				index_page=self.opts.get('index-page'),
				document_root_url=self.opts.get('root-url'),
			)

		return exporter
コード例 #47
0
ファイル: config.py プロジェクト: thejeshgn/Zim
def _set_basedirs():
	'''This method sets the global configuration paths for according to the
	freedesktop basedir specification.
	'''
	global ZIM_DATA_DIR
	global XDG_DATA_HOME
	global XDG_DATA_DIRS
	global XDG_CONFIG_HOME
	global XDG_CONFIG_DIRS
	global XDG_CACHE_HOME

	# Detect if we are running from the source dir
	try:
		if isfile('./zim.py'):
			scriptdir = Dir('.') # maybe running module in test / debug
		else:
			encoding = sys.getfilesystemencoding() # not 100% sure this is correct
			path = sys.argv[0].decode(encoding)
			scriptdir = File(path).dir
		zim_data_dir = scriptdir.subdir('data')
		if zim_data_dir.exists():
			ZIM_DATA_DIR = zim_data_dir
		else:
			ZIM_DATA_DIR = None
	except:
		# Catch encoding errors in argv
		logger.exception('Exception locating application data')
		ZIM_DATA_DIR = None

	if os.name == 'nt':
		APPDATA = get_environ('APPDATA')

		XDG_DATA_HOME = Dir(
			get_environ('XDG_DATA_HOME', APPDATA + r'\zim\data'))

		XDG_DATA_DIRS = map(Dir,
			get_environ_list('XDG_DATA_DIRS', '~/.local/share/')) # Backwards compatibility

		XDG_CONFIG_HOME = Dir(
			get_environ('XDG_CONFIG_HOME', APPDATA + r'\zim\config'))

		XDG_CONFIG_DIRS = map(Dir,
			get_environ_list('XDG_CONFIG_DIRS', '~/.config/')) # Backwards compatibility

		try:
			import _winreg as wreg
			wreg_key = wreg.OpenKey(
				wreg.HKEY_CURRENT_USER,
				r'Software\Microsoft\Windows\CurrentVersion\Explorer\User Shell Folders')
			cache_dir = str(wreg.QueryValueEx(wreg_key, "Cache")[0].replace(u'%USERPROFILE%', get_environ['USERPROFILE']))
			wreg.CloseKey(wreg_key)
		except:
			cache_dir = os.environ['TEMP']

		XDG_CACHE_HOME = Dir(
			get_environ('XDG_CACHE_HOME', cache_dir + r'\zim'))
	else:
		XDG_DATA_HOME = Dir(
			get_environ('XDG_DATA_HOME', '~/.local/share/'))

		XDG_DATA_DIRS = map(Dir,
			get_environ_list('XDG_DATA_DIRS', ('/usr/share/', '/usr/local/share/')))

		XDG_CONFIG_HOME = Dir(
			get_environ('XDG_CONFIG_HOME', '~/.config/'))

		XDG_CONFIG_DIRS = map(Dir,
			get_environ_list('XDG_CONFIG_DIRS', ('/etc/xdg/',)))

		XDG_CACHE_HOME = Dir(
			get_environ('XDG_CACHE_HOME', '~/.cache'))
コード例 #48
0
ファイル: attachmentbrowser.py プロジェクト: DarioGT/Zim-QDA
from zim.parsing import url_encode, URL_ENCODE_READABLE

from zim.gui.widgets import Button, BOTTOM_PANE, PANE_POSITIONS, \
    IconButton, ScrolledWindow, button_set_statusbar_style, \
    WindowSidePaneWidget
from zim.gui.applications import OpenWithMenu
from zim.gui.clipboard import \
    URI_TARGETS, URI_TARGET_NAMES, \
    pack_urilist, unpack_urilist


logger = logging.getLogger('zim.plugins.attachmentbrowser')


# freedesktop.org spec
LOCAL_THUMB_STORAGE = Dir('~/.thumbnails')
LOCAL_THUMB_STORAGE_NORMAL = LOCAL_THUMB_STORAGE.subdir('normal')
LOCAL_THUMB_STORAGE_LARGE = LOCAL_THUMB_STORAGE.subdir('large')
LOCAL_THUMB_STORAGE_FAIL = LOCAL_THUMB_STORAGE.subdir('fail/zim-%s' % zim.__version__)

THUMB_SIZE_NORMAL = 128
THUMB_SIZE_LARGE = 256

# For plugin
MIN_ICON_SIZE = 16
DEFAULT_ICON_SIZE = 64


_last_warning_missing_icon = None
    # used to surpress redundant logging
コード例 #49
0
ファイル: export.py プロジェクト: Jam71/Zim-QDA
	def runTest(self):
		'''Test ExportDialog'''
		from zim.gui.exportdialog import ExportDialog

		dir = Dir(self.create_tmp_dir())

		notebook = tests.new_notebook(fakedir='/foo/bar')

		ui = tests.MockObject()
		ui.notebook = notebook
		ui.page = Path('foo')
		ui.mainwindow = None
		ui.uistate = ConfigDict()

		## Test export all pages
		dialog = ExportDialog(ui)
		dialog.set_page(0)

		page = dialog.get_page()
		page.form['selection'] = 'all'
		dialog.next_page()

		page = dialog.get_page()
		page.form['format'] = 'HTML'
		page.form['template'] = 'Print'
		dialog.next_page()

		page = dialog.get_page()
		page.form['folder'] = dir
		page.form['index'] = 'INDEX_PAGE'
		dialog.assert_response_ok()

		file = dir.file('Test/foo.html')
		self.assertTrue(file.exists())
		text = file.read()
		self.assertTrue('<!-- Wiki content -->' in text, 'template used')
		self.assertTrue('<h1>Foo</h1>' in text)

		#~ print dialog.uistate
		self.assertEqual(dialog.uistate, ui.uistate['ExportDialog'])
		self.assertIsInstance(dialog.uistate['output_folder'], Dir)

		## Test export single page
		dialog = ExportDialog(ui)
		dialog.set_page(0)

		page = dialog.get_page()
		page.form['selection'] = 'page'
		page.form['page'] = 'Test:foo'
		dialog.next_page()

		page = dialog.get_page()
		page.form['format'] = 'HTML'
		page.form['template'] = 'Print'
		dialog.next_page()

		page = dialog.get_page()
		page.form['file'] = dir.file('SINGLE_FILE_EXPORT.html').path
		dialog.assert_response_ok()

		file = dir.file('SINGLE_FILE_EXPORT.html')
		self.assertTrue(file.exists())
		text = file.read()
		self.assertTrue('<!-- Wiki content -->' in text, 'template used')
		self.assertTrue('<h1>Foo</h1>' in text)

		#~ print dialog.uistate
		self.assertEqual(dialog.uistate, ui.uistate['ExportDialog'])
		self.assertIsInstance(dialog.uistate['output_file'], File)
		self.assertIsInstance(dialog.uistate['output_folder'], Dir) # Keep this in state as well
コード例 #50
0
ファイル: __init__.py プロジェクト: gdw2/zim
	def __init__(self):
		BaseLinker.__init__(self)
		self.path = '<PATH>'
		self.base = Dir('<NOBASE>')
コード例 #51
0
ファイル: export.py プロジェクト: Jam71/Zim-QDA
	def setUp(self):
		self.dir = Dir(self.create_tmp_dir('exported_files'))
コード例 #52
0
ファイル: index.py プロジェクト: Jam71/Zim-QDA
	def runTest(self):
		'''Test synchronization'''
		# Test if zim detects pages, that where created with another
		# zim instance and transfered to this instance with
		# dropbox or another file synchronization tool.
		#
		# The scenario is as follow:
		# 1) Page.txt is created in this instance
		# 2) Page/Subpage.txt is created in another instance
		#    and copied into the notebook by the synchronization tool
		# 3) Zim runs a standard index update
		# Outcome should be that Page:Subpage shows up in the index

		# create notebook
		dir = Dir(self.create_tmp_dir())

		init_notebook(dir, name='foo')
		notebook = get_notebook(dir)
		index = notebook.index
		index.update()

		# add page in this instance
		path = Path('Page')
		page =  notebook.get_page(path)
		page.parse('wiki', 'nothing important')
		notebook.store_page(page)

		# check file exists
		self.assertTrue(dir.file('Page.txt').exists())

		# check file is indexed
		self.assertTrue(page in list(index.list_all_pages()))

		# check attachment dir does not exist
		subdir = dir.subdir('Page')
		self.assertEqual(notebook.get_attachments_dir(page), subdir)
		self.assertFalse(subdir.exists())

		for newfile, newpath in (
			(subdir.file('NewSubpage.txt').path, Path('Page:NewSubpage')),
			(dir.file('Newtoplevel.txt').path, Path('Newtoplevel')),
			(dir.file('SomeDir/Dir/Newpage.txt').path, Path('SomeDir:Dir:Newpage')),
		):
			# make sure ctime changed since last index
			import time
			time.sleep(2)

			# create new page without using zim classes
			self.assertFalse(os.path.isfile(newfile))

			mydir = os.path.dirname(newfile)
			if not os.path.isdir(mydir):
				os.makedirs(mydir)

			fh = open(newfile, 'w')
			fh.write('Test 123\n')
			fh.close()

			self.assertTrue(os.path.isfile(newfile))

			# simple index reload
			index.update()

			# check if the new page is found in the index
			self.assertTrue(newpath in list(index.list_all_pages()))