File: __init__.py

package info (click to toggle)
zim 0.76.3-2
  • links: PTS, VCS
  • area: main
  • in suites: forky
  • size: 10,952 kB
  • sloc: python: 68,612; xml: 1,270; javascript: 512; sh: 101; makefile: 47
file content (905 lines) | stat: -rw-r--r-- 25,198 bytes parent folder | download | duplicates (2)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905

# Copyright 2008-2017 Jaap Karssenberg <jaap.karssenberg@gmail.com>

'''Zim test suite'''




import os
import sys
import tempfile
import shutil
import logging
import gettext
import xml.etree.cElementTree as etree
import types
import glob
import logging

logger = logging.getLogger('tests')

from functools import partial


try:
	import gi
	gi.require_version('Gtk', '3.0')
	from gi.repository import Gtk
except ImportError:
	Gtk = None


import unittest
from unittest import skip, skipIf, skipUnless, expectedFailure


def expectedFailureIf(condition):
	'''Decorator to do a conditional expected failure'''
	if condition:
		return expectedFailure
	else:
		return lambda method: method # do nothing


os.environ['LANGUAGE'] = 'C.UTF-8'
gettext.install('zim', names=('_', 'gettext', 'ngettext'))

FAST_TEST = False #: determines whether we skip slow tests or not
FULL_TEST = False #: determine whether we mock filesystem tests or not

# This list also determines the order in which tests will executed
__all__ = [
	# Packaging etc.
	'package', 'translations',
	# Basic libraries
	'datetimetz', 'base', 'errors', 'signals', 'actions',
	'fs', 'newfs',
	'config', 'applications',
	'parsing',
	# Notebook components
	'formats', 'templates',
	'indexers', 'indexviews', 'operations', 'notebook', 'history',
	'export', 'import_files', 'www', 'search',
	# Core application
	'widgets', 'pageview', 'save_page', 'find', 'clipboard', 'uiactions',
	'mainwindow', 'notebookdialog',
	'preferencesdialog', 'searchdialog', 'customtools', 'templateeditordialog',
	'main', 'plugins',
	# Plugins
	'pathbar', 'pageindex', 'toolbar',
	'journal', 'printtobrowser', 'versioncontrol', 'inlinecalculator',
	'tasklist', 'tags', 'imagegenerators', 'tableofcontents',
	'quicknote', 'attachmentbrowser', 'insertsymbol',
	'sourceview', 'tableeditor', 'bookmarksbar', 'spell',
	'arithmetic', 'linesorter', 'commandpalette', 'windowtitleeditor',
	'indexed_fts'
]


_mydir = os.path.abspath(os.path.dirname(__file__))

# when a test is missing from the list that should be detected
for file in glob.glob(_mydir + '/*.py'):
	name = os.path.basename(file)[:-3]
	if name != '__init__' and not name in __all__:
		raise AssertionError('Test missing in __all__: %s' % name)

# get our own tmpdir
TMPDIR = os.path.abspath(os.path.join(_mydir, 'tmp'))
	# Wanted to use tempfile.get_tempdir here to put everything in
	# e.g. /tmp/zim but since /tmp is often mounted as special file
	# system this conflicts with thrash support. For writing in source
	# dir we have conflict with bazaar controls, this is worked around
	# by a config mode switch in the bazaar backend of the version
	# control plugin

# also get the default tmpdir and put a copy in the env
REAL_TMPDIR = tempfile.gettempdir()


def load_tests(loader, tests, pattern):
	'''Load all test cases and return a unittest.TestSuite object.
	The parameters 'tests' and 'pattern' are ignored.
	'''
	suite = unittest.TestSuite()
	for name in ['tests.' + name for name in __all__]:
		test = loader.loadTestsFromName(name)
		suite.addTest(test)
	return suite


