Esempio n. 1
0
	def runTest(self):
		'Test WWW interface'
		config = VirtualConfigManager()
		notebook = tests.new_notebook(fakedir=self.get_tmp_name())
		notebook.index.update()
		interface = WWWInterface(notebook, config=config, template=self.template)
		validator = wsgiref.validate.validator(interface)

		def call(command, path):
			environ = {
				'REQUEST_METHOD': command,
				'SCRIPT_NAME': '',
				'PATH_INFO': path,
				'QUERY_STRING': '',
				'SERVER_NAME': 'localhost',
				'SERVER_PORT': '80',
				'SERVER_PROTOCOL': '1.0'
			}
			rfile = StringIO('')
			wfile = StringIO()
			handler = wsgiref.handlers.SimpleHandler(rfile, wfile, sys.stderr, environ)
			if os.name == 'nt':
				# HACK: on windows we have no file system encoding,
				# but use unicode instead for os API.
				# However wsgiref.validate fails on unicode param
				# in environmnet.
				for k, v in handler.os_environ.items():
					if isinstance(v, unicode):
						handler.os_environ[k] = v.encode('utf-8')

			handler.run(validator)
			#~ print '>>>>\n', wfile.getvalue(), '<<<<'
			return wfile.getvalue()

		# index
		for path in ('/', '/Test/'):
			response = call('HEAD', path)
			self.assertResponseOK(response, expectbody=False)
			response = call('GET', path)
			#~ print '>'*80, '\n', response, '<'*80
			self.assertResponseOK(response)
			self.assertTrue('<li><a href="/Test/foo.html" title="foo" class="page">foo</a>' in response)

		# page
		response = call('GET', '/Test/foo.html')
		self.assertResponseOK(response)
		self.assertTrue('<h1>Foo</h1>' in response)

		# page not found
		with Filter404():
			for path in self.file_not_found_paths:
				response = call('GET', path)
				header, body = self.assertResponseWellFormed(response)
				self.assertEqual(header[0], 'HTTP/1.0 404 Not Found')

		# favicon and other files
		for path in self.file_found_paths:
			response = call('GET', path)
			header, body = self.assertResponseWellFormed(response)
			self.assertEqual(header[0], 'HTTP/1.0 200 OK')
Esempio n. 2
0
 def setUp(self):
     zim.history.MAX_HISTORY = 100
     self.notebook = tests.new_notebook()
     self.pages = [
         self.notebook.get_page(Path(name))
         for name in self.notebook.testdata_manifest
     ]
Esempio n. 3
0
	def testTaskListTreeView(self):
		klass = PluginManager.get_plugin_class('tasklist')
		plugin = klass()

		notebook = tests.new_notebook()
		plugin.extend(notebook)
		notebook.index.check_and_update()

		from zim.plugins.tasklist.gui import TaskListTreeView
		view = TasksView.new_from_index(notebook.index)
		opener = tests.MockObject()
		treeview = TaskListTreeView(view, opener, task_labels=['TODO', 'FIXME'])

		menu = treeview.get_popup()

		# Check these do not cause errors - how to verify state ?
		tests.gtk_activate_menu_item(menu, _("Expand _All"))
		tests.gtk_activate_menu_item(menu, _("_Collapse All"))

		# Copy tasklist -> csv
		from zim.gui.clipboard import Clipboard
		tests.gtk_activate_menu_item(menu, 'gtk-copy')
		text = Clipboard.get_text()
		lines = text.splitlines()
		self.assertTrue(len(lines) > 10)
		self.assertTrue(len(lines[0].split(',')) > 3)
		self.assertFalse(any('<span' in l for l in lines)) # make sure encoding is removed

		# Test tags
		tags = treeview.get_tags()
		for tag in ('home', 'FIXME', '__no_tags__', 'tags'):
			self.assertIn(tag, tags)
			self.assertGreater(tags[tag], 0)
Esempio n. 4
0
	def setUp(self):
		# Note that in this test our index is not the default index
		# for the notebook. So any assumption from the notebook about
		# the index will be wrong.
		self.index = Index(dbfile=':memory:')
		self.notebook = tests.new_notebook()
		self.index.set_notebook(self.notebook)
Esempio n. 5
0
 def setUp(self):
     # Note that in this test our index is not the default index
     # for the notebook. So any assumption from the notebook about
     # the index will be wrong.
     self.index = Index(dbfile=':memory:')
     self.notebook = tests.new_notebook()
     self.index.set_notebook(self.notebook)
Esempio n. 6
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')
Esempio n. 7
0
    def testParseExec(self):
        """Test parsing of custom tool Exec strings"""
        # %f for source file as tmp file current page
        # %d for attachment directory
        # %s for real source file (if any)
        # %n for notebook location (file or directory)
        # %D for document root
        # %t for selected text or word under cursor
        # %T for selected text or word under cursor with wiki format

        path = self.get_tmp_name()
        notebook = tests.new_notebook(fakedir=path)
        page = notebook.get_page(Path("Test:Foo"))
        pageview = StubPageView()
        args = (notebook, page, pageview)

        tmpfile = TmpFile("tmp-page-source.txt").path
        dir = notebook.dir

        tool = CustomToolDict()
        tool.update({"Name": "Test", "Description": "Test 1 2 3", "X-Zim-ExecTool": "foo"})
        for cmd, wanted in (
            ("foo %f", ("foo", tmpfile)),
            ("foo %d", ("foo", dir.subdir("Test/Foo").path)),
            ("foo %s", ("foo", "")),  # no file source
            ("foo %n", ("foo", dir.path)),
            ("foo %D", ("foo", "")),  # no document root
            ("foo %t", ("foo", "FooBar")),
            ("foo %T", ("foo", "**FooBar**")),
        ):
            # ~ print '>>>', cmd
            tool["Desktop Entry"]["X-Zim-ExecTool"] = cmd
            self.assertEqual(tool.parse_exec(args), wanted)
