예제 #1
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
    def testSetSimpleValue(self):
        config = VirtualConfigManager()
        preferences = config.get_config_dict('<profile>/preferences.conf')

        dialog = PreferencesDialog(MyWindow(config), config)
        self.assertEqual(dialog.forms['Interface']['toggle_on_ctrlspace'],
                         False)
        dialog.assert_response_ok()
        self.assertEqual(preferences['GtkInterface']['toggle_on_ctrlspace'],
                         False)

        dialog = PreferencesDialog(MyWindow(config), config)
        dialog.forms['Interface']['toggle_on_ctrlspace'] = True
        dialog.assert_response_ok()
        self.assertEqual(preferences['GtkInterface']['toggle_on_ctrlspace'],
                         True)
예제 #3
0
    def __init__(self, config=None):
        '''Constructor
		@param config: a L{ConfigManager} object that is used to load
		plugin preferences.
		Defaults to a L{VirtualConfigManager} for testing.
		'''
        assert 'name' in self.plugin_info, 'Missing "name" in plugin_info'
        assert 'description' in self.plugin_info, 'Missing "description" in plugin_info'
        assert 'author' in self.plugin_info, 'Missing "author" in plugin_info'
        self.extensions = WeakSet()

        if self.plugin_preferences:
            assert isinstance(
                self.plugin_preferences[0],
                tuple), 'BUG: preferences should be defined as tuples'

        self.config = config or VirtualConfigManager()
        self.preferences = self.config.get_config_dict(
            '<profile>/preferences.conf')[self.config_key]

        for pref in self.plugin_preferences:
            if len(pref) == 4:
                key, type, label, default = pref
                self.preferences.setdefault(key, default)
                #~ print ">>>>", key, default, '--', self.preferences[key]
            else:
                key, type, label, default, check = pref
                self.preferences.setdefault(key, default, check=check)
                #~ print ">>>>", key, default, check, '--', self.preferences[key]

        self.load_extensions_classes()
예제 #4
0
    def __init__(self, config=None):
        '''Constructor
		@param config: a L{ConfigManager} object that is used to load
		plugin preferences.
		Defaults to a L{VirtualConfigManager} for testing.
		'''
        assert 'name' in self.plugin_info, 'Missing "name" in plugin_info'
        assert 'description' in self.plugin_info, 'Missing "description" in plugin_info'
        assert 'author' in self.plugin_info, 'Missing "author" in plugin_info'
        self.extensions = WeakSet()

        if self.plugin_preferences:
            assert isinstance(
                self.plugin_preferences[0],
                tuple), 'BUG: preferences should be defined as tuples'

        self.config = config or VirtualConfigManager()
        self.preferences = self.config.get_config_dict(
            '<profile>/preferences.conf')[self.config_key]
        self._init_config(self.preferences, self.plugin_preferences)
        self._init_config(self.preferences, self.plugin_notebook_properties
                          )  # defaults for the properties are preferences

        self.load_insertedobject_types()
        self.load_extensions_classes()
예제 #5
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')
예제 #6
0
파일: gui.py 프로젝트: pombredanne/zim
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
예제 #7
0
def setUpMainWindow(notebook, path='Test'):
    if isinstance(path, str):
        path = Path(path)

    config = VirtualConfigManager()
    mainwindow = MainWindow(notebook, config, page=path)
    mainwindow.__pluginmanager__ = PluginManager(config)
    mainwindow.init_uistate()  # XXX
    return mainwindow
    def testConfigurePlugin(self):
        config = VirtualConfigManager()

        from zim.plugins.journal import JournalPlugin
        plugin = JournalPlugin()

        window = MyWindow(config)
        pref_dialog = PreferencesDialog(window, config)
        dialog = PluginConfigureDialog(pref_dialog, plugin)
        dialog.assert_response_ok()
예제 #9
0
 def setUp(self):
     self.notebook = self.setUpNotebook(content=tests.FULL_NOTEBOOK)
     config = VirtualConfigManager()
     navigation = tests.MockObject()
     self.model = PageTreeStore(self.notebook.index)
     init_model_validator_wrapper(self, self.model)
     self.treeview = PageTreeView(self.notebook,
                                  config,
                                  navigation,
                                  model=self.model)
     treepath = self.treeview.set_current_page(Path('Test'))
     assert treepath is not None
     self.treeview.select_treepath(treepath)