def _setUpEnvironment():
	'''Method to be run once before test suite starts'''
	# In fact to be loaded before loading some of the zim modules
	# like zim.config and any that export constants from it

	# NOTE: do *not* touch XDG_DATA_DIRS here because it is used by Gtk to
	# find resources like pixbuf loaders etc. not finding these will lead to
	# a crash. Especially under msys the defaults are not set but also not
	# map to the default folders. So not touching it is the safest path.
	# For zim internal usage this is overloaded in config.basedirs.set_basedirs()
	os.environ.update({
		'ZIM_TEST_RUNNING': 'True',
		'ZIM_TEST_ROOT': os.getcwd(),
		'TMP': TMPDIR,
		'REAL_TMP': REAL_TMPDIR,
		'XDG_DATA_HOME': os.path.join(TMPDIR, 'data_home'),
		'TEST_XDG_DATA_DIRS': os.path.join(TMPDIR, 'data_dir'),
		'XDG_CONFIG_HOME': os.path.join(TMPDIR, 'config_home'),
		'XDG_CONFIG_DIRS': os.path.join(TMPDIR, 'config_dir'),
		'XDG_CACHE_HOME': os.path.join(TMPDIR, 'cache_home'),
		'XDG_RUNTIME_DIR': os.path.join(TMPDIR, 'runtime')
	})

	if os.path.isdir(TMPDIR):
		shutil.rmtree(TMPDIR)
	os.makedirs(TMPDIR)


if os.environ.get('ZIM_TEST_RUNNING') != 'True':
	# Do this when loaded, but not re-do in sub processes
	# (doing so will kill e.g. the ipc test...)
	_setUpEnvironment()


## Setup special logging for tests

class UncaughtWarningError(AssertionError):
	pass


class TestLoggingHandler(logging.Handler):
	'''Handler class that raises uncaught errors to ensure test don't fail silently'''

	def __init__(self, level=logging.WARNING):
		logging.Handler.__init__(self, level)
		fmt = logging.Formatter('%(levelname)s %(filename)s %(lineno)s: %(message)s')
		self.setFormatter(fmt)

	def emit(self, record):
		if record.levelno >= logging.WARNING \
		and not record.name.startswith('tests'):
			raise UncaughtWarningError(self.format(record))
		else:
			pass

logging.getLogger().addHandler(TestLoggingHandler())
	# Handle all errors that make it up to the root level

try:
	logging.getLogger('zim.test').warning('foo')
except UncaughtWarningError:
	pass
else:
	raise AssertionError('Raising errors on warning fails')

###


from zim.newfs import LocalFolder

import zim.config.manager
import zim.plugins


# Define runtime folder & data folders for use in test cases
ZIM_SRC_FOLDER = LocalFolder(_mydir + '/..')
ZIM_DATA_FOLDER = LocalFolder(_mydir + '/../data')
TEST_SRC_FOLDER = LocalFolder(_mydir)
TEST_DATA_FOLDER = LocalFolder(_mydir + '/data')


_zim_pyfiles = []

def zim_pyfiles():
	'''Returns a list with file paths for all the zim python files'''
	if not _zim_pyfiles:
		for d, dirs, files in os.walk('zim'):
			_zim_pyfiles.extend([d + '/' + f for f in files if f.endswith('.py')])
		_zim_pyfiles.sort()
	for file in _zim_pyfiles:
		yield file # shallow copy


def slowTest(obj):
	'''Decorator for slow tests

	Tests wrapped with this decorator are ignored when you run
	C{test.py --fast}. You can either wrap whole test classes::

		@tests.slowTest
		class MyTest(tests.TestCase):
			...

	or individual test functions::

		class MyTest(tests.TestCase):

			@tests.slowTest
			def testFoo(self):
				...

			def testBar(self):
				...
	'''
	if FAST_TEST:
		wrapper = skip('Slow test')
		return wrapper(obj)
	else:
		return obj


MOCK_ALWAYS_MOCK = 'mock' #: Always choose mock folder, alwasy fast
MOCK_DEFAULT_MOCK = 'default_mock' #: By default use mock, but sometimes at random use real fs or at --full
MOCK_DEFAULT_REAL = 'default_real' #: By default use real fs, mock oly for --fast
MOCK_ALWAYS_REAL = 'real' #: always use real fs -- not recommended unless test fails for mock