Esempio n. 8
0
 def setUp(self):
     self.ui = tests.MockObject()
     self.ui.page = Path('Test')
     self.notebook = tests.new_notebook()
     self.ui.notebook = self.notebook
     self.model = PageTreeStore(self.notebook.index)
     self.treeview = PageTreeView(self.ui, self.model)
Esempio n. 9
0
	def testTemplate(self):
		pluginklass = zim.plugins.get_plugin_class('calendar')
		plugin = pluginklass()

		notebook = tests.new_notebook()

		template = get_template('wiki', 'Journal')
		zim.datetimetz.FIRST_DAY_OF_WEEK = \
			zim.datetimetz.MONDAY
		plugin.preferences['namespace'] = Path('Calendar')

		for path in (
			'Calendar:2012',
			'Calendar:2012:04:27',
			'Calendar:2012:Week 17',
			'Calendar:2012:04',
		):
			page = notebook.get_page(Path(path))
			lines = template.process(notebook, page)
			text = ''.join(lines)
			#~ print text
			self.assertTrue(not 'Created' in text) # No fall back
			if 'Week' in path:
				days = [l for l in lines if l.startswith('=== ')]
				self.assertEqual(len(days), 7)
Esempio n. 10
0
	def setUp(self):
		self.ui = tests.MockObject()
		self.ui.page = Path('Test')
		self.notebook = tests.new_notebook()
		self.ui.notebook = self.notebook
		self.model = PageTreeStore(self.notebook.index)
		self.treeview = PageTreeView(self.ui, self.model)
Esempio n. 11
0
def setupGtkInterface(test, klass=None, notebook=None):
    '''Setup a new GtkInterface object for testing.
	Will have test notebook, and default preferences.
	@param test: the test that wants to use this ui object
	@param klass: the klass to use, defaults to L{GtkInterface}, but
	could be partially mocked subclass
	'''
    if klass is None:
        klass = zim.gui.GtkInterface

    # start filtering
    filter = FilterNoSuchImageWarning()
    filter.wrap_test(test)

    # create interface object with new notebook
    if notebook is None:
        dirpath = test.get_tmp_name()
        notebook = tests.new_notebook(fakedir=dirpath)

    config = VirtualConfigManager()
    ui = klass(config=config, notebook=notebook)

    ui.mainwindow.init_uistate()
    ui.open_page(Path('Test:foo:bar'))

    return ui
Esempio n. 12
0
def setupGtkInterface(test, klass=None, notebook=None):
    '''Setup a new GtkInterface object for testing.
	Will have test notebook, and default preferences.
	@param test: the test that wants to use this ui object
	@param klass: the klass to use, defaults to L{GtkInterface}, but
	could be partially mocked subclass
	'''
    if klass is None:
        klass = zim.gui.GtkInterface

    # start filtering
    filter = FilterNoSuchImageWarning()
    filter.wrap_test(test)

    # create interface object with new notebook
    if notebook is None:
        test.clear_tmp_dir()
        dirpath = test.get_tmp_name()
        notebook = tests.new_notebook(fakedir=dirpath)

    config = VirtualConfigManager()
    prefs = config.get_config_dict('<profile>/preferences.conf')
    prefs['General'].input(
        plugins=['calendar', 'insertsymbol', 'printtobrowser'])
    # version control interferes with source folder, leave other default plugins

    ui = klass(config=config, notebook=notebook)

    ui._mainwindow.init_uistate()  # XXX
    ui.open_page(Path('Test:foo:bar'))

    return ui
Esempio n. 13
0
    def runTest(self):
        '''Test proper linking of files in export'''
        notebook = tests.new_notebook(fakedir='/source/dir/')

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

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

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

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

        href = interwiki_link('foo?Ideas:Task List')
        self.assertIsNotNone(href)
        self.assertEqual(linker.link('foo?Ideas:Task List'),
                         uri + '/Ideas/Task_List.txt')
Esempio n. 14
0
	def testTemplate(self):
		pluginklass = PluginManager.get_plugin_class('calendar')
		plugin = pluginklass()
		plugin.preferences['namespace'] = Path('Calendar')

		notebook = tests.new_notebook()
		plugin.extend(notebook)

		dumper = get_dumper('wiki')

		zim.datetimetz.FIRST_DAY_OF_WEEK = \
			zim.datetimetz.MONDAY
		for path in (
			Path('Calendar:2012'),
			Path('Calendar:2012:04:27'),
			Path('Calendar:2012:Week 17'),
			Path('Calendar:2012:04'),
		):
			tree = notebook.get_template(path)
			lines = dumper.dump(tree)
			#~ print lines
			self.assertTrue(not 'Created' in ''.join(lines)) # No fall back
			if 'Week' in path.name:
				days = [l for l in lines if l.startswith('=== ')]
				self.assertEqual(len(days), 7)
Esempio n. 15
0
def setupGtkInterface(test, klass=None, notebook=None):
	'''Setup a new GtkInterface object for testing.
	Will have test notebook, and default preferences.
	@param test: the test that wants to use this ui object
	@param klass: the klass to use, defaults to L{GtkInterface}, but
	could be partially mocked subclass
	'''
	if klass is None:
		klass = zim.gui.GtkInterface

	# start filtering
	filter = FilterNoSuchImageWarning()
	filter.wrap_test(test)


	# create interface object with new notebook
	if notebook is None:
		dirpath = test.get_tmp_name()
		notebook = tests.new_notebook(fakedir=dirpath)

	config = VirtualConfigManager()
	ui = klass(config=config, notebook=notebook)

	ui.mainwindow.init_uistate()
	ui.open_page(Path('Test:foo:bar'))

	return ui
