Exemplo n.º 1
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.º 2
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')
Exemplo n.º 3
0
	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))
Exemplo n.º 4
0
	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))
Exemplo n.º 5
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.º 6
0
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)
Exemplo n.º 7
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.º 8
0
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)
Exemplo n.º 9
0
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
Exemplo n.º 10
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.º 11
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.º 12
0
    def runTest(self):
        tdir = Dir(self.get_tmp_name())
        topfile = tdir.file('page.html')
        dir = tdir.subdir('page_files')
        rdir = dir.subdir('_resources')

        layout = SingleFileLayout(topfile, page=Path('Test'))
        self.assertEqual(layout.relative_root, dir)
        self.assertEqual(layout.resources_dir(), rdir)

        for path, file, adir in (
            (Path('Test'), topfile, dir),
            (Path('Test:Foo'), topfile, dir.subdir('Foo')),
            (Path('Test:Foo:Bar'), topfile, 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.º 13
0
    def testResolveFile(self):
        '''Test notebook.resolve_file()'''
        from zim.fs import adapt_from_newfs, Dir
        dir = Dir(self.notebook.folder.path)  # XXX

        path = Path('Foo:Bar')
        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 link, wanted, cleaned in (
            ('~/test.txt', File('~/test.txt'), '~/test.txt'),
            (r'~\test.txt', File('~/test.txt'), '~/test.txt'),
            ('file:///test.txt', File('file:///test.txt'), None),
            ('file:/test.txt', File('file:///test.txt'), None),
            ('file://localhost/test.txt', File('file:///test.txt'), None),
            ('/test.txt', doc_root.file('test.txt'), '/test.txt'),
            ('../../notebook_document_root/test.txt',
             doc_root.file('test.txt'), '/test.txt'),
            ('./test.txt', dir.file('Foo/Bar/test.txt'), './test.txt'),
            (r'.\test.txt', dir.file('Foo/Bar/test.txt'), './test.txt'),
            ('../test.txt', dir.file('Foo/test.txt'), '../test.txt'),
            (r'..\test.txt', dir.file('Foo/test.txt'), '../test.txt'),
            ('../Bar/Baz/test.txt', dir.file('Foo/Bar/Baz/test.txt'),
             './Baz/test.txt'),
            (r'C:\foo\bar', File('file:///C:/foo/bar'), None),
            (r'Z:\foo\bar', File('file:///Z:/foo/bar'), None),
        ):
            #~ print link, '>>', self.notebook.resolve_file(link, path)
            if cleaned is not None and not cleaned.startswith('/'):
                cleaned = os_native_path(cleaned)
            self.assertEqual(self.notebook.resolve_file(link, path), wanted)
            self.assertEqual(self.notebook.relative_filepath(wanted, path),
                             cleaned)

        # check relative path without Path
        self.assertEqual(
            self.notebook.relative_filepath(doc_root.file('foo.txt')),
            '/foo.txt')
        self.assertEqual(self.notebook.relative_filepath(dir.file('foo.txt')),
                         os_native_path('./foo.txt'))
Exemplo n.º 14
0
from zim.applications import Application
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

Exemplo n.º 15
0
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'))
Exemplo n.º 16
0
    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 = Notebook(dir=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()))
Exemplo n.º 17
0
	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) )
Exemplo n.º 18
0
    def runTest(self):
        tmp_dir = Dir(self.create_tmp_dir())

        for name in ('test1.txt', 'test2.txt', 'test3.txt'):
            tmp_dir.file(name).write('test 123')

        tmp_dir.subdir('folder1').touch()

        # Single file
        file = tmp_dir.file('test1.txt')
        self.assertTrue(file.exists())

        dialog = FileDialog(None, 'Test')
        self.assertIsNone(dialog.get_file())

        dialog.set_file(file)
        tests.gtk_process_events()
        dialog.set_file(file)
        tests.gtk_process_events()
        dialog.set_file(file)
        tests.gtk_process_events()

        myfile = dialog.get_file()
        self.assertIsInstance(myfile, File)
        self.assertEqual(myfile.uri, file.uri)

        dialog.assert_response_ok()
        self.assertIsInstance(dialog.result, File)
        self.assertEqual(dialog.result.uri, file.uri)

        # Multiple files
        file1 = tmp_dir.file('test1.txt')
        file2 = tmp_dir.file('test2.txt')
        self.assertTrue(file1.exists())
        self.assertTrue(file2.exists())

        dialog = FileDialog(None, 'Test', multiple=True)
        assert dialog.filechooser.select_uri(file1.uri)
        assert dialog.filechooser.select_uri(file2.uri)
        tests.gtk_process_events()

        self.assertRaises(AssertionError, dialog.get_file)

        files = dialog.get_files()
        self.assertTrue(all(isinstance(f, File) for f in files))
        #~ self.assertEqual([f.uri for f in files], [file1.uri, file2.uri]) -- TODO

        ## FIXME, fails for unclear reason on windows under msys
        #dialog.assert_response_ok()
        #self.assertIsInstance(dialog.result, list)

        # Select folder
        folder = tmp_dir.subdir('folder1')
        self.assertTrue(folder.exists())

        dialog = FileDialog(None,
                            'Test',
                            action=Gtk.FileChooserAction.SELECT_FOLDER)
        assert dialog.filechooser.select_uri(folder.uri)
        tests.gtk_process_events()
        assert dialog.filechooser.select_uri(folder.uri)
        tests.gtk_process_events()
        assert dialog.filechooser.select_uri(folder.uri)
        tests.gtk_process_events()

        myfolder = dialog.get_dir()
        self.assertIsInstance(myfolder, Dir)
        self.assertEqual(myfolder.uri, folder.uri)

        dialog.assert_response_ok()
        self.assertIsInstance(dialog.result, Dir)