import random
import time

TIMINGS = []

class TestCase(unittest.TestCase):
	'''Base class for test cases'''

	maxDiff = None

	mockConfigManager = True

	def run(self, *a, **kwa):
		start = time.time()
		unittest.TestCase.run(self, *a, **kwa)
		end = time.time()
		TIMINGS.append((self.__class__.__name__ + '.' + self._testMethodName, end - start))

	@classmethod
	def setUpClass(cls):
		if cls.mockConfigManager:
			zim.config.manager.makeConfigManagerVirtual()
			zim.plugins.resetPluginManager()

	@classmethod
	def tearDownClass(cls):
		if Gtk is not None:
			gtk_process_events() # flush any pending events / warnings

		zim.config.manager.resetConfigManager()
		zim.plugins.resetPluginManager()

	def setUpFolder(self, name=None, mock=MOCK_DEFAULT_MOCK):
		'''Convenience method to create a temporary folder for testing
		@param name: name postfix for the folder
		@param mock: mock level for this test, one of C{MOCK_ALWAYS_MOCK},
		C{MOCK_DEFAULT_MOCK}, C{MOCK_DEFAULT_REAL} or C{MOCK_ALWAYS_REAL}.
		The C{MOCK_ALWAYS_*} arguments force the use of a real folder or a
		mock object. The C{MOCK_DEFAULT_*} arguments give a preference but
		for these the behavior is overruled by "--fast" and "--full" in the
		test script.
		@returns: a L{Folder} object (either L{LocalFolder} or L{MockFolder})
		that is guarenteed non-existing
		'''
		path = self._get_tmp_name(name)

		if mock == MOCK_ALWAYS_MOCK:
			use_mock = True
		elif mock == MOCK_ALWAYS_REAL:
			use_mock = False
		else:
			if FULL_TEST:
				use_mock = False
			elif FAST_TEST:
				use_mock = True
			else:
				use_mock = (mock == MOCK_DEFAULT_MOCK)

		if use_mock:
			from zim.newfs.mock import MockFolder
			folder = MockFolder(path)
		else:
			from zim.newfs import LocalFolder
			if os.path.exists(path):
				logger.debug('Clear tmp folder: %s', path)
				shutil.rmtree(path)
				assert not os.path.exists(path) # make real sure
			folder = LocalFolder(path)

		assert not folder.exists()
		return folder

	def setUpNotebook(self, name='testnotebook', mock=MOCK_ALWAYS_MOCK, content={}, folder=None):
		'''
		@param name: name postfix for the folder, see L{setUpFolder}, and name for the notebook
		@param mock: see L{setUpFolder}, default is C{MOCK_ALWAYS_MOCK}
		@param content: dictionary where the keys are page names and the
		values the page content. If a tuple or list is given, pages are created
		with default text. L{Path} objects are allowed instead of page names
		@param folder: determine the folder to be used, only needed in special
		cases where the folder must be outside of the project folder, like
		when testing version control logic
		'''
		import datetime
		from zim.newfs.mock import MockFolder
		from zim.notebook.notebook import NotebookConfig, Notebook
		from zim.notebook.page import Path
		from zim.notebook.layout import FilesLayout
		from zim.notebook.index import Index
		from zim.formats.wiki import WIKI_FORMAT_VERSION

		if folder is None:
			folder = self.setUpFolder(name, mock)
		folder.touch() # Must exist for sane notebook
		cache_dir = folder.folder('.zim')
		layout = FilesLayout(folder, endofline='unix')

		conffile = folder.file('notebook.zim')
		config = NotebookConfig(conffile)
		config.write()
		if isinstance(folder, MockFolder):
			index = Index(':memory:', layout)
		else:
			f = cache_dir.file('index.db')
			index = Index(cache_dir.file('index.db').path, layout)

		if isinstance(content, (list, tuple)):
			content = dict((p, 'test 123') for p in content)

		notebook = Notebook(cache_dir, config, folder, layout, index)
		notebook.properties['name'] = name
		for name, text in list(content.items()):
			path = Path(name) if isinstance(name, str) else name
			file, folder = layout.map_page(path)
			file.write(
				(
					'Content-Type: text/x-zim-wiki\n'
					'Wiki-Format: %s\n'
					'Creation-Date: %s\n\n'
				) % (WIKI_FORMAT_VERSION, datetime.datetime.now().isoformat())
				+ text
			)

		notebook.index.check_and_update()
		assert notebook.index.is_uptodate
		return notebook

	def _get_tmp_name(self, postfix):
		name = self.__class__.__name__
		if self._testMethodName != 'runTest':
			name += '_' + self._testMethodName

		if postfix:
			assert '/' not in postfix and '\\' not in postfix, 'Don\'t use this method to get sub folders or files'
			name += '_' + postfix

		return os.path.join(TMPDIR, name)