Esempio n. 16
0
    def testTaskListTreeView(self):
        klass = zim.plugins.get_plugin_class('tasklist')
        plugin = klass()

        notebook = tests.new_notebook()
        plugin.extend(notebook.index)
        index_ext = plugin.get_extension(IndexExtension)
        self.assertIsNotNone(index_ext)

        notebook.index.flush()
        notebook.index.update()

        from zim.plugins.tasklist import TaskListTreeView
        opener = tests.MockObject()
        treeview = TaskListTreeView(index_ext, opener)

        menu = treeview.get_popup()

        # Check these do not cause errors - how to verify state ?
        tests.gtk_activate_menu_item(menu, _("Expand _All"))
        tests.gtk_activate_menu_item(menu, _("_Collapse All"))

        # Copy tasklist -> csv
        from zim.gui.clipboard import Clipboard
        tests.gtk_activate_menu_item(menu, 'gtk-copy')
        text = Clipboard.get_text()
        lines = text.splitlines()
        self.assertTrue(len(lines) > 10)
        self.assertTrue(len(lines[0].split(',')) > 3)
        self.assertFalse(any('<span' in l
                             for l in lines))  # make sure encoding is removed
Esempio n. 17
0
    def setUp(self):
        tmpdir = self.get_tmp_name()
        notebook = tests.new_notebook(tmpdir + '/notebook')
        layout = MultiFileLayout(Dir(tmpdir + '/export'), 'html')
        linker_factory = partial(ExportLinker,
                                 notebook=notebook,
                                 layout=layout,
                                 output=layout.page_file(Path('test')),
                                 usebase=True)
        dumper_factory = get_format('html').Dumper

        title = 'Test Export'
        self.content = [notebook.get_page(Path('Test:foo'))]
        self.context = ExportTemplateContext(
            notebook,
            linker_factory,
            dumper_factory,
            title,
            self.content,
            special=None,
            home=None,
            up=None,
            prevpage=None,
            nextpage=None,
            links=None,
        )
Esempio n. 18
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)
Esempio n. 19
0
File: gui.py Progetto: Jam71/Zim-QDA
def setupGtkInterface(test, klass=None):
	'''Setup a new GtkInterface object for testing.
	Will have test notebook, and default preferences.
	@param test: the test that wants to use this ui object
	@param klass: the klass to use, defaults to L{GtkInterface}, but
	could be partially mocked subclass
	'''
	if klass is None:
		klass = zim.gui.GtkInterface

	# start filtering
	filter = FilterNoSuchImageWarning()
	filter.wrap_test(test)

	# flush preferences
	preferences = config_file('preferences.conf')
	preferences.file.remove()

	# create interface object with new notebook
	dirpath = test.get_tmp_name()
	notebook = tests.new_notebook(fakedir=dirpath)
	path = Path('Test:foo:bar')
	ui = klass(notebook=notebook, page=path)

	# finalize plugins
	for plugin in ui.plugins:
		plugin.finalize_ui(ui)

	ui.mainwindow.init_uistate()

	return ui
Esempio n. 20
0
	def testTaskListTreeView(self):
		klass = PluginManager.get_plugin_class('tasklist')
		plugin = klass()

		notebook = tests.new_notebook()
		plugin.extend(notebook.index)
		index_ext = plugin.get_extension(IndexExtension)
		self.assertIsNotNone(index_ext)

		notebook.index.flush()
		notebook.index.update()

		from zim.plugins.tasklist import TaskListTreeView
		opener = tests.MockObject()
		treeview = TaskListTreeView(index_ext, opener)

		menu = treeview.get_popup()

		# Check these do not cause errors - how to verify state ?
		tests.gtk_activate_menu_item(menu, _("Expand _All"))
		tests.gtk_activate_menu_item(menu, _("_Collapse All"))

		# Copy tasklist -> csv
		from zim.gui.clipboard import Clipboard
		tests.gtk_activate_menu_item(menu, 'gtk-copy')
		text = Clipboard.get_text()
		lines = text.splitlines()
		self.assertTrue(len(lines) > 10)
		self.assertTrue(len(lines[0].split(',')) > 3)
		self.assertFalse(any('<span' in l for l in lines)) # make sure encoding is removed
Esempio n. 21
0
    def testTemplate(self):
        pluginklass = PluginManager.get_plugin_class('calendar')
        plugin = pluginklass()
        plugin.preferences['namespace'] = Path('Calendar')

        notebook = tests.new_notebook()
        plugin.extend(notebook)

        dumper = get_dumper('wiki')

        zim.datetimetz.FIRST_DAY_OF_WEEK = \
         zim.datetimetz.MONDAY
        for path in (
                Path('Calendar:2012'),
                Path('Calendar:2012:04:27'),
                Path('Calendar:2012:Week 17'),
                Path('Calendar:2012:04'),
        ):
            tree = notebook.get_template(path)
            lines = dumper.dump(tree)
            #~ print lines
            self.assertTrue(not 'Created' in ''.join(lines))  # No fall back
            if 'Week' in path.name:
                days = [l for l in lines if l.startswith('=== ')]
                self.assertEqual(len(days), 7)