예제 #10
0
 def setUp(self):
     window = EmptyWindowObject()
     self.notebook = self.setUpNotebook(mock=tests.MOCK_ALWAYS_REAL,
                                        name='UIActions',
                                        content={'Test': 'Test 123'})
     self.page = self.notebook.get_page(Path('Test'))
     self.navigation = MockNavigation()
     self.uiactions = UIActions(
         window,
         self.notebook,
         self.page,
         VirtualConfigManager(),
         self.navigation,
     )
예제 #11
0
    def testChangeFont(self):
        config = VirtualConfigManager()
        preferences = config.get_config_dict('<profile>/preferences.conf')

        text_style = config.get_config_dict('<profile>/style.conf')
        text_style['TextView'].setdefault('font', None, str)
        text_style['TextView']['font'] = 'Sans 12'

        dialog = PreferencesDialog(MyWindow(config), config)
        self.assertEqual(dialog.forms['Interface']['use_custom_font'], True)
        dialog.assert_response_ok()
        self.assertEqual(text_style['TextView']['font'], 'Sans 12')
        self.assertFalse(
            any(['use_custom_font' in d for d in list(preferences.values())]))

        text_style['TextView']['font'] = 'Sans 12'
        dialog = PreferencesDialog(MyWindow(config), config)
        self.assertEqual(dialog.forms['Interface']['use_custom_font'], True)
        dialog.forms['Interface']['use_custom_font'] = False
        dialog.assert_response_ok()
        self.assertEqual(text_style['TextView']['font'], None)
        self.assertFalse(
            any(['use_custom_font' in d for d in list(preferences.values())]))
예제 #12
0
파일: __init__.py 프로젝트: pombredanne/zim
	def __init__(self, config=None):
		self.config = config or VirtualConfigManager()
		self._preferences = \
			self.config.get_config_dict('<profile>/preferences.conf')
		self.general_preferences = self._preferences['General']
		self.general_preferences.setdefault('plugins', [])

		self._plugins = {}
		self._extendables = WeakSet()

		self._load_plugins()

		self.connectto(self._preferences, 'changed',
			self.on_preferences_changed)
예제 #13
0
 def setUp(self):
     window = EmptyWindowObject()
     self.notebook = self.setUpNotebook(name='UIActions',
                                        content={
                                            'Test': 'Test 123',
                                            'ExistingPage': 'Exists !'
                                        })
     self.page = self.notebook.get_page(Path('Test'))
     self.navigation = MockNavigation()
     self.uiactions = UIActions(
         window,
         self.notebook,
         self.page,
         VirtualConfigManager(),
         self.navigation,
     )
예제 #14
0
    def runTest(self):
        notebook = self.setUpNotebook()
        config = VirtualConfigManager()
        navigation = tests.MockObject()
        model = PageTreeStore(notebook.index)
        init_model_validator_wrapper(self, model)
        treeview = PageTreeView(notebook, config, navigation, model=model)

        signals = []

        def signal_logger(o, *a):
            path = a[0].to_string()
            signal = a[-1]
            signals.append((signal, path))
            #print(">>>", signal, path)

        for signal in ('row-inserted', 'row-changed', 'row-deleted',
                       'row-has-child-toggled'):
            model.connect(signal, signal_logger, signal)

        for path in map(Path, self.PAGES):
            page = notebook.get_page(path)
            page.parse('plain', 'Test 123\n')
            notebook.store_page(page)

        expect_add = [('row-inserted', '0'), ('row-changed', '0'),
                      ('row-inserted', '0:0'), ('row-has-child-toggled', '0'),
                      ('row-changed', '0'), ('row-changed', '0:0'),
                      ('row-inserted', '0:1'), ('row-changed', '0'),
                      ('row-changed', '0:1'), ('row-inserted', '1'),
                      ('row-changed', '1'), ('row-inserted', '2'),
                      ('row-changed', '2')]
        self.assertEqual(signals, expect_add)
        signals[:] = []

        for path in reversed(self.PAGES):
            notebook.delete_page(Path(path))

        expect_del = [('row-deleted', '2'), ('row-deleted', '1'),
                      ('row-deleted', '0:1'), ('row-changed', '0'),
                      ('row-deleted', '0:0'), ('row-has-child-toggled', '0'),
                      ('row-changed', '0'), ('row-deleted', '0')]
        self.assertEqual(signals, expect_del)