Exemplo n.º 19
0
	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()))
Exemplo n.º 20
0
    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))
Exemplo n.º 21
0
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

Exemplo n.º 22
0
class TestExportCommand(tests.TestCase):
    def setUp(self):
        self.tmpdir = Dir(self.create_tmp_dir())
        self.notebook = self.tmpdir.subdir('notebook')
        init_notebook(self.notebook)

    def testOptions(self):
        # Only testing we get a valid exporter, not the full command,
        # because the command is very slow

        ## Full notebook, minimal options
        cmd = ExportCommand('export')
        cmd.parse_options(self.notebook.path)
        self.assertRaises(UsageError, cmd.get_exporter, None)

        cmd = ExportCommand('export')
        cmd.parse_options(
            self.notebook.path,
            '--output',
            self.tmpdir.subdir('output').path,
        )
        exp = cmd.get_exporter(None)
        self.assertIsInstance(exp, MultiFileExporter)
        self.assertIsInstance(exp.layout, MultiFileLayout)
        self.assertIsInstance(exp.layout.dir, Dir)
        self.assertIsInstance(exp.template, Template)
        self.assertIsNone(exp.document_root_url)
        self.assertIsNotNone(exp.format)
        self.assertIsNone(exp.index_page)

        ## Full notebook, full options
        cmd = ExportCommand('export')
        cmd.parse_options(
            self.notebook.path,
            '--format',
            'markdown',
            '--template',
            './tests/data/TestTemplate.html',
            '--output',
            self.tmpdir.subdir('output').path,
            '--root-url',
            '/foo/',
            '--index-page',
            'myindex',
            '--overwrite',
        )
        exp = cmd.get_exporter(None)
        self.assertIsInstance(exp, MultiFileExporter)
        self.assertIsInstance(exp.layout, MultiFileLayout)
        self.assertIsInstance(exp.layout.dir, Dir)
        self.assertIsInstance(exp.template, Template)
        self.assertIsNotNone(exp.document_root_url)
        self.assertIsNotNone(exp.format)
        self.assertIsNotNone(exp.index_page)

        ## Full notebook, single page
        cmd = ExportCommand('export')
        cmd.parse_options(self.notebook.path, '--format', 'markdown',
                          '--template', './tests/data/TestTemplate.html',
                          '--output',
                          self.tmpdir.file('output.md').path, '-s')
        exp = cmd.get_exporter(None)
        self.assertIsInstance(exp, SingleFileExporter)
        self.assertIsInstance(exp.layout, SingleFileLayout)
        self.assertIsInstance(exp.layout.file, File)

        ## Single page
        cmd = ExportCommand('export')
        cmd.parse_options(
            self.notebook.path,
            'Foo:Bar',
            '--output',
            self.tmpdir.subdir('output').path,
        )
        exp = cmd.get_exporter(Path('Foo:Bar'))
        self.assertIsInstance(exp, MultiFileExporter)
        self.assertIsInstance(exp.layout, FileLayout)
        self.assertIsInstance(exp.layout.file, File)
        self.assertIsInstance(exp.template, Template)
        self.assertIsNone(exp.document_root_url)
        self.assertIsNotNone(exp.format)
        self.assertIsNone(exp.index_page)

        cmd = ExportCommand('export')
        cmd.parse_options(
            self.notebook.path,
            'Foo:Bar',
            '--recursive',
            '--output',
            self.tmpdir.subdir('output').path,
        )
        exp = cmd.get_exporter(Path('Foo:Bar'))
        self.assertIsInstance(exp, MultiFileExporter)
        self.assertIsInstance(exp.layout, FileLayout)
        self.assertIsInstance(exp.layout.file, File)
        self.assertIsInstance(exp.template, Template)
        self.assertIsNone(exp.document_root_url)
        self.assertIsNotNone(exp.format)
        self.assertIsNone(exp.index_page)

        cmd = ExportCommand('export')
        cmd.parse_options(
            self.notebook.path,
            'Foo:Bar',
            '-rs',
            '--output',
            self.tmpdir.subdir('output').path,
        )
        exp = cmd.get_exporter(Path('Foo:Bar'))
        self.assertIsInstance(exp, SingleFileExporter)
        self.assertIsInstance(exp.layout, SingleFileLayout)
        self.assertIsInstance(exp.layout.file, File)
        self.assertIsInstance(exp.template, Template)
        self.assertIsNone(exp.document_root_url)
        self.assertIsNotNone(exp.format)

        ## MHTML exporter
        cmd = ExportCommand('export')
        cmd.parse_options(
            self.notebook.path,
            'Foo:Bar',
            '-rs',
            '--format',
            'mhtml',
            '--output',
            self.tmpdir.subdir('output').path,
        )
        exp = cmd.get_exporter(Path('Foo:Bar'))
        self.assertIsInstance(exp, MHTMLExporter)
        self.assertIsInstance(exp.file, File)
        self.assertIsInstance(exp.template, Template)
        self.assertIsNone(exp.document_root_url)

    @tests.slowTest
    def testExport(self):
        # Only test single page, just to show "run()" works
        file = self.notebook.file('Foo/Bar.txt')
        file.write('=== Foo\ntest 123\n')

        output = self.tmpdir.file('output.html')

        cmd = ExportCommand('export')
        cmd.parse_options(self.notebook.path, 'Foo:Bar', '--output',
                          output.path, '--template',
                          'tests/data/TestTemplate.html')
        cmd.run()

        self.assertTrue(output.exists())
        html = output.read()
        self.assertTrue('<h1>Foo' in html)
        self.assertTrue('test 123' in html)
Exemplo n.º 23
0
	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) )