File: customtools.py

package info (click to toggle)
zim 0.76.3-2
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 10,952 kB
  • sloc: python: 68,612; xml: 1,270; javascript: 512; sh: 101; makefile: 47
file content (352 lines) | stat: -rw-r--r-- 9,902 bytes parent folder | download | duplicates (3)
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

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



import tests

from zim.newfs import TmpFile
from zim.notebook import Path

from zim.gui.customtools import *


def clear_customtools():
	listfile = XDG_CONFIG_HOME.file('zim/customtools/customtools.list')
	folder = XDG_CONFIG_HOME.folder('zim/customtools/')
	assert 'tests/tmp' in listfile.path.replace('\\', '/')
	assert 'tests/tmp' in folder.path.replace('\\', '/')
	listfile.remove()
	if folder.exists():
		folder.remove_children()


class MockStubPageView(StubPageView):

	def get_word(self, format=None):
		if format:
			return '**FooBar**'
		else:
			return 'FooBar'


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

	mockConfigManager = False  # breaks hack in customtools

	def setUp(self):
		clear_customtools()

	def testManager(self):
		'''Test CustomToolManager API'''
		# initialize the list
		manager = CustomToolManager()
		self.assertEqual(list(manager), [])
		self.assertEqual(list(manager._names), [])

		# add a tool
		properties = {
			'Name': 'Foo',
			'Comment': 'Test 1 2 3',
			'Icon': '',
			'X-Zim-ExecTool': 'foo %t "quoted"',
			'X-Zim-ReadOnly': False,
			'X-Zim-ShowInToolBar': True,
		}
		tool = manager.create(**properties)
		self.assertEqual(list(manager), [tool])
		self.assertEqual(list(manager._names), ['foo-usercreated'])

		self.assertTrue(tool.isvalid)
		self.assertEqual(tool.name, 'Foo')
		self.assertEqual(tool.comment, 'Test 1 2 3')
		self.assertFalse(tool.isreadonly)
		self.assertTrue(tool.showintoolbar)
		self.assertTrue(tool.get_pixbuf(Gtk.IconSize.MENU))
		self.assertEqual(tool.showincontextmenu, 'Text') # Auto generated

		# test file saved correctly
		#~ from pprint import pprint
		#~ pprint(tool)
		lines = tool.dump()
		self.assertTrue(len(lines) > 5)
		lines = tool.file.readlines()
		self.assertTrue(len(lines) > 5)

		# refresh list
		manager = CustomToolManager()
		self.assertEqual(list(manager), [tool])
		self.assertEqual(list(manager._names), ['foo-usercreated'])

		# add a second tool
		tool1 = tool
		properties = {
			'Name': 'Foo',
			'Comment': 'Test 1 2 3',
			'Icon': None,
			'X-Zim-ExecTool': 'foo %f',
			'X-Zim-ReadOnly': False,
			'X-Zim-ShowInToolBar': True,
		}
		tool = manager.create(**properties)
		self.assertEqual(list(manager), [tool1, tool])
		self.assertEqual(list(manager._names), ['foo-usercreated', 'foo-usercreated-1'])

		self.assertTrue(tool.isvalid)
		self.assertEqual(tool.name, 'Foo')
		self.assertEqual(tool.comment, 'Test 1 2 3')
		self.assertFalse(tool.isreadonly)
		self.assertTrue(tool.showintoolbar)
		self.assertTrue(tool.get_pixbuf(Gtk.IconSize.MENU))
		self.assertEqual(tool.showincontextmenu, 'Page') # Auto generated

		# switch order
		i = manager.index(tool)
		self.assertTrue(i == 1)
		manager.reorder(tool, 0)
		i = manager.index(tool)
		self.assertTrue(i == 0)
		self.assertEqual(list(manager._names), ['foo-usercreated-1', 'foo-usercreated'])

		# delete
		file = tool1.file
		self.assertTrue(file.exists())
		manager.delete(tool1)
		self.assertEqual(list(manager._names), ['foo-usercreated-1'])
		self.assertFalse(file.exists())

	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)
		# %p for the page name
		# %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

		notebook = self.setUpNotebook()
		page = notebook.get_page(Path('Test:Foo'))
		pageview = MockStubPageView(notebook, page)
		args = (notebook, page, pageview)

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

		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', notebook.folder.folder('Test/Foo').path)),
			('foo %s', ('foo', page.source_file.path)),
			('foo %p', ('foo', 'Test:Foo')),
			('foo %n', ('foo', notebook.folder.path)),
			('foo %D', ('foo', '')), # no document root
			('foo %t', ('foo', 'FooBar')),
			('foo "text %t"', ('foo', 'text FooBar')),
			('foo %T', ('foo', '**FooBar**')),
			('foo "text %T"', ('foo', 'text **FooBar**')),
			('foo %%t', ('foo', '%t')),
		):
			#~ print('>>>', cmd)
			tool['Desktop Entry']['X-Zim-ExecTool'] = cmd
			self.assertEqual(tool.parse_exec(args), wanted)