예제 #15
0
    def testSelectPlugins(self):
        config = VirtualConfigManager()
        window = MyWindow(config)

        pref_dialog = PreferencesDialog(window, config)
        treeview = pref_dialog.plugins_tab.treeview
        for name in window.__pluginmanager__.list_installed_plugins():
            pref_dialog.plugins_tab.select_plugin(name)
            model, iter = treeview.get_selection().get_selected()
            self.assertEqual(model[iter][0], name)

            path = model.get_path(iter)
            wasactive = model[iter][1]
            model.do_toggle_path(path)
            if wasactive:
                self.assertEqual(model[iter][1], False)
            else:
                self.assertEqual(model[iter][1],
                                 model[iter][2])  # active matched activatable

        pref_dialog.do_response_cancel()
예제 #16
0
파일: __init__.py 프로젝트: pombredanne/zim
	def __init__(self, config=None):
		assert 'name' in self.plugin_info
		assert 'description' in self.plugin_info
		assert 'author' in self.plugin_info
		self.extensions = WeakSet()

		if self.plugin_preferences:
			assert isinstance(self.plugin_preferences[0], tuple), 'BUG: preferences should be defined as tuples'

		self.config = config or VirtualConfigManager()
		self.preferences = self.config.get_config_dict('<profile>/preferences.conf')[self.config_key]

		for pref in self.plugin_preferences:
				if len(pref) == 4:
					key, type, label, default = pref
					self.preferences.setdefault(key, default)
					#~ print ">>>>", key, default, '--', self.preferences[key]
				else:
					key, type, label, default, check = pref
					self.preferences.setdefault(key, default, check=check)
					#~ print ">>>>", key, default, check, '--', self.preferences[key]

		self.load_extensions_classes()
예제 #17
0
    def __init__(self, config=None):
        '''Constructor
		Constructor will directly load a list of default plugins
		based on the preferences in the config. Failures while loading
		these plugins will be logged but not raise errors.

		@param config: a L{ConfigManager} object that is passed along
		to the plugins and is used to load plugin preferences.
		Defaults to a L{VirtualConfigManager} for testing.
		'''
        self.config = config or VirtualConfigManager()
        self._preferences = \
         self.config.get_config_dict('<profile>/preferences.conf')
        self.general_preferences = self._preferences['General']
        self.general_preferences.setdefault('plugins', [])

        self._plugins = {}
        self._extendables = WeakSet()

        self._load_plugins()

        self.connectto(self._preferences, 'changed',
                       self.on_preferences_changed)
예제 #18
0
    def runTest(self):
        'Test WWW interface'
        config = VirtualConfigManager()
        notebook = self.setUpNotebook(content=tests.FULL_NOTEBOOK)
        notebook.index.check_and_update()
        interface = WWWInterface(notebook,
                                 config=config,
                                 template=self.template)
        validator = wsgiref.validate.validator(interface)

        def call(command, path):
            #print("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 = BytesIO(b'')
            wfile = BytesIO()
            handler = wsgiref.handlers.SimpleHandler(rfile, wfile, sys.stderr,
                                                     environ)
            handler.run(validator)
            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)
            header, body = self.assertResponseOK(response)
            self.assertIn(
                b'<li><a href="/Test/foo.html" title="foo" class="page">foo</a>',
                body)

        # page
        afolder = notebook.get_attachments_dir(Path('Test:foo'))
        afile = afolder.file('attachment.pdf')
        afile.touch()

        response = call('GET', '/Test/foo.html')
        header, body = self.assertResponseOK(response)
        self.assertIn(b'<h1>Foo <a name=\'Test:foo\'></a></h1>', body)

        # - ensure page link works
        self.assertIn(b'<a href="/Test/foo/bar.html"', body)

        # - ensure attachment link works
        self.assertIn(
            b"<td><a href='/%2Bfile/Test/foo/attachment.pdf'>attachment.pdf</a></td>",
            body)

        # - ensure sub page does not show up as attachment
        self.assertNotIn(b'bar.txt', body)

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