Esempio n. 22
0
    def __init__(self, page=None, fakedir=None):
        tests.MockObject.__init__(self)

        if page and not isinstance(page, Path):
            self.page = Path(page)
        else:
            self.page = page

        self.notebook = tests.new_notebook(fakedir=fakedir)
Esempio n. 23
0
	def setUp(self):
		self.ui = tests.MockObject()
		self.ui.page = Path('Test')
		self.notebook = tests.new_notebook()
		self.ui.notebook = self.notebook
		self.model = PageTreeStore(self.notebook.index)
		self.treeview = PageTreeView(self.ui, self.model)
		treepath = self.treeview.set_current_page(Path('Test'))
		self.treeview.select_treepath(treepath)
Esempio n. 24
0
    def setUp(self):
        path = self.get_tmp_name()
        self.nb = tests.new_notebook(fakedir=path)
        self.assertIsNone(self.nb.profile)

        with FilterFailedToLoadPlugin():
            self.ui = NotebookInterface(self.nb)

        configfile = self.ui.preferences.file
        configfile.file.remove()  # just in case
Esempio n. 25
0
	def testDefaulPlugins(self):
		'''Test loading default plugins'''
		# Note that we use parent interface class here, so plugins
		# will not really attach - just testing loading and prereq
		# checks are OK.
		notebook = tests.new_notebook()
		interface = zim.NotebookInterface(notebook)
		interface.uistate = zim.config.ConfigDict()
		interface.load_plugins()
		self.assertTrue(len(interface.plugins) > 3)
Esempio n. 26
0
    def testExport(self):
        """test the export of a wiki page to latex"""
        with LatexLoggingFilter():
            format = get_format("LaTeX")
            testpage = tests.WikiTestData.get("Test:wiki")
            tree = get_format("wiki").Parser().parse(testpage)
            output = format.Dumper(linker=StubLinker()).dump(tree)
            # ~ print '>>>\n' + ''.join(output) + '<<<'
            self.assertTrue("\chapter{Foo Bar}\n" in output)

            # Test template_options.document_type
        input = r"""
[% options.document_type = 'book' -%]
\title{[% page.basename %]}

\begin{document}
\maketitle
\tableofcontents
[% page.body %]
\end{document}
"""
        wanted = r"""
\title{FooBar}

\begin{document}
\maketitle
\tableofcontents
\textbf{foo bar !}



\chapter{Heading 2}

duss


\end{document}
"""

        notebook = tests.new_notebook()
        page = notebook.get_page(Path("FooBar"))
        page.parse(
            "wiki",
            """\
====== Page Heading ======
**foo bar !**

===== Heading 2 =====
duss
""",
        )

        template = Template(input, "latex", linker=StubLinker())
        result = template.process(notebook, page)
        self.assertEqual("".join(result), wanted)
Esempio n. 27
0
	def runTest(self):
		input = u'''\
Version [% zim.version %]
<title>[% page.title %]</title>
Created [% page.properties['Creation-Date'] %]
<h1>[% notebook.name %]: [% page.name %]</h1>
<h2>[% page.heading %]</h2>
[% options.foo = "bar" %]
[%- page.body -%]
Option: [% options.foo %]
'''
		wantedresult = u'''\
Version %s
<title>Page Heading</title>
Created TODAY
<h1>Unnamed Notebook: FooBar</h1>
<h2>Page Heading</h2>
<p>
<b>foo bar !</b>
</p>
Option: bar
''' % zim.__version__
		notebook = tests.new_notebook()
		page = notebook.get_page(Path('FooBar'))
		page.parse('wiki', '''\
====== Page Heading ======
**foo bar !**
''')
		page.properties['Creation-Date'] = 'TODAY'
		self.assertTrue(len(page.dump('html', linker=StubLinker())) > 0)
		template = Template(input, 'html', linker=StubLinker())
		result = template.process(notebook, page)
		self.assertEqual(''.join(result), wantedresult)
		self.assertEqual(template.template_options['foo'], 'bar')

		# Check new page template
		notebook = tests.new_notebook()
		page = notebook.get_page(Path('Some New None existing page'))
		template = notebook.get_template(page)
		tree = template.process_to_parsetree(notebook, page) # No linker !
		head = tree.find('h').gettext()
		self.assertEqual(head, u'Some New None existing page')
Esempio n. 28
0
	def runTest(self):
		'Test PrintToBrowser plugin'
		pluginklass = PluginManager.get_plugin_class('printtobrowser')
		plugin = pluginklass()

		notebook = tests.new_notebook()
		page = notebook.get_page(Path('Test:foo'))
		file = plugin.print_to_file(notebook, page)
		self.assertTrue(file.exists())
		content = file.read()
		self.assertTrue('<h1>Foo</h1>' in content)
Esempio n. 29
0
    def runTest(self):
        'Test PrintToBrowser plugin'
        pluginklass = zim.plugins.get_plugin_class('printtobrowser')
        plugin = pluginklass()

        notebook = tests.new_notebook()
        page = notebook.get_page(Path('Test:foo'))
        file = plugin.print_to_file(notebook, page)
        self.assertTrue(file.exists())
        content = file.read()
        self.assertTrue('<h1>Foo</h1>' in content)