class LoggingFilter(logging.Filter):
	'''Convenience class to surpress zim errors and warnings in the
	test suite. Acts as a context manager and can be used with the
	'with' keyword.

	Alternatively you can call L{wrap_test()} from test C{setUp}.
	This will start the filter and make sure it is cleaned up again.
	'''

	# Due to how the "logging" module works, logging channels do inherit
	# handlers of parents but not filters. Therefore setting a filter
	# on the "zim" channel will not supress messages from sub-channels.
	# Instead we need to set the filter both on the channel and on
	# top level handlers to get the desired effect.

	def __init__(self, logger, message=None):
		'''Constructor
		@param logger: the logging channel name
		@param message: can be a string, or a sequence of strings.
		Any messages that start with this string or any of these
		strings are surpressed.
		'''
		self.logger = logger
		self.message = message

	def __enter__(self):
		logging.getLogger(self.logger).addFilter(self)
		for handler in logging.getLogger().handlers:
			handler.addFilter(self)

	def __exit__(self, *a):
		logging.getLogger(self.logger).removeFilter(self)
		for handler in logging.getLogger().handlers:
			handler.removeFilter(self)

	def filter(self, record):
		if record.name.startswith(self.logger):
			msg = record.getMessage()
			if self.message is None:
				return False
			elif isinstance(self.message, tuple):
				return not any(msg.startswith(m) for m in self.message)
			else:
				return not msg.startswith(self.message)
		else:
			return True


	def wrap_test(self, test):
		self.__enter__()
		test.addCleanup(self.__exit__)


class DialogContext(object):
	'''Context manager to catch dialogs being opened

	Inteded to be used like this::

		def myCustomTest(dialog):
			self.assertTrue(isinstance(dialog, CustomDialogClass))
			# ...
			dialog.assert_response_ok()

		with DialogContext(
			myCustomTest,
			SomeOtherDialogClass
		):
			gui.show_dialogs()

	In this example the first dialog that is run by C{gui.show_dialogs()}
	is checked by the function C{myCustomTest()} while the second dialog
	just needs to be of class C{SomeOtherDialogClass} and will then
	be closed with C{assert_response_ok()} by the context manager.

	This context only works for dialogs derived from zim's Dialog class
	as it uses a special hook in L{zim.gui.widgets}.
	'''

	def __init__(self, *definitions):
		'''Constructor
		@param definitions: list of either classes or methods
		'''
		self.stack = list(definitions)
		self.old_test_mode = None

	def __enter__(self):
		import zim.gui.widgets
		self.old_test_mode = zim.gui.widgets.TEST_MODE
		self.old_callback = zim.gui.widgets.TEST_MODE_RUN_CB
		zim.gui.widgets.TEST_MODE = True
		zim.gui.widgets.TEST_MODE_RUN_CB = self._callback

	def _callback(self, dialog):
		#~ print('>>>', dialog)
		if not self.stack:
			raise AssertionError('Unexpected dialog run: %s' % dialog)

		handler = self.stack.pop(0)

		if isinstance(handler, type): # is a class
			self._default_handler(handler, dialog)
		elif isinstance(handler, tuple):
			klass, func = handler
			self._default_handler(klass, dialog, func)
		else: # assume a function
			handler(dialog)

	def _default_handler(self, cls, dialog, func=None):
		if not isinstance(dialog, cls):
			raise AssertionError('Expected dialog of class %s, but got %s instead' % (cls, dialog.__class__))
		if func:
			func(dialog)
		dialog.assert_response_ok()

	def __exit__(self, *error):
		import zim.gui.widgets
		zim.gui.widgets.TEST_MODE = self.old_test_mode
		zim.gui.widgets.TEST_MODE_RUN_CB = self.old_callback

		has_error = any(error)
		if self.stack and not has_error:
			raise AssertionError('%i expected dialog(s) not run' % len(self.stack))

		return False # Raise any errors again outside context