class TestCustomToolsUI(tests.TestCase):

	mockConfigManager = False  # breaks hack in customtools

	def setUp(self):
		clear_customtools()

		notebook = self.setUpNotebook(content=('test',))
		page = notebook.get_page(Path('test'))

		self.uimanager = Gtk.UIManager()
		group = Gtk.ActionGroup('test')
		group.add_actions([('tools_menu', None, '_Tools')])
		self.uimanager.insert_action_group(group)


		self.pageview = StubPageView(notebook, page)
		self.customtoolsui = CustomToolManagerUI(self.uimanager, self.pageview)

	def get_action(self, name):
		for group in self.uimanager.get_action_groups():
			action = group.get_action(name)
			if action:
				return action
		else:
			raise ValueError

	def testMenuUpdatedWhenToolAdded(self):
		# Key in this test is that the changes happens via a different instance
		# of the manager - demonstrating the singleton-like behavior
		self.assertNotIn('edit-usercreated', self.uimanager.get_ui())
		mymanager = CustomToolManager()
		mytool = {
			'Name': 'Edit',
			'Comment': 'Test Edit',
			'X-Zim-ExecTool': 'edit %f',
		}
		mymanager.create(**mytool)
		self.assertIn('edit-usercreated', self.uimanager.get_ui())

	def testMenuUpdatedWhenToolChanges(self):
		# Key in this test is that the changes happens via a different instance
		# of the manager - demonstrating the singleton-like behavior
		mymanager = CustomToolManager()
		mytool = {
			'Name': 'Edit',
			'Comment': 'Test Edit',
			'X-Zim-ExecTool': 'edit %f',
		}
		mymanager.create(**mytool)
		self.assertIn('edit-usercreated', self.uimanager.get_ui())
		action = self.get_action('edit-usercreated')
		self.assertEqual(action.get_property('label'), 'Edit')

		tool = mymanager.get_tool('Edit')
		tool.update({'Name': 'My Editting tool'})
		tool.write()
		self.assertIn('edit-usercreated', self.uimanager.get_ui())
		action = self.get_action('edit-usercreated')
		self.assertEqual(action.get_property('label'), 'My Editting tool')

	def testExecuteCustomToolAction(self):
		mymanager = CustomToolManager()
		mytool = {
			'Name': 'Edit',
			'Comment': 'Test Edit',
			'X-Zim-ExecTool': 'edit %f',
		}
		mymanager.create(**mytool)
		action = self.get_action('edit-usercreated')

		def tool_run(args):
			self.assertIn(args[0], ('edit', b'edit'))

		with tests.ApplicationContext(tool_run):
			action.activate()

	def testExecuteCustomToolActionModifyPage(self):
		mymanager = CustomToolManager()
		mytool = {
			'Name': 'Edit',
			'Comment': 'Test Edit',
			'X-Zim-ExecTool': 'edit %s',
			'X-Zim-ReadOnly': False,
		}
		mymanager.create(**mytool)
		action = self.get_action('edit-usercreated')

		def tool_run(args):
			self.assertIn(args[0], ('edit', b'edit'))
			self.pageview.page.source_file.write('test 123')

		with tests.ApplicationContext(tool_run):
			action.activate()

	def testExecuteCustomToolActionReplaceSelection(self):
		mymanager = CustomToolManager()
		mytool = {
			'Name': 'Edit',
			'Comment': 'Test Edit',
			'X-Zim-ExecTool': 'edit %f',
			'X-Zim-ReplaceSelection': True,
		}
		tool = mymanager.create(**mytool)
		self.assertTrue(tool.replaceselection)
		action = self.get_action('edit-usercreated')

		got = []
		self.pageview.replace_selection = lambda *a, **kwa: got.append(a)

		def tool_run(args):
			self.assertIn(args[0], ('edit', b'edit'))
			return "TEST 123"

		with tests.ApplicationContext(tool_run):
			action.activate()

		self.assertEqual(got, [('TEST 123',)])

class TestCustomToolDialog(tests.TestCase):

	mockConfigManager = False  # breaks hack in customtools

	def setUp(self):
		clear_customtools()

	def testAddCustomTool(self):
		manager = CustomToolManager()
		mytool = {
			'Name': 'Add',
			'Comment': 'Test Add',
			'X-Zim-ExecTool': 'add %f',
			'X-Zim-ReadOnly': False,
			'X-Zim-ShowInToolBar': False,
			'X-Zim-ReplaceSelection': False,
		}

		self.assertIsNone(manager.get_tool('Add'))

		def add_tool(dialog):
			dialog.set_input(**mytool)
			dialog.assert_response_ok()

		dialog = CustomToolManagerDialog(None)
		with tests.DialogContext(add_tool):
			dialog.on_add()
			dialog.assert_response_ok()

		# XXX listview intialization fails in test ???
		#model = dialog.listview.get_model()
		#self.assertIn('Add', [r[CustomToolList.NAME_COL] for r in model])

		tool = manager.get_tool('Add')
		self.assertIsNotNone(tool)
		for key, value in list(mytool.items()):
			self.assertEqual(tool['Desktop Entry'][key], value)

	@tests.expectedFailure # Fails because of select_by_name fails - listview initialized ?
	def testEditCustomTool(self):
		manager = CustomToolManager()
		mytool = {
			'Name': 'Edit',
			'Comment': 'Test Edit',
			'X-Zim-ExecTool': 'edit %f',
		}
		manager.create(**mytool)
		self.assertIsNotNone(manager.get_tool('Edit'))

		def edit_tool(dialog):
			dialog.set_input(Comment='Editted Comment')
			dialog.assert_response_ok()

		dialog = CustomToolManagerDialog(None)
		#model = dialog.listview.get_model()
		#self.assertIn('Edit', [r[CustomToolList.NAME_COL] for r in model])
		with tests.DialogContext(edit_tool):
			dialog.listview.select_by_name('Edit')
			dialog.on_edit()
			dialog.assert_response_ok()

		tool = manager.get_tool('Edit')
		self.assertEqual(tool.comment, 'Editted Comment')

	@tests.expectedFailure
	def testRemoveCustomTool(self):
		# Need initialized listview
		raise NotImplementedError

	@tests.expectedFailure
	def testMovePositionInList(self):
		# Need initialized listview
		raise NotImplementedError