Esempio n. 30
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')
Esempio n. 31
0
	def runTest(self):
		ui = MockUI()
		ui.notebook = tests.new_notebook()
		uistate = ConfigDict()
		widget = TagsPluginWidget(ui.notebook.index, uistate, ui)

		# Excersize all model switches and check we still have a sane state
		widget.toggle_treeview()
		widget.toggle_treeview()

		path = Path('Test:tags')
		ui.notebook.pages.lookup_by_pagename(path)
		treepath = widget.treeview.get_model().find(path)

		widget.disconnect_model()
		widget.reconnect_model()

		path = Path('Test:tags')
		treepath = widget.treeview.get_model().find(path)

		# Check signals
		widget.treeview.emit('populate-popup', gtk.Menu())
		widget.treeview.emit('insert-link', path)

		# Toggles in popup
		widget.toggle_show_full_page_name()
		widget.toggle_show_full_page_name()

		# Check tag filtering
		cloud = widget.tagcloud
		self.assertFalse(cloud.get_tag_filter())
		tag = None
		for button in cloud.get_children():
			if button.indextag.name == 'tags':
				tag = button.indextag
				button.clicked()
				break
		else:
			raise AssertionError('No button for @tags ?')

		selected = cloud.get_tag_filter()
		self.assertEqual(selected, [tag])
		model = widget.treeview.get_model()
		self.assertIsInstance(model, TaggedPageTreeStore)
		self.assertEqual(model.tags, [tag.name])

		# check menu and sorting of tag cloud
		cloud.emit('populate-popup', gtk.Menu())
		mockaction = tests.MockObject()
		mockaction.get_active = lambda: True
		cloud._switch_sorting(mockaction)
		mockaction.get_active = lambda: False
		cloud._switch_sorting(mockaction)
Esempio n. 32
0
    def __init__(self, page=None, fakedir=None):
        tests.MockObject.__init__(self)

        self.tmp_dir = self.create_tmp_dir()

        if page and not isinstance(page, Path):
            self.page = Path(page)
        else:
            self.page = page

        self.mainwindow = None
        self.notebook = tests.new_notebook(fakedir=fakedir)
Esempio n. 33
0
File: gui.py Progetto: Jam71/Zim-QDA
	def __init__(self, page=None, fakedir=None):
		tests.MockObject.__init__(self)

		self.tmp_dir = self.create_tmp_dir()

		if page and not isinstance(page, Path):
			self.page = Path(page)
		else:
			self.page = page

		self.mainwindow = None
		self.notebook = tests.new_notebook(fakedir=fakedir)
Esempio n. 34
0
	def testExport(self):
		'''test the export of a wiki page to latex'''
		with LatexLoggingFilter():
			format = get_format('LaTeX')
			testpage = tests.WikiTestData.get('Test:wiki')
			tree = get_format('wiki').Parser().parse(testpage)
			output = format.Dumper(linker=StubLinker()).dump(tree)
			#~ print '>>>\n' + ''.join(output) + '<<<'
			self.assertTrue('\chapter{Foo Bar}\n' in output)

		# Test template_options.document_type
		input = r'''
[% options.document_type = 'book' -%]
\title{[% page.basename %]}

\begin{document}
\maketitle
\tableofcontents
[% page.body %]
\end{document}
'''
		wanted = r'''
\title{FooBar}

\begin{document}
\maketitle
\tableofcontents
\textbf{foo bar !}



\chapter{Heading 2}

duss


\end{document}
'''

		notebook = tests.new_notebook()
		page = notebook.get_page(Path('FooBar'))
		page.parse('wiki', '''\
====== Page Heading ======
**foo bar !**

===== Heading 2 =====
duss
''')

		template = Template(input, 'latex', linker=StubLinker())
		result = template.process(notebook, page)
		self.assertEqual(''.join(result), wanted)
Esempio n. 35
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
Esempio n. 36
0
	def runTest(self):
		dir =  Dir(self.create_tmp_dir())
		#~ dir =  VirtualDir('/test')
		notebook = tests.new_notebook(fakedir='/foo')
		pages = AllPages(notebook)

		exporter = build_notebook_exporter(dir, 'html', 'Default')
		self.assertIsInstance(exporter, MultiFileExporter)
		exporter.export(pages)

		file = exporter.layout.page_file(Path('roundtrip'))
		text =  file.read()
		self.assertIn('Lorem ipsum dolor sit amet', text)
Esempio n. 37
0
    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)
Esempio n. 38
0
File: gui.py Progetto: Jam71/Zim-QDA
	def testSearchDialog(self):
		'''Test SearchDialog'''
		from zim.gui.searchdialog import SearchDialog
		self.ui.notebook = tests.new_notebook()
		dialog = SearchDialog(self.ui)
		dialog.query_entry.set_text('Foo')
		dialog.query_entry.activate()
		model = dialog.results_treeview.get_model()
		self.assertTrue(len(model) > 3)

		self.ui.mainwindow = tests.MockObject()
		self.ui.mainwindow.pageview = tests.MockObject()
		col = dialog.results_treeview.get_column(0)
		dialog.results_treeview.row_activated((0,), col)
Esempio n. 39
0
    def runTest(self):
        manager = PluginManager()
        preferences = manager.config.get_config_dict(
            '<profile>/preferences.conf')
        self.assertFalse(preferences.modified)
        for name in list_plugins():
            klass = get_plugin_class(name)
            if klass.check_dependencies_ok():
                manager.load_plugin(name)
                self.assertIn(name, manager)

                self.assertFalse(
                    preferences.modified,
                    'Plugin "%s" modified the preferences while loading' %
                    name)

        self.assertTrue(len(manager) > 3)

        for i, name in enumerate(manager):
            manager[name].preferences.emit('changed')
            # Checking for exceptions and infinite recursion

        self.assertTrue(i > 0)
        #~ self.assertTrue(preferences.modified)
        # If "False" the check while loading the plugins is not valid
        # FIXME this detection is broken due to autosave in ConfigManager ...

        notebook = tests.new_notebook(self.get_tmp_name())
        ui = setupGtkInterface(self, notebook=notebook)
        dialog = PropertiesDialog(ui)  # random dialog
        for obj in (
                notebook,
                notebook.index,
                ui.mainwindow,
                ui.mainwindow.pageview,
                dialog,
        ):
            manager.extend(obj)

        for i, name in enumerate(manager):
            manager[name].preferences.emit('changed')
            # Checking for exceptions and infinite recursion

        for name in manager:
            #~ print "REMOVE:", name
            self.assertIsInstance(manager[name], PluginClass)
            manager.remove_plugin(name)
            self.assertNotIn(name, manager)

        self.assertTrue(len(manager) == 0)
Esempio n. 40
0
    def testSearchDialog(self):
        '''Test SearchDialog'''
        from zim.gui.searchdialog import SearchDialog
        self.ui.notebook = tests.new_notebook()
        dialog = SearchDialog(self.ui)
        dialog.query_entry.set_text('Foo')
        dialog.query_entry.activate()
        model = dialog.results_treeview.get_model()
        self.assertTrue(len(model) > 3)

        self.ui.mainwindow = tests.MockObject()
        self.ui.mainwindow.pageview = tests.MockObject()
        col = dialog.results_treeview.get_column(0)
        dialog.results_treeview.row_activated((0, ), col)
Esempio n. 41
0
	def runTest(self):
		notebook = tests.new_notebook()
		page = notebook.get_page(Path('FooBar'))

		page.parse('wiki', '''\
====== Page Heading ======
**foo bar !**
''')
		self.assertTrue(len(page.dump('html', linker=StubLinker())) > 0)
		proxy = PageProxy(Notebook(), page, zim.formats.get_format('html'), StubLinker(), {})
		self.assertEqual(proxy.name, page.name)
		self.assertEqual(proxy.namespace, page.namespace)
		self.assertEqual(proxy.basename, page.basename)
		self.assertTrue(isinstance(proxy.properties, dict))
		self.assertTrue(len(proxy.body) > 0)
Esempio n. 42
0
	def testDeletePages(self):
		'''Check deleting a bookmark after deleting a page in the notebook.'''

		notebook = tests.new_notebook()
		ui = MockUI()
		ui.notebook = notebook
		self.uistate['bookmarks'] = list(self.PATHS)

		Bar = BookmarkBar(ui, self.uistate, get_page_func = lambda: '')
		for i, path in enumerate(self.PATHS):
			self.assertTrue(path in Bar.paths)
			notebook.delete_page(Path(path))
			self.assertTrue(path not in Bar.paths)
			self.assertEqual(len(Bar.paths), self.LEN_PATHS - i - 1)
		self.assertEqual(Bar.paths, [])
Esempio n. 43
0
	def testDeletePages(self):
		'''Check deleting a bookmark after deleting a page in the notebook.'''

		notebook = tests.new_notebook()
		ui = MockUI()
		ui.notebook = notebook
		self.uistate['bookmarks'] = list(self.PATHS)

		Bar = BookmarkBar(ui, self.uistate, get_page_func = lambda: '')
		for i, path in enumerate(self.PATHS):
			self.assertTrue(path in Bar.paths)
			notebook.delete_page(Path(path))
			self.assertTrue(path not in Bar.paths)
			self.assertEqual(len(Bar.paths), self.LEN_PATHS - i - 1)
		self.assertEqual(Bar.paths, [])
Esempio n. 44
0
	def runTest(self):
		notebook = tests.new_notebook()
		page = notebook.get_page(Path('FooBar'))

		page.parse('wiki', '''\
====== Page Heading ======
**foo bar !**
''')
		self.assertTrue(len(page.dump('html', linker=StubLinker())) > 0)
		proxy = PageProxy(Notebook(), page, zim.formats.get_format('html'), StubLinker(), {})
		self.assertEqual(proxy.name, page.name)
		self.assertEqual(proxy.namespace, page.namespace)
		self.assertEqual(proxy.basename, page.basename)
		self.assertTrue(isinstance(proxy.properties, dict))
		self.assertTrue(len(proxy.body) > 0)
Esempio n. 45
0
    def testMultiFile(self):
        # TODO: run this with mock file
        # TODO: ensure template has resources
        # TODO: add attachements to test notebook

        from zim.fs import Dir
        folder = self.setUpFolder('multi', mock=tests.MOCK_ALWAYS_REAL)
        exporter = build_notebook_exporter(Dir(folder.path), 'html',
                                           'Default.html')

        notebook = tests.new_notebook(fakedir='/foo')
        pages = AllPages(notebook)

        # Now do it twice - should not raise for file exists
        exporter.export(pages)
        exporter.export(pages)
Esempio n. 46
0
	def runTest(self):
		manager = PluginManager()
		preferences = manager.config.get_config_dict('<profile>/preferences.conf')
		self.assertFalse(preferences.modified)
		for name in PluginManager.list_installed_plugins():
			klass = PluginManager.get_plugin_class(name)
			if klass.check_dependencies_ok():
				manager.load_plugin(name)
				self.assertIn(name, manager)

				self.assertFalse(preferences.modified,
					'Plugin "%s" modified the preferences while loading' % name)

		self.assertTrue(len(manager) > 3)

		for i, name in enumerate(manager):
			manager[name].preferences.emit('changed')
				# Checking for exceptions and infinite recursion

		self.assertTrue(i > 0)
		#~ self.assertTrue(preferences.modified)
			# If "False" the check while loading the plugins is not valid
			# FIXME this detection is broken due to autosave in ConfigManager ...

		notebook = tests.new_notebook(self.get_tmp_name())
		ui = setupGtkInterface(self, notebook=notebook)
		dialog = PropertiesDialog(ui) # random dialog
		for obj in (
			notebook,
			notebook.index,
			ui.mainwindow,
			ui.mainwindow.pageview,
			dialog,
		):
			manager.extend(obj)

		for i, name in enumerate(manager):
			manager[name].preferences.emit('changed')
				# Checking for exceptions and infinite recursion

		for name in manager:
			#~ print "REMOVE:", name
			self.assertIsInstance(manager[name], PluginClass)
			manager.remove_plugin(name)
			self.assertNotIn(name, manager)

		self.assertTrue(len(manager) == 0)