class WindowContext(DialogContext):

	def _default_handler(self, cls, window):
		if not isinstance(window, cls):
			raise AssertionError('Expected window of class %s, but got %s instead' % (cls, window.__class__))


class ApplicationContext(object):

	def __init__(self, *callbacks):
		self.stack = list(callbacks)

	def __enter__(self):
		import zim.applications
		self.old_test_mode = zim.applications.TEST_MODE
		self.old_callback = zim.applications.TEST_MODE_RUN_CB
		zim.applications.TEST_MODE = True
		zim.applications.TEST_MODE_RUN_CB = self._callback

	def _callback(self, cmd):
		if not self.stack:
			raise AssertionError('Unexpected application run: %s' % cmd)

		handler = self.stack.pop(0)
		return handler(cmd) # need to return for pipe()

	def __exit__(self, *error):
		import zim.gui.widgets
		zim.applications.TEST_MODE = self.old_test_mode
		zim.applications.TEST_MODE_RUN_CB = self.old_callback

		if self.stack and not any(error):
			raise AssertionError('%i expected command(s) not run' % len(self.stack))

		return False # Raise any errors again outside context


from zim.newfs.mock import os_native_path as _os_native_path

def os_native_path(path, drive='C:'):
	return _os_native_path(path, drive)


class _TestData(object):
	'''Wrapper for a set of test data in tests/data'''

	def __init__(self):
		root = os.environ['ZIM_TEST_ROOT']
		tree = etree.ElementTree(file=root + '/tests/data/notebook-wiki.xml')

		test_data = []
		for node in tree.iter(tag='page'):
			name = node.attrib['name']
			text = str(node.text.lstrip('\n'))
			test_data.append((name, text))

		self._test_data = tuple(test_data)

	def __iter__(self):
		'''Yield the test data as 2 tuple (pagename, text)'''
		for name, text in self._test_data:
			yield name, text # shallow copy

	def items(self):
		return list(self)

	def __getitem__(self, key):
		return self.get(key)

	def get(self, pagename):
		'''Return text for a specific pagename'''
		for n, text in self._test_data:
			if n == pagename:
				return text
		assert False, 'Could not find data for page: %s' % pagename

FULL_NOTEBOOK = _TestData() #: singleton to be used by various tests


def _expand_manifest(names):
	'''Build a set of all pages names and all namespaces that need to
	exist to host those page names.
	'''
	manifest = set()
	for name in names:
		manifest.add(name)
		while name.rfind(':') > 0:
			i = name.rfind(':')
			name = name[:i]
			manifest.add(name)
	return manifest


_cache = {}


def new_page_as_wiki_text():
	'''Returns data from C{tests/data/formats/wiki.txt}'''
	if 'new_page_as_wiki_text' not in _cache:
		root = os.environ['ZIM_TEST_ROOT']
		with open(root + '/tests/data/formats/wiki.txt', encoding='UTF-8') as file:
			_cache['new_page_as_wiki_text'] = file.read()

	return _cache['new_page_as_wiki_text']