Esempio n. 47
0
File: calendar.py Progetto: gdw2/zim
	def testNotebookExtension(self):
		pluginklass = zim.plugins.get_plugin_class('calendar')
		plugin = pluginklass()

		notebook = tests.new_notebook(self.get_tmp_name())
		plugin.extend(notebook)

		ext = list(plugin.extensions)
		self.assertEqual(len(ext), 1)
		self.assertIsInstance(ext[0], NotebookExtension)

		page = Path('Foo')
		link = notebook.suggest_link(page, '2014-01-06')
		self.assertEqual(link.name, 'Journal:2014:01:06')

		link = notebook.suggest_link(page, 'foo')
		self.assertIsNone(link)
Esempio n. 48
0
    def testNotebookExtension(self):
        pluginklass = PluginManager.get_plugin_class('calendar')
        plugin = pluginklass()

        notebook = tests.new_notebook(self.get_tmp_name())
        plugin.extend(notebook)

        ext = list(plugin.extensions)
        self.assertEqual(len(ext), 1)
        self.assertIsInstance(ext[0], NotebookExtension)

        page = Path('Foo')
        link = notebook.suggest_link(page, '2014-01-06')
        self.assertEqual(link.name, 'Journal:2014:01:06')

        link = notebook.suggest_link(page, 'foo')
        self.assertIsNone(link)
Esempio n. 49
0
	def testIndexing(self):
		'''Check indexing of tasklist plugin'''
		klass = PluginManager.get_plugin_class('tasklist')
		plugin = klass()

		notebook = tests.new_notebook()
		plugin.extend(notebook.index)
		index_ext = plugin.get_extension(IndexExtension)
		self.assertIsNotNone(index_ext)

		# Test indexing based on index signals
		notebook.index.flush()
		notebook.index.update()
		self.assertTrue(index_ext.db_initialized)
		tasks = list(index_ext.list_tasks())
		self.assertTrue(len(tasks) > 5)
		for task in tasks:
			path = index_ext.get_path(task)
			self.assertTrue(not path is None)
Esempio n. 50
0
File: calendar.py Progetto: gdw2/zim
	def testMainWindowExtensions(self):
		pluginklass = zim.plugins.get_plugin_class('calendar')
		plugin = pluginklass()

		notebook = tests.new_notebook(self.get_tmp_name())
		ui = setupGtkInterface(self, notebook=notebook)

		plugin.preferences['embedded'] = True
		self.assertEqual(plugin.extension_classes['MainWindow'], MainWindowExtensionEmbedded)
		plugin.extend(ui.mainwindow)

		ext = list(plugin.extensions)
		self.assertEqual(len(ext), 1)
		self.assertIsInstance(ext[0], MainWindowExtensionEmbedded)

		plugin.preferences.changed() # make sure no errors are triggered

		ext[0].go_page_today()
		self.assertTrue(ui.page.name.startswith('Journal:'))

		plugin.preferences['embedded'] = False
		self.assertEqual(plugin.extension_classes['MainWindow'], MainWindowExtensionDialog)
		plugin.extend(ui.mainwindow) # plugin does not remember objects, manager does that

		ext = list(plugin.extensions)
		self.assertEqual(len(ext), 1)
		self.assertIsInstance(ext[0], MainWindowExtensionDialog)

		plugin.preferences.changed() # make sure no errors are triggered

		def test_dialog(dialog):
			self.assertIsInstance(dialog, CalendarDialog)
			dialog.do_today('xxx')
			ui.open_page(Path('foo'))

		with tests.DialogContext(test_dialog):
			ext[0].show_calendar()


		plugin.preferences['embedded'] = True # switch back
Esempio n. 51
0
	def testParseExec(self):
		'''Test parsing of custom tool Exec strings'''
		# %f for source file as tmp file current page
		# %d for attachment directory
		# %s for real source file (if any)
		# %n for notebook location (file or directory)
		# %D for document root
		# %t for selected text or word under cursor
		# %T for selected text or word under cursor with wiki format

		path = self.get_tmp_name()
		notebook = tests.new_notebook(fakedir=path)
		page = notebook.get_page(Path('Test:Foo'))
		pageview = StubPageView()
		args = (notebook, page, pageview)

		tmpfile = TmpFile('tmp-page-source.txt').path
		dir = notebook.dir

		tool = CustomToolDict()
		tool.update( {
			'Name': 'Test',
			'Comment': 'Test 1 2 3',
			'X-Zim-ExecTool': 'foo',
		} )
		for cmd, wanted in (
			('foo %f', ('foo', tmpfile)),
			('foo %d', ('foo', dir.subdir('Test/Foo').path)),
			('foo %s', ('foo', '')), # no file source
			('foo %n', ('foo', dir.path)),
			('foo %D', ('foo', '')), # no document root
			('foo %t', ('foo', 'FooBar')),
			('foo %T', ('foo', '**FooBar**')),
		):
			#~ print '>>>', cmd
			tool['Desktop Entry']['X-Zim-ExecTool'] = cmd
			self.assertEqual(tool.parse_exec(args), wanted)
Esempio n. 52
0
	def testMainWindowExtensions(self):
		plugin = ToCPlugin()

		notebook = tests.new_notebook(self.get_tmp_name())
		ui = setupGtkInterface(self, notebook=notebook)

		plugin.preferences['floating'] = True
		self.assertEqual(plugin.extension_classes['MainWindow'], MainWindowExtensionFloating)
		plugin.extend(ui.mainwindow)

		ext = list(plugin.extensions)
		self.assertEqual(len(ext), 1)
		self.assertIsInstance(ext[0], MainWindowExtensionFloating)

		plugin.preferences.changed() # make sure no errors are triggered
		plugin.preferences['show_h1'] = True
		plugin.preferences['show_h1'] = False
		plugin.preferences['pane'] = RIGHT_PANE
		plugin.preferences['pane'] = LEFT_PANE


		plugin.preferences['floating'] = False
		self.assertEqual(plugin.extension_classes['MainWindow'], MainWindowExtensionEmbedded)
		plugin.extend(ui.mainwindow) # plugin does not remember objects, manager does that

		ext = list(plugin.extensions)
		self.assertEqual(len(ext), 1)
		self.assertIsInstance(ext[0], MainWindowExtensionEmbedded)

		plugin.preferences.changed() # make sure no errors are triggered
		plugin.preferences['show_h1'] = True
		plugin.preferences['show_h1'] = False
		plugin.preferences['pane'] = RIGHT_PANE
		plugin.preferences['pane'] = LEFT_PANE

		plugin.preferences['floating'] = True  # switch back
Esempio n. 53
0
	def setUp(self):
		self.ui = tests.MockObject()
		self.ui.page = None
		self.ui.notebook = tests.new_notebook()
Esempio n. 54
0
	def setUp(self):
		zim.history.MAX_HISTORY = 100
		self.notebook = tests.new_notebook()
		self.pages = [self.notebook.get_page(Path(name))
			for name in self.notebook.testdata_manifest]
Esempio n. 55
0
File: tags.py Progetto: gdw2/zim
	def runTest(self):
		ui = MockUI()
		ui.notebook = tests.new_notebook()
		uistate = ConfigDict()
		widget = TagsPluginWidget(ui.notebook.index, uistate, ui)

		# Excersize all model switches and check we still have a sane state
		widget.toggle_treeview()
		widget.toggle_treeview()

		path = Path('Test:foo')
		treepath = widget.treeview.get_model().get_treepath(path)
		self.assertTrue(not treepath is None)

		widget.disconnect_model()
		widget.reload_model()

		path = Path('Test:foo')
		treepath = widget.treeview.get_model().get_treepath(path)
		self.assertTrue(not treepath is None)

		# Check signals
		#~ widget.treeview.emit('popup-menu')
		widget.treeview.emit('insert-link', path)

		# Check tag filtering
		cloud = widget.tagcloud
		self.assertEqual(cloud.get_tag_filter(), None)
		tag = None
		for button in cloud.get_children():
			if button.indextag.name == 'tags':
				tag = button.indextag
				button.clicked()
				break
		else:
			raise AssertionError, 'No button for @tags ?'

		selected, filtered = cloud.get_tag_filter()
		self.assertEqual(selected, [tag])
		self.assertTrue(len(filtered) > 3)
		self.assertTrue(tag in filtered)

		self.assertTrue(not widget.treeview._tag_filter is None)

		# check filtering in treestore
		tagfilter = (selected, filtered)
		selected = frozenset(selected)
		filtered = frozenset(filtered)

		def toplevel(model):
			iter = model.get_iter_first()
			assert not iter is None
			while not iter is None:
				yield iter
				iter = model.iter_next(iter)

		def childiter(model, iter):
			iter = model.iter_children(iter)
			assert not iter is None
			while not iter is None:
				yield iter
				iter = model.iter_next(iter)

		self.assertEqual(uistate['treeview'], 'tagged')
		filteredmodel = widget.treeview.get_model()
		for iter in toplevel(filteredmodel):
			path = filteredmodel.get_indexpath(iter)
			self.assertTrue(not path is None)
			tags = list(ui.notebook.index.list_tags(path))
			tags = frozenset(tags)
			self.assertTrue(selected.issubset(tags)) # Needs to contains selected tags
			self.assertTrue(tags.issubset(filtered)) # All other tags should be in the filter selection
			treepaths = filteredmodel.get_treepaths(path)
			self.assertTrue(filteredmodel.get_path(iter) in treepaths)

		widget.toggle_treeview()
		self.assertEqual(uistate['treeview'], 'tags')
		filteredmodel = widget.treeview.get_model()
		for iter in toplevel(filteredmodel):
			self.assertEqual(filteredmodel.get_indexpath(iter), None)
				# toplevel has tags, not pages
			tag = filteredmodel[iter][PATH_COL]
			self.assertTrue(tag in filtered)
			for iter in childiter(filteredmodel, iter):
				path = filteredmodel.get_indexpath(iter)
				self.assertTrue(not path is None)
				tags = list(ui.notebook.index.list_tags(path))
				tags = frozenset(tags)
				self.assertTrue(selected.issubset(tags)) # Needs to contains selected tags
				self.assertTrue(tags.issubset(filtered)) # All other tags should be in the filter selection
				treepaths = filteredmodel.get_treepaths(path)
				self.assertTrue(filteredmodel.get_path(iter) in treepaths)