def new_parsetree():
	'''Returns a new ParseTree object for testing
	Uses data from C{tests/data/formats/wiki.txt}
	'''
	if 'new_parsetree' not in _cache:
		import zim.formats.wiki

		text = new_page_as_wiki_text()
		parser = zim.formats.wiki.Parser()
		tree = parser.parse(text)

		_cache['new_parsetree'] = tree

	return _cache['new_parsetree'].copy()


def new_parsetree_from_text(text, format='wiki'):
	import zim.formats
	parser = zim.formats.get_format(format).Parser()
	return parser.parse(text)


def new_parsetree_from_xml(xml):
	# For some reason this does not work with cElementTree.XMLBuilder ...
	from xml.etree.ElementTree import XMLParser
	from zim.formats import ParseTree
	builder = XMLParser()
	builder.feed(xml)
	root = builder.close()
	return ParseTree(root)


def new_page():
	from zim.notebook import Path, Page
	from zim.newfs.mock import MockFile, MockFolder
	file = MockFile('/mock/test/page.txt')
	folder = MockFile('/mock/test/page/')
	page = Page(Path('Test'), False, file, folder)
	page.set_parsetree(new_parsetree())
	return page


def new_page_from_text(text, format='wiki'):
	from zim.notebook import Path, Page
	from zim.newfs.mock import MockFile, MockFolder
	file = MockFile('/mock/test/page.txt')
	folder = MockFile('/mock/test/page/')
	page = Page(Path('Test'), False, file, folder)
	page.set_parsetree(new_parsetree_from_text(text, format))
	return page


class MockObject(object):
	'''Simple class to quickly create mock objects

	It allows defining methods with a static return value and logs the calls
	to the defined methods

	Example usage:

		myobject = MockObject(return_values={'foo': "test 123"})
			# define an object with a single method "foo" which returns "test 123"
		object_to_be_tested.some_method(myobject)
		self.assertEqual(myobject.allMethodCalls, [('foo', 'abc')])
			# assert method called with single argument

	'''

	def __init__(self, methods=(), return_values={}):
		'''Constructor
		@param methods: a list of method names that are to be supported; these
		methods will do nothing and return a C{None} value
		@param return_values: mapping of method names to return value for the
		method. Names do not have to be defined in C{methods}.
		'''
		self.allMethodCalls = []
		self.__return_values = {}

		for name in methods:
			self.__return_values[name] = None

		self.__return_values.update(return_values)

	@property
	def lastMethodCall(self):
		return self.allMethodCalls[-1]

	def __getattr__(self, name):
		'''Automatically mock methods'''
		if not name in self.__return_values:
			raise AttributeError('No such method defined for MockObject: %s (we do know %r)' % (name, self.__return_values.keys()))

		return_value = self.__return_values[name]
		def my_mock_method(*arg, **kwarg):
			call = [name] + list(arg)
			if kwarg:
				call.append(kwarg)
			self.allMethodCalls.append(tuple(call))
			return return_value

		setattr(self, name, my_mock_method)
		return my_mock_method

	def addMockMethod(self, name, return_value=None):
		'''Installs a mock method with a given name that returns
		a given value.
		'''
		self.__return_values[name] = return_value


class CallBackLogger(list):
	'''Object that is callable as a function and keeps count how often
	it was called and with what arguments
	'''

	def __init__(self, return_value=None):
		'''Constructor
		@param return_value: the value to return when called as a function
		'''
		self.return_value = return_value
		self.count = 0

	@property
	def hasBeenCalled(self):
		return bool(self)

	@property
	def numberOfCalls(self):
		return len(self)

	def __call__(self, *arg, **kwarg):
		self.count += 1

		call = list(arg)
		if kwarg:
			call.append(kwarg)
		self.append(tuple(call))

		return self.return_value


def wrap_method_with_logger(object, name):
	orig_function = getattr(object, name)
	wrapper = CallBackWrapper(orig_function)
	setattr(object, name, wrapper)
	return wrapper


class CallBackWrapper(CallBackLogger):

	def __init__(self, orig_function):
		assert orig_function is not None
		self.count = 0
		self.orig_function = orig_function

	def __call__(self, *arg, **kwarg):
		self.count += 1

		call = list(arg)
		if kwarg:
			call.append(kwarg)
		self.append(tuple(call))

		return self.orig_function(*arg, **kwarg)


class SignalLogger(dict):
	'''Listening object that attaches to all signals of the target and records
	all signals calls in a dictionary of lists.

	Example usage:

		signals = SignalLogger(myobject)
		... # some code causing signals to be emitted
		self.assertEqual(signals['mysignal'], [args])
			# assert "mysignal" is called once with "*args"

	If you don't want to match all arguments, the "filter_func" can be used to
	transform the arguments before logging.

		filter_func(signal_name, object, args) --> args

	'''

	def __init__(self, obj, filter_func=None):
		self._obj = obj
		self._ids = []

		if filter_func is None:
			filter_func = lambda s, o, a: a

		for signal in self._obj.__signals__:
			seen = []
			self[signal] = seen

			def handler(seen, signal, obj, *a):
				seen.append(filter_func(signal, obj, a))
				logger.debug('Signal: %s %r', signal, a)

			id = obj.connect(signal, partial(handler, seen, signal))
			self._ids.append(id)

	def __enter__(self):
		pass

	def __exit__(self, *e):
		self.disconnect()

	def clear(self):
		for signal, seen in list(self.items()):
			seen[:] = []

	def disconnect(self):
		for id in self._ids:
			self._obj.disconnect(id)
		self._ids = []


class MaskedObject(object):
	'''Proxy object that allows filtering what methods of an interface are
	accesible.

	Example Usage:

		myproxy = MaskedObject(realobject, ('connect', 'disconnect'))
			# proxy only allows calling "connect()" and "disconnect()"
			# other calls lead to exception

	'''

	def __init__(self, obj, names):
		self.__obj = obj
		self.__names = names

	def setObjectAccess(self, *names):
		self.__names = names

	def __getattr__(self, name):
		if name in self.__names:
			return getattr(self.__obj, name)
		else:
			raise AttributeError('Acces to \'%s\' not allowed' % name)


def gtk_process_events(*a):
	'''Method to simulate a few iterations of the gtk main loop'''
	assert Gtk is not None
	while Gtk.events_pending():
		Gtk.main_iteration()
	return True # continue


def gtk_get_menu_item(menu, id):
	'''Get a menu item from a C{Gtk.Menu}
	@param menu: a C{Gtk.Menu}
	@param id: either the menu item label or the stock id
	@returns: a C{Gtk.MenuItem} or C{None}
	'''
	items = menu.get_children()
	ids = [i.get_property('label') for i in items]
		# Gtk.ImageMenuItems that have a stock id happen to use the
		# 'label' property to store it...

	assert id in ids, \
		'Menu item "%s" not found, we got:\n' % id \
		+ ''.join('- %s \n' % i for i in ids)

	i = ids.index(id)
	return items[i]


def gtk_activate_menu_item(menu, id):
	'''Trigger the 'click' action an a menu item
	@param menu: a C{Gtk.Menu}
	@param id: either the menu item label or the stock id
	'''
	item = gtk_get_menu_item(menu, id)
	item.activate()


def find_widgets(type):
	'''Iterate through all top level windows and recursively walk through their
	children, returning all childs which are of given type.
	@param type: any class inherited from C{Gtk.Widget}
	@returns: list of widgets of given type
	'''
	widgets = []
	def walk_containers(root_container):
		if not hasattr(root_container, 'get_children'):
			return
		for child in root_container.get_children():
			if isinstance(child, type):
				widgets.append(child)
			walk_containers(child)
	for window in Gtk.Window.list_toplevels():
		walk_containers(window)
	return widgets