blob: 42fadaab697b054f1a9c5ea7616c36fffcc2a7f8 [file] [log] [blame]
Bram Moolenaara58883b2017-01-29 21:31:09 +01001" Test for python 2 commands.
Bram Moolenaara58883b2017-01-29 21:31:09 +01002
Bram Moolenaarb46fecd2019-06-15 17:58:09 +02003source check.vim
4CheckFeature python
Bram Moolenaar92fdd1e2020-07-03 18:00:05 +02005CheckFeature quickfix
Bram Moolenaarab589462020-07-06 21:03:06 +02006source shared.vim
Bram Moolenaar92fdd1e2020-07-03 18:00:05 +02007
8" NOTE: This will cause errors when run under valgrind.
9" This would require recompiling Python with:
10" ./configure --without-pymalloc
11" See http://svn.python.org/view/python/trunk/Misc/README.valgrind?view=markup
12"
13
14" This function should be called first. This sets up python functions used by
15" the other tests.
16func Test_AAA_python_setup()
17 py << trim EOF
18 import vim
19 import sys
20
21 def emsg(ei):
22 return ei[0].__name__ + ':' + repr(ei[1].args)
23
24 def ee(expr, g=globals(), l=locals()):
25 try:
26 exec(expr, g, l)
27 except:
28 ei = sys.exc_info()
29 msg = emsg(ei)
30 msg = msg.replace('TypeError:(\'argument 1 ', 'TypeError:(\'')
31 if expr.find('None') > -1:
32 msg = msg.replace('TypeError:(\'iteration over non-sequence\',)',
33 'TypeError:("\'NoneType\' object is not iterable",)')
34 if expr.find('FailingNumber') > -1:
35 msg = msg.replace(', not \'FailingNumber\'', '').replace('"', '\'')
36 msg = msg.replace('TypeError:(\'iteration over non-sequence\',)',
37 'TypeError:("\'FailingNumber\' object is not iterable",)')
38 if msg.find('(\'\'') > -1 or msg.find('(\'can\'t') > -1:
39 msg = msg.replace('(\'', '("').replace('\',)', '",)')
40 # Some Python versions say can't, others cannot.
41 if msg.find('can\'t') > -1:
42 msg = msg.replace('can\'t', 'cannot')
43 # Some Python versions use single quote, some double quote
44 if msg.find('"cannot ') > -1:
45 msg = msg.replace('"cannot ', '\'cannot ')
46 if msg.find(' attributes"') > -1:
47 msg = msg.replace(' attributes"', ' attributes\'')
48 if expr == 'fd(self=[])':
49 # HACK: PyMapping_Check changed meaning
50 msg = msg.replace('AttributeError:(\'keys\',)',
51 'TypeError:(\'unable to convert list to vim dictionary\',)')
52 vim.current.buffer.append(expr + ':' + msg)
53 else:
54 vim.current.buffer.append(expr + ':NOT FAILED')
55 EOF
56endfunc
Bram Moolenaara58883b2017-01-29 21:31:09 +010057
58func Test_pydo()
Bram Moolenaarab589462020-07-06 21:03:06 +020059 " Check deleting lines does not trigger an ml_get error.
Bram Moolenaara58883b2017-01-29 21:31:09 +010060 new
61 call setline(1, ['one', 'two', 'three'])
62 pydo vim.command("%d_")
63 bwipe!
64
Bram Moolenaarab589462020-07-06 21:03:06 +020065 " Check switching to another buffer does not trigger an ml_get error.
Bram Moolenaara58883b2017-01-29 21:31:09 +010066 new
67 let wincount = winnr('$')
68 call setline(1, ['one', 'two', 'three'])
69 pydo vim.command("new")
70 call assert_equal(wincount + 1, winnr('$'))
71 bwipe!
72 bwipe!
Bram Moolenaarab589462020-07-06 21:03:06 +020073
74 " Try modifying a buffer with 'nomodifiable' set
75 set nomodifiable
76 call assert_fails('pydo toupper(line)', 'cannot save undo information')
77 set modifiable
78
79 " Invalid command
80 call AssertException(['pydo non_existing_cmd'],
81 \ "Vim(pydo):NameError: global name 'non_existing_cmd' is not defined")
82 call AssertException(["pydo raise Exception('test')"],
83 \ 'Vim(pydo):Exception: test')
84 call AssertException(["pydo {lambda}"],
85 \ 'Vim(pydo):SyntaxError: invalid syntax')
Bram Moolenaara58883b2017-01-29 21:31:09 +010086endfunc
Bram Moolenaar53901442018-07-25 22:02:36 +020087
88func Test_set_cursor()
89 " Check that setting the cursor position works.
Bram Moolenaar53901442018-07-25 22:02:36 +020090 new
91 call setline(1, ['first line', 'second line'])
92 normal gg
93 pydo vim.current.window.cursor = (1, 5)
94 call assert_equal([1, 6], [line('.'), col('.')])
95
96 " Check that movement after setting cursor position keeps current column.
97 normal j
98 call assert_equal([2, 6], [line('.'), col('.')])
99endfunc
Bram Moolenaar9123c0b2018-12-22 18:59:06 +0100100
101func Test_vim_function()
102 " Check creating vim.Function object
Bram Moolenaar9123c0b2018-12-22 18:59:06 +0100103
104 func s:foo()
105 return matchstr(expand('<sfile>'), '<SNR>\zs\d\+_foo$')
106 endfunc
107 let name = '<SNR>' . s:foo()
108
109 try
110 py f = vim.bindeval('function("s:foo")')
111 call assert_equal(name, pyeval('f.name'))
112 catch
113 call assert_false(v:exception)
114 endtry
115
116 try
117 py f = vim.Function('\x80\xfdR' + vim.eval('s:foo()'))
Bram Moolenaar3f4f3d82019-09-04 20:05:59 +0200118 call assert_equal(name, 'f.name'->pyeval())
Bram Moolenaar9123c0b2018-12-22 18:59:06 +0100119 catch
120 call assert_false(v:exception)
121 endtry
122
Bram Moolenaarab589462020-07-06 21:03:06 +0200123 " Non-existing function attribute
124 call AssertException(["let x = pyeval('f.abc')"],
125 \ 'Vim(let):AttributeError: abc')
Bram Moolenaar92fdd1e2020-07-03 18:00:05 +0200126
Bram Moolenaar9123c0b2018-12-22 18:59:06 +0100127 py del f
128 delfunc s:foo
129endfunc
Bram Moolenaar14816ad2019-02-18 22:04:56 +0100130
131func Test_skipped_python_command_does_not_affect_pyxversion()
132 set pyxversion=0
133 if 0
134 python import vim
135 endif
136 call assert_equal(0, &pyxversion) " This assertion would have failed with Vim 8.0.0251. (pyxversion was introduced in 8.0.0251.)
137endfunc
Bram Moolenaar63dbfd32019-03-23 17:41:59 +0100138
139func _SetUpHiddenBuffer()
Bram Moolenaar63dbfd32019-03-23 17:41:59 +0100140 new
141 edit hidden
142 setlocal bufhidden=hide
143
144 enew
145 let lnum = 0
146 while lnum < 10
147 call append( 1, string( lnum ) )
148 let lnum = lnum + 1
149 endwhile
150 normal G
151
152 call assert_equal( line( '.' ), 11 )
153endfunc
154
Bram Moolenaarbfd36032019-03-30 12:33:13 +0100155func _CleanUpHiddenBuffer()
156 bwipe! hidden
157 bwipe!
158endfunc
159
Bram Moolenaar63dbfd32019-03-23 17:41:59 +0100160func Test_Write_To_HiddenBuffer_Does_Not_Fix_Cursor_Clear()
161 call _SetUpHiddenBuffer()
162 py vim.buffers[ int( vim.eval( 'bufnr("hidden")' ) ) ][:] = None
163 call assert_equal( line( '.' ), 11 )
Bram Moolenaarbfd36032019-03-30 12:33:13 +0100164 call _CleanUpHiddenBuffer()
Bram Moolenaar63dbfd32019-03-23 17:41:59 +0100165endfunc
166
167func Test_Write_To_HiddenBuffer_Does_Not_Fix_Cursor_List()
168 call _SetUpHiddenBuffer()
169 py vim.buffers[ int( vim.eval( 'bufnr("hidden")' ) ) ][:] = [ 'test' ]
170 call assert_equal( line( '.' ), 11 )
Bram Moolenaarbfd36032019-03-30 12:33:13 +0100171 call _CleanUpHiddenBuffer()
Bram Moolenaar63dbfd32019-03-23 17:41:59 +0100172endfunc
173
174func Test_Write_To_HiddenBuffer_Does_Not_Fix_Cursor_Str()
175 call _SetUpHiddenBuffer()
176 py vim.buffers[ int( vim.eval( 'bufnr("hidden")' ) ) ][0] = 'test'
177 call assert_equal( line( '.' ), 11 )
Bram Moolenaarbfd36032019-03-30 12:33:13 +0100178 call _CleanUpHiddenBuffer()
Bram Moolenaar63dbfd32019-03-23 17:41:59 +0100179endfunc
180
181func Test_Write_To_HiddenBuffer_Does_Not_Fix_Cursor_ClearLine()
182 call _SetUpHiddenBuffer()
183 py vim.buffers[ int( vim.eval( 'bufnr("hidden")' ) ) ][0] = None
184 call assert_equal( line( '.' ), 11 )
Bram Moolenaarbfd36032019-03-30 12:33:13 +0100185 call _CleanUpHiddenBuffer()
Bram Moolenaar63dbfd32019-03-23 17:41:59 +0100186endfunc
187
188func _SetUpVisibleBuffer()
Bram Moolenaar63dbfd32019-03-23 17:41:59 +0100189 new
190 let lnum = 0
191 while lnum < 10
192 call append( 1, string( lnum ) )
193 let lnum = lnum + 1
194 endwhile
195 normal G
196 call assert_equal( line( '.' ), 11 )
197endfunc
198
199func Test_Write_To_Current_Buffer_Fixes_Cursor_Clear()
200 call _SetUpVisibleBuffer()
201
202 py vim.current.buffer[:] = None
203 call assert_equal( line( '.' ), 1 )
204
205 bwipe!
206endfunc
207
208func Test_Write_To_Current_Buffer_Fixes_Cursor_List()
209 call _SetUpVisibleBuffer()
210
211 py vim.current.buffer[:] = [ 'test' ]
212 call assert_equal( line( '.' ), 1 )
213
214 bwipe!
Bram Moolenaar92fdd1e2020-07-03 18:00:05 +0200215endfunc
Bram Moolenaar63dbfd32019-03-23 17:41:59 +0100216
217func Test_Write_To_Current_Buffer_Fixes_Cursor_Str()
218 call _SetUpVisibleBuffer()
219
220 py vim.current.buffer[-1] = None
221 call assert_equal( line( '.' ), 10 )
222
223 bwipe!
Bram Moolenaar92fdd1e2020-07-03 18:00:05 +0200224endfunc
Bram Moolenaar7f3a2842019-05-18 15:02:25 +0200225
226func Test_Catch_Exception_Message()
227 try
228 py raise RuntimeError( 'TEST' )
229 catch /.*/
230 call assert_match( '^Vim(.*):RuntimeError: TEST$', v:exception )
231 endtry
232endfunc
Bram Moolenaar6c2b7b82020-04-14 20:15:49 +0200233
234" Test for various heredoc syntax
235func Test_python_heredoc()
236 python << END
237s='A'
238END
239 python <<
240s+='B'
241.
242 python << trim END
243 s+='C'
244 END
245 python << trim
246 s+='D'
247 .
Bram Moolenaar6ab09532020-05-01 14:10:13 +0200248 python << trim eof
249 s+='E'
250 eof
251 call assert_equal('ABCDE', pyxeval('s'))
Bram Moolenaar6c2b7b82020-04-14 20:15:49 +0200252endfunc
253
Bram Moolenaar92fdd1e2020-07-03 18:00:05 +0200254" Test for the buffer range object
255func Test_python_range()
256 new
257 call setline(1, ['one', 'two', 'three'])
258 py b = vim.current.buffer
259 py r = b.range(1, 3)
260 call assert_equal(0, pyeval('r.start'))
261 call assert_equal(2, pyeval('r.end'))
Bram Moolenaarab589462020-07-06 21:03:06 +0200262 call assert_equal('one', pyeval('r[0]'))
263 call assert_equal('one', pyeval('r[-3]'))
264 call assert_equal('three', pyeval('r[-4]'))
Bram Moolenaar92fdd1e2020-07-03 18:00:05 +0200265 call assert_equal(['two', 'three'], pyeval('r[1:]'))
266 py r[0] = 'green'
267 call assert_equal(['green', 'two', 'three'], getline(1, '$'))
268 py r[0:2] = ['red', 'blue']
269 call assert_equal(['red', 'blue', 'three'], getline(1, '$'))
270 call assert_equal(['start', 'end', '__members__'], pyeval('r.__members__'))
271
Bram Moolenaarab589462020-07-06 21:03:06 +0200272 " try different invalid start/end index for the range slice
273 %d
274 call setline(1, ['one', 'two', 'three'])
275 py r[-10:1] = ["a"]
276 py r[10:12] = ["b"]
277 py r[-10:-9] = ["c"]
278 py r[1:0] = ["d"]
279 call assert_equal(['c', 'd', 'a', 'two', 'three', 'b'], getline(1, '$'))
280
Bram Moolenaarbb790dc2020-07-07 20:12:54 +0200281 " The following code used to trigger an ml_get error
282 %d
283 let x = pyeval('r[:]')
Bram Moolenaarab589462020-07-06 21:03:06 +0200284
285 " Non-existing range attribute
286 call AssertException(["let x = pyeval('r.abc')"],
287 \ 'Vim(let):AttributeError: abc')
Bram Moolenaar92fdd1e2020-07-03 18:00:05 +0200288
289 close!
290endfunc
291
292" Test for the python tabpage object
293func Test_python_tabpage()
294 tabnew
295 py t = vim.tabpages[1]
Bram Moolenaarab589462020-07-06 21:03:06 +0200296 py wl = t.windows
Bram Moolenaar92fdd1e2020-07-03 18:00:05 +0200297 tabclose
Bram Moolenaarab589462020-07-06 21:03:06 +0200298 " Accessing a closed tabpage
299 call AssertException(["let n = pyeval('t.number')"],
300 \ 'Vim(let):vim.error: attempt to refer to deleted tab page')
301 call AssertException(["let n = pyeval('len(wl)')"],
302 \ 'Vim(let):vim.error: attempt to refer to deleted tab page')
303 call AssertException(["py w = wl[0]"],
304 \ 'Vim(python):vim.error: attempt to refer to deleted tab page')
305 call AssertException(["py vim.current.tabpage = t"],
306 \ 'Vim(python):vim.error: attempt to refer to deleted tab page')
307 call assert_match('<tabpage object (deleted)', pyeval('repr(t)'))
Bram Moolenaar92fdd1e2020-07-03 18:00:05 +0200308 %bw!
309endfunc
310
311" Test for the python window object
312func Test_python_window()
Bram Moolenaarab589462020-07-06 21:03:06 +0200313 " Test for setting the window height
314 10new
315 py vim.current.window.height = 5
316 call assert_equal(5, winheight(0))
317
318 " Test for setting the window width
319 10vnew
320 py vim.current.window.width = 6
321 call assert_equal(6, winwidth(0))
322
323 " Try accessing a closed window
Bram Moolenaar92fdd1e2020-07-03 18:00:05 +0200324 py w = vim.current.window
Bram Moolenaarab589462020-07-06 21:03:06 +0200325 py wopts = w.options
Bram Moolenaar92fdd1e2020-07-03 18:00:05 +0200326 close
Bram Moolenaarab589462020-07-06 21:03:06 +0200327 " Access the attributes of a closed window
328 call AssertException(["let n = pyeval('w.number')"],
329 \ 'Vim(let):vim.error: attempt to refer to deleted window')
330 call AssertException(["py w.height = 5"],
331 \ 'Vim(python):vim.error: attempt to refer to deleted window')
332 call AssertException(["py vim.current.window = w"],
333 \ 'Vim(python):vim.error: attempt to refer to deleted window')
334 " Try to set one of the options of the closed window
Bram Moolenaarbb790dc2020-07-07 20:12:54 +0200335 " The following caused an ASAN failure
336 call AssertException(["py wopts['list'] = False"],
337 \ 'vim.error: attempt to refer to deleted window')
Bram Moolenaarab589462020-07-06 21:03:06 +0200338 call assert_match('<window object (deleted)', pyeval("repr(w)"))
339 %bw!
Bram Moolenaar92fdd1e2020-07-03 18:00:05 +0200340endfunc
341
342" Test for the python List object
343func Test_python_list()
344 let l = [1, 2]
345 py pl = vim.bindeval('l')
346 call assert_equal(['locked', '__members__'], pyeval('pl.__members__'))
347
Bram Moolenaarab589462020-07-06 21:03:06 +0200348 " Try to convert a null List
349 call AssertException(["py t = vim.eval('test_null_list()')"],
350 \ 'Vim(python):SystemError: error return without exception set')
351
352 " Try to convert a List with a null List item
353 call AssertException(["py t = vim.eval('[test_null_list()]')"],
354 \ 'Vim(python):SystemError: error return without exception set')
355
356 " Try to bind a null List variable
357 let cmds =<< trim END
358 let l = test_null_list()
359 py ll = vim.bindeval('l')
360 END
361 call AssertException(cmds, 'Vim(python):SystemError: error return without exception set')
362
Bram Moolenaar92fdd1e2020-07-03 18:00:05 +0200363 let l = []
364 py l = vim.bindeval('l')
365 py f = vim.bindeval('function("strlen")')
366 " Extending List directly with different types
367 py l.extend([1, "as'd", [1, 2, f, {'a': 1}]])
368 call assert_equal([1, "as'd", [1, 2, function("strlen"), {'a': 1}]], l)
369 call assert_equal([1, 2, function("strlen"), {'a': 1}], l[-1])
370 call assert_fails('echo l[-4]', 'E684:')
371
372 " List assignment
373 py l[0] = 0
374 call assert_equal([0, "as'd", [1, 2, function("strlen"), {'a': 1}]], l)
375 py l[-2] = f
376 call assert_equal([0, function("strlen"), [1, 2, function("strlen"), {'a': 1}]], l)
Bram Moolenaarab589462020-07-06 21:03:06 +0200377
378 " appending to a list
379 let l = [1, 2]
380 py ll = vim.bindeval('l')
381 py ll[2] = 8
382 call assert_equal([1, 2, 8], l)
383
384 " Using dict as an index
385 call AssertException(['py ll[{}] = 10'],
386 \ 'Vim(python):TypeError: index must be int or slice, not dict')
Bram Moolenaar92fdd1e2020-07-03 18:00:05 +0200387endfunc
388
389" Test for the python Dict object
390func Test_python_dict()
391 let d = {}
392 py pd = vim.bindeval('d')
393 call assert_equal(['locked', 'scope', '__members__'],
394 \ pyeval('pd.__members__'))
Bram Moolenaarab589462020-07-06 21:03:06 +0200395
396 " Try to convert a null Dict
397 call AssertException(["py t = vim.eval('test_null_dict()')"],
398 \ 'Vim(python):SystemError: error return without exception set')
399
400 " Try to convert a Dict with a null List value
401 call AssertException(["py t = vim.eval(\"{'a' : test_null_list()}\")"],
402 \ 'Vim(python):SystemError: error return without exception set')
403
404 " Try to convert a Dict with a null string key
405 py t = vim.eval("{test_null_string() : 10}")
406 call assert_fails("let d = pyeval('t')", 'E859:')
407
408 " Dict length
409 let d = {'a' : 10, 'b' : 20}
410 py d = vim.bindeval('d')
411 call assert_equal(2, pyeval('len(d)'))
412
413 " Deleting an non-existing key
414 call AssertException(["py del d['c']"], "Vim(python):KeyError: 'c'")
Bram Moolenaar92fdd1e2020-07-03 18:00:05 +0200415endfunc
416
417" Extending Dictionary directly with different types
418func Test_python_dict_extend()
419 let d = {}
420 func d.f()
421 return 1
422 endfunc
423
424 py f = vim.bindeval('function("strlen")')
425 py << trim EOF
426 d = vim.bindeval('d')
427 d['1'] = 'asd'
428 d.update() # Must not do anything, including throwing errors
429 d.update(b = [1, 2, f])
430 d.update((('-1', {'a': 1}),))
431 d.update({'0': -1})
432 dk = d.keys()
433 dv = d.values()
434 di = d.items()
435 cmpfun = lambda a, b: cmp(repr(a), repr(b))
436 dk.sort(cmpfun)
437 dv.sort(cmpfun)
438 di.sort(cmpfun)
439 EOF
440
Bram Moolenaarab589462020-07-06 21:03:06 +0200441 " Try extending a locked dictionary
442 lockvar d
443 call AssertException(["py d.update({'b' : 20})"],
444 \ 'Vim(python):vim.error: dictionary is locked')
445 unlockvar d
446
Bram Moolenaar92fdd1e2020-07-03 18:00:05 +0200447 call assert_equal(1, pyeval("d['f'](self={})"))
448 call assert_equal("['-1', '0', '1', 'b', 'f']", pyeval('repr(dk)'))
449 call assert_equal("['asd', -1L, <vim.Function '1'>, <vim.dictionary object at >, <vim.list object at >]", substitute(pyeval('repr(dv)'),'0x\x\+','','g'))
450 call assert_equal("[('-1', <vim.dictionary object at >), ('0', -1L), ('1', 'asd'), ('b', <vim.list object at >), ('f', <vim.Function '1'>)]", substitute(pyeval('repr(di)'),'0x\x\+','','g'))
451 call assert_equal(['0', '1', 'b', 'f', '-1'], keys(d))
452 call assert_equal("[-1, 'asd', [1, 2, function('strlen')], function('1'), {'a': 1}]", string(values(d)))
453 py del dk
454 py del di
455 py del dv
456endfunc
457
458func Test_python_list_del_items()
459 " removing items with del
460 let l = [0, function("strlen"), [1, 2, function("strlen"), {'a': 1}]]
461 py l = vim.bindeval('l')
462 py del l[2]
463 call assert_equal("[0, function('strlen')]", string(l))
464
465 let l = range(8)
466 py l = vim.bindeval('l')
467 py del l[:3]
468 py del l[1:]
469 call assert_equal([3], l)
470
471 " removing items out of range: silently skip items that don't exist
472
473 " The following two ranges delete nothing as they match empty list:
474 let l = [0, 1, 2, 3]
475 py l = vim.bindeval('l')
476 py del l[2:1]
477 call assert_equal([0, 1, 2, 3], l)
478 py del l[2:2]
479 call assert_equal([0, 1, 2, 3], l)
480 py del l[2:3]
481 call assert_equal([0, 1, 3], l)
482
483 let l = [0, 1, 2, 3]
484 py l = vim.bindeval('l')
485 py del l[2:4]
486 call assert_equal([0, 1], l)
487
488 let l = [0, 1, 2, 3]
489 py l = vim.bindeval('l')
490 py del l[2:5]
491 call assert_equal([0, 1], l)
492
493 let l = [0, 1, 2, 3]
494 py l = vim.bindeval('l')
495 py del l[2:6]
496 call assert_equal([0, 1], l)
497
498 " The following two ranges delete nothing as they match empty list:
499 let l = [0, 1, 2, 3]
500 py l = vim.bindeval('l')
501 py del l[-1:2]
502 call assert_equal([0, 1, 2, 3], l)
503 py del l[-2:2]
504 call assert_equal([0, 1, 2, 3], l)
505 py del l[-3:2]
506 call assert_equal([0, 2, 3], l)
507
508 let l = [0, 1, 2, 3]
509 py l = vim.bindeval('l')
510 py del l[-4:2]
511 call assert_equal([2, 3], l)
512
513 let l = [0, 1, 2, 3]
514 py l = vim.bindeval('l')
515 py del l[-5:2]
516 call assert_equal([2, 3], l)
517
518 let l = [0, 1, 2, 3]
519 py l = vim.bindeval('l')
520 py del l[-6:2]
521 call assert_equal([2, 3], l)
522
523 let l = [0, 1, 2, 3]
524 py l = vim.bindeval('l')
525 py del l[::2]
526 call assert_equal([1, 3], l)
527
528 let l = [0, 1, 2, 3]
529 py l = vim.bindeval('l')
530 py del l[3:0:-2]
531 call assert_equal([0, 2], l)
532
533 let l = [0, 1, 2, 3]
534 py l = vim.bindeval('l')
535 py del l[2:4:-2]
536 let l = [0, 1, 2, 3]
537endfunc
538
539func Test_python_dict_del_items()
540 let d = eval("{'0' : -1, '1' : 'asd', 'b' : [1, 2, function('strlen')], 'f' : function('min'), '-1' : {'a': 1}}")
541 py d = vim.bindeval('d')
542 py del d['-1']
543 py del d['f']
544 call assert_equal([1, 2, function('strlen')], pyeval('d.get(''b'', 1)'))
545 call assert_equal([1, 2, function('strlen')], pyeval('d.pop(''b'')'))
546 call assert_equal(1, pyeval('d.get(''b'', 1)'))
547 call assert_equal('asd', pyeval('d.pop(''1'', 2)'))
548 call assert_equal(2, pyeval('d.pop(''1'', 2)'))
549 call assert_equal('True', pyeval('repr(d.has_key(''0''))'))
550 call assert_equal('False', pyeval('repr(d.has_key(''1''))'))
551 call assert_equal('True', pyeval('repr(''0'' in d)'))
552 call assert_equal('False', pyeval('repr(''1'' in d)'))
553 call assert_equal("['0']", pyeval('repr(list(iter(d)))'))
554 call assert_equal({'0' : -1}, d)
555 call assert_equal("('0', -1L)", pyeval('repr(d.popitem())'))
556 call assert_equal('None', pyeval('repr(d.get(''0''))'))
557 call assert_equal('[]', pyeval('repr(list(iter(d)))'))
558endfunc
559
560" Slice assignment to a list
561func Test_python_slice_assignment()
562 let l = [0, 1, 2, 3]
563 py l = vim.bindeval('l')
564 py l[0:0] = ['a']
565 call assert_equal(['a', 0, 1, 2, 3], l)
566
567 let l = [0, 1, 2, 3]
568 py l = vim.bindeval('l')
569 py l[1:2] = ['b']
570 call assert_equal([0, 'b', 2, 3], l)
571
572 let l = [0, 1, 2, 3]
573 py l = vim.bindeval('l')
574 py l[2:4] = ['c']
575 call assert_equal([0, 1, 'c'], l)
576
577 let l = [0, 1, 2, 3]
578 py l = vim.bindeval('l')
579 py l[4:4] = ['d']
580 call assert_equal([0, 1, 2, 3, 'd'], l)
581
582 let l = [0, 1, 2, 3]
583 py l = vim.bindeval('l')
584 py l[-1:2] = ['e']
585 call assert_equal([0, 1, 2, 'e', 3], l)
586
587 let l = [0, 1, 2, 3]
588 py l = vim.bindeval('l')
589 py l[-10:2] = ['f']
590 call assert_equal(['f', 2, 3], l)
591
592 let l = [0, 1, 2, 3]
593 py l = vim.bindeval('l')
594 py l[2:-10] = ['g']
595 call assert_equal([0, 1, 'g', 2, 3], l)
596
597 let l = []
598 py l = vim.bindeval('l')
599 py l[0:0] = ['h']
600 call assert_equal(['h'], l)
601
602 let l = range(8)
603 py l = vim.bindeval('l')
604 py l[2:6:2] = [10, 20]
605 call assert_equal([0, 1, 10, 3, 20, 5, 6, 7], l)
606
607 let l = range(8)
608 py l = vim.bindeval('l')
609 py l[6:2:-2] = [10, 20]
610 call assert_equal([0, 1, 2, 3, 20, 5, 10, 7], l)
611
612 let l = range(8)
613 py l = vim.bindeval('l')
614 py l[6:2] = ()
615 call assert_equal([0, 1, 2, 3, 4, 5, 6, 7], l)
616
617 let l = range(8)
618 py l = vim.bindeval('l')
619 py l[6:2:1] = ()
620 call assert_equal([0, 1, 2, 3, 4, 5, 6, 7], l)
621
622 let l = range(8)
623 py l = vim.bindeval('l')
624 py l[2:2:1] = ()
625 call assert_equal([0, 1, 2, 3, 4, 5, 6, 7], l)
Bram Moolenaar0ab55d62020-07-07 20:50:39 +0200626
627 call AssertException(["py x = l[10:11:0]"],
628 \ "Vim(python):ValueError: slice step cannot be zero")
Bram Moolenaar92fdd1e2020-07-03 18:00:05 +0200629endfunc
630
631" Locked variables
632func Test_python_lockedvar()
633 new
634 py cb = vim.current.buffer
635 let l = [0, 1, 2, 3]
636 py l = vim.bindeval('l')
637 lockvar! l
638 py << trim EOF
639 try:
640 l[2]='i'
641 except vim.error:
642 cb.append('l[2] threw vim.error: ' + emsg(sys.exc_info()))
643 EOF
644 call assert_equal(['', "l[2] threw vim.error: error:('list is locked',)"],
645 \ getline(1, '$'))
Bram Moolenaarab589462020-07-06 21:03:06 +0200646
647 " Try to concatenate a locked list
648 call AssertException(['py l += [4, 5]'],
649 \ 'Vim(python):vim.error: list is locked')
650
Bram Moolenaar92fdd1e2020-07-03 18:00:05 +0200651 call assert_equal([0, 1, 2, 3], l)
652 unlockvar! l
653 close!
654endfunc
655
656" Test for calling a function
657func Test_python_function_call()
658 func New(...)
Bram Moolenaareffb0cd2020-07-03 21:17:34 +0200659 return ['NewStart'] + a:000 + ['NewEnd']
Bram Moolenaar92fdd1e2020-07-03 18:00:05 +0200660 endfunc
661
662 func DictNew(...) dict
Bram Moolenaareffb0cd2020-07-03 21:17:34 +0200663 return ['DictNewStart'] + a:000 + ['DictNewEnd', self]
Bram Moolenaar92fdd1e2020-07-03 18:00:05 +0200664 endfunc
665
666 new
667 let l = [function('New'), function('DictNew')]
668 py l = vim.bindeval('l')
669 py l.extend(list(l[0](1, 2, 3)))
670 call assert_equal([function('New'), function('DictNew'), 'NewStart', 1, 2, 3, 'NewEnd'], l)
671 py l.extend(list(l[1](1, 2, 3, self={'a': 'b'})))
672 call assert_equal([function('New'), function('DictNew'), 'NewStart', 1, 2, 3, 'NewEnd', 'DictNewStart', 1, 2, 3, 'DictNewEnd', {'a': 'b'}], l)
673 py l.extend([l[0].name])
674 call assert_equal([function('New'), function('DictNew'), 'NewStart', 1, 2, 3, 'NewEnd', 'DictNewStart', 1, 2, 3, 'DictNewEnd', {'a': 'b'}, 'New'], l)
675 py ee('l[1](1, 2, 3)')
676 call assert_equal("l[1](1, 2, 3):error:('Vim:E725: Calling dict function without Dictionary: DictNew',)", getline(2))
677 %d
678 py f = l[0]
679 delfunction New
680 py ee('f(1, 2, 3)')
681 call assert_equal("f(1, 2, 3):error:('Vim:E117: Unknown function: New',)", getline(2))
682 close!
683 delfunction DictNew
684endfunc
685
686func Test_python_float()
687 CheckFeature float
688 let l = [0.0]
689 py l = vim.bindeval('l')
690 py l.extend([0.0])
691 call assert_equal([0.0, 0.0], l)
692endfunc
693
694" Test for Dict key errors
695func Test_python_dict_key_error()
696 let messages = []
697 py << trim EOF
698 d = vim.bindeval('{}')
699 m = vim.bindeval('messages')
700 def em(expr, g=globals(), l=locals()):
701 try:
702 exec(expr, g, l)
703 except:
704 m.extend([sys.exc_type.__name__])
705
706 em('d["abc1"]')
707 em('d["abc1"]="\\0"')
708 em('d["abc1"]=vim')
709 em('d[""]=1')
710 em('d["a\\0b"]=1')
711 em('d[u"a\\0b"]=1')
712 em('d.pop("abc1")')
713 em('d.popitem()')
714 del em
715 del m
716 EOF
717
718 call assert_equal(['KeyError', 'TypeError', 'TypeError', 'ValueError',
719 \ 'TypeError', 'TypeError', 'KeyError', 'KeyError'], messages)
720 unlet messages
721endfunc
722
723" Test for locked and scope attributes
724func Test_python_lock_scope_attr()
725 let d = {} | let dl = {} | lockvar dl
726 let res = []
727 for s in split("d dl v: g:")
728 let name = tr(s, ':', 's')
729 execute 'py ' .. name .. ' = vim.bindeval("' .. s .. '")'
730 call add(res, s .. ' : ' .. join(map(['locked', 'scope'],
731 \ 'v:val .. ":" .. pyeval(name .. "." .. v:val)'), ';'))
732 endfor
733 call assert_equal(['d : locked:0;scope:0', 'dl : locked:1;scope:0',
734 \ 'v: : locked:2;scope:1', 'g: : locked:0;scope:2'], res)
735
736 silent! let d.abc2 = 1
737 silent! let dl.abc3 = 1
738 py d.locked = True
739 py dl.locked = False
740 silent! let d.def = 1
741 silent! let dl.def = 1
742 call assert_equal({'abc2': 1}, d)
743 call assert_equal({'def': 1}, dl)
744 unlet d dl
745
746 let l = [] | let ll = [] | lockvar ll
747 let res = []
748 for s in split("l ll")
749 let name = tr(s, ':', 's')
750 execute 'py ' .. name .. '=vim.bindeval("' .. s .. '")'
751 call add(res, s .. ' : locked:' .. pyeval(name .. '.locked'))
752 endfor
753 call assert_equal(['l : locked:0', 'll : locked:1'], res)
754
755 silent! call extend(l, [0])
756 silent! call extend(ll, [0])
757 py l.locked = True
758 py ll.locked = False
759 silent! call extend(l, [1])
760 silent! call extend(ll, [1])
761 call assert_equal([0], l)
762 call assert_equal([1], ll)
763 unlet l ll
Bram Moolenaarab589462020-07-06 21:03:06 +0200764
765 " Try changing an attribute of a fixed list
766 py a = vim.bindeval('v:argv')
767 call AssertException(['py a.locked = 0'],
768 \ 'Vim(python):TypeError: cannot modify fixed list')
Bram Moolenaar92fdd1e2020-07-03 18:00:05 +0200769endfunc
770
771" Test for pyeval()
772func Test_python_pyeval()
773 let l = pyeval('range(3)')
774 call assert_equal([0, 1, 2], l)
775
776 let d = pyeval('{"a": "b", "c": 1, "d": ["e"]}')
777 call assert_equal([['a', 'b'], ['c', 1], ['d', ['e']]], sort(items(d)))
778
779 let v:errmsg = ''
780 call assert_equal(v:none, pyeval('None'))
781 call assert_equal('', v:errmsg)
782
Bram Moolenaarab589462020-07-06 21:03:06 +0200783 py v = vim.eval('test_null_function()')
784 call assert_equal(v:none, pyeval('v'))
785
Bram Moolenaar92fdd1e2020-07-03 18:00:05 +0200786 if has('float')
787 call assert_equal(0.0, pyeval('0.0'))
788 endif
789
Bram Moolenaarab589462020-07-06 21:03:06 +0200790 " Evaluate an invalid values
791 call AssertException(['let v = pyeval(''"\0"'')'], 'E859:')
792 call AssertException(['let v = pyeval(''{"\0" : 1}'')'], 'E859:')
793 call AssertException(['let v = pyeval("undefined_name")'],
794 \ "Vim(let):NameError: name 'undefined_name' is not defined")
795 call AssertException(['let v = pyeval("vim")'], 'E859:')
796endfunc
Bram Moolenaar92fdd1e2020-07-03 18:00:05 +0200797
Bram Moolenaarab589462020-07-06 21:03:06 +0200798" Test for vim.bindeval()
799func Test_python_vim_bindeval()
800 " Float
801 let f = 3.14
802 py f = vim.bindeval('f')
803 call assert_equal(3.14, pyeval('f'))
Bram Moolenaar92fdd1e2020-07-03 18:00:05 +0200804
Bram Moolenaarab589462020-07-06 21:03:06 +0200805 " Blob
806 let b = 0z12
807 py b = vim.bindeval('b')
808 call assert_equal("\x12", pyeval('b'))
Bram Moolenaar92fdd1e2020-07-03 18:00:05 +0200809
Bram Moolenaarab589462020-07-06 21:03:06 +0200810 " Bool
811 call assert_equal(1, pyeval("vim.bindeval('v:true')"))
812 call assert_equal(0, pyeval("vim.bindeval('v:false')"))
813 call assert_equal(v:none, pyeval("vim.bindeval('v:null')"))
814 call assert_equal(v:none, pyeval("vim.bindeval('v:none')"))
Bram Moolenaar0ab55d62020-07-07 20:50:39 +0200815
816 " channel/job
817 call assert_equal(v:none, pyeval("vim.bindeval('test_null_channel()')"))
818 call assert_equal(v:none, pyeval("vim.bindeval('test_null_job()')"))
Bram Moolenaar92fdd1e2020-07-03 18:00:05 +0200819endfunc
820
821" threading
822" Running pydo command (Test_pydo) before this test, stops the python thread
823" from running. So this test should be run before the pydo test
824func Test_aaa_python_threading()
825 let l = [0]
826 py l = vim.bindeval('l')
827 py << trim EOF
828 import threading
829 import time
830
831 class T(threading.Thread):
832 def __init__(self):
833 threading.Thread.__init__(self)
834 self.t = 0
835 self.running = True
836
837 def run(self):
838 while self.running:
839 self.t += 1
840 time.sleep(0.1)
841
842 t = T()
843 del T
844 t.start()
845 EOF
846
847 sleep 1
848 py t.running = False
849 py t.join()
850
851 " Check if the background thread is working. Count should be 10, but on a
852 " busy system (AppVeyor) it can be much lower.
853 py l[0] = t.t > 4
854 py del time
855 py del threading
856 py del t
857 call assert_equal([1], l)
858endfunc
859
860" settrace
861func Test_python_settrace()
862 let l = []
863 py l = vim.bindeval('l')
864 py << trim EOF
865 import sys
866
867 def traceit(frame, event, arg):
868 global l
869 if event == "line":
870 l.extend([frame.f_lineno])
871 return traceit
872
873 def trace_main():
874 for i in range(5):
875 pass
876 EOF
877 py sys.settrace(traceit)
878 py trace_main()
879 py sys.settrace(None)
880 py del traceit
881 py del trace_main
882 call assert_equal([1, 10, 11, 10, 11, 10, 11, 10, 11, 10, 11, 10, 1], l)
883endfunc
884
885" Slice
886func Test_python_list_slice()
887 py ll = vim.bindeval('[0, 1, 2, 3, 4, 5]')
888 py l = ll[:4]
889 call assert_equal([0, 1, 2, 3], pyeval('l'))
890 py l = ll[2:]
891 call assert_equal([2, 3, 4, 5], pyeval('l'))
892 py l = ll[:-4]
893 call assert_equal([0, 1], pyeval('l'))
894 py l = ll[-2:]
895 call assert_equal([4, 5], pyeval('l'))
896 py l = ll[2:4]
897 call assert_equal([2, 3], pyeval('l'))
898 py l = ll[4:2]
899 call assert_equal([], pyeval('l'))
900 py l = ll[-4:-2]
901 call assert_equal([2, 3], pyeval('l'))
902 py l = ll[-2:-4]
903 call assert_equal([], pyeval('l'))
904 py l = ll[:]
905 call assert_equal([0, 1, 2, 3, 4, 5], pyeval('l'))
906 py l = ll[0:6]
907 call assert_equal([0, 1, 2, 3, 4, 5], pyeval('l'))
908 py l = ll[-10:10]
909 call assert_equal([0, 1, 2, 3, 4, 5], pyeval('l'))
910 py l = ll[4:2:-1]
911 call assert_equal([4, 3], pyeval('l'))
912 py l = ll[::2]
913 call assert_equal([0, 2, 4], pyeval('l'))
914 py l = ll[4:2:1]
915 call assert_equal([], pyeval('l'))
Bram Moolenaarab589462020-07-06 21:03:06 +0200916
917 " Error case: Use an invalid index
918 call AssertException(['py ll[-10] = 5'], 'Vim(python):vim.error: internal error:')
919
920 " Use a step value of 0
921 call AssertException(['py ll[0:3:0] = [1, 2, 3]'],
922 \ 'Vim(python):ValueError: slice step cannot be zero')
923
924 " Error case: Invalid slice type
925 call AssertException(["py x = ll['abc']"],
926 \ 'Vim(python):TypeError: index must be int or slice, not str')
Bram Moolenaar92fdd1e2020-07-03 18:00:05 +0200927 py del l
Bram Moolenaarab589462020-07-06 21:03:06 +0200928
929 " Error case: List with a null list item
930 let l = [test_null_list()]
931 py ll = vim.bindeval('l')
932 call AssertException(["py x = ll[:]"],
933 \ 'Vim(python):SystemError: error return without exception set')
Bram Moolenaar92fdd1e2020-07-03 18:00:05 +0200934endfunc
935
936" Vars
937func Test_python_vars()
938 let g:foo = 'bac'
939 let w:abc3 = 'def'
940 let b:baz = 'bar'
941 let t:bar = 'jkl'
942 try
943 throw "Abc"
944 catch /Abc/
945 call assert_equal('Abc', pyeval('vim.vvars[''exception'']'))
946 endtry
947 call assert_equal('bac', pyeval('vim.vars[''foo'']'))
948 call assert_equal('def', pyeval('vim.current.window.vars[''abc3'']'))
949 call assert_equal('bar', pyeval('vim.current.buffer.vars[''baz'']'))
950 call assert_equal('jkl', pyeval('vim.current.tabpage.vars[''bar'']'))
951endfunc
952
953" Options
954" paste: boolean, global
955" previewheight number, global
956" operatorfunc: string, global
957" number: boolean, window-local
958" numberwidth: number, window-local
959" colorcolumn: string, window-local
960" statusline: string, window-local/global
961" autoindent: boolean, buffer-local
962" shiftwidth: number, buffer-local
963" omnifunc: string, buffer-local
964" preserveindent: boolean, buffer-local/global
965" path: string, buffer-local/global
966func Test_python_opts()
967 let g:res = []
968 let g:bufs = [bufnr('%')]
969 new
970 let g:bufs += [bufnr('%')]
971 vnew
972 let g:bufs += [bufnr('%')]
973 wincmd j
974 vnew
975 let g:bufs += [bufnr('%')]
976 wincmd l
977
978 func RecVars(opt)
979 let gval = string(eval('&g:' .. a:opt))
980 let wvals = join(map(range(1, 4),
981 \ 'v:val .. ":" .. string(getwinvar(v:val, "&" .. a:opt))'))
982 let bvals = join(map(copy(g:bufs),
983 \ 'v:val .. ":" .. string(getbufvar(v:val, "&" .. a:opt))'))
984 call add(g:res, ' G: ' .. gval)
985 call add(g:res, ' W: ' .. wvals)
986 call add(g:res, ' B: ' .. wvals)
987 endfunc
988
989 py << trim EOF
990 def e(s, g=globals(), l=locals()):
991 try:
992 exec(s, g, l)
993 except:
994 vim.command('return ' + repr(sys.exc_type.__name__))
995
996 def ev(s, g=globals(), l=locals()):
997 try:
998 return eval(s, g, l)
999 except:
1000 vim.command('let exc=' + repr(sys.exc_type.__name__))
1001 return 0
1002 EOF
1003
1004 func E(s)
1005 python e(vim.eval('a:s'))
1006 endfunc
1007
1008 func Ev(s)
1009 let r = pyeval('ev(vim.eval("a:s"))')
1010 if exists('exc')
1011 throw exc
1012 endif
1013 return r
1014 endfunc
1015
1016 py gopts1 = vim.options
1017 py wopts1 = vim.windows[2].options
1018 py wopts2 = vim.windows[0].options
1019 py wopts3 = vim.windows[1].options
1020 py bopts1 = vim.buffers[vim.bindeval("g:bufs")[2]].options
1021 py bopts2 = vim.buffers[vim.bindeval("g:bufs")[1]].options
1022 py bopts3 = vim.buffers[vim.bindeval("g:bufs")[0]].options
1023 call add(g:res, 'wopts iters equal: ' ..
1024 \ pyeval('list(wopts1) == list(wopts2)'))
1025 call add(g:res, 'bopts iters equal: ' ..
1026 \ pyeval('list(bopts1) == list(bopts2)'))
1027 py gset = set(iter(gopts1))
1028 py wset = set(iter(wopts1))
1029 py bset = set(iter(bopts1))
1030
1031 set path=.,..,,
1032 let lst = []
1033 let lst += [['paste', 1, 0, 1, 2, 1, 1, 0]]
1034 let lst += [['previewheight', 5, 1, 6, 'a', 0, 1, 0]]
1035 let lst += [['operatorfunc', 'A', 'B', 'C', 2, 0, 1, 0]]
1036 let lst += [['number', 0, 1, 1, 0, 1, 0, 1]]
1037 let lst += [['numberwidth', 2, 3, 5, -100, 0, 0, 1]]
1038 let lst += [['colorcolumn', '+1', '+2', '+3', 'abc4', 0, 0, 1]]
1039 let lst += [['statusline', '1', '2', '4', 0, 0, 1, 1]]
1040 let lst += [['autoindent', 0, 1, 1, 2, 1, 0, 2]]
1041 let lst += [['shiftwidth', 0, 2, 1, 3, 0, 0, 2]]
1042 let lst += [['omnifunc', 'A', 'B', 'C', 1, 0, 0, 2]]
1043 let lst += [['preserveindent', 0, 1, 1, 2, 1, 1, 2]]
1044 let lst += [['path', '.,,', ',,', '.', 0, 0, 1, 2]]
1045 for [oname, oval1, oval2, oval3, invval, bool, global, local] in lst
1046 py oname = vim.eval('oname')
1047 py oval1 = vim.bindeval('oval1')
1048 py oval2 = vim.bindeval('oval2')
1049 py oval3 = vim.bindeval('oval3')
1050 if invval is 0 || invval is 1
1051 py invval = bool(vim.bindeval('invval'))
1052 else
1053 py invval = vim.bindeval('invval')
1054 endif
1055 if bool
1056 py oval1 = bool(oval1)
1057 py oval2 = bool(oval2)
1058 py oval3 = bool(oval3)
1059 endif
1060 call add(g:res, '>>> ' .. oname)
1061 call add(g:res, ' g/w/b:' .. pyeval('oname in gset') .. '/' ..
1062 \ pyeval('oname in wset') .. '/' .. pyeval('oname in bset'))
1063 call add(g:res, ' g/w/b (in):' .. pyeval('oname in gopts1') .. '/' ..
1064 \ pyeval('oname in wopts1') .. '/' .. pyeval('oname in bopts1'))
1065 for v in ['gopts1', 'wopts1', 'bopts1']
1066 try
1067 call add(g:res, ' p/' .. v .. ': ' .. Ev('repr(' .. v .. '[''' .. oname .. '''])'))
1068 catch
1069 call add(g:res, ' p/' .. v .. '! ' .. v:exception)
1070 endtry
1071 let r = E(v .. '[''' .. oname .. ''']=invval')
1072 if r isnot 0
1073 call add(g:res, ' inv: ' .. string(invval) .. '! ' .. r)
1074 endif
1075 for vv in (v is# 'gopts1' ? [v] : [v, v[:-2] .. '2', v[:-2] .. '3'])
1076 let val = substitute(vv, '^.opts', 'oval', '')
1077 let r = E(vv .. '[''' .. oname .. ''']=' .. val)
1078 if r isnot 0
1079 call add(g:res, ' ' .. vv .. '! ' .. r)
1080 endif
1081 endfor
1082 endfor
1083 call RecVars(oname)
1084 for v in ['wopts3', 'bopts3']
1085 let r = E('del ' .. v .. '["' .. oname .. '"]')
1086 if r isnot 0
1087 call add(g:res, ' del ' .. v .. '! ' .. r)
1088 endif
1089 endfor
1090 call RecVars(oname)
1091 endfor
1092 delfunction RecVars
1093 delfunction E
1094 delfunction Ev
1095 py del ev
1096 py del e
1097 only
1098 for buf in g:bufs[1:]
1099 execute 'bwipeout!' buf
1100 endfor
1101 py del gopts1
1102 py del wopts1
1103 py del wopts2
1104 py del wopts3
1105 py del bopts1
1106 py del bopts2
1107 py del bopts3
1108 py del oval1
1109 py del oval2
1110 py del oval3
1111 py del oname
1112 py del invval
1113
1114 let expected =<< trim END
1115 wopts iters equal: 1
1116 bopts iters equal: 1
1117 >>> paste
1118 g/w/b:1/0/0
1119 g/w/b (in):1/0/0
1120 p/gopts1: False
1121 p/wopts1! KeyError
1122 inv: 2! KeyError
1123 wopts1! KeyError
1124 wopts2! KeyError
1125 wopts3! KeyError
1126 p/bopts1! KeyError
1127 inv: 2! KeyError
1128 bopts1! KeyError
1129 bopts2! KeyError
1130 bopts3! KeyError
1131 G: 1
1132 W: 1:1 2:1 3:1 4:1
1133 B: 1:1 2:1 3:1 4:1
1134 del wopts3! KeyError
1135 del bopts3! KeyError
1136 G: 1
1137 W: 1:1 2:1 3:1 4:1
1138 B: 1:1 2:1 3:1 4:1
1139 >>> previewheight
1140 g/w/b:1/0/0
1141 g/w/b (in):1/0/0
1142 p/gopts1: 12
1143 inv: 'a'! TypeError
1144 p/wopts1! KeyError
1145 inv: 'a'! KeyError
1146 wopts1! KeyError
1147 wopts2! KeyError
1148 wopts3! KeyError
1149 p/bopts1! KeyError
1150 inv: 'a'! KeyError
1151 bopts1! KeyError
1152 bopts2! KeyError
1153 bopts3! KeyError
1154 G: 5
1155 W: 1:5 2:5 3:5 4:5
1156 B: 1:5 2:5 3:5 4:5
1157 del wopts3! KeyError
1158 del bopts3! KeyError
1159 G: 5
1160 W: 1:5 2:5 3:5 4:5
1161 B: 1:5 2:5 3:5 4:5
1162 >>> operatorfunc
1163 g/w/b:1/0/0
1164 g/w/b (in):1/0/0
1165 p/gopts1: ''
1166 inv: 2! TypeError
1167 p/wopts1! KeyError
1168 inv: 2! KeyError
1169 wopts1! KeyError
1170 wopts2! KeyError
1171 wopts3! KeyError
1172 p/bopts1! KeyError
1173 inv: 2! KeyError
1174 bopts1! KeyError
1175 bopts2! KeyError
1176 bopts3! KeyError
1177 G: 'A'
1178 W: 1:'A' 2:'A' 3:'A' 4:'A'
1179 B: 1:'A' 2:'A' 3:'A' 4:'A'
1180 del wopts3! KeyError
1181 del bopts3! KeyError
1182 G: 'A'
1183 W: 1:'A' 2:'A' 3:'A' 4:'A'
1184 B: 1:'A' 2:'A' 3:'A' 4:'A'
1185 >>> number
1186 g/w/b:0/1/0
1187 g/w/b (in):0/1/0
1188 p/gopts1! KeyError
1189 inv: 0! KeyError
1190 gopts1! KeyError
1191 p/wopts1: False
1192 p/bopts1! KeyError
1193 inv: 0! KeyError
1194 bopts1! KeyError
1195 bopts2! KeyError
1196 bopts3! KeyError
1197 G: 0
1198 W: 1:1 2:1 3:0 4:0
1199 B: 1:1 2:1 3:0 4:0
1200 del wopts3! ValueError
1201 del bopts3! KeyError
1202 G: 0
1203 W: 1:1 2:1 3:0 4:0
1204 B: 1:1 2:1 3:0 4:0
1205 >>> numberwidth
1206 g/w/b:0/1/0
1207 g/w/b (in):0/1/0
1208 p/gopts1! KeyError
1209 inv: -100! KeyError
1210 gopts1! KeyError
1211 p/wopts1: 4
1212 inv: -100! error
1213 p/bopts1! KeyError
1214 inv: -100! KeyError
1215 bopts1! KeyError
1216 bopts2! KeyError
1217 bopts3! KeyError
1218 G: 4
1219 W: 1:3 2:5 3:2 4:4
1220 B: 1:3 2:5 3:2 4:4
1221 del wopts3! ValueError
1222 del bopts3! KeyError
1223 G: 4
1224 W: 1:3 2:5 3:2 4:4
1225 B: 1:3 2:5 3:2 4:4
1226 >>> colorcolumn
1227 g/w/b:0/1/0
1228 g/w/b (in):0/1/0
1229 p/gopts1! KeyError
1230 inv: 'abc4'! KeyError
1231 gopts1! KeyError
1232 p/wopts1: ''
1233 inv: 'abc4'! error
1234 p/bopts1! KeyError
1235 inv: 'abc4'! KeyError
1236 bopts1! KeyError
1237 bopts2! KeyError
1238 bopts3! KeyError
1239 G: ''
1240 W: 1:'+2' 2:'+3' 3:'+1' 4:''
1241 B: 1:'+2' 2:'+3' 3:'+1' 4:''
1242 del wopts3! ValueError
1243 del bopts3! KeyError
1244 G: ''
1245 W: 1:'+2' 2:'+3' 3:'+1' 4:''
1246 B: 1:'+2' 2:'+3' 3:'+1' 4:''
1247 >>> statusline
1248 g/w/b:1/1/0
1249 g/w/b (in):1/1/0
1250 p/gopts1: ''
1251 inv: 0! TypeError
1252 p/wopts1: None
1253 inv: 0! TypeError
1254 p/bopts1! KeyError
1255 inv: 0! KeyError
1256 bopts1! KeyError
1257 bopts2! KeyError
1258 bopts3! KeyError
1259 G: '1'
1260 W: 1:'2' 2:'4' 3:'1' 4:'1'
1261 B: 1:'2' 2:'4' 3:'1' 4:'1'
1262 del bopts3! KeyError
1263 G: '1'
1264 W: 1:'2' 2:'1' 3:'1' 4:'1'
1265 B: 1:'2' 2:'1' 3:'1' 4:'1'
1266 >>> autoindent
1267 g/w/b:0/0/1
1268 g/w/b (in):0/0/1
1269 p/gopts1! KeyError
1270 inv: 2! KeyError
1271 gopts1! KeyError
1272 p/wopts1! KeyError
1273 inv: 2! KeyError
1274 wopts1! KeyError
1275 wopts2! KeyError
1276 wopts3! KeyError
1277 p/bopts1: False
1278 G: 0
1279 W: 1:0 2:1 3:0 4:1
1280 B: 1:0 2:1 3:0 4:1
1281 del wopts3! KeyError
1282 del bopts3! ValueError
1283 G: 0
1284 W: 1:0 2:1 3:0 4:1
1285 B: 1:0 2:1 3:0 4:1
1286 >>> shiftwidth
1287 g/w/b:0/0/1
1288 g/w/b (in):0/0/1
1289 p/gopts1! KeyError
1290 inv: 3! KeyError
1291 gopts1! KeyError
1292 p/wopts1! KeyError
1293 inv: 3! KeyError
1294 wopts1! KeyError
1295 wopts2! KeyError
1296 wopts3! KeyError
1297 p/bopts1: 8
1298 G: 8
1299 W: 1:0 2:2 3:8 4:1
1300 B: 1:0 2:2 3:8 4:1
1301 del wopts3! KeyError
1302 del bopts3! ValueError
1303 G: 8
1304 W: 1:0 2:2 3:8 4:1
1305 B: 1:0 2:2 3:8 4:1
1306 >>> omnifunc
1307 g/w/b:0/0/1
1308 g/w/b (in):0/0/1
1309 p/gopts1! KeyError
1310 inv: 1! KeyError
1311 gopts1! KeyError
1312 p/wopts1! KeyError
1313 inv: 1! KeyError
1314 wopts1! KeyError
1315 wopts2! KeyError
1316 wopts3! KeyError
1317 p/bopts1: ''
1318 inv: 1! TypeError
1319 G: ''
1320 W: 1:'A' 2:'B' 3:'' 4:'C'
1321 B: 1:'A' 2:'B' 3:'' 4:'C'
1322 del wopts3! KeyError
1323 del bopts3! ValueError
1324 G: ''
1325 W: 1:'A' 2:'B' 3:'' 4:'C'
1326 B: 1:'A' 2:'B' 3:'' 4:'C'
1327 >>> preserveindent
1328 g/w/b:0/0/1
1329 g/w/b (in):0/0/1
1330 p/gopts1! KeyError
1331 inv: 2! KeyError
1332 gopts1! KeyError
1333 p/wopts1! KeyError
1334 inv: 2! KeyError
1335 wopts1! KeyError
1336 wopts2! KeyError
1337 wopts3! KeyError
1338 p/bopts1: False
1339 G: 0
1340 W: 1:0 2:1 3:0 4:1
1341 B: 1:0 2:1 3:0 4:1
1342 del wopts3! KeyError
1343 del bopts3! ValueError
1344 G: 0
1345 W: 1:0 2:1 3:0 4:1
1346 B: 1:0 2:1 3:0 4:1
1347 >>> path
1348 g/w/b:1/0/1
1349 g/w/b (in):1/0/1
1350 p/gopts1: '.,..,,'
1351 inv: 0! TypeError
1352 p/wopts1! KeyError
1353 inv: 0! KeyError
1354 wopts1! KeyError
1355 wopts2! KeyError
1356 wopts3! KeyError
1357 p/bopts1: None
1358 inv: 0! TypeError
1359 G: '.,,'
1360 W: 1:'.,,' 2:',,' 3:'.,,' 4:'.'
1361 B: 1:'.,,' 2:',,' 3:'.,,' 4:'.'
1362 del wopts3! KeyError
1363 G: '.,,'
1364 W: 1:'.,,' 2:',,' 3:'.,,' 4:'.,,'
1365 B: 1:'.,,' 2:',,' 3:'.,,' 4:'.,,'
1366 END
1367
1368 call assert_equal(expected, g:res)
1369 unlet g:res
Bram Moolenaarab589462020-07-06 21:03:06 +02001370
1371 call assert_equal(0, pyeval("'' in vim.options"))
1372
1373 " use an empty key to index vim.options
1374 call AssertException(["let v = pyeval(\"vim.options['']\")"],
1375 \ 'Vim(let):ValueError: empty keys are not allowed')
1376 call AssertException(["py vim.current.window.options[''] = 0"],
1377 \ 'Vim(python):ValueError: empty keys are not allowed')
1378 call AssertException(["py vim.current.window.options[{}] = 0"],
1379 \ 'Vim(python):TypeError: expected str() or unicode() instance, but got dict')
1380
1381 " set one of the number options to a very large number
1382 let cmd = ["py vim.options['previewheight'] = 9999999999999999"]
1383 call AssertException(cmd, 'OverflowError:')
1384
1385 " unset a global-local string option
1386 call AssertException(["py del vim.options['errorformat']"],
1387 \ 'Vim(python):ValueError: unable to unset global option errorformat')
Bram Moolenaar92fdd1e2020-07-03 18:00:05 +02001388endfunc
1389
1390" Test for vim.buffer object
1391func Test_python_buffer()
1392 new
1393 call setline(1, "Hello\nWorld")
1394 call assert_fails("let x = pyeval('vim.current.buffer[0]')", 'E859:')
1395 %bw!
1396
1397 edit Xfile1
1398 let bnr1 = bufnr()
1399 py cb = vim.current.buffer
1400 vnew Xfile2
1401 let bnr2 = bufnr()
1402 call setline(1, ['First line', 'Second line', 'Third line'])
1403 py b = vim.current.buffer
1404 wincmd w
1405
Bram Moolenaarab589462020-07-06 21:03:06 +02001406 " Test for getting lines from the buffer using a slice
1407 call assert_equal(['First line'], pyeval('b[-10:1]'))
1408 call assert_equal(['Third line'], pyeval('b[2:10]'))
1409 call assert_equal([], pyeval('b[2:0]'))
1410 call assert_equal([], pyeval('b[10:12]'))
1411 call assert_equal([], pyeval('b[-10:-8]'))
Bram Moolenaar0ab55d62020-07-07 20:50:39 +02001412 call AssertException(["py x = b[0:3:0]"],
1413 \ "Vim(python):TypeError: sequence index must be integer, not 'slice'")
1414 call AssertException(["py b[0:3:0] = 'abc'"],
1415 \ "Vim(python):TypeError: sequence index must be integer, not 'slice'")
1416 call AssertException(["py x = b[{}]"],
1417 \ "Vim(python):TypeError: sequence index must be integer, not 'dict'")
1418 call AssertException(["py b[{}] = 'abc'"],
1419 \ "Vim(python):TypeError: sequence index must be integer, not 'dict'")
1420
1421 " Test for getting lines using a range
1422 call AssertException(["py x = b.range(0,3)[0:2:0]"],
1423 \ "Vim(python):TypeError: sequence index must be integer, not 'slice'")
1424 call AssertException(["py b.range(0,3)[0:2:0] = 'abc'"],
1425 \ "Vim(python):TypeError: sequence index must be integer, not 'slice'")
Bram Moolenaarab589462020-07-06 21:03:06 +02001426
Bram Moolenaar92fdd1e2020-07-03 18:00:05 +02001427 " Tests BufferAppend and BufferItem
1428 py cb.append(b[0])
1429 call assert_equal(['First line'], getbufline(bnr1, 2))
1430 %d
1431
Bram Moolenaarab589462020-07-06 21:03:06 +02001432 " Try to append using out-of-range line number
1433 call AssertException(["py b.append('abc', 10)"],
1434 \ 'Vim(python):IndexError: line number out of range')
1435
1436 " Append a non-string item
1437 call AssertException(["py b.append([22])"],
1438 \ 'Vim(python):TypeError: expected str() or unicode() instance, but got int')
1439
Bram Moolenaar92fdd1e2020-07-03 18:00:05 +02001440 " Tests BufferSlice and BufferAssSlice
1441 py cb.append('abc5') # Will be overwritten
1442 py cb[-1:] = b[:-2]
1443 call assert_equal(['First line'], getbufline(bnr1, 2))
1444 %d
1445
1446 " Test BufferLength and BufferAssSlice
1447 py cb.append('def') # Will not be overwritten
1448 py cb[len(cb):] = b[:]
1449 call assert_equal(['def', 'First line', 'Second line', 'Third line'],
1450 \ getbufline(bnr1, 2, '$'))
1451 %d
1452
1453 " Test BufferAssItem and BufferMark
1454 call setbufline(bnr1, 1, ['one', 'two', 'three'])
1455 call cursor(1, 3)
1456 normal ma
1457 py cb.append('ghi') # Will be overwritten
1458 py cb[-1] = repr((len(cb) - cb.mark('a')[0], cb.mark('a')[1]))
1459 call assert_equal(['(3, 2)'], getbufline(bnr1, 4))
1460 %d
1461
1462 " Test BufferRepr
1463 py cb.append(repr(cb) + repr(b))
1464 call assert_equal(['<buffer Xfile1><buffer Xfile2>'], getbufline(bnr1, 2))
1465 %d
1466
1467 " Modify foreign buffer
1468 py << trim EOF
1469 b.append('foo')
1470 b[0]='bar'
1471 b[0:0]=['baz']
1472 vim.command('call append("$", getbufline(%i, 1, "$"))' % b.number)
1473 EOF
1474 call assert_equal(['baz', 'bar', 'Second line', 'Third line', 'foo'],
1475 \ getbufline(bnr2, 1, '$'))
1476 %d
1477
1478 " Test assigning to name property
1479 augroup BUFS
Bram Moolenaareffb0cd2020-07-03 21:17:34 +02001480 autocmd BufFilePost * python cb.append(vim.eval('expand("<abuf>")') + ':BufFilePost:' + vim.eval('bufnr("%")'))
1481 autocmd BufFilePre * python cb.append(vim.eval('expand("<abuf>")') + ':BufFilePre:' + vim.eval('bufnr("%")'))
Bram Moolenaar92fdd1e2020-07-03 18:00:05 +02001482 augroup END
1483 py << trim EOF
1484 import os
1485 old_name = cb.name
1486 cb.name = 'foo'
1487 cb.append(cb.name[-11:].replace(os.path.sep, '/'))
1488 b.name = 'bar'
1489 cb.append(b.name[-11:].replace(os.path.sep, '/'))
1490 cb.name = old_name
1491 cb.append(cb.name[-14:].replace(os.path.sep, '/'))
1492 del old_name
1493 EOF
1494 call assert_equal([bnr1 .. ':BufFilePre:' .. bnr1,
1495 \ bnr1 .. ':BufFilePost:' .. bnr1,
1496 \ 'testdir/foo',
1497 \ bnr2 .. ':BufFilePre:' .. bnr2,
1498 \ bnr2 .. ':BufFilePost:' .. bnr2,
1499 \ 'testdir/bar',
1500 \ bnr1 .. ':BufFilePre:' .. bnr1,
1501 \ bnr1 .. ':BufFilePost:' .. bnr1,
1502 \ 'testdir/Xfile1'], getbufline(bnr1, 2, '$'))
1503 %d
1504
1505 " Test CheckBuffer
1506 py << trim EOF
1507 for _b in vim.buffers:
1508 if _b is not cb:
1509 vim.command('bwipeout! ' + str(_b.number))
1510 del _b
1511 cb.append('valid: b:%s, cb:%s' % (repr(b.valid), repr(cb.valid)))
1512 EOF
1513 call assert_equal('valid: b:False, cb:True', getline(2))
1514 %d
1515
1516 py << trim EOF
1517 for expr in ('b[1]','b[:] = ["A", "B"]','b[:]','b.append("abc6")', 'b.name = "!"'):
1518 try:
1519 exec(expr)
1520 except vim.error:
1521 pass
1522 else:
1523 # Usually a SEGV here
1524 # Should not happen in any case
1525 cb.append('No exception for ' + expr)
1526 vim.command('cd .')
1527 del b
1528 EOF
1529 call assert_equal([''], getline(1, '$'))
1530
Bram Moolenaarab589462020-07-06 21:03:06 +02001531 " Delete all the lines in a buffer
1532 call setline(1, ['a', 'b', 'c'])
1533 py vim.current.buffer[:] = []
1534 call assert_equal([''], getline(1, '$'))
1535
Bram Moolenaar0ab55d62020-07-07 20:50:39 +02001536 " Test for buffer marks
1537 call assert_equal(v:none, pyeval("vim.current.buffer.mark('r')"))
1538
Bram Moolenaarab589462020-07-06 21:03:06 +02001539 " Test for modifying a 'nomodifiable' buffer
1540 setlocal nomodifiable
1541 call AssertException(["py vim.current.buffer[0] = 'abc'"],
1542 \ "Vim(python):vim.error: Vim:E21: Cannot make changes, 'modifiable' is off")
1543 call AssertException(["py vim.current.buffer[0] = None"],
1544 \ "Vim(python):vim.error: Vim:E21: Cannot make changes, 'modifiable' is off")
1545 call AssertException(["py vim.current.buffer[:] = None"],
1546 \ "Vim(python):vim.error: Vim:E21: Cannot make changes, 'modifiable' is off")
1547 call AssertException(["py vim.current.buffer[:] = []"],
1548 \ "Vim(python):vim.error: Vim:E21: Cannot make changes, 'modifiable' is off")
1549 call AssertException(["py vim.current.buffer.append('abc')"],
1550 \ "Vim(python):vim.error: Vim:E21: Cannot make changes, 'modifiable' is off")
1551 call AssertException(["py vim.current.buffer.append([])"],
1552 \ "Vim(python):vim.error: Vim:E21: Cannot make changes, 'modifiable' is off")
1553 setlocal modifiable
1554
Bram Moolenaar92fdd1e2020-07-03 18:00:05 +02001555 augroup BUFS
Bram Moolenaareffb0cd2020-07-03 21:17:34 +02001556 autocmd!
Bram Moolenaar92fdd1e2020-07-03 18:00:05 +02001557 augroup END
1558 augroup! BUFS
1559 %bw!
Bram Moolenaarab589462020-07-06 21:03:06 +02001560
1561 " Range object for a deleted buffer
1562 new Xfile
1563 call setline(1, ['one', 'two', 'three'])
1564 py b = vim.current.buffer
1565 py r = vim.current.buffer.range(0, 2)
1566 call assert_equal('<range Xfile (0:2)>', pyeval('repr(r)'))
1567 %bw!
1568 call AssertException(['py r[:] = []'],
1569 \ 'Vim(python):vim.error: attempt to refer to deleted buffer')
1570 call assert_match('<buffer object (deleted)', pyeval('repr(b)'))
1571 call assert_match('<range object (for deleted buffer)', pyeval('repr(r)'))
1572 call AssertException(["let n = pyeval('len(r)')"],
1573 \ 'Vim(let):vim.error: attempt to refer to deleted buffer')
1574 call AssertException(["py r.append('abc')"],
1575 \ 'Vim(python):vim.error: attempt to refer to deleted buffer')
1576
1577 " object for a deleted buffer
1578 call AssertException(["py b[0] = 'one'"],
1579 \ 'Vim(python):vim.error: attempt to refer to deleted buffer')
1580 call AssertException(["py b.append('one')"],
1581 \ 'Vim(python):vim.error: attempt to refer to deleted buffer')
1582 call AssertException(["let n = pyeval('len(b)')"],
1583 \ 'Vim(let):vim.error: attempt to refer to deleted buffer')
1584 call AssertException(["py pos = b.mark('a')"],
1585 \ 'Vim(python):vim.error: attempt to refer to deleted buffer')
1586 call AssertException(["py vim.current.buffer = b"],
1587 \ 'Vim(python):vim.error: attempt to refer to deleted buffer')
1588 call AssertException(["py rn = b.range(0, 2)"],
1589 \ 'Vim(python):vim.error: attempt to refer to deleted buffer')
Bram Moolenaar92fdd1e2020-07-03 18:00:05 +02001590endfunc
1591
1592" Test vim.buffers object
1593func Test_python_buffers()
1594 %bw!
1595 edit Xfile
1596 py cb = vim.current.buffer
1597 set hidden
1598 edit a
1599 buffer #
1600 edit b
1601 buffer #
1602 edit c
1603 buffer #
1604 py << trim EOF
1605 try:
1606 from __builtin__ import next
1607 except ImportError:
1608 next = lambda o: o.next()
1609 # Check GCing iterator that was not fully exhausted
1610 i = iter(vim.buffers)
1611 cb.append('i:' + str(next(i)))
1612 # and also check creating more than one iterator at a time
1613 i2 = iter(vim.buffers)
1614 cb.append('i2:' + str(next(i2)))
1615 cb.append('i:' + str(next(i)))
1616 # The following should trigger GC and not cause any problems
1617 del i
1618 del i2
1619 i3 = iter(vim.buffers)
1620 cb.append('i3:' + str(next(i3)))
1621 del i3
1622 EOF
1623 call assert_equal(['i:<buffer Xfile>',
1624 \ 'i2:<buffer Xfile>', 'i:<buffer a>', 'i3:<buffer Xfile>'],
1625 \ getline(2, '$'))
1626 %d
1627
1628 py << trim EOF
1629 prevnum = 0
1630 for b in vim.buffers:
1631 # Check buffer order
1632 if prevnum >= b.number:
1633 cb.append('!!! Buffer numbers not in strictly ascending order')
1634 # Check indexing: vim.buffers[number].number == number
1635 cb.append(str(b.number) + ':' + repr(vim.buffers[b.number]) + \
1636 '=' + repr(b))
1637 prevnum = b.number
1638 del prevnum
1639
1640 cb.append(str(len(vim.buffers)))
1641 EOF
1642 call assert_equal([bufnr('Xfile') .. ':<buffer Xfile>=<buffer Xfile>',
1643 \ bufnr('a') .. ':<buffer a>=<buffer a>',
1644 \ bufnr('b') .. ':<buffer b>=<buffer b>',
1645 \ bufnr('c') .. ':<buffer c>=<buffer c>', '4'], getline(2, '$'))
1646 %d
1647
1648 py << trim EOF
1649 bnums = list(map(lambda b: b.number, vim.buffers))[1:]
1650
1651 # Test wiping out buffer with existing iterator
1652 i4 = iter(vim.buffers)
1653 cb.append('i4:' + str(next(i4)))
1654 vim.command('bwipeout! ' + str(bnums.pop(0)))
1655 try:
1656 next(i4)
1657 except vim.error:
1658 pass
1659 else:
1660 cb.append('!!!! No vim.error')
1661 i4 = iter(vim.buffers)
1662 vim.command('bwipeout! ' + str(bnums.pop(-1)))
1663 vim.command('bwipeout! ' + str(bnums.pop(-1)))
1664 cb.append('i4:' + str(next(i4)))
1665 try:
1666 next(i4)
1667 except StopIteration:
1668 cb.append('StopIteration')
1669 del i4
1670 del bnums
1671 EOF
1672 call assert_equal(['i4:<buffer Xfile>',
1673 \ 'i4:<buffer Xfile>', 'StopIteration'], getline(2, '$'))
1674 %bw!
1675endfunc
1676
1677" Test vim.{tabpage,window}list and vim.{tabpage,window} objects
1678func Test_python_tabpage_window()
1679 %bw
1680 edit Xfile
1681 py cb = vim.current.buffer
1682 tabnew 0
1683 tabnew 1
1684 vnew a.1
1685 tabnew 2
1686 vnew a.2
1687 vnew b.2
1688 vnew c.2
1689
Bram Moolenaarab589462020-07-06 21:03:06 +02001690 call assert_equal(4, pyeval('vim.current.window.tabpage.number'))
1691
Bram Moolenaar92fdd1e2020-07-03 18:00:05 +02001692 py << trim EOF
1693 cb.append('Number of tabs: ' + str(len(vim.tabpages)))
1694 cb.append('Current tab pages:')
1695 def W(w):
1696 if repr(w).find('(unknown)') != -1:
1697 return '<window object (unknown)>'
1698 else:
1699 return repr(w)
1700
1701 start = len(cb)
1702
1703 def Cursor(w):
1704 if w.buffer is cb:
1705 return repr((start - w.cursor[0], w.cursor[1]))
1706 else:
1707 return repr(w.cursor)
1708
1709 for t in vim.tabpages:
1710 cb.append(' ' + repr(t) + '(' + str(t.number) + ')' + ': ' + \
1711 str(len(t.windows)) + ' windows, current is ' + W(t.window))
1712 cb.append(' Windows:')
1713 for w in t.windows:
1714 cb.append(' ' + W(w) + '(' + str(w.number) + ')' + \
1715 ': displays buffer ' + repr(w.buffer) + \
1716 '; cursor is at ' + Cursor(w))
1717 # Other values depend on the size of the terminal, so they are checked
1718 # partly:
1719 for attr in ('height', 'row', 'width', 'col'):
1720 try:
1721 aval = getattr(w, attr)
1722 if type(aval) is not long:
1723 raise TypeError
1724 if aval < 0:
1725 raise ValueError
1726 except Exception:
1727 cb.append('!!!!!! Error while getting attribute ' + attr + \
1728 ': ' + sys.exc_type.__name__)
1729 del aval
1730 del attr
1731 w.cursor = (len(w.buffer), 0)
1732 del W
1733 del Cursor
1734 cb.append('Number of windows in current tab page: ' + \
1735 str(len(vim.windows)))
1736 if list(vim.windows) != list(vim.current.tabpage.windows):
1737 cb.append('!!!!!! Windows differ')
1738 EOF
1739
Bram Moolenaareffb0cd2020-07-03 21:17:34 +02001740 let expected =<< trim END
Bram Moolenaar92fdd1e2020-07-03 18:00:05 +02001741 Number of tabs: 4
1742 Current tab pages:
1743 <tabpage 0>(1): 1 windows, current is <window object (unknown)>
1744 Windows:
1745 <window object (unknown)>(1): displays buffer <buffer Xfile>; cursor is at (2, 0)
1746 <tabpage 1>(2): 1 windows, current is <window object (unknown)>
1747 Windows:
1748 <window object (unknown)>(1): displays buffer <buffer 0>; cursor is at (1, 0)
1749 <tabpage 2>(3): 2 windows, current is <window object (unknown)>
1750 Windows:
1751 <window object (unknown)>(1): displays buffer <buffer a.1>; cursor is at (1, 0)
1752 <window object (unknown)>(2): displays buffer <buffer 1>; cursor is at (1, 0)
1753 <tabpage 3>(4): 4 windows, current is <window 0>
1754 Windows:
1755 <window 0>(1): displays buffer <buffer c.2>; cursor is at (1, 0)
1756 <window 1>(2): displays buffer <buffer b.2>; cursor is at (1, 0)
1757 <window 2>(3): displays buffer <buffer a.2>; cursor is at (1, 0)
1758 <window 3>(4): displays buffer <buffer 2>; cursor is at (1, 0)
1759 Number of windows in current tab page: 4
1760 END
1761 call assert_equal(expected, getbufline(bufnr('Xfile'), 2, '$'))
1762 %bw!
1763endfunc
1764
1765" Test vim.current
1766func Test_python_vim_current()
1767 %bw
1768 edit Xfile
1769 py cb = vim.current.buffer
1770 tabnew 0
1771 tabnew 1
1772 vnew a.1
1773 tabnew 2
1774 vnew a.2
1775 vnew b.2
1776 vnew c.2
1777
1778 py << trim EOF
1779 def H(o):
1780 return repr(o)
1781 cb.append('Current tab page: ' + repr(vim.current.tabpage))
1782 cb.append('Current window: ' + repr(vim.current.window) + ': ' + \
1783 H(vim.current.window) + ' is ' + H(vim.current.tabpage.window))
1784 cb.append('Current buffer: ' + repr(vim.current.buffer) + ': ' + \
1785 H(vim.current.buffer) + ' is ' + H(vim.current.window.buffer)+ \
1786 ' is ' + H(vim.current.tabpage.window.buffer))
1787 del H
1788 EOF
1789 let expected =<< trim END
1790 Current tab page: <tabpage 3>
1791 Current window: <window 0>: <window 0> is <window 0>
1792 Current buffer: <buffer c.2>: <buffer c.2> is <buffer c.2> is <buffer c.2>
1793 END
1794 call assert_equal(expected, getbufline(bufnr('Xfile'), 2, '$'))
1795 call deletebufline(bufnr('Xfile'), 1, '$')
1796
1797 " Assigning: fails
1798 py << trim EOF
1799 try:
1800 vim.current.window = vim.tabpages[0].window
1801 except ValueError:
1802 cb.append('ValueError at assigning foreign tab window')
1803
1804 for attr in ('window', 'tabpage', 'buffer'):
1805 try:
1806 setattr(vim.current, attr, None)
1807 except TypeError:
1808 cb.append('Type error at assigning None to vim.current.' + attr)
1809 del attr
1810 EOF
1811
1812 let expected =<< trim END
1813 ValueError at assigning foreign tab window
1814 Type error at assigning None to vim.current.window
1815 Type error at assigning None to vim.current.tabpage
1816 Type error at assigning None to vim.current.buffer
1817 END
1818 call assert_equal(expected, getbufline(bufnr('Xfile'), 2, '$'))
1819 call deletebufline(bufnr('Xfile'), 1, '$')
1820
1821 call setbufline(bufnr('Xfile'), 1, 'python interface')
1822 py << trim EOF
1823 # Assigning: success
1824 vim.current.tabpage = vim.tabpages[-2]
1825 vim.current.buffer = cb
1826 vim.current.window = vim.windows[0]
1827 vim.current.window.cursor = (len(vim.current.buffer), 0)
1828 cb.append('Current tab page: ' + repr(vim.current.tabpage))
1829 cb.append('Current window: ' + repr(vim.current.window))
1830 cb.append('Current buffer: ' + repr(vim.current.buffer))
1831 cb.append('Current line: ' + repr(vim.current.line))
1832 EOF
1833
1834 let expected =<< trim END
1835 Current tab page: <tabpage 2>
1836 Current window: <window 0>
1837 Current buffer: <buffer Xfile>
1838 Current line: 'python interface'
1839 END
1840 call assert_equal(expected, getbufline(bufnr('Xfile'), 2, '$'))
Bram Moolenaarab589462020-07-06 21:03:06 +02001841 py vim.current.line = 'one line'
1842 call assert_equal('one line', getline('.'))
Bram Moolenaar92fdd1e2020-07-03 18:00:05 +02001843 call deletebufline(bufnr('Xfile'), 1, '$')
1844
1845 py << trim EOF
1846 ws = list(vim.windows)
1847 ts = list(vim.tabpages)
1848 for b in vim.buffers:
1849 if b is not cb:
1850 vim.command('bwipeout! ' + str(b.number))
1851 del b
1852 cb.append('w.valid: ' + repr([w.valid for w in ws]))
1853 cb.append('t.valid: ' + repr([t.valid for t in ts]))
1854 del w
1855 del t
1856 del ts
1857 del ws
1858 EOF
1859 let expected =<< trim END
1860 w.valid: [True, False]
1861 t.valid: [True, False, True, False]
1862 END
1863 call assert_equal(expected, getbufline(bufnr('Xfile'), 2, '$'))
1864 %bw!
1865endfunc
1866
1867" Test types
1868func Test_python_types()
1869 %d
1870 py cb = vim.current.buffer
1871 py << trim EOF
1872 for expr, attr in (
1873 ('vim.vars', 'Dictionary'),
1874 ('vim.options', 'Options'),
1875 ('vim.bindeval("{}")', 'Dictionary'),
1876 ('vim.bindeval("[]")', 'List'),
1877 ('vim.bindeval("function(\'tr\')")', 'Function'),
1878 ('vim.current.buffer', 'Buffer'),
1879 ('vim.current.range', 'Range'),
1880 ('vim.current.window', 'Window'),
1881 ('vim.current.tabpage', 'TabPage'),
1882 ):
1883 cb.append(expr + ':' + attr + ':' + \
1884 repr(type(eval(expr)) is getattr(vim, attr)))
1885 del expr
1886 del attr
1887 EOF
1888 let expected =<< trim END
1889 vim.vars:Dictionary:True
1890 vim.options:Options:True
1891 vim.bindeval("{}"):Dictionary:True
1892 vim.bindeval("[]"):List:True
1893 vim.bindeval("function('tr')"):Function:True
1894 vim.current.buffer:Buffer:True
1895 vim.current.range:Range:True
1896 vim.current.window:Window:True
1897 vim.current.tabpage:TabPage:True
1898 END
1899 call assert_equal(expected, getline(2, '$'))
1900endfunc
1901
1902" Test __dir__() method
1903func Test_python_dir_method()
1904 %d
1905 py cb = vim.current.buffer
1906 py << trim EOF
1907 for name, o in (
1908 ('current', vim.current),
1909 ('buffer', vim.current.buffer),
1910 ('window', vim.current.window),
1911 ('tabpage', vim.current.tabpage),
1912 ('range', vim.current.range),
1913 ('dictionary', vim.bindeval('{}')),
1914 ('list', vim.bindeval('[]')),
1915 ('function', vim.bindeval('function("tr")')),
1916 ('output', sys.stdout),
1917 ):
1918 cb.append(name + ':' + ','.join(dir(o)))
1919 del name
1920 del o
1921 EOF
1922 let expected =<< trim END
1923 current:__dir__,__members__,buffer,line,range,tabpage,window
1924 buffer:__dir__,__members__,append,mark,name,number,options,range,valid,vars
1925 window:__dir__,__members__,buffer,col,cursor,height,number,options,row,tabpage,valid,vars,width
1926 tabpage:__dir__,__members__,number,valid,vars,window,windows
1927 range:__dir__,__members__,append,end,start
1928 dictionary:__dir__,__members__,get,has_key,items,keys,locked,pop,popitem,scope,update,values
1929 list:__dir__,__members__,extend,locked
1930 function:__dir__,__members__,args,auto_rebind,self,softspace
1931 output:__dir__,__members__,close,closed,flush,isatty,readable,seekable,softspace,writable,write,writelines
1932 END
1933 call assert_equal(expected, getline(2, '$'))
1934endfunc
1935
1936" Test vim.*.__new__
1937func Test_python_new()
1938 call assert_equal({}, pyeval('vim.Dictionary({})'))
1939 call assert_equal({'a': 1}, pyeval('vim.Dictionary(a=1)'))
1940 call assert_equal({'a': 1}, pyeval('vim.Dictionary(((''a'', 1),))'))
1941 call assert_equal([], pyeval('vim.List()'))
1942 call assert_equal(['a', 'b', 'c', '7'], pyeval('vim.List(iter(''abc7''))'))
1943 call assert_equal(function('tr'), pyeval('vim.Function(''tr'')'))
1944 call assert_equal(function('tr', [123, 3, 4]),
1945 \ pyeval('vim.Function(''tr'', args=[123, 3, 4])'))
1946 call assert_equal(function('tr'), pyeval('vim.Function(''tr'', args=[])'))
1947 call assert_equal(function('tr', {}),
1948 \ pyeval('vim.Function(''tr'', self={})'))
1949 call assert_equal(function('tr', [123, 3, 4], {}),
1950 \ pyeval('vim.Function(''tr'', args=[123, 3, 4], self={})'))
1951 call assert_equal(function('tr'),
1952 \ pyeval('vim.Function(''tr'', auto_rebind=False)'))
1953 call assert_equal(function('tr', [123, 3, 4]),
1954 \ pyeval('vim.Function(''tr'', args=[123, 3, 4], auto_rebind=False)'))
1955 call assert_equal(function('tr'),
1956 \ pyeval('vim.Function(''tr'', args=[], auto_rebind=False)'))
1957 call assert_equal(function('tr', {}),
1958 \ pyeval('vim.Function(''tr'', self={}, auto_rebind=False)'))
1959 call assert_equal(function('tr', [123, 3, 4], {}),
1960 \ pyeval('vim.Function(''tr'', args=[123, 3, 4], self={}, auto_rebind=False)'))
1961endfunc
1962
1963" Test vim.Function
1964func Test_python_vim_func()
Bram Moolenaarab589462020-07-06 21:03:06 +02001965 func Args(...)
Bram Moolenaar92fdd1e2020-07-03 18:00:05 +02001966 return a:000
Bram Moolenaarab589462020-07-06 21:03:06 +02001967 endfunc
Bram Moolenaar92fdd1e2020-07-03 18:00:05 +02001968
Bram Moolenaarab589462020-07-06 21:03:06 +02001969 func SelfArgs(...) dict
Bram Moolenaar92fdd1e2020-07-03 18:00:05 +02001970 return [a:000, self]
Bram Moolenaarab589462020-07-06 21:03:06 +02001971 endfunc
Bram Moolenaar92fdd1e2020-07-03 18:00:05 +02001972
1973 " The following four lines should not crash
1974 let Pt = function('tr', [[]], {'l': []})
1975 py Pt = vim.bindeval('Pt')
1976 unlet Pt
1977 py del Pt
1978
Bram Moolenaarab589462020-07-06 21:03:06 +02001979 call assert_equal(3, pyeval('vim.strwidth("a\tb")'))
1980
Bram Moolenaar92fdd1e2020-07-03 18:00:05 +02001981 %bw!
1982 py cb = vim.current.buffer
1983 py << trim EOF
1984 def ecall(out_prefix, func, *args, **kwargs):
1985 line = out_prefix + ': '
1986 try:
1987 ret = func(*args, **kwargs)
1988 except Exception:
1989 line += '!exception: ' + emsg(sys.exc_info())
1990 else:
1991 line += '!result: ' + vim.Function('string')(ret)
1992 cb.append(line)
1993 a = vim.Function('Args')
1994 pa1 = vim.Function('Args', args=['abcArgsPA1'])
1995 pa2 = vim.Function('Args', args=[])
1996 pa3 = vim.Function('Args', args=['abcArgsPA3'], self={'abcSelfPA3': 'abcSelfPA3Val'})
1997 pa4 = vim.Function('Args', self={'abcSelfPA4': 'abcSelfPA4Val'})
1998 cb.append('a: ' + repr(a))
1999 cb.append('pa1: ' + repr(pa1))
2000 cb.append('pa2: ' + repr(pa2))
2001 cb.append('pa3: ' + repr(pa3))
2002 cb.append('pa4: ' + repr(pa4))
2003 sa = vim.Function('SelfArgs')
2004 psa1 = vim.Function('SelfArgs', args=['abcArgsPSA1'])
2005 psa2 = vim.Function('SelfArgs', args=[])
2006 psa3 = vim.Function('SelfArgs', args=['abcArgsPSA3'], self={'abcSelfPSA3': 'abcSelfPSA3Val'})
2007 psa4 = vim.Function('SelfArgs', self={'abcSelfPSA4': 'abcSelfPSA4Val'})
2008 psa5 = vim.Function('SelfArgs', self={'abcSelfPSA5': 'abcSelfPSA5Val'}, auto_rebind=0)
2009 psa6 = vim.Function('SelfArgs', args=['abcArgsPSA6'], self={'abcSelfPSA6': 'abcSelfPSA6Val'}, auto_rebind=())
2010 psa7 = vim.Function('SelfArgs', args=['abcArgsPSA7'], auto_rebind=[])
2011 psa8 = vim.Function('SelfArgs', auto_rebind=False)
2012 psa9 = vim.Function('SelfArgs', self={'abcSelfPSA9': 'abcSelfPSA9Val'}, auto_rebind=True)
2013 psaA = vim.Function('SelfArgs', args=['abcArgsPSAA'], self={'abcSelfPSAA': 'abcSelfPSAAVal'}, auto_rebind=1)
2014 psaB = vim.Function('SelfArgs', args=['abcArgsPSAB'], auto_rebind={'abcARPSAB': 'abcARPSABVal'})
2015 psaC = vim.Function('SelfArgs', auto_rebind=['abcARPSAC'])
2016 cb.append('sa: ' + repr(sa))
2017 cb.append('psa1: ' + repr(psa1))
2018 cb.append('psa2: ' + repr(psa2))
2019 cb.append('psa3: ' + repr(psa3))
2020 cb.append('psa4: ' + repr(psa4))
2021 cb.append('psa5: ' + repr(psa5))
2022 cb.append('psa6: ' + repr(psa6))
2023 cb.append('psa7: ' + repr(psa7))
2024 cb.append('psa8: ' + repr(psa8))
2025 cb.append('psa9: ' + repr(psa9))
2026 cb.append('psaA: ' + repr(psaA))
2027 cb.append('psaB: ' + repr(psaB))
2028 cb.append('psaC: ' + repr(psaC))
Bram Moolenaareffb0cd2020-07-03 21:17:34 +02002029
Bram Moolenaar92fdd1e2020-07-03 18:00:05 +02002030 psar = vim.Function('SelfArgs', args=[{'abcArgsPSAr': 'abcArgsPSArVal'}], self={'abcSelfPSAr': 'abcSelfPSArVal'})
2031 psar.args[0]['abcArgsPSAr2'] = [psar.self, psar.args[0]]
2032 psar.self['rec'] = psar
2033 psar.self['self'] = psar.self
2034 psar.self['args'] = psar.args
Bram Moolenaareffb0cd2020-07-03 21:17:34 +02002035
Bram Moolenaar92fdd1e2020-07-03 18:00:05 +02002036 try:
2037 cb.append('psar: ' + repr(psar))
2038 except Exception:
2039 cb.append('!!!!!!!! Caught exception: ' + emsg(sys.exc_info()))
2040 EOF
2041
2042 let expected =<< trim END
2043 a: <vim.Function 'Args'>
2044 pa1: <vim.Function 'Args', args=['abcArgsPA1']>
2045 pa2: <vim.Function 'Args'>
2046 pa3: <vim.Function 'Args', args=['abcArgsPA3'], self={'abcSelfPA3': 'abcSelfPA3Val'}>
2047 pa4: <vim.Function 'Args', self={'abcSelfPA4': 'abcSelfPA4Val'}>
2048 sa: <vim.Function 'SelfArgs'>
2049 psa1: <vim.Function 'SelfArgs', args=['abcArgsPSA1']>
2050 psa2: <vim.Function 'SelfArgs'>
2051 psa3: <vim.Function 'SelfArgs', args=['abcArgsPSA3'], self={'abcSelfPSA3': 'abcSelfPSA3Val'}>
2052 psa4: <vim.Function 'SelfArgs', self={'abcSelfPSA4': 'abcSelfPSA4Val'}>
2053 psa5: <vim.Function 'SelfArgs', self={'abcSelfPSA5': 'abcSelfPSA5Val'}>
2054 psa6: <vim.Function 'SelfArgs', args=['abcArgsPSA6'], self={'abcSelfPSA6': 'abcSelfPSA6Val'}>
2055 psa7: <vim.Function 'SelfArgs', args=['abcArgsPSA7']>
2056 psa8: <vim.Function 'SelfArgs'>
2057 psa9: <vim.Function 'SelfArgs', self={'abcSelfPSA9': 'abcSelfPSA9Val'}, auto_rebind=True>
2058 psaA: <vim.Function 'SelfArgs', args=['abcArgsPSAA'], self={'abcSelfPSAA': 'abcSelfPSAAVal'}, auto_rebind=True>
2059 psaB: <vim.Function 'SelfArgs', args=['abcArgsPSAB']>
2060 psaC: <vim.Function 'SelfArgs'>
2061 psar: <vim.Function 'SelfArgs', args=[{'abcArgsPSAr2': [{'rec': function('SelfArgs', [{...}], {...}), 'self': {...}, 'abcSelfPSAr': 'abcSelfPSArVal', 'args': [{...}]}, {...}], 'abcArgsPSAr': 'abcArgsPSArVal'}], self={'rec': function('SelfArgs', [{'abcArgsPSAr2': [{...}, {...}], 'abcArgsPSAr': 'abcArgsPSArVal'}], {...}), 'self': {...}, 'abcSelfPSAr': 'abcSelfPSArVal', 'args': [{'abcArgsPSAr2': [{...}, {...}], 'abcArgsPSAr': 'abcArgsPSArVal'}]}>
2062 END
2063 call assert_equal(expected, getline(2, '$'))
2064 %d
2065
2066 call assert_equal(function('Args'), pyeval('a'))
2067 call assert_equal(function('Args', ['abcArgsPA1']), pyeval('pa1'))
2068 call assert_equal(function('Args'), pyeval('pa2'))
2069 call assert_equal(function('Args', ['abcArgsPA3'], {'abcSelfPA3': 'abcSelfPA3Val'}), pyeval('pa3'))
2070 call assert_equal(function('Args', {'abcSelfPA4': 'abcSelfPA4Val'}), pyeval('pa4'))
2071 call assert_equal(function('SelfArgs'), pyeval('sa'))
2072 call assert_equal(function('SelfArgs', ['abcArgsPSA1']), pyeval('psa1'))
2073 call assert_equal(function('SelfArgs'), pyeval('psa2'))
2074 call assert_equal(function('SelfArgs', ['abcArgsPSA3'], {'abcSelfPSA3': 'abcSelfPSA3Val'}), pyeval('psa3'))
2075 call assert_equal(function('SelfArgs', {'abcSelfPSA4': 'abcSelfPSA4Val'}), pyeval('psa4'))
2076 call assert_equal(function('SelfArgs', {'abcSelfPSA5': 'abcSelfPSA5Val'}), pyeval('psa5'))
2077 call assert_equal(function('SelfArgs', ['abcArgsPSA6'], {'abcSelfPSA6': 'abcSelfPSA6Val'}), pyeval('psa6'))
2078 call assert_equal(function('SelfArgs', ['abcArgsPSA7']), pyeval('psa7'))
2079 call assert_equal(function('SelfArgs'), pyeval('psa8'))
2080 call assert_equal(function('SelfArgs', {'abcSelfPSA9': 'abcSelfPSA9Val'}), pyeval('psa9'))
2081 call assert_equal(function('SelfArgs', ['abcArgsPSAA'], {'abcSelfPSAA': 'abcSelfPSAAVal'}), pyeval('psaA'))
2082 call assert_equal(function('SelfArgs', ['abcArgsPSAB']), pyeval('psaB'))
2083 call assert_equal(function('SelfArgs'), pyeval('psaC'))
2084
2085 let res = []
2086 for v in ['sa', 'psa1', 'psa2', 'psa3', 'psa4', 'psa5', 'psa6', 'psa7',
2087 \ 'psa8', 'psa9', 'psaA', 'psaB', 'psaC']
2088 let d = {'f': pyeval(v)}
2089 call add(res, 'd.' .. v .. '(): ' .. string(d.f()))
2090 endfor
2091
2092 let expected =<< trim END
2093 d.sa(): [[], {'f': function('SelfArgs')}]
2094 d.psa1(): [['abcArgsPSA1'], {'f': function('SelfArgs', ['abcArgsPSA1'])}]
2095 d.psa2(): [[], {'f': function('SelfArgs')}]
2096 d.psa3(): [['abcArgsPSA3'], {'abcSelfPSA3': 'abcSelfPSA3Val'}]
2097 d.psa4(): [[], {'abcSelfPSA4': 'abcSelfPSA4Val'}]
2098 d.psa5(): [[], {'abcSelfPSA5': 'abcSelfPSA5Val'}]
2099 d.psa6(): [['abcArgsPSA6'], {'abcSelfPSA6': 'abcSelfPSA6Val'}]
2100 d.psa7(): [['abcArgsPSA7'], {'f': function('SelfArgs', ['abcArgsPSA7'])}]
2101 d.psa8(): [[], {'f': function('SelfArgs')}]
2102 d.psa9(): [[], {'f': function('SelfArgs', {'abcSelfPSA9': 'abcSelfPSA9Val'})}]
2103 d.psaA(): [['abcArgsPSAA'], {'f': function('SelfArgs', ['abcArgsPSAA'], {'abcSelfPSAA': 'abcSelfPSAAVal'})}]
2104 d.psaB(): [['abcArgsPSAB'], {'f': function('SelfArgs', ['abcArgsPSAB'])}]
2105 d.psaC(): [[], {'f': function('SelfArgs')}]
2106 END
2107 call assert_equal(expected, res)
2108
2109 py ecall('a()', a, )
2110 py ecall('pa1()', pa1, )
2111 py ecall('pa2()', pa2, )
2112 py ecall('pa3()', pa3, )
2113 py ecall('pa4()', pa4, )
2114 py ecall('sa()', sa, )
2115 py ecall('psa1()', psa1, )
2116 py ecall('psa2()', psa2, )
2117 py ecall('psa3()', psa3, )
2118 py ecall('psa4()', psa4, )
2119
2120 py ecall('a(42, 43)', a, 42, 43)
2121 py ecall('pa1(42, 43)', pa1, 42, 43)
2122 py ecall('pa2(42, 43)', pa2, 42, 43)
2123 py ecall('pa3(42, 43)', pa3, 42, 43)
2124 py ecall('pa4(42, 43)', pa4, 42, 43)
2125 py ecall('sa(42, 43)', sa, 42, 43)
2126 py ecall('psa1(42, 43)', psa1, 42, 43)
2127 py ecall('psa2(42, 43)', psa2, 42, 43)
2128 py ecall('psa3(42, 43)', psa3, 42, 43)
2129 py ecall('psa4(42, 43)', psa4, 42, 43)
2130
2131 py ecall('a(42, self={"20": 1})', a, 42, self={'20': 1})
2132 py ecall('pa1(42, self={"20": 1})', pa1, 42, self={'20': 1})
2133 py ecall('pa2(42, self={"20": 1})', pa2, 42, self={'20': 1})
2134 py ecall('pa3(42, self={"20": 1})', pa3, 42, self={'20': 1})
2135 py ecall('pa4(42, self={"20": 1})', pa4, 42, self={'20': 1})
2136 py ecall('sa(42, self={"20": 1})', sa, 42, self={'20': 1})
2137 py ecall('psa1(42, self={"20": 1})', psa1, 42, self={'20': 1})
2138 py ecall('psa2(42, self={"20": 1})', psa2, 42, self={'20': 1})
2139 py ecall('psa3(42, self={"20": 1})', psa3, 42, self={'20': 1})
2140 py ecall('psa4(42, self={"20": 1})', psa4, 42, self={'20': 1})
2141
2142 py ecall('a(self={"20": 1})', a, self={'20': 1})
2143 py ecall('pa1(self={"20": 1})', pa1, self={'20': 1})
2144 py ecall('pa2(self={"20": 1})', pa2, self={'20': 1})
2145 py ecall('pa3(self={"20": 1})', pa3, self={'20': 1})
2146 py ecall('pa4(self={"20": 1})', pa4, self={'20': 1})
2147 py ecall('sa(self={"20": 1})', sa, self={'20': 1})
2148 py ecall('psa1(self={"20": 1})', psa1, self={'20': 1})
2149 py ecall('psa2(self={"20": 1})', psa2, self={'20': 1})
2150 py ecall('psa3(self={"20": 1})', psa3, self={'20': 1})
2151 py ecall('psa4(self={"20": 1})', psa4, self={'20': 1})
2152
2153 py << trim EOF
2154 def s(v):
2155 if v is None:
2156 return repr(v)
2157 else:
2158 return vim.Function('string')(v)
Bram Moolenaareffb0cd2020-07-03 21:17:34 +02002159
Bram Moolenaar92fdd1e2020-07-03 18:00:05 +02002160 cb.append('a.args: ' + s(a.args))
2161 cb.append('pa1.args: ' + s(pa1.args))
2162 cb.append('pa2.args: ' + s(pa2.args))
2163 cb.append('pa3.args: ' + s(pa3.args))
2164 cb.append('pa4.args: ' + s(pa4.args))
2165 cb.append('sa.args: ' + s(sa.args))
2166 cb.append('psa1.args: ' + s(psa1.args))
2167 cb.append('psa2.args: ' + s(psa2.args))
2168 cb.append('psa3.args: ' + s(psa3.args))
2169 cb.append('psa4.args: ' + s(psa4.args))
Bram Moolenaareffb0cd2020-07-03 21:17:34 +02002170
Bram Moolenaar92fdd1e2020-07-03 18:00:05 +02002171 cb.append('a.self: ' + s(a.self))
2172 cb.append('pa1.self: ' + s(pa1.self))
2173 cb.append('pa2.self: ' + s(pa2.self))
2174 cb.append('pa3.self: ' + s(pa3.self))
2175 cb.append('pa4.self: ' + s(pa4.self))
2176 cb.append('sa.self: ' + s(sa.self))
2177 cb.append('psa1.self: ' + s(psa1.self))
2178 cb.append('psa2.self: ' + s(psa2.self))
2179 cb.append('psa3.self: ' + s(psa3.self))
2180 cb.append('psa4.self: ' + s(psa4.self))
Bram Moolenaareffb0cd2020-07-03 21:17:34 +02002181
Bram Moolenaar92fdd1e2020-07-03 18:00:05 +02002182 cb.append('a.name: ' + s(a.name))
2183 cb.append('pa1.name: ' + s(pa1.name))
2184 cb.append('pa2.name: ' + s(pa2.name))
2185 cb.append('pa3.name: ' + s(pa3.name))
2186 cb.append('pa4.name: ' + s(pa4.name))
2187 cb.append('sa.name: ' + s(sa.name))
2188 cb.append('psa1.name: ' + s(psa1.name))
2189 cb.append('psa2.name: ' + s(psa2.name))
2190 cb.append('psa3.name: ' + s(psa3.name))
2191 cb.append('psa4.name: ' + s(psa4.name))
Bram Moolenaareffb0cd2020-07-03 21:17:34 +02002192
Bram Moolenaar92fdd1e2020-07-03 18:00:05 +02002193 cb.append('a.auto_rebind: ' + s(a.auto_rebind))
2194 cb.append('pa1.auto_rebind: ' + s(pa1.auto_rebind))
2195 cb.append('pa2.auto_rebind: ' + s(pa2.auto_rebind))
2196 cb.append('pa3.auto_rebind: ' + s(pa3.auto_rebind))
2197 cb.append('pa4.auto_rebind: ' + s(pa4.auto_rebind))
2198 cb.append('sa.auto_rebind: ' + s(sa.auto_rebind))
2199 cb.append('psa1.auto_rebind: ' + s(psa1.auto_rebind))
2200 cb.append('psa2.auto_rebind: ' + s(psa2.auto_rebind))
2201 cb.append('psa3.auto_rebind: ' + s(psa3.auto_rebind))
2202 cb.append('psa4.auto_rebind: ' + s(psa4.auto_rebind))
2203 cb.append('psa5.auto_rebind: ' + s(psa5.auto_rebind))
2204 cb.append('psa6.auto_rebind: ' + s(psa6.auto_rebind))
2205 cb.append('psa7.auto_rebind: ' + s(psa7.auto_rebind))
2206 cb.append('psa8.auto_rebind: ' + s(psa8.auto_rebind))
2207 cb.append('psa9.auto_rebind: ' + s(psa9.auto_rebind))
2208 cb.append('psaA.auto_rebind: ' + s(psaA.auto_rebind))
2209 cb.append('psaB.auto_rebind: ' + s(psaB.auto_rebind))
2210 cb.append('psaC.auto_rebind: ' + s(psaC.auto_rebind))
Bram Moolenaareffb0cd2020-07-03 21:17:34 +02002211
Bram Moolenaar92fdd1e2020-07-03 18:00:05 +02002212 del s
Bram Moolenaareffb0cd2020-07-03 21:17:34 +02002213
Bram Moolenaar92fdd1e2020-07-03 18:00:05 +02002214 del a
2215 del pa1
2216 del pa2
2217 del pa3
2218 del pa4
2219 del sa
2220 del psa1
2221 del psa2
2222 del psa3
2223 del psa4
2224 del psa5
2225 del psa6
2226 del psa7
2227 del psa8
2228 del psa9
2229 del psaA
2230 del psaB
2231 del psaC
2232 del psar
Bram Moolenaareffb0cd2020-07-03 21:17:34 +02002233
Bram Moolenaar92fdd1e2020-07-03 18:00:05 +02002234 del ecall
2235 EOF
2236
2237 let expected =<< trim END
2238 a(): !result: []
2239 pa1(): !result: ['abcArgsPA1']
2240 pa2(): !result: []
2241 pa3(): !result: ['abcArgsPA3']
2242 pa4(): !result: []
2243 sa(): !exception: error:('Vim:E725: Calling dict function without Dictionary: SelfArgs',)
2244 psa1(): !exception: error:('Vim:E725: Calling dict function without Dictionary: SelfArgs',)
2245 psa2(): !exception: error:('Vim:E725: Calling dict function without Dictionary: SelfArgs',)
2246 psa3(): !result: [['abcArgsPSA3'], {'abcSelfPSA3': 'abcSelfPSA3Val'}]
2247 psa4(): !result: [[], {'abcSelfPSA4': 'abcSelfPSA4Val'}]
2248 a(42, 43): !result: [42, 43]
2249 pa1(42, 43): !result: ['abcArgsPA1', 42, 43]
2250 pa2(42, 43): !result: [42, 43]
2251 pa3(42, 43): !result: ['abcArgsPA3', 42, 43]
2252 pa4(42, 43): !result: [42, 43]
2253 sa(42, 43): !exception: error:('Vim:E725: Calling dict function without Dictionary: SelfArgs',)
2254 psa1(42, 43): !exception: error:('Vim:E725: Calling dict function without Dictionary: SelfArgs',)
2255 psa2(42, 43): !exception: error:('Vim:E725: Calling dict function without Dictionary: SelfArgs',)
2256 psa3(42, 43): !result: [['abcArgsPSA3', 42, 43], {'abcSelfPSA3': 'abcSelfPSA3Val'}]
2257 psa4(42, 43): !result: [[42, 43], {'abcSelfPSA4': 'abcSelfPSA4Val'}]
2258 a(42, self={"20": 1}): !result: [42]
2259 pa1(42, self={"20": 1}): !result: ['abcArgsPA1', 42]
2260 pa2(42, self={"20": 1}): !result: [42]
2261 pa3(42, self={"20": 1}): !result: ['abcArgsPA3', 42]
2262 pa4(42, self={"20": 1}): !result: [42]
2263 sa(42, self={"20": 1}): !result: [[42], {'20': 1}]
2264 psa1(42, self={"20": 1}): !result: [['abcArgsPSA1', 42], {'20': 1}]
2265 psa2(42, self={"20": 1}): !result: [[42], {'20': 1}]
2266 psa3(42, self={"20": 1}): !result: [['abcArgsPSA3', 42], {'20': 1}]
2267 psa4(42, self={"20": 1}): !result: [[42], {'20': 1}]
2268 a(self={"20": 1}): !result: []
2269 pa1(self={"20": 1}): !result: ['abcArgsPA1']
2270 pa2(self={"20": 1}): !result: []
2271 pa3(self={"20": 1}): !result: ['abcArgsPA3']
2272 pa4(self={"20": 1}): !result: []
2273 sa(self={"20": 1}): !result: [[], {'20': 1}]
2274 psa1(self={"20": 1}): !result: [['abcArgsPSA1'], {'20': 1}]
2275 psa2(self={"20": 1}): !result: [[], {'20': 1}]
2276 psa3(self={"20": 1}): !result: [['abcArgsPSA3'], {'20': 1}]
2277 psa4(self={"20": 1}): !result: [[], {'20': 1}]
2278 a.args: None
2279 pa1.args: ['abcArgsPA1']
2280 pa2.args: None
2281 pa3.args: ['abcArgsPA3']
2282 pa4.args: None
2283 sa.args: None
2284 psa1.args: ['abcArgsPSA1']
2285 psa2.args: None
2286 psa3.args: ['abcArgsPSA3']
2287 psa4.args: None
2288 a.self: None
2289 pa1.self: None
2290 pa2.self: None
2291 pa3.self: {'abcSelfPA3': 'abcSelfPA3Val'}
2292 pa4.self: {'abcSelfPA4': 'abcSelfPA4Val'}
2293 sa.self: None
2294 psa1.self: None
2295 psa2.self: None
2296 psa3.self: {'abcSelfPSA3': 'abcSelfPSA3Val'}
2297 psa4.self: {'abcSelfPSA4': 'abcSelfPSA4Val'}
2298 a.name: 'Args'
2299 pa1.name: 'Args'
2300 pa2.name: 'Args'
2301 pa3.name: 'Args'
2302 pa4.name: 'Args'
2303 sa.name: 'SelfArgs'
2304 psa1.name: 'SelfArgs'
2305 psa2.name: 'SelfArgs'
2306 psa3.name: 'SelfArgs'
2307 psa4.name: 'SelfArgs'
2308 a.auto_rebind: 1
2309 pa1.auto_rebind: 1
2310 pa2.auto_rebind: 1
2311 pa3.auto_rebind: 0
2312 pa4.auto_rebind: 0
2313 sa.auto_rebind: 1
2314 psa1.auto_rebind: 1
2315 psa2.auto_rebind: 1
2316 psa3.auto_rebind: 0
2317 psa4.auto_rebind: 0
2318 psa5.auto_rebind: 0
2319 psa6.auto_rebind: 0
2320 psa7.auto_rebind: 1
2321 psa8.auto_rebind: 1
2322 psa9.auto_rebind: 1
2323 psaA.auto_rebind: 1
2324 psaB.auto_rebind: 1
2325 psaC.auto_rebind: 1
2326 END
2327 call assert_equal(expected, getline(2, '$'))
2328 %bw!
2329endfunc
2330
2331" Test stdout/stderr
2332func Test_python_stdin_stderr()
2333 let caught_writeerr = 0
2334 let caught_writelineerr = 0
2335 redir => messages
2336 py sys.stdout.write('abc8') ; sys.stdout.write('def')
2337 try
2338 py sys.stderr.write('abc9') ; sys.stderr.write('def')
2339 catch /abc9def/
2340 let caught_writeerr = 1
2341 endtry
2342 py sys.stdout.writelines(iter('abcA'))
2343 try
2344 py sys.stderr.writelines(iter('abcB'))
2345 catch /abcB/
2346 let caught_writelineerr = 1
2347 endtry
2348 redir END
2349 call assert_equal("\nabc8def\nabcA", messages)
2350 call assert_equal(1, caught_writeerr)
2351 call assert_equal(1, caught_writelineerr)
2352endfunc
2353
2354" Test subclassing
2355func Test_python_subclass()
2356 new
Bram Moolenaarab589462020-07-06 21:03:06 +02002357 func Put(...)
2358 return a:000
2359 endfunc
Bram Moolenaar92fdd1e2020-07-03 18:00:05 +02002360
2361 py << trim EOF
2362 class DupDict(vim.Dictionary):
2363 def __setitem__(self, key, value):
2364 super(DupDict, self).__setitem__(key, value)
2365 super(DupDict, self).__setitem__('dup_' + key, value)
2366 dd = DupDict()
2367 dd['a'] = 'b'
Bram Moolenaareffb0cd2020-07-03 21:17:34 +02002368
Bram Moolenaar92fdd1e2020-07-03 18:00:05 +02002369 class DupList(vim.List):
2370 def __getitem__(self, idx):
2371 return [super(DupList, self).__getitem__(idx)] * 2
Bram Moolenaareffb0cd2020-07-03 21:17:34 +02002372
Bram Moolenaar92fdd1e2020-07-03 18:00:05 +02002373 dl = DupList()
2374 dl2 = DupList(iter('abcC'))
2375 dl.extend(dl2[0])
Bram Moolenaareffb0cd2020-07-03 21:17:34 +02002376
Bram Moolenaar92fdd1e2020-07-03 18:00:05 +02002377 class DupFun(vim.Function):
2378 def __call__(self, arg):
2379 return super(DupFun, self).__call__(arg, arg)
Bram Moolenaareffb0cd2020-07-03 21:17:34 +02002380
Bram Moolenaar92fdd1e2020-07-03 18:00:05 +02002381 df = DupFun('Put')
2382 EOF
2383
2384 call assert_equal(['a', 'dup_a'], sort(keys(pyeval('dd'))))
2385 call assert_equal(['a', 'a'], pyeval('dl'))
2386 call assert_equal(['a', 'b', 'c', 'C'], pyeval('dl2'))
2387 call assert_equal([2, 2], pyeval('df(2)'))
2388 call assert_equal(1, pyeval('dl') is# pyeval('dl'))
2389 call assert_equal(1, pyeval('dd') is# pyeval('dd'))
2390 call assert_equal(function('Put'), pyeval('df'))
2391 delfunction Put
2392 py << trim EOF
2393 del DupDict
2394 del DupList
2395 del DupFun
2396 del dd
2397 del dl
2398 del dl2
2399 del df
2400 EOF
2401 close!
2402endfunc
2403
2404" Test chdir
2405func Test_python_chdir()
2406 new Xfile
2407 py cb = vim.current.buffer
2408 py << trim EOF
2409 import os
2410 fnamemodify = vim.Function('fnamemodify')
2411 cb.append(fnamemodify('.', ':p:h:t'))
2412 cb.append(vim.eval('@%'))
2413 os.chdir('..')
2414 path = fnamemodify('.', ':p:h:t')
2415 if path != 'src':
2416 # Running tests from a shadow directory, so move up another level
2417 # This will result in @% looking like shadow/testdir/Xfile, hence the
2418 # extra fnamemodify
2419 os.chdir('..')
2420 cb.append(fnamemodify('.', ':p:h:t'))
2421 cb.append(fnamemodify(vim.eval('@%'), ':s?^%s.??' % path).replace(os.path.sep, '/'))
2422 os.chdir(path)
2423 del path
2424 else:
2425 cb.append(fnamemodify('.', ':p:h:t'))
2426 cb.append(vim.eval('@%').replace(os.path.sep, '/'))
2427 os.chdir('testdir')
2428 cb.append(fnamemodify('.', ':p:h:t'))
2429 cb.append(vim.eval('@%'))
2430 del fnamemodify
2431 EOF
2432 call assert_equal(['testdir', 'Xfile', 'src', 'testdir/Xfile', 'testdir',
2433 \ 'Xfile'], getline(2, '$'))
2434 close!
Bram Moolenaar0ab55d62020-07-07 20:50:39 +02002435 call AssertException(["py vim.chdir(None)"], "Vim(python):TypeError:")
Bram Moolenaar92fdd1e2020-07-03 18:00:05 +02002436endfunc
2437
2438" Test errors
2439func Test_python_errors()
Bram Moolenaarab589462020-07-06 21:03:06 +02002440 func F() dict
2441 endfunc
Bram Moolenaar92fdd1e2020-07-03 18:00:05 +02002442
Bram Moolenaarab589462020-07-06 21:03:06 +02002443 func D()
2444 endfunc
Bram Moolenaar92fdd1e2020-07-03 18:00:05 +02002445
2446 new
2447 py cb = vim.current.buffer
2448
2449 py << trim EOF
2450 d = vim.Dictionary()
2451 ned = vim.Dictionary(foo='bar', baz='abcD')
2452 dl = vim.Dictionary(a=1)
2453 dl.locked = True
2454 l = vim.List()
2455 ll = vim.List('abcE')
2456 ll.locked = True
2457 nel = vim.List('abcO')
2458 f = vim.Function('string')
2459 fd = vim.Function('F')
2460 fdel = vim.Function('D')
2461 vim.command('delfunction D')
Bram Moolenaareffb0cd2020-07-03 21:17:34 +02002462
Bram Moolenaar92fdd1e2020-07-03 18:00:05 +02002463 def subexpr_test(expr, name, subexprs):
2464 cb.append('>>> Testing %s using %s' % (name, expr))
2465 for subexpr in subexprs:
2466 ee(expr % subexpr)
2467 cb.append('<<< Finished')
Bram Moolenaareffb0cd2020-07-03 21:17:34 +02002468
Bram Moolenaar92fdd1e2020-07-03 18:00:05 +02002469 def stringtochars_test(expr):
2470 return subexpr_test(expr, 'StringToChars', (
2471 '1', # Fail type checks
2472 'u"\\0"', # Fail PyString_AsStringAndSize(bytes, , NULL) check
2473 '"\\0"', # Fail PyString_AsStringAndSize(object, , NULL) check
2474 ))
Bram Moolenaareffb0cd2020-07-03 21:17:34 +02002475
Bram Moolenaar92fdd1e2020-07-03 18:00:05 +02002476 class Mapping(object):
2477 def __init__(self, d):
2478 self.d = d
Bram Moolenaareffb0cd2020-07-03 21:17:34 +02002479
Bram Moolenaar92fdd1e2020-07-03 18:00:05 +02002480 def __getitem__(self, key):
2481 return self.d[key]
Bram Moolenaareffb0cd2020-07-03 21:17:34 +02002482
Bram Moolenaar92fdd1e2020-07-03 18:00:05 +02002483 def keys(self):
2484 return self.d.keys()
Bram Moolenaareffb0cd2020-07-03 21:17:34 +02002485
Bram Moolenaar92fdd1e2020-07-03 18:00:05 +02002486 def items(self):
2487 return self.d.items()
Bram Moolenaareffb0cd2020-07-03 21:17:34 +02002488
Bram Moolenaar92fdd1e2020-07-03 18:00:05 +02002489 def convertfrompyobject_test(expr, recurse=True):
2490 # pydict_to_tv
2491 stringtochars_test(expr % '{%s : 1}')
2492 if recurse:
2493 convertfrompyobject_test(expr % '{"abcF" : %s}', False)
2494 # pymap_to_tv
2495 stringtochars_test(expr % 'Mapping({%s : 1})')
2496 if recurse:
2497 convertfrompyobject_test(expr % 'Mapping({"abcG" : %s})', False)
2498 # pyseq_to_tv
2499 iter_test(expr)
2500 return subexpr_test(expr, 'ConvertFromPyObject', (
2501 'None', # Not conversible
2502 '{"": 1}', # Empty key not allowed
2503 '{u"": 1}', # Same, but with unicode object
2504 'FailingMapping()', #
2505 'FailingMappingKey()', #
2506 'FailingNumber()', #
2507 ))
Bram Moolenaareffb0cd2020-07-03 21:17:34 +02002508
Bram Moolenaar92fdd1e2020-07-03 18:00:05 +02002509 def convertfrompymapping_test(expr):
2510 convertfrompyobject_test(expr)
2511 return subexpr_test(expr, 'ConvertFromPyMapping', (
2512 '[]',
2513 ))
Bram Moolenaareffb0cd2020-07-03 21:17:34 +02002514
Bram Moolenaar92fdd1e2020-07-03 18:00:05 +02002515 def iter_test(expr):
2516 return subexpr_test(expr, '*Iter*', (
2517 'FailingIter()',
2518 'FailingIterNext()',
2519 ))
Bram Moolenaareffb0cd2020-07-03 21:17:34 +02002520
Bram Moolenaar92fdd1e2020-07-03 18:00:05 +02002521 def number_test(expr, natural=False, unsigned=False):
2522 if natural:
2523 unsigned = True
2524 return subexpr_test(expr, 'NumberToLong', (
2525 '[]',
2526 'None',
2527 ) + (unsigned and ('-1',) or ())
2528 + (natural and ('0',) or ()))
Bram Moolenaareffb0cd2020-07-03 21:17:34 +02002529
Bram Moolenaar92fdd1e2020-07-03 18:00:05 +02002530 class FailingTrue(object):
2531 def __nonzero__(self):
2532 raise NotImplementedError('bool')
Bram Moolenaareffb0cd2020-07-03 21:17:34 +02002533
Bram Moolenaar92fdd1e2020-07-03 18:00:05 +02002534 class FailingIter(object):
2535 def __iter__(self):
2536 raise NotImplementedError('iter')
Bram Moolenaareffb0cd2020-07-03 21:17:34 +02002537
Bram Moolenaar92fdd1e2020-07-03 18:00:05 +02002538 class FailingIterNext(object):
2539 def __iter__(self):
2540 return self
Bram Moolenaareffb0cd2020-07-03 21:17:34 +02002541
Bram Moolenaar92fdd1e2020-07-03 18:00:05 +02002542 def next(self):
2543 raise NotImplementedError('next')
Bram Moolenaareffb0cd2020-07-03 21:17:34 +02002544
Bram Moolenaar92fdd1e2020-07-03 18:00:05 +02002545 class FailingIterNextN(object):
2546 def __init__(self, n):
2547 self.n = n
Bram Moolenaareffb0cd2020-07-03 21:17:34 +02002548
Bram Moolenaar92fdd1e2020-07-03 18:00:05 +02002549 def __iter__(self):
2550 return self
Bram Moolenaareffb0cd2020-07-03 21:17:34 +02002551
Bram Moolenaar92fdd1e2020-07-03 18:00:05 +02002552 def next(self):
2553 if self.n:
2554 self.n -= 1
2555 return 1
2556 else:
2557 raise NotImplementedError('next N')
Bram Moolenaareffb0cd2020-07-03 21:17:34 +02002558
Bram Moolenaar92fdd1e2020-07-03 18:00:05 +02002559 class FailingMappingKey(object):
2560 def __getitem__(self, item):
2561 raise NotImplementedError('getitem:mappingkey')
Bram Moolenaareffb0cd2020-07-03 21:17:34 +02002562
Bram Moolenaar92fdd1e2020-07-03 18:00:05 +02002563 def keys(self):
2564 return list("abcH")
Bram Moolenaareffb0cd2020-07-03 21:17:34 +02002565
Bram Moolenaar92fdd1e2020-07-03 18:00:05 +02002566 class FailingMapping(object):
2567 def __getitem__(self):
2568 raise NotImplementedError('getitem:mapping')
Bram Moolenaareffb0cd2020-07-03 21:17:34 +02002569
Bram Moolenaar92fdd1e2020-07-03 18:00:05 +02002570 def keys(self):
2571 raise NotImplementedError('keys')
Bram Moolenaareffb0cd2020-07-03 21:17:34 +02002572
Bram Moolenaar92fdd1e2020-07-03 18:00:05 +02002573 class FailingList(list):
2574 def __getitem__(self, idx):
2575 if i == 2:
2576 raise NotImplementedError('getitem:list')
2577 else:
2578 return super(FailingList, self).__getitem__(idx)
Bram Moolenaareffb0cd2020-07-03 21:17:34 +02002579
Bram Moolenaar92fdd1e2020-07-03 18:00:05 +02002580 class NoArgsCall(object):
2581 def __call__(self):
2582 pass
Bram Moolenaareffb0cd2020-07-03 21:17:34 +02002583
Bram Moolenaar92fdd1e2020-07-03 18:00:05 +02002584 class FailingCall(object):
2585 def __call__(self, path):
2586 raise NotImplementedError('call')
Bram Moolenaareffb0cd2020-07-03 21:17:34 +02002587
Bram Moolenaar92fdd1e2020-07-03 18:00:05 +02002588 class FailingNumber(object):
2589 def __int__(self):
2590 raise NotImplementedError('int')
Bram Moolenaareffb0cd2020-07-03 21:17:34 +02002591
Bram Moolenaar92fdd1e2020-07-03 18:00:05 +02002592 cb.append("> Output")
2593 cb.append(">> OutputSetattr")
2594 ee('del sys.stdout.softspace')
2595 number_test('sys.stdout.softspace = %s', unsigned=True)
2596 number_test('sys.stderr.softspace = %s', unsigned=True)
2597 ee('assert sys.stdout.isatty()==False')
2598 ee('assert sys.stdout.seekable()==False')
2599 ee('sys.stdout.close()')
2600 ee('sys.stdout.flush()')
2601 ee('assert sys.stderr.isatty()==False')
2602 ee('assert sys.stderr.seekable()==False')
2603 ee('sys.stderr.close()')
2604 ee('sys.stderr.flush()')
2605 ee('sys.stdout.attr = None')
2606 cb.append(">> OutputWrite")
2607 ee('assert sys.stdout.writable()==True')
2608 ee('assert sys.stdout.readable()==False')
2609 ee('assert sys.stderr.writable()==True')
2610 ee('assert sys.stderr.readable()==False')
2611 ee('assert sys.stdout.closed()==False')
2612 ee('assert sys.stderr.closed()==False')
2613 ee('assert sys.stdout.errors=="strict"')
2614 ee('assert sys.stderr.errors=="strict"')
2615 ee('assert sys.stdout.encoding==sys.stderr.encoding')
2616 ee('sys.stdout.write(None)')
2617 cb.append(">> OutputWriteLines")
2618 ee('sys.stdout.writelines(None)')
2619 ee('sys.stdout.writelines([1])')
2620 iter_test('sys.stdout.writelines(%s)')
2621 cb.append("> VimCommand")
2622 stringtochars_test('vim.command(%s)')
2623 ee('vim.command("", 2)')
2624 #! Not checked: vim->python exceptions translating: checked later
2625 cb.append("> VimToPython")
2626 #! Not checked: everything: needs errors in internal python functions
2627 cb.append("> VimEval")
2628 stringtochars_test('vim.eval(%s)')
2629 ee('vim.eval("", FailingTrue())')
2630 #! Not checked: everything: needs errors in internal python functions
2631 cb.append("> VimEvalPy")
2632 stringtochars_test('vim.bindeval(%s)')
2633 ee('vim.eval("", 2)')
2634 #! Not checked: vim->python exceptions translating: checked later
2635 cb.append("> VimStrwidth")
2636 stringtochars_test('vim.strwidth(%s)')
2637 cb.append("> VimForeachRTP")
2638 ee('vim.foreach_rtp(None)')
2639 ee('vim.foreach_rtp(NoArgsCall())')
2640 ee('vim.foreach_rtp(FailingCall())')
2641 ee('vim.foreach_rtp(int, 2)')
2642 cb.append('> import')
2643 old_rtp = vim.options['rtp']
2644 vim.options['rtp'] = os.getcwd().replace('\\', '\\\\').replace(',', '\\,')
2645 ee('import xxx_no_such_module_xxx')
2646 ee('import failing_import')
2647 ee('import failing')
2648 vim.options['rtp'] = old_rtp
2649 del old_rtp
2650 cb.append("> Options")
2651 cb.append(">> OptionsItem")
2652 ee('vim.options["abcQ"]')
2653 ee('vim.options[""]')
2654 stringtochars_test('vim.options[%s]')
2655 cb.append(">> OptionsContains")
2656 stringtochars_test('%s in vim.options')
2657 cb.append("> Dictionary")
2658 cb.append(">> DictionaryConstructor")
2659 ee('vim.Dictionary("abcI")')
2660 ##! Not checked: py_dict_alloc failure
2661 cb.append(">> DictionarySetattr")
2662 ee('del d.locked')
2663 ee('d.locked = FailingTrue()')
2664 ee('vim.vvars.locked = False')
2665 ee('d.scope = True')
2666 ee('d.xxx = True')
2667 cb.append(">> _DictionaryItem")
2668 ee('d.get("a", 2, 3)')
2669 stringtochars_test('d.get(%s)')
2670 ee('d.pop("a")')
2671 ee('dl.pop("a")')
2672 cb.append(">> DictionaryContains")
2673 ee('"" in d')
2674 ee('0 in d')
2675 cb.append(">> DictionaryIterNext")
2676 ee('for i in ned: ned["a"] = 1')
2677 del i
2678 cb.append(">> DictionaryAssItem")
2679 ee('dl["b"] = 1')
2680 stringtochars_test('d[%s] = 1')
2681 convertfrompyobject_test('d["a"] = %s')
2682 cb.append(">> DictionaryUpdate")
2683 cb.append(">>> kwargs")
2684 cb.append(">>> iter")
2685 ee('d.update(FailingMapping())')
2686 ee('d.update([FailingIterNext()])')
2687 ee('d.update([FailingIterNextN(1)])')
2688 iter_test('d.update(%s)')
2689 convertfrompyobject_test('d.update(%s)')
2690 stringtochars_test('d.update(((%s, 0),))')
2691 convertfrompyobject_test('d.update((("a", %s),))')
2692 cb.append(">> DictionaryPopItem")
2693 ee('d.popitem(1, 2)')
2694 cb.append(">> DictionaryHasKey")
2695 ee('d.has_key()')
2696 cb.append("> List")
2697 cb.append(">> ListConstructor")
2698 ee('vim.List(1, 2)')
2699 ee('vim.List(a=1)')
2700 iter_test('vim.List(%s)')
2701 convertfrompyobject_test('vim.List([%s])')
2702 cb.append(">> ListItem")
2703 ee('l[1000]')
2704 cb.append(">> ListAssItem")
2705 ee('ll[1] = 2')
2706 ee('l[1000] = 3')
2707 cb.append(">> ListAssSlice")
2708 ee('ll[1:100] = "abcJ"')
2709 iter_test('l[:] = %s')
2710 ee('nel[1:10:2] = "abcK"')
2711 cb.append(repr(tuple(nel)))
2712 ee('nel[1:10:2] = "a"')
2713 cb.append(repr(tuple(nel)))
2714 ee('nel[1:1:-1] = "a"')
2715 cb.append(repr(tuple(nel)))
2716 ee('nel[:] = FailingIterNextN(2)')
2717 cb.append(repr(tuple(nel)))
2718 convertfrompyobject_test('l[:] = [%s]')
2719 cb.append(">> ListConcatInPlace")
2720 iter_test('l.extend(%s)')
2721 convertfrompyobject_test('l.extend([%s])')
2722 cb.append(">> ListSetattr")
2723 ee('del l.locked')
2724 ee('l.locked = FailingTrue()')
2725 ee('l.xxx = True')
2726 cb.append("> Function")
2727 cb.append(">> FunctionConstructor")
2728 cb.append(">>> FunctionConstructor")
2729 ee('vim.Function("123")')
2730 ee('vim.Function("xxx_non_existent_function_xxx")')
2731 ee('vim.Function("xxx#non#existent#function#xxx")')
2732 ee('vim.Function("xxx_non_existent_function_xxx2", args=[])')
2733 ee('vim.Function("xxx_non_existent_function_xxx3", self={})')
2734 ee('vim.Function("xxx_non_existent_function_xxx4", args=[], self={})')
2735 cb.append(">>> FunctionNew")
2736 ee('vim.Function("tr", self="abcFuncSelf")')
2737 ee('vim.Function("tr", args=427423)')
2738 ee('vim.Function("tr", self="abcFuncSelf2", args="abcFuncArgs2")')
2739 ee('vim.Function(self="abcFuncSelf2", args="abcFuncArgs2")')
2740 ee('vim.Function("tr", "", self="abcFuncSelf2", args="abcFuncArgs2")')
2741 ee('vim.Function("tr", "")')
2742 cb.append(">> FunctionCall")
2743 convertfrompyobject_test('f(%s)')
2744 convertfrompymapping_test('fd(self=%s)')
2745 cb.append("> TabPage")
2746 cb.append(">> TabPageAttr")
2747 ee('vim.current.tabpage.xxx')
2748 cb.append("> TabList")
2749 cb.append(">> TabListItem")
2750 ee('vim.tabpages[1000]')
2751 cb.append("> Window")
2752 cb.append(">> WindowAttr")
2753 ee('vim.current.window.xxx')
2754 cb.append(">> WindowSetattr")
2755 ee('vim.current.window.buffer = 0')
2756 ee('vim.current.window.cursor = (100000000, 100000000)')
2757 ee('vim.current.window.cursor = True')
2758 number_test('vim.current.window.height = %s', unsigned=True)
2759 number_test('vim.current.window.width = %s', unsigned=True)
2760 ee('vim.current.window.xxxxxx = True')
2761 cb.append("> WinList")
2762 cb.append(">> WinListItem")
2763 ee('vim.windows[1000]')
2764 cb.append("> Buffer")
2765 cb.append(">> StringToLine (indirect)")
Bram Moolenaar92fdd1e2020-07-03 18:00:05 +02002766 ee('vim.current.buffer[0] = "\\na"')
Bram Moolenaarab589462020-07-06 21:03:06 +02002767 ee('vim.current.buffer[0] = u"\\na"')
Bram Moolenaar92fdd1e2020-07-03 18:00:05 +02002768 cb.append(">> SetBufferLine (indirect)")
2769 ee('vim.current.buffer[0] = True')
2770 cb.append(">> SetBufferLineList (indirect)")
2771 ee('vim.current.buffer[:] = True')
2772 ee('vim.current.buffer[:] = ["\\na", "bc"]')
2773 cb.append(">> InsertBufferLines (indirect)")
2774 ee('vim.current.buffer.append(None)')
2775 ee('vim.current.buffer.append(["\\na", "bc"])')
2776 ee('vim.current.buffer.append("\\nbc")')
2777 cb.append(">> RBItem")
2778 ee('vim.current.buffer[100000000]')
2779 cb.append(">> RBAsItem")
2780 ee('vim.current.buffer[100000000] = ""')
2781 cb.append(">> BufferAttr")
2782 ee('vim.current.buffer.xxx')
2783 cb.append(">> BufferSetattr")
2784 ee('vim.current.buffer.name = True')
2785 ee('vim.current.buffer.xxx = True')
2786 cb.append(">> BufferMark")
2787 ee('vim.current.buffer.mark(0)')
2788 ee('vim.current.buffer.mark("abcM")')
2789 ee('vim.current.buffer.mark("!")')
2790 cb.append(">> BufferRange")
2791 ee('vim.current.buffer.range(1, 2, 3)')
2792 cb.append("> BufMap")
2793 cb.append(">> BufMapItem")
2794 ee('vim.buffers[100000000]')
2795 number_test('vim.buffers[%s]', natural=True)
2796 cb.append("> Current")
2797 cb.append(">> CurrentGetattr")
2798 ee('vim.current.xxx')
2799 cb.append(">> CurrentSetattr")
2800 ee('vim.current.line = True')
2801 ee('vim.current.buffer = True')
2802 ee('vim.current.window = True')
2803 ee('vim.current.tabpage = True')
2804 ee('vim.current.xxx = True')
2805 del d
2806 del ned
2807 del dl
2808 del l
2809 del ll
2810 del nel
2811 del f
2812 del fd
2813 del fdel
2814 del subexpr_test
2815 del stringtochars_test
2816 del Mapping
2817 del convertfrompyobject_test
2818 del convertfrompymapping_test
2819 del iter_test
2820 del number_test
2821 del FailingTrue
2822 del FailingIter
2823 del FailingIterNext
2824 del FailingIterNextN
2825 del FailingMapping
2826 del FailingMappingKey
2827 del FailingList
2828 del NoArgsCall
2829 del FailingCall
2830 del FailingNumber
2831 EOF
2832 delfunction F
2833
2834 let expected =<< trim END
2835 > Output
2836 >> OutputSetattr
2837 del sys.stdout.softspace:AttributeError:('cannot delete OutputObject attributes',)
2838 >>> Testing NumberToLong using sys.stdout.softspace = %s
2839 sys.stdout.softspace = []:TypeError:('expected int(), long() or something supporting coercing to long(), but got list',)
2840 sys.stdout.softspace = None:TypeError:('expected int(), long() or something supporting coercing to long(), but got NoneType',)
2841 sys.stdout.softspace = -1:ValueError:('number must be greater or equal to zero',)
2842 <<< Finished
2843 >>> Testing NumberToLong using sys.stderr.softspace = %s
2844 sys.stderr.softspace = []:TypeError:('expected int(), long() or something supporting coercing to long(), but got list',)
2845 sys.stderr.softspace = None:TypeError:('expected int(), long() or something supporting coercing to long(), but got NoneType',)
2846 sys.stderr.softspace = -1:ValueError:('number must be greater or equal to zero',)
2847 <<< Finished
2848 assert sys.stdout.isatty()==False:NOT FAILED
2849 assert sys.stdout.seekable()==False:NOT FAILED
2850 sys.stdout.close():NOT FAILED
2851 sys.stdout.flush():NOT FAILED
2852 assert sys.stderr.isatty()==False:NOT FAILED
2853 assert sys.stderr.seekable()==False:NOT FAILED
2854 sys.stderr.close():NOT FAILED
2855 sys.stderr.flush():NOT FAILED
2856 sys.stdout.attr = None:AttributeError:('invalid attribute: attr',)
2857 >> OutputWrite
2858 assert sys.stdout.writable()==True:NOT FAILED
2859 assert sys.stdout.readable()==False:NOT FAILED
2860 assert sys.stderr.writable()==True:NOT FAILED
2861 assert sys.stderr.readable()==False:NOT FAILED
2862 assert sys.stdout.closed()==False:NOT FAILED
2863 assert sys.stderr.closed()==False:NOT FAILED
2864 assert sys.stdout.errors=="strict":NOT FAILED
2865 assert sys.stderr.errors=="strict":NOT FAILED
2866 assert sys.stdout.encoding==sys.stderr.encoding:NOT FAILED
2867 sys.stdout.write(None):TypeError:('coercing to Unicode: need string or buffer, NoneType found',)
2868 >> OutputWriteLines
2869 sys.stdout.writelines(None):TypeError:("'NoneType' object is not iterable",)
2870 sys.stdout.writelines([1]):TypeError:('coercing to Unicode: need string or buffer, int found',)
2871 >>> Testing *Iter* using sys.stdout.writelines(%s)
2872 sys.stdout.writelines(FailingIter()):NotImplementedError:('iter',)
2873 sys.stdout.writelines(FailingIterNext()):NotImplementedError:('next',)
2874 <<< Finished
2875 > VimCommand
2876 >>> Testing StringToChars using vim.command(%s)
2877 vim.command(1):TypeError:('expected str() or unicode() instance, but got int',)
2878 vim.command(u"\0"):TypeError:('expected string without null bytes',)
2879 vim.command("\0"):TypeError:('expected string without null bytes',)
2880 <<< Finished
2881 vim.command("", 2):TypeError:('command() takes exactly one argument (2 given)',)
2882 > VimToPython
2883 > VimEval
2884 >>> Testing StringToChars using vim.eval(%s)
2885 vim.eval(1):TypeError:('expected str() or unicode() instance, but got int',)
2886 vim.eval(u"\0"):TypeError:('expected string without null bytes',)
2887 vim.eval("\0"):TypeError:('expected string without null bytes',)
2888 <<< Finished
2889 vim.eval("", FailingTrue()):TypeError:('function takes exactly 1 argument (2 given)',)
2890 > VimEvalPy
2891 >>> Testing StringToChars using vim.bindeval(%s)
2892 vim.bindeval(1):TypeError:('expected str() or unicode() instance, but got int',)
2893 vim.bindeval(u"\0"):TypeError:('expected string without null bytes',)
2894 vim.bindeval("\0"):TypeError:('expected string without null bytes',)
2895 <<< Finished
2896 vim.eval("", 2):TypeError:('function takes exactly 1 argument (2 given)',)
2897 > VimStrwidth
2898 >>> Testing StringToChars using vim.strwidth(%s)
2899 vim.strwidth(1):TypeError:('expected str() or unicode() instance, but got int',)
2900 vim.strwidth(u"\0"):TypeError:('expected string without null bytes',)
2901 vim.strwidth("\0"):TypeError:('expected string without null bytes',)
2902 <<< Finished
2903 > VimForeachRTP
2904 vim.foreach_rtp(None):TypeError:("'NoneType' object is not callable",)
2905 vim.foreach_rtp(NoArgsCall()):TypeError:('__call__() takes exactly 1 argument (2 given)',)
2906 vim.foreach_rtp(FailingCall()):NotImplementedError:('call',)
2907 vim.foreach_rtp(int, 2):TypeError:('foreach_rtp() takes exactly one argument (2 given)',)
2908 > import
2909 import xxx_no_such_module_xxx:ImportError:('No module named xxx_no_such_module_xxx',)
2910 import failing_import:ImportError:()
2911 import failing:NotImplementedError:()
2912 > Options
2913 >> OptionsItem
2914 vim.options["abcQ"]:KeyError:('abcQ',)
2915 vim.options[""]:ValueError:('empty keys are not allowed',)
2916 >>> Testing StringToChars using vim.options[%s]
2917 vim.options[1]:TypeError:('expected str() or unicode() instance, but got int',)
2918 vim.options[u"\0"]:TypeError:('expected string without null bytes',)
2919 vim.options["\0"]:TypeError:('expected string without null bytes',)
2920 <<< Finished
2921 >> OptionsContains
2922 >>> Testing StringToChars using %s in vim.options
2923 1 in vim.options:TypeError:('expected str() or unicode() instance, but got int',)
2924 u"\0" in vim.options:TypeError:('expected string without null bytes',)
2925 "\0" in vim.options:TypeError:('expected string without null bytes',)
2926 <<< Finished
2927 > Dictionary
2928 >> DictionaryConstructor
2929 vim.Dictionary("abcI"):ValueError:('expected sequence element of size 2, but got sequence of size 1',)
2930 >> DictionarySetattr
2931 del d.locked:AttributeError:('cannot delete vim.Dictionary attributes',)
2932 d.locked = FailingTrue():NotImplementedError:('bool',)
2933 vim.vvars.locked = False:TypeError:('cannot modify fixed dictionary',)
2934 d.scope = True:AttributeError:('cannot set attribute scope',)
2935 d.xxx = True:AttributeError:('cannot set attribute xxx',)
2936 >> _DictionaryItem
2937 d.get("a", 2, 3):TypeError:('function takes at most 2 arguments (3 given)',)
2938 >>> Testing StringToChars using d.get(%s)
2939 d.get(1):TypeError:('expected str() or unicode() instance, but got int',)
2940 d.get(u"\0"):TypeError:('expected string without null bytes',)
2941 d.get("\0"):TypeError:('expected string without null bytes',)
2942 <<< Finished
2943 d.pop("a"):KeyError:('a',)
2944 dl.pop("a"):error:('dictionary is locked',)
2945 >> DictionaryContains
2946 "" in d:ValueError:('empty keys are not allowed',)
2947 0 in d:TypeError:('expected str() or unicode() instance, but got int',)
2948 >> DictionaryIterNext
2949 for i in ned: ned["a"] = 1:RuntimeError:('hashtab changed during iteration',)
2950 >> DictionaryAssItem
2951 dl["b"] = 1:error:('dictionary is locked',)
2952 >>> Testing StringToChars using d[%s] = 1
2953 d[1] = 1:TypeError:('expected str() or unicode() instance, but got int',)
2954 d[u"\0"] = 1:TypeError:('expected string without null bytes',)
2955 d["\0"] = 1:TypeError:('expected string without null bytes',)
2956 <<< Finished
2957 >>> Testing StringToChars using d["a"] = {%s : 1}
2958 d["a"] = {1 : 1}:TypeError:('expected str() or unicode() instance, but got int',)
2959 d["a"] = {u"\0" : 1}:TypeError:('expected string without null bytes',)
2960 d["a"] = {"\0" : 1}:TypeError:('expected string without null bytes',)
2961 <<< Finished
2962 >>> Testing StringToChars using d["a"] = {"abcF" : {%s : 1}}
2963 d["a"] = {"abcF" : {1 : 1}}:TypeError:('expected str() or unicode() instance, but got int',)
2964 d["a"] = {"abcF" : {u"\0" : 1}}:TypeError:('expected string without null bytes',)
2965 d["a"] = {"abcF" : {"\0" : 1}}:TypeError:('expected string without null bytes',)
2966 <<< Finished
2967 >>> Testing StringToChars using d["a"] = {"abcF" : Mapping({%s : 1})}
2968 d["a"] = {"abcF" : Mapping({1 : 1})}:TypeError:('expected str() or unicode() instance, but got int',)
2969 d["a"] = {"abcF" : Mapping({u"\0" : 1})}:TypeError:('expected string without null bytes',)
2970 d["a"] = {"abcF" : Mapping({"\0" : 1})}:TypeError:('expected string without null bytes',)
2971 <<< Finished
2972 >>> Testing *Iter* using d["a"] = {"abcF" : %s}
2973 d["a"] = {"abcF" : FailingIter()}:TypeError:('unable to convert FailingIter to a Vim structure',)
2974 d["a"] = {"abcF" : FailingIterNext()}:NotImplementedError:('next',)
2975 <<< Finished
2976 >>> Testing ConvertFromPyObject using d["a"] = {"abcF" : %s}
2977 d["a"] = {"abcF" : None}:NOT FAILED
2978 d["a"] = {"abcF" : {"": 1}}:ValueError:('empty keys are not allowed',)
2979 d["a"] = {"abcF" : {u"": 1}}:ValueError:('empty keys are not allowed',)
2980 d["a"] = {"abcF" : FailingMapping()}:NotImplementedError:('keys',)
2981 d["a"] = {"abcF" : FailingMappingKey()}:NotImplementedError:('getitem:mappingkey',)
2982 d["a"] = {"abcF" : FailingNumber()}:TypeError:('long() argument must be a string or a number',)
2983 <<< Finished
2984 >>> Testing StringToChars using d["a"] = Mapping({%s : 1})
2985 d["a"] = Mapping({1 : 1}):TypeError:('expected str() or unicode() instance, but got int',)
2986 d["a"] = Mapping({u"\0" : 1}):TypeError:('expected string without null bytes',)
2987 d["a"] = Mapping({"\0" : 1}):TypeError:('expected string without null bytes',)
2988 <<< Finished
2989 >>> Testing StringToChars using d["a"] = Mapping({"abcG" : {%s : 1}})
2990 d["a"] = Mapping({"abcG" : {1 : 1}}):TypeError:('expected str() or unicode() instance, but got int',)
2991 d["a"] = Mapping({"abcG" : {u"\0" : 1}}):TypeError:('expected string without null bytes',)
2992 d["a"] = Mapping({"abcG" : {"\0" : 1}}):TypeError:('expected string without null bytes',)
2993 <<< Finished
2994 >>> Testing StringToChars using d["a"] = Mapping({"abcG" : Mapping({%s : 1})})
2995 d["a"] = Mapping({"abcG" : Mapping({1 : 1})}):TypeError:('expected str() or unicode() instance, but got int',)
2996 d["a"] = Mapping({"abcG" : Mapping({u"\0" : 1})}):TypeError:('expected string without null bytes',)
2997 d["a"] = Mapping({"abcG" : Mapping({"\0" : 1})}):TypeError:('expected string without null bytes',)
2998 <<< Finished
2999 >>> Testing *Iter* using d["a"] = Mapping({"abcG" : %s})
3000 d["a"] = Mapping({"abcG" : FailingIter()}):TypeError:('unable to convert FailingIter to a Vim structure',)
3001 d["a"] = Mapping({"abcG" : FailingIterNext()}):NotImplementedError:('next',)
3002 <<< Finished
3003 >>> Testing ConvertFromPyObject using d["a"] = Mapping({"abcG" : %s})
3004 d["a"] = Mapping({"abcG" : None}):NOT FAILED
3005 d["a"] = Mapping({"abcG" : {"": 1}}):ValueError:('empty keys are not allowed',)
3006 d["a"] = Mapping({"abcG" : {u"": 1}}):ValueError:('empty keys are not allowed',)
3007 d["a"] = Mapping({"abcG" : FailingMapping()}):NotImplementedError:('keys',)
3008 d["a"] = Mapping({"abcG" : FailingMappingKey()}):NotImplementedError:('getitem:mappingkey',)
3009 d["a"] = Mapping({"abcG" : FailingNumber()}):TypeError:('long() argument must be a string or a number',)
3010 <<< Finished
3011 >>> Testing *Iter* using d["a"] = %s
3012 d["a"] = FailingIter():TypeError:('unable to convert FailingIter to a Vim structure',)
3013 d["a"] = FailingIterNext():NotImplementedError:('next',)
3014 <<< Finished
3015 >>> Testing ConvertFromPyObject using d["a"] = %s
3016 d["a"] = None:NOT FAILED
3017 d["a"] = {"": 1}:ValueError:('empty keys are not allowed',)
3018 d["a"] = {u"": 1}:ValueError:('empty keys are not allowed',)
3019 d["a"] = FailingMapping():NotImplementedError:('keys',)
3020 d["a"] = FailingMappingKey():NotImplementedError:('getitem:mappingkey',)
3021 d["a"] = FailingNumber():TypeError:('long() argument must be a string or a number',)
3022 <<< Finished
3023 >> DictionaryUpdate
3024 >>> kwargs
3025 >>> iter
3026 d.update(FailingMapping()):NotImplementedError:('keys',)
3027 d.update([FailingIterNext()]):NotImplementedError:('next',)
3028 d.update([FailingIterNextN(1)]):NotImplementedError:('next N',)
3029 >>> Testing *Iter* using d.update(%s)
3030 d.update(FailingIter()):NotImplementedError:('iter',)
3031 d.update(FailingIterNext()):NotImplementedError:('next',)
3032 <<< Finished
3033 >>> Testing StringToChars using d.update({%s : 1})
3034 d.update({1 : 1}):TypeError:('expected str() or unicode() instance, but got int',)
3035 d.update({u"\0" : 1}):TypeError:('expected string without null bytes',)
3036 d.update({"\0" : 1}):TypeError:('expected string without null bytes',)
3037 <<< Finished
3038 >>> Testing StringToChars using d.update({"abcF" : {%s : 1}})
3039 d.update({"abcF" : {1 : 1}}):TypeError:('expected str() or unicode() instance, but got int',)
3040 d.update({"abcF" : {u"\0" : 1}}):TypeError:('expected string without null bytes',)
3041 d.update({"abcF" : {"\0" : 1}}):TypeError:('expected string without null bytes',)
3042 <<< Finished
3043 >>> Testing StringToChars using d.update({"abcF" : Mapping({%s : 1})})
3044 d.update({"abcF" : Mapping({1 : 1})}):TypeError:('expected str() or unicode() instance, but got int',)
3045 d.update({"abcF" : Mapping({u"\0" : 1})}):TypeError:('expected string without null bytes',)
3046 d.update({"abcF" : Mapping({"\0" : 1})}):TypeError:('expected string without null bytes',)
3047 <<< Finished
3048 >>> Testing *Iter* using d.update({"abcF" : %s})
3049 d.update({"abcF" : FailingIter()}):TypeError:('unable to convert FailingIter to a Vim structure',)
3050 d.update({"abcF" : FailingIterNext()}):NotImplementedError:('next',)
3051 <<< Finished
3052 >>> Testing ConvertFromPyObject using d.update({"abcF" : %s})
3053 d.update({"abcF" : None}):NOT FAILED
3054 d.update({"abcF" : {"": 1}}):ValueError:('empty keys are not allowed',)
3055 d.update({"abcF" : {u"": 1}}):ValueError:('empty keys are not allowed',)
3056 d.update({"abcF" : FailingMapping()}):NotImplementedError:('keys',)
3057 d.update({"abcF" : FailingMappingKey()}):NotImplementedError:('getitem:mappingkey',)
3058 d.update({"abcF" : FailingNumber()}):TypeError:('long() argument must be a string or a number',)
3059 <<< Finished
3060 >>> Testing StringToChars using d.update(Mapping({%s : 1}))
3061 d.update(Mapping({1 : 1})):TypeError:('expected str() or unicode() instance, but got int',)
3062 d.update(Mapping({u"\0" : 1})):TypeError:('expected string without null bytes',)
3063 d.update(Mapping({"\0" : 1})):TypeError:('expected string without null bytes',)
3064 <<< Finished
3065 >>> Testing StringToChars using d.update(Mapping({"abcG" : {%s : 1}}))
3066 d.update(Mapping({"abcG" : {1 : 1}})):TypeError:('expected str() or unicode() instance, but got int',)
3067 d.update(Mapping({"abcG" : {u"\0" : 1}})):TypeError:('expected string without null bytes',)
3068 d.update(Mapping({"abcG" : {"\0" : 1}})):TypeError:('expected string without null bytes',)
3069 <<< Finished
3070 >>> Testing StringToChars using d.update(Mapping({"abcG" : Mapping({%s : 1})}))
3071 d.update(Mapping({"abcG" : Mapping({1 : 1})})):TypeError:('expected str() or unicode() instance, but got int',)
3072 d.update(Mapping({"abcG" : Mapping({u"\0" : 1})})):TypeError:('expected string without null bytes',)
3073 d.update(Mapping({"abcG" : Mapping({"\0" : 1})})):TypeError:('expected string without null bytes',)
3074 <<< Finished
3075 >>> Testing *Iter* using d.update(Mapping({"abcG" : %s}))
3076 d.update(Mapping({"abcG" : FailingIter()})):TypeError:('unable to convert FailingIter to a Vim structure',)
3077 d.update(Mapping({"abcG" : FailingIterNext()})):NotImplementedError:('next',)
3078 <<< Finished
3079 >>> Testing ConvertFromPyObject using d.update(Mapping({"abcG" : %s}))
3080 d.update(Mapping({"abcG" : None})):NOT FAILED
3081 d.update(Mapping({"abcG" : {"": 1}})):ValueError:('empty keys are not allowed',)
3082 d.update(Mapping({"abcG" : {u"": 1}})):ValueError:('empty keys are not allowed',)
3083 d.update(Mapping({"abcG" : FailingMapping()})):NotImplementedError:('keys',)
3084 d.update(Mapping({"abcG" : FailingMappingKey()})):NotImplementedError:('getitem:mappingkey',)
3085 d.update(Mapping({"abcG" : FailingNumber()})):TypeError:('long() argument must be a string or a number',)
3086 <<< Finished
3087 >>> Testing *Iter* using d.update(%s)
3088 d.update(FailingIter()):NotImplementedError:('iter',)
3089 d.update(FailingIterNext()):NotImplementedError:('next',)
3090 <<< Finished
3091 >>> Testing ConvertFromPyObject using d.update(%s)
3092 d.update(None):TypeError:("'NoneType' object is not iterable",)
3093 d.update({"": 1}):ValueError:('empty keys are not allowed',)
3094 d.update({u"": 1}):ValueError:('empty keys are not allowed',)
3095 d.update(FailingMapping()):NotImplementedError:('keys',)
3096 d.update(FailingMappingKey()):NotImplementedError:('getitem:mappingkey',)
3097 d.update(FailingNumber()):TypeError:("'FailingNumber' object is not iterable",)
3098 <<< Finished
3099 >>> Testing StringToChars using d.update(((%s, 0),))
3100 d.update(((1, 0),)):TypeError:('expected str() or unicode() instance, but got int',)
3101 d.update(((u"\0", 0),)):TypeError:('expected string without null bytes',)
3102 d.update((("\0", 0),)):TypeError:('expected string without null bytes',)
3103 <<< Finished
3104 >>> Testing StringToChars using d.update((("a", {%s : 1}),))
3105 d.update((("a", {1 : 1}),)):TypeError:('expected str() or unicode() instance, but got int',)
3106 d.update((("a", {u"\0" : 1}),)):TypeError:('expected string without null bytes',)
3107 d.update((("a", {"\0" : 1}),)):TypeError:('expected string without null bytes',)
3108 <<< Finished
3109 >>> Testing StringToChars using d.update((("a", {"abcF" : {%s : 1}}),))
3110 d.update((("a", {"abcF" : {1 : 1}}),)):TypeError:('expected str() or unicode() instance, but got int',)
3111 d.update((("a", {"abcF" : {u"\0" : 1}}),)):TypeError:('expected string without null bytes',)
3112 d.update((("a", {"abcF" : {"\0" : 1}}),)):TypeError:('expected string without null bytes',)
3113 <<< Finished
3114 >>> Testing StringToChars using d.update((("a", {"abcF" : Mapping({%s : 1})}),))
3115 d.update((("a", {"abcF" : Mapping({1 : 1})}),)):TypeError:('expected str() or unicode() instance, but got int',)
3116 d.update((("a", {"abcF" : Mapping({u"\0" : 1})}),)):TypeError:('expected string without null bytes',)
3117 d.update((("a", {"abcF" : Mapping({"\0" : 1})}),)):TypeError:('expected string without null bytes',)
3118 <<< Finished
3119 >>> Testing *Iter* using d.update((("a", {"abcF" : %s}),))
3120 d.update((("a", {"abcF" : FailingIter()}),)):TypeError:('unable to convert FailingIter to a Vim structure',)
3121 d.update((("a", {"abcF" : FailingIterNext()}),)):NotImplementedError:('next',)
3122 <<< Finished
3123 >>> Testing ConvertFromPyObject using d.update((("a", {"abcF" : %s}),))
3124 d.update((("a", {"abcF" : None}),)):error:("failed to add key 'a' to dictionary",)
3125 d.update((("a", {"abcF" : {"": 1}}),)):ValueError:('empty keys are not allowed',)
3126 d.update((("a", {"abcF" : {u"": 1}}),)):ValueError:('empty keys are not allowed',)
3127 d.update((("a", {"abcF" : FailingMapping()}),)):NotImplementedError:('keys',)
3128 d.update((("a", {"abcF" : FailingMappingKey()}),)):NotImplementedError:('getitem:mappingkey',)
3129 d.update((("a", {"abcF" : FailingNumber()}),)):TypeError:('long() argument must be a string or a number',)
3130 <<< Finished
3131 >>> Testing StringToChars using d.update((("a", Mapping({%s : 1})),))
3132 d.update((("a", Mapping({1 : 1})),)):TypeError:('expected str() or unicode() instance, but got int',)
3133 d.update((("a", Mapping({u"\0" : 1})),)):TypeError:('expected string without null bytes',)
3134 d.update((("a", Mapping({"\0" : 1})),)):TypeError:('expected string without null bytes',)
3135 <<< Finished
3136 >>> Testing StringToChars using d.update((("a", Mapping({"abcG" : {%s : 1}})),))
3137 d.update((("a", Mapping({"abcG" : {1 : 1}})),)):TypeError:('expected str() or unicode() instance, but got int',)
3138 d.update((("a", Mapping({"abcG" : {u"\0" : 1}})),)):TypeError:('expected string without null bytes',)
3139 d.update((("a", Mapping({"abcG" : {"\0" : 1}})),)):TypeError:('expected string without null bytes',)
3140 <<< Finished
3141 >>> Testing StringToChars using d.update((("a", Mapping({"abcG" : Mapping({%s : 1})})),))
3142 d.update((("a", Mapping({"abcG" : Mapping({1 : 1})})),)):TypeError:('expected str() or unicode() instance, but got int',)
3143 d.update((("a", Mapping({"abcG" : Mapping({u"\0" : 1})})),)):TypeError:('expected string without null bytes',)
3144 d.update((("a", Mapping({"abcG" : Mapping({"\0" : 1})})),)):TypeError:('expected string without null bytes',)
3145 <<< Finished
3146 >>> Testing *Iter* using d.update((("a", Mapping({"abcG" : %s})),))
3147 d.update((("a", Mapping({"abcG" : FailingIter()})),)):TypeError:('unable to convert FailingIter to a Vim structure',)
3148 d.update((("a", Mapping({"abcG" : FailingIterNext()})),)):NotImplementedError:('next',)
3149 <<< Finished
3150 >>> Testing ConvertFromPyObject using d.update((("a", Mapping({"abcG" : %s})),))
3151 d.update((("a", Mapping({"abcG" : None})),)):error:("failed to add key 'a' to dictionary",)
3152 d.update((("a", Mapping({"abcG" : {"": 1}})),)):ValueError:('empty keys are not allowed',)
3153 d.update((("a", Mapping({"abcG" : {u"": 1}})),)):ValueError:('empty keys are not allowed',)
3154 d.update((("a", Mapping({"abcG" : FailingMapping()})),)):NotImplementedError:('keys',)
3155 d.update((("a", Mapping({"abcG" : FailingMappingKey()})),)):NotImplementedError:('getitem:mappingkey',)
3156 d.update((("a", Mapping({"abcG" : FailingNumber()})),)):TypeError:('long() argument must be a string or a number',)
3157 <<< Finished
3158 >>> Testing *Iter* using d.update((("a", %s),))
3159 d.update((("a", FailingIter()),)):TypeError:('unable to convert FailingIter to a Vim structure',)
3160 d.update((("a", FailingIterNext()),)):NotImplementedError:('next',)
3161 <<< Finished
3162 >>> Testing ConvertFromPyObject using d.update((("a", %s),))
3163 d.update((("a", None),)):error:("failed to add key 'a' to dictionary",)
3164 d.update((("a", {"": 1}),)):ValueError:('empty keys are not allowed',)
3165 d.update((("a", {u"": 1}),)):ValueError:('empty keys are not allowed',)
3166 d.update((("a", FailingMapping()),)):NotImplementedError:('keys',)
3167 d.update((("a", FailingMappingKey()),)):NotImplementedError:('getitem:mappingkey',)
3168 d.update((("a", FailingNumber()),)):TypeError:('long() argument must be a string or a number',)
3169 <<< Finished
3170 >> DictionaryPopItem
3171 d.popitem(1, 2):TypeError:('popitem() takes no arguments (2 given)',)
3172 >> DictionaryHasKey
3173 d.has_key():TypeError:('has_key() takes exactly one argument (0 given)',)
3174 > List
3175 >> ListConstructor
3176 vim.List(1, 2):TypeError:('function takes at most 1 argument (2 given)',)
3177 vim.List(a=1):TypeError:('list constructor does not accept keyword arguments',)
3178 >>> Testing *Iter* using vim.List(%s)
3179 vim.List(FailingIter()):NotImplementedError:('iter',)
3180 vim.List(FailingIterNext()):NotImplementedError:('next',)
3181 <<< Finished
3182 >>> Testing StringToChars using vim.List([{%s : 1}])
3183 vim.List([{1 : 1}]):TypeError:('expected str() or unicode() instance, but got int',)
3184 vim.List([{u"\0" : 1}]):TypeError:('expected string without null bytes',)
3185 vim.List([{"\0" : 1}]):TypeError:('expected string without null bytes',)
3186 <<< Finished
3187 >>> Testing StringToChars using vim.List([{"abcF" : {%s : 1}}])
3188 vim.List([{"abcF" : {1 : 1}}]):TypeError:('expected str() or unicode() instance, but got int',)
3189 vim.List([{"abcF" : {u"\0" : 1}}]):TypeError:('expected string without null bytes',)
3190 vim.List([{"abcF" : {"\0" : 1}}]):TypeError:('expected string without null bytes',)
3191 <<< Finished
3192 >>> Testing StringToChars using vim.List([{"abcF" : Mapping({%s : 1})}])
3193 vim.List([{"abcF" : Mapping({1 : 1})}]):TypeError:('expected str() or unicode() instance, but got int',)
3194 vim.List([{"abcF" : Mapping({u"\0" : 1})}]):TypeError:('expected string without null bytes',)
3195 vim.List([{"abcF" : Mapping({"\0" : 1})}]):TypeError:('expected string without null bytes',)
3196 <<< Finished
3197 >>> Testing *Iter* using vim.List([{"abcF" : %s}])
3198 vim.List([{"abcF" : FailingIter()}]):TypeError:('unable to convert FailingIter to a Vim structure',)
3199 vim.List([{"abcF" : FailingIterNext()}]):NotImplementedError:('next',)
3200 <<< Finished
3201 >>> Testing ConvertFromPyObject using vim.List([{"abcF" : %s}])
3202 vim.List([{"abcF" : None}]):NOT FAILED
3203 vim.List([{"abcF" : {"": 1}}]):ValueError:('empty keys are not allowed',)
3204 vim.List([{"abcF" : {u"": 1}}]):ValueError:('empty keys are not allowed',)
3205 vim.List([{"abcF" : FailingMapping()}]):NotImplementedError:('keys',)
3206 vim.List([{"abcF" : FailingMappingKey()}]):NotImplementedError:('getitem:mappingkey',)
3207 vim.List([{"abcF" : FailingNumber()}]):TypeError:('long() argument must be a string or a number',)
3208 <<< Finished
3209 >>> Testing StringToChars using vim.List([Mapping({%s : 1})])
3210 vim.List([Mapping({1 : 1})]):TypeError:('expected str() or unicode() instance, but got int',)
3211 vim.List([Mapping({u"\0" : 1})]):TypeError:('expected string without null bytes',)
3212 vim.List([Mapping({"\0" : 1})]):TypeError:('expected string without null bytes',)
3213 <<< Finished
3214 >>> Testing StringToChars using vim.List([Mapping({"abcG" : {%s : 1}})])
3215 vim.List([Mapping({"abcG" : {1 : 1}})]):TypeError:('expected str() or unicode() instance, but got int',)
3216 vim.List([Mapping({"abcG" : {u"\0" : 1}})]):TypeError:('expected string without null bytes',)
3217 vim.List([Mapping({"abcG" : {"\0" : 1}})]):TypeError:('expected string without null bytes',)
3218 <<< Finished
3219 >>> Testing StringToChars using vim.List([Mapping({"abcG" : Mapping({%s : 1})})])
3220 vim.List([Mapping({"abcG" : Mapping({1 : 1})})]):TypeError:('expected str() or unicode() instance, but got int',)
3221 vim.List([Mapping({"abcG" : Mapping({u"\0" : 1})})]):TypeError:('expected string without null bytes',)
3222 vim.List([Mapping({"abcG" : Mapping({"\0" : 1})})]):TypeError:('expected string without null bytes',)
3223 <<< Finished
3224 >>> Testing *Iter* using vim.List([Mapping({"abcG" : %s})])
3225 vim.List([Mapping({"abcG" : FailingIter()})]):TypeError:('unable to convert FailingIter to a Vim structure',)
3226 vim.List([Mapping({"abcG" : FailingIterNext()})]):NotImplementedError:('next',)
3227 <<< Finished
3228 >>> Testing ConvertFromPyObject using vim.List([Mapping({"abcG" : %s})])
3229 vim.List([Mapping({"abcG" : None})]):NOT FAILED
3230 vim.List([Mapping({"abcG" : {"": 1}})]):ValueError:('empty keys are not allowed',)
3231 vim.List([Mapping({"abcG" : {u"": 1}})]):ValueError:('empty keys are not allowed',)
3232 vim.List([Mapping({"abcG" : FailingMapping()})]):NotImplementedError:('keys',)
3233 vim.List([Mapping({"abcG" : FailingMappingKey()})]):NotImplementedError:('getitem:mappingkey',)
3234 vim.List([Mapping({"abcG" : FailingNumber()})]):TypeError:('long() argument must be a string or a number',)
3235 <<< Finished
3236 >>> Testing *Iter* using vim.List([%s])
3237 vim.List([FailingIter()]):TypeError:('unable to convert FailingIter to a Vim structure',)
3238 vim.List([FailingIterNext()]):NotImplementedError:('next',)
3239 <<< Finished
3240 >>> Testing ConvertFromPyObject using vim.List([%s])
3241 vim.List([None]):NOT FAILED
3242 vim.List([{"": 1}]):ValueError:('empty keys are not allowed',)
3243 vim.List([{u"": 1}]):ValueError:('empty keys are not allowed',)
3244 vim.List([FailingMapping()]):NotImplementedError:('keys',)
3245 vim.List([FailingMappingKey()]):NotImplementedError:('getitem:mappingkey',)
3246 vim.List([FailingNumber()]):TypeError:('long() argument must be a string or a number',)
3247 <<< Finished
3248 >> ListItem
3249 l[1000]:IndexError:('list index out of range',)
3250 >> ListAssItem
3251 ll[1] = 2:error:('list is locked',)
3252 l[1000] = 3:IndexError:('list index out of range',)
3253 >> ListAssSlice
3254 ll[1:100] = "abcJ":error:('list is locked',)
3255 >>> Testing *Iter* using l[:] = %s
3256 l[:] = FailingIter():NotImplementedError:('iter',)
3257 l[:] = FailingIterNext():NotImplementedError:('next',)
3258 <<< Finished
3259 nel[1:10:2] = "abcK":ValueError:('attempt to assign sequence of size greater than 2 to extended slice',)
3260 ('a', 'b', 'c', 'O')
3261 nel[1:10:2] = "a":ValueError:('attempt to assign sequence of size 1 to extended slice of size 2',)
3262 ('a', 'b', 'c', 'O')
3263 nel[1:1:-1] = "a":ValueError:('attempt to assign sequence of size greater than 0 to extended slice',)
3264 ('a', 'b', 'c', 'O')
3265 nel[:] = FailingIterNextN(2):NotImplementedError:('next N',)
3266 ('a', 'b', 'c', 'O')
3267 >>> Testing StringToChars using l[:] = [{%s : 1}]
3268 l[:] = [{1 : 1}]:TypeError:('expected str() or unicode() instance, but got int',)
3269 l[:] = [{u"\0" : 1}]:TypeError:('expected string without null bytes',)
3270 l[:] = [{"\0" : 1}]:TypeError:('expected string without null bytes',)
3271 <<< Finished
3272 >>> Testing StringToChars using l[:] = [{"abcF" : {%s : 1}}]
3273 l[:] = [{"abcF" : {1 : 1}}]:TypeError:('expected str() or unicode() instance, but got int',)
3274 l[:] = [{"abcF" : {u"\0" : 1}}]:TypeError:('expected string without null bytes',)
3275 l[:] = [{"abcF" : {"\0" : 1}}]:TypeError:('expected string without null bytes',)
3276 <<< Finished
3277 >>> Testing StringToChars using l[:] = [{"abcF" : Mapping({%s : 1})}]
3278 l[:] = [{"abcF" : Mapping({1 : 1})}]:TypeError:('expected str() or unicode() instance, but got int',)
3279 l[:] = [{"abcF" : Mapping({u"\0" : 1})}]:TypeError:('expected string without null bytes',)
3280 l[:] = [{"abcF" : Mapping({"\0" : 1})}]:TypeError:('expected string without null bytes',)
3281 <<< Finished
3282 >>> Testing *Iter* using l[:] = [{"abcF" : %s}]
3283 l[:] = [{"abcF" : FailingIter()}]:TypeError:('unable to convert FailingIter to a Vim structure',)
3284 l[:] = [{"abcF" : FailingIterNext()}]:NotImplementedError:('next',)
3285 <<< Finished
3286 >>> Testing ConvertFromPyObject using l[:] = [{"abcF" : %s}]
3287 l[:] = [{"abcF" : None}]:NOT FAILED
3288 l[:] = [{"abcF" : {"": 1}}]:ValueError:('empty keys are not allowed',)
3289 l[:] = [{"abcF" : {u"": 1}}]:ValueError:('empty keys are not allowed',)
3290 l[:] = [{"abcF" : FailingMapping()}]:NotImplementedError:('keys',)
3291 l[:] = [{"abcF" : FailingMappingKey()}]:NotImplementedError:('getitem:mappingkey',)
3292 l[:] = [{"abcF" : FailingNumber()}]:TypeError:('long() argument must be a string or a number',)
3293 <<< Finished
3294 >>> Testing StringToChars using l[:] = [Mapping({%s : 1})]
3295 l[:] = [Mapping({1 : 1})]:TypeError:('expected str() or unicode() instance, but got int',)
3296 l[:] = [Mapping({u"\0" : 1})]:TypeError:('expected string without null bytes',)
3297 l[:] = [Mapping({"\0" : 1})]:TypeError:('expected string without null bytes',)
3298 <<< Finished
3299 >>> Testing StringToChars using l[:] = [Mapping({"abcG" : {%s : 1}})]
3300 l[:] = [Mapping({"abcG" : {1 : 1}})]:TypeError:('expected str() or unicode() instance, but got int',)
3301 l[:] = [Mapping({"abcG" : {u"\0" : 1}})]:TypeError:('expected string without null bytes',)
3302 l[:] = [Mapping({"abcG" : {"\0" : 1}})]:TypeError:('expected string without null bytes',)
3303 <<< Finished
3304 >>> Testing StringToChars using l[:] = [Mapping({"abcG" : Mapping({%s : 1})})]
3305 l[:] = [Mapping({"abcG" : Mapping({1 : 1})})]:TypeError:('expected str() or unicode() instance, but got int',)
3306 l[:] = [Mapping({"abcG" : Mapping({u"\0" : 1})})]:TypeError:('expected string without null bytes',)
3307 l[:] = [Mapping({"abcG" : Mapping({"\0" : 1})})]:TypeError:('expected string without null bytes',)
3308 <<< Finished
3309 >>> Testing *Iter* using l[:] = [Mapping({"abcG" : %s})]
3310 l[:] = [Mapping({"abcG" : FailingIter()})]:TypeError:('unable to convert FailingIter to a Vim structure',)
3311 l[:] = [Mapping({"abcG" : FailingIterNext()})]:NotImplementedError:('next',)
3312 <<< Finished
3313 >>> Testing ConvertFromPyObject using l[:] = [Mapping({"abcG" : %s})]
3314 l[:] = [Mapping({"abcG" : None})]:NOT FAILED
3315 l[:] = [Mapping({"abcG" : {"": 1}})]:ValueError:('empty keys are not allowed',)
3316 l[:] = [Mapping({"abcG" : {u"": 1}})]:ValueError:('empty keys are not allowed',)
3317 l[:] = [Mapping({"abcG" : FailingMapping()})]:NotImplementedError:('keys',)
3318 l[:] = [Mapping({"abcG" : FailingMappingKey()})]:NotImplementedError:('getitem:mappingkey',)
3319 l[:] = [Mapping({"abcG" : FailingNumber()})]:TypeError:('long() argument must be a string or a number',)
3320 <<< Finished
3321 >>> Testing *Iter* using l[:] = [%s]
3322 l[:] = [FailingIter()]:TypeError:('unable to convert FailingIter to a Vim structure',)
3323 l[:] = [FailingIterNext()]:NotImplementedError:('next',)
3324 <<< Finished
3325 >>> Testing ConvertFromPyObject using l[:] = [%s]
3326 l[:] = [None]:NOT FAILED
3327 l[:] = [{"": 1}]:ValueError:('empty keys are not allowed',)
3328 l[:] = [{u"": 1}]:ValueError:('empty keys are not allowed',)
3329 l[:] = [FailingMapping()]:NotImplementedError:('keys',)
3330 l[:] = [FailingMappingKey()]:NotImplementedError:('getitem:mappingkey',)
3331 l[:] = [FailingNumber()]:TypeError:('long() argument must be a string or a number',)
3332 <<< Finished
3333 >> ListConcatInPlace
3334 >>> Testing *Iter* using l.extend(%s)
3335 l.extend(FailingIter()):NotImplementedError:('iter',)
3336 l.extend(FailingIterNext()):NotImplementedError:('next',)
3337 <<< Finished
3338 >>> Testing StringToChars using l.extend([{%s : 1}])
3339 l.extend([{1 : 1}]):TypeError:('expected str() or unicode() instance, but got int',)
3340 l.extend([{u"\0" : 1}]):TypeError:('expected string without null bytes',)
3341 l.extend([{"\0" : 1}]):TypeError:('expected string without null bytes',)
3342 <<< Finished
3343 >>> Testing StringToChars using l.extend([{"abcF" : {%s : 1}}])
3344 l.extend([{"abcF" : {1 : 1}}]):TypeError:('expected str() or unicode() instance, but got int',)
3345 l.extend([{"abcF" : {u"\0" : 1}}]):TypeError:('expected string without null bytes',)
3346 l.extend([{"abcF" : {"\0" : 1}}]):TypeError:('expected string without null bytes',)
3347 <<< Finished
3348 >>> Testing StringToChars using l.extend([{"abcF" : Mapping({%s : 1})}])
3349 l.extend([{"abcF" : Mapping({1 : 1})}]):TypeError:('expected str() or unicode() instance, but got int',)
3350 l.extend([{"abcF" : Mapping({u"\0" : 1})}]):TypeError:('expected string without null bytes',)
3351 l.extend([{"abcF" : Mapping({"\0" : 1})}]):TypeError:('expected string without null bytes',)
3352 <<< Finished
3353 >>> Testing *Iter* using l.extend([{"abcF" : %s}])
3354 l.extend([{"abcF" : FailingIter()}]):TypeError:('unable to convert FailingIter to a Vim structure',)
3355 l.extend([{"abcF" : FailingIterNext()}]):NotImplementedError:('next',)
3356 <<< Finished
3357 >>> Testing ConvertFromPyObject using l.extend([{"abcF" : %s}])
3358 l.extend([{"abcF" : None}]):NOT FAILED
3359 l.extend([{"abcF" : {"": 1}}]):ValueError:('empty keys are not allowed',)
3360 l.extend([{"abcF" : {u"": 1}}]):ValueError:('empty keys are not allowed',)
3361 l.extend([{"abcF" : FailingMapping()}]):NotImplementedError:('keys',)
3362 l.extend([{"abcF" : FailingMappingKey()}]):NotImplementedError:('getitem:mappingkey',)
3363 l.extend([{"abcF" : FailingNumber()}]):TypeError:('long() argument must be a string or a number',)
3364 <<< Finished
3365 >>> Testing StringToChars using l.extend([Mapping({%s : 1})])
3366 l.extend([Mapping({1 : 1})]):TypeError:('expected str() or unicode() instance, but got int',)
3367 l.extend([Mapping({u"\0" : 1})]):TypeError:('expected string without null bytes',)
3368 l.extend([Mapping({"\0" : 1})]):TypeError:('expected string without null bytes',)
3369 <<< Finished
3370 >>> Testing StringToChars using l.extend([Mapping({"abcG" : {%s : 1}})])
3371 l.extend([Mapping({"abcG" : {1 : 1}})]):TypeError:('expected str() or unicode() instance, but got int',)
3372 l.extend([Mapping({"abcG" : {u"\0" : 1}})]):TypeError:('expected string without null bytes',)
3373 l.extend([Mapping({"abcG" : {"\0" : 1}})]):TypeError:('expected string without null bytes',)
3374 <<< Finished
3375 >>> Testing StringToChars using l.extend([Mapping({"abcG" : Mapping({%s : 1})})])
3376 l.extend([Mapping({"abcG" : Mapping({1 : 1})})]):TypeError:('expected str() or unicode() instance, but got int',)
3377 l.extend([Mapping({"abcG" : Mapping({u"\0" : 1})})]):TypeError:('expected string without null bytes',)
3378 l.extend([Mapping({"abcG" : Mapping({"\0" : 1})})]):TypeError:('expected string without null bytes',)
3379 <<< Finished
3380 >>> Testing *Iter* using l.extend([Mapping({"abcG" : %s})])
3381 l.extend([Mapping({"abcG" : FailingIter()})]):TypeError:('unable to convert FailingIter to a Vim structure',)
3382 l.extend([Mapping({"abcG" : FailingIterNext()})]):NotImplementedError:('next',)
3383 <<< Finished
3384 >>> Testing ConvertFromPyObject using l.extend([Mapping({"abcG" : %s})])
3385 l.extend([Mapping({"abcG" : None})]):NOT FAILED
3386 l.extend([Mapping({"abcG" : {"": 1}})]):ValueError:('empty keys are not allowed',)
3387 l.extend([Mapping({"abcG" : {u"": 1}})]):ValueError:('empty keys are not allowed',)
3388 l.extend([Mapping({"abcG" : FailingMapping()})]):NotImplementedError:('keys',)
3389 l.extend([Mapping({"abcG" : FailingMappingKey()})]):NotImplementedError:('getitem:mappingkey',)
3390 l.extend([Mapping({"abcG" : FailingNumber()})]):TypeError:('long() argument must be a string or a number',)
3391 <<< Finished
3392 >>> Testing *Iter* using l.extend([%s])
3393 l.extend([FailingIter()]):TypeError:('unable to convert FailingIter to a Vim structure',)
3394 l.extend([FailingIterNext()]):NotImplementedError:('next',)
3395 <<< Finished
3396 >>> Testing ConvertFromPyObject using l.extend([%s])
3397 l.extend([None]):NOT FAILED
3398 l.extend([{"": 1}]):ValueError:('empty keys are not allowed',)
3399 l.extend([{u"": 1}]):ValueError:('empty keys are not allowed',)
3400 l.extend([FailingMapping()]):NotImplementedError:('keys',)
3401 l.extend([FailingMappingKey()]):NotImplementedError:('getitem:mappingkey',)
3402 l.extend([FailingNumber()]):TypeError:('long() argument must be a string or a number',)
3403 <<< Finished
3404 >> ListSetattr
3405 del l.locked:AttributeError:('cannot delete vim.List attributes',)
3406 l.locked = FailingTrue():NotImplementedError:('bool',)
3407 l.xxx = True:AttributeError:('cannot set attribute xxx',)
3408 > Function
3409 >> FunctionConstructor
3410 >>> FunctionConstructor
3411 vim.Function("123"):ValueError:('unnamed function 123 does not exist',)
3412 vim.Function("xxx_non_existent_function_xxx"):ValueError:('function xxx_non_existent_function_xxx does not exist',)
3413 vim.Function("xxx#non#existent#function#xxx"):NOT FAILED
3414 vim.Function("xxx_non_existent_function_xxx2", args=[]):ValueError:('function xxx_non_existent_function_xxx2 does not exist',)
3415 vim.Function("xxx_non_existent_function_xxx3", self={}):ValueError:('function xxx_non_existent_function_xxx3 does not exist',)
3416 vim.Function("xxx_non_existent_function_xxx4", args=[], self={}):ValueError:('function xxx_non_existent_function_xxx4 does not exist',)
3417 >>> FunctionNew
3418 vim.Function("tr", self="abcFuncSelf"):TypeError:('unable to convert str to a Vim dictionary',)
3419 vim.Function("tr", args=427423):TypeError:('unable to convert int to a Vim list',)
3420 vim.Function("tr", self="abcFuncSelf2", args="abcFuncArgs2"):TypeError:('unable to convert str to a Vim dictionary',)
3421 vim.Function(self="abcFuncSelf2", args="abcFuncArgs2"):TypeError:('unable to convert str to a Vim dictionary',)
3422 vim.Function("tr", "", self="abcFuncSelf2", args="abcFuncArgs2"):TypeError:('unable to convert str to a Vim dictionary',)
3423 vim.Function("tr", ""):TypeError:('function takes exactly 1 argument (2 given)',)
3424 >> FunctionCall
3425 >>> Testing StringToChars using f({%s : 1})
3426 f({1 : 1}):TypeError:('expected str() or unicode() instance, but got int',)
3427 f({u"\0" : 1}):TypeError:('expected string without null bytes',)
3428 f({"\0" : 1}):TypeError:('expected string without null bytes',)
3429 <<< Finished
3430 >>> Testing StringToChars using f({"abcF" : {%s : 1}})
3431 f({"abcF" : {1 : 1}}):TypeError:('expected str() or unicode() instance, but got int',)
3432 f({"abcF" : {u"\0" : 1}}):TypeError:('expected string without null bytes',)
3433 f({"abcF" : {"\0" : 1}}):TypeError:('expected string without null bytes',)
3434 <<< Finished
3435 >>> Testing StringToChars using f({"abcF" : Mapping({%s : 1})})
3436 f({"abcF" : Mapping({1 : 1})}):TypeError:('expected str() or unicode() instance, but got int',)
3437 f({"abcF" : Mapping({u"\0" : 1})}):TypeError:('expected string without null bytes',)
3438 f({"abcF" : Mapping({"\0" : 1})}):TypeError:('expected string without null bytes',)
3439 <<< Finished
3440 >>> Testing *Iter* using f({"abcF" : %s})
3441 f({"abcF" : FailingIter()}):TypeError:('unable to convert FailingIter to a Vim structure',)
3442 f({"abcF" : FailingIterNext()}):NotImplementedError:('next',)
3443 <<< Finished
3444 >>> Testing ConvertFromPyObject using f({"abcF" : %s})
3445 f({"abcF" : None}):NOT FAILED
3446 f({"abcF" : {"": 1}}):ValueError:('empty keys are not allowed',)
3447 f({"abcF" : {u"": 1}}):ValueError:('empty keys are not allowed',)
3448 f({"abcF" : FailingMapping()}):NotImplementedError:('keys',)
3449 f({"abcF" : FailingMappingKey()}):NotImplementedError:('getitem:mappingkey',)
3450 f({"abcF" : FailingNumber()}):TypeError:('long() argument must be a string or a number',)
3451 <<< Finished
3452 >>> Testing StringToChars using f(Mapping({%s : 1}))
3453 f(Mapping({1 : 1})):TypeError:('expected str() or unicode() instance, but got int',)
3454 f(Mapping({u"\0" : 1})):TypeError:('expected string without null bytes',)
3455 f(Mapping({"\0" : 1})):TypeError:('expected string without null bytes',)
3456 <<< Finished
3457 >>> Testing StringToChars using f(Mapping({"abcG" : {%s : 1}}))
3458 f(Mapping({"abcG" : {1 : 1}})):TypeError:('expected str() or unicode() instance, but got int',)
3459 f(Mapping({"abcG" : {u"\0" : 1}})):TypeError:('expected string without null bytes',)
3460 f(Mapping({"abcG" : {"\0" : 1}})):TypeError:('expected string without null bytes',)
3461 <<< Finished
3462 >>> Testing StringToChars using f(Mapping({"abcG" : Mapping({%s : 1})}))
3463 f(Mapping({"abcG" : Mapping({1 : 1})})):TypeError:('expected str() or unicode() instance, but got int',)
3464 f(Mapping({"abcG" : Mapping({u"\0" : 1})})):TypeError:('expected string without null bytes',)
3465 f(Mapping({"abcG" : Mapping({"\0" : 1})})):TypeError:('expected string without null bytes',)
3466 <<< Finished
3467 >>> Testing *Iter* using f(Mapping({"abcG" : %s}))
3468 f(Mapping({"abcG" : FailingIter()})):TypeError:('unable to convert FailingIter to a Vim structure',)
3469 f(Mapping({"abcG" : FailingIterNext()})):NotImplementedError:('next',)
3470 <<< Finished
3471 >>> Testing ConvertFromPyObject using f(Mapping({"abcG" : %s}))
3472 f(Mapping({"abcG" : None})):NOT FAILED
3473 f(Mapping({"abcG" : {"": 1}})):ValueError:('empty keys are not allowed',)
3474 f(Mapping({"abcG" : {u"": 1}})):ValueError:('empty keys are not allowed',)
3475 f(Mapping({"abcG" : FailingMapping()})):NotImplementedError:('keys',)
3476 f(Mapping({"abcG" : FailingMappingKey()})):NotImplementedError:('getitem:mappingkey',)
3477 f(Mapping({"abcG" : FailingNumber()})):TypeError:('long() argument must be a string or a number',)
3478 <<< Finished
3479 >>> Testing *Iter* using f(%s)
3480 f(FailingIter()):TypeError:('unable to convert FailingIter to a Vim structure',)
3481 f(FailingIterNext()):NotImplementedError:('next',)
3482 <<< Finished
3483 >>> Testing ConvertFromPyObject using f(%s)
3484 f(None):NOT FAILED
3485 f({"": 1}):ValueError:('empty keys are not allowed',)
3486 f({u"": 1}):ValueError:('empty keys are not allowed',)
3487 f(FailingMapping()):NotImplementedError:('keys',)
3488 f(FailingMappingKey()):NotImplementedError:('getitem:mappingkey',)
3489 f(FailingNumber()):TypeError:('long() argument must be a string or a number',)
3490 <<< Finished
3491 >>> Testing StringToChars using fd(self={%s : 1})
3492 fd(self={1 : 1}):TypeError:('expected str() or unicode() instance, but got int',)
3493 fd(self={u"\0" : 1}):TypeError:('expected string without null bytes',)
3494 fd(self={"\0" : 1}):TypeError:('expected string without null bytes',)
3495 <<< Finished
3496 >>> Testing StringToChars using fd(self={"abcF" : {%s : 1}})
3497 fd(self={"abcF" : {1 : 1}}):TypeError:('expected str() or unicode() instance, but got int',)
3498 fd(self={"abcF" : {u"\0" : 1}}):TypeError:('expected string without null bytes',)
3499 fd(self={"abcF" : {"\0" : 1}}):TypeError:('expected string without null bytes',)
3500 <<< Finished
3501 >>> Testing StringToChars using fd(self={"abcF" : Mapping({%s : 1})})
3502 fd(self={"abcF" : Mapping({1 : 1})}):TypeError:('expected str() or unicode() instance, but got int',)
3503 fd(self={"abcF" : Mapping({u"\0" : 1})}):TypeError:('expected string without null bytes',)
3504 fd(self={"abcF" : Mapping({"\0" : 1})}):TypeError:('expected string without null bytes',)
3505 <<< Finished
3506 >>> Testing *Iter* using fd(self={"abcF" : %s})
3507 fd(self={"abcF" : FailingIter()}):TypeError:('unable to convert FailingIter to a Vim structure',)
3508 fd(self={"abcF" : FailingIterNext()}):NotImplementedError:('next',)
3509 <<< Finished
3510 >>> Testing ConvertFromPyObject using fd(self={"abcF" : %s})
3511 fd(self={"abcF" : None}):NOT FAILED
3512 fd(self={"abcF" : {"": 1}}):ValueError:('empty keys are not allowed',)
3513 fd(self={"abcF" : {u"": 1}}):ValueError:('empty keys are not allowed',)
3514 fd(self={"abcF" : FailingMapping()}):NotImplementedError:('keys',)
3515 fd(self={"abcF" : FailingMappingKey()}):NotImplementedError:('getitem:mappingkey',)
3516 fd(self={"abcF" : FailingNumber()}):TypeError:('long() argument must be a string or a number',)
3517 <<< Finished
3518 >>> Testing StringToChars using fd(self=Mapping({%s : 1}))
3519 fd(self=Mapping({1 : 1})):TypeError:('expected str() or unicode() instance, but got int',)
3520 fd(self=Mapping({u"\0" : 1})):TypeError:('expected string without null bytes',)
3521 fd(self=Mapping({"\0" : 1})):TypeError:('expected string without null bytes',)
3522 <<< Finished
3523 >>> Testing StringToChars using fd(self=Mapping({"abcG" : {%s : 1}}))
3524 fd(self=Mapping({"abcG" : {1 : 1}})):TypeError:('expected str() or unicode() instance, but got int',)
3525 fd(self=Mapping({"abcG" : {u"\0" : 1}})):TypeError:('expected string without null bytes',)
3526 fd(self=Mapping({"abcG" : {"\0" : 1}})):TypeError:('expected string without null bytes',)
3527 <<< Finished
3528 >>> Testing StringToChars using fd(self=Mapping({"abcG" : Mapping({%s : 1})}))
3529 fd(self=Mapping({"abcG" : Mapping({1 : 1})})):TypeError:('expected str() or unicode() instance, but got int',)
3530 fd(self=Mapping({"abcG" : Mapping({u"\0" : 1})})):TypeError:('expected string without null bytes',)
3531 fd(self=Mapping({"abcG" : Mapping({"\0" : 1})})):TypeError:('expected string without null bytes',)
3532 <<< Finished
3533 >>> Testing *Iter* using fd(self=Mapping({"abcG" : %s}))
3534 fd(self=Mapping({"abcG" : FailingIter()})):TypeError:('unable to convert FailingIter to a Vim structure',)
3535 fd(self=Mapping({"abcG" : FailingIterNext()})):NotImplementedError:('next',)
3536 <<< Finished
3537 >>> Testing ConvertFromPyObject using fd(self=Mapping({"abcG" : %s}))
3538 fd(self=Mapping({"abcG" : None})):NOT FAILED
3539 fd(self=Mapping({"abcG" : {"": 1}})):ValueError:('empty keys are not allowed',)
3540 fd(self=Mapping({"abcG" : {u"": 1}})):ValueError:('empty keys are not allowed',)
3541 fd(self=Mapping({"abcG" : FailingMapping()})):NotImplementedError:('keys',)
3542 fd(self=Mapping({"abcG" : FailingMappingKey()})):NotImplementedError:('getitem:mappingkey',)
3543 fd(self=Mapping({"abcG" : FailingNumber()})):TypeError:('long() argument must be a string or a number',)
3544 <<< Finished
3545 >>> Testing *Iter* using fd(self=%s)
3546 fd(self=FailingIter()):TypeError:('unable to convert FailingIter to a Vim dictionary',)
3547 fd(self=FailingIterNext()):TypeError:('unable to convert FailingIterNext to a Vim dictionary',)
3548 <<< Finished
3549 >>> Testing ConvertFromPyObject using fd(self=%s)
3550 fd(self=None):TypeError:('unable to convert NoneType to a Vim dictionary',)
3551 fd(self={"": 1}):ValueError:('empty keys are not allowed',)
3552 fd(self={u"": 1}):ValueError:('empty keys are not allowed',)
3553 fd(self=FailingMapping()):NotImplementedError:('keys',)
3554 fd(self=FailingMappingKey()):NotImplementedError:('getitem:mappingkey',)
3555 fd(self=FailingNumber()):TypeError:('unable to convert FailingNumber to a Vim dictionary',)
3556 <<< Finished
3557 >>> Testing ConvertFromPyMapping using fd(self=%s)
3558 fd(self=[]):TypeError:('unable to convert list to a Vim dictionary',)
3559 <<< Finished
3560 > TabPage
3561 >> TabPageAttr
3562 vim.current.tabpage.xxx:AttributeError:('xxx',)
3563 > TabList
3564 >> TabListItem
3565 vim.tabpages[1000]:IndexError:('no such tab page',)
3566 > Window
3567 >> WindowAttr
3568 vim.current.window.xxx:AttributeError:('xxx',)
3569 >> WindowSetattr
3570 vim.current.window.buffer = 0:TypeError:('readonly attribute: buffer',)
3571 vim.current.window.cursor = (100000000, 100000000):error:('cursor position outside buffer',)
3572 vim.current.window.cursor = True:TypeError:('argument must be 2-item sequence, not bool',)
3573 >>> Testing NumberToLong using vim.current.window.height = %s
3574 vim.current.window.height = []:TypeError:('expected int(), long() or something supporting coercing to long(), but got list',)
3575 vim.current.window.height = None:TypeError:('expected int(), long() or something supporting coercing to long(), but got NoneType',)
3576 vim.current.window.height = -1:ValueError:('number must be greater or equal to zero',)
3577 <<< Finished
3578 >>> Testing NumberToLong using vim.current.window.width = %s
3579 vim.current.window.width = []:TypeError:('expected int(), long() or something supporting coercing to long(), but got list',)
3580 vim.current.window.width = None:TypeError:('expected int(), long() or something supporting coercing to long(), but got NoneType',)
3581 vim.current.window.width = -1:ValueError:('number must be greater or equal to zero',)
3582 <<< Finished
3583 vim.current.window.xxxxxx = True:AttributeError:('xxxxxx',)
3584 > WinList
3585 >> WinListItem
3586 vim.windows[1000]:IndexError:('no such window',)
3587 > Buffer
3588 >> StringToLine (indirect)
Bram Moolenaar92fdd1e2020-07-03 18:00:05 +02003589 vim.current.buffer[0] = "\na":error:('string cannot contain newlines',)
Bram Moolenaarab589462020-07-06 21:03:06 +02003590 vim.current.buffer[0] = u"\na":error:('string cannot contain newlines',)
Bram Moolenaar92fdd1e2020-07-03 18:00:05 +02003591 >> SetBufferLine (indirect)
3592 vim.current.buffer[0] = True:TypeError:('bad argument type for built-in operation',)
3593 >> SetBufferLineList (indirect)
3594 vim.current.buffer[:] = True:TypeError:('bad argument type for built-in operation',)
3595 vim.current.buffer[:] = ["\na", "bc"]:error:('string cannot contain newlines',)
3596 >> InsertBufferLines (indirect)
3597 vim.current.buffer.append(None):TypeError:('bad argument type for built-in operation',)
3598 vim.current.buffer.append(["\na", "bc"]):error:('string cannot contain newlines',)
3599 vim.current.buffer.append("\nbc"):error:('string cannot contain newlines',)
3600 >> RBItem
3601 vim.current.buffer[100000000]:IndexError:('line number out of range',)
3602 >> RBAsItem
3603 vim.current.buffer[100000000] = "":IndexError:('line number out of range',)
3604 >> BufferAttr
3605 vim.current.buffer.xxx:AttributeError:('xxx',)
3606 >> BufferSetattr
3607 vim.current.buffer.name = True:TypeError:('expected str() or unicode() instance, but got bool',)
3608 vim.current.buffer.xxx = True:AttributeError:('xxx',)
3609 >> BufferMark
3610 vim.current.buffer.mark(0):TypeError:('expected str() or unicode() instance, but got int',)
3611 vim.current.buffer.mark("abcM"):ValueError:('mark name must be a single character',)
3612 vim.current.buffer.mark("!"):error:('invalid mark name',)
3613 >> BufferRange
3614 vim.current.buffer.range(1, 2, 3):TypeError:('function takes exactly 2 arguments (3 given)',)
3615 > BufMap
3616 >> BufMapItem
3617 vim.buffers[100000000]:KeyError:(100000000,)
3618 >>> Testing NumberToLong using vim.buffers[%s]
3619 vim.buffers[[]]:TypeError:('expected int(), long() or something supporting coercing to long(), but got list',)
3620 vim.buffers[None]:TypeError:('expected int(), long() or something supporting coercing to long(), but got NoneType',)
3621 vim.buffers[-1]:ValueError:('number must be greater than zero',)
3622 vim.buffers[0]:ValueError:('number must be greater than zero',)
3623 <<< Finished
3624 > Current
3625 >> CurrentGetattr
3626 vim.current.xxx:AttributeError:('xxx',)
3627 >> CurrentSetattr
3628 vim.current.line = True:TypeError:('bad argument type for built-in operation',)
3629 vim.current.buffer = True:TypeError:('expected vim.Buffer object, but got bool',)
3630 vim.current.window = True:TypeError:('expected vim.Window object, but got bool',)
3631 vim.current.tabpage = True:TypeError:('expected vim.TabPage object, but got bool',)
3632 vim.current.xxx = True:AttributeError:('xxx',)
3633 END
3634
3635 call assert_equal(expected, getline(2, '$'))
3636 close!
3637endfunc
3638
3639" Test import
3640func Test_python_import()
3641 new
3642 py cb = vim.current.buffer
3643
3644 py << trim EOF
3645 sys.path.insert(0, os.path.join(os.getcwd(), 'python_before'))
3646 sys.path.append(os.path.join(os.getcwd(), 'python_after'))
3647 vim.options['rtp'] = os.getcwd().replace(',', '\\,').replace('\\', '\\\\')
3648 l = []
3649 def callback(path):
3650 l.append(path[-len('/testdir'):].replace(os.path.sep, '/'))
3651 vim.foreach_rtp(callback)
3652 cb.append(repr(l))
3653 del l
3654 def callback(path):
3655 return path[-len('/testdir'):].replace(os.path.sep, '/')
3656 cb.append(repr(vim.foreach_rtp(callback)))
3657 del callback
3658 from module import dir as d
3659 from modulex import ddir
3660 cb.append(d + ',' + ddir)
3661 import before
3662 cb.append(before.dir)
3663 import after
3664 cb.append(after.dir)
3665 import topmodule as tm
3666 import topmodule.submodule as tms
3667 import topmodule.submodule.subsubmodule.subsubsubmodule as tmsss
3668 cb.append(tm.__file__.replace('.pyc', '.py').replace(os.path.sep, '/')[-len('modulex/topmodule/__init__.py'):])
3669 cb.append(tms.__file__.replace('.pyc', '.py').replace(os.path.sep, '/')[-len('modulex/topmodule/submodule/__init__.py'):])
3670 cb.append(tmsss.__file__.replace('.pyc', '.py').replace(os.path.sep, '/')[-len('modulex/topmodule/submodule/subsubmodule/subsubsubmodule.py'):])
Bram Moolenaarab589462020-07-06 21:03:06 +02003671
Bram Moolenaar92fdd1e2020-07-03 18:00:05 +02003672 del before
3673 del after
3674 del d
3675 del ddir
3676 del tm
3677 del tms
3678 del tmsss
3679 EOF
3680
3681 let expected =<< trim END
3682 ['/testdir']
3683 '/testdir'
3684 2,xx
3685 before
3686 after
3687 pythonx/topmodule/__init__.py
3688 pythonx/topmodule/submodule/__init__.py
3689 pythonx/topmodule/submodule/subsubmodule/subsubsubmodule.py
3690 END
3691 call assert_equal(expected, getline(2, '$'))
3692 close!
Bram Moolenaarab589462020-07-06 21:03:06 +02003693
3694 " Try to import a non-existing moudle with a dot (.)
3695 call AssertException(['py import a.b.c'], 'ImportError:')
Bram Moolenaar92fdd1e2020-07-03 18:00:05 +02003696endfunc
3697
3698" Test exceptions
3699func Test_python_exception()
Bram Moolenaarab589462020-07-06 21:03:06 +02003700 func Exe(e)
Bram Moolenaar92fdd1e2020-07-03 18:00:05 +02003701 execute a:e
Bram Moolenaarab589462020-07-06 21:03:06 +02003702 endfunc
Bram Moolenaar92fdd1e2020-07-03 18:00:05 +02003703
3704 new
3705 py cb = vim.current.buffer
3706
3707 py << trim EOF
3708 Exe = vim.bindeval('function("Exe")')
3709 ee('vim.command("throw \'abcN\'")')
3710 ee('Exe("throw \'def\'")')
3711 ee('vim.eval("Exe(\'throw \'\'ghi\'\'\')")')
3712 ee('vim.eval("Exe(\'echoerr \'\'jkl\'\'\')")')
3713 ee('vim.eval("Exe(\'xxx_non_existent_command_xxx\')")')
3714 ee('vim.eval("xxx_unknown_function_xxx()")')
3715 ee('vim.bindeval("Exe(\'xxx_non_existent_command_xxx\')")')
3716 del Exe
3717 EOF
3718 delfunction Exe
3719
3720 let expected =<< trim END
3721 vim.command("throw 'abcN'"):error:('abcN',)
3722 Exe("throw 'def'"):error:('def',)
3723 vim.eval("Exe('throw ''ghi''')"):error:('ghi',)
3724 vim.eval("Exe('echoerr ''jkl''')"):error:('Vim(echoerr):jkl',)
3725 vim.eval("Exe('xxx_non_existent_command_xxx')"):error:('Vim:E492: Not an editor command: xxx_non_existent_command_xxx',)
3726 vim.eval("xxx_unknown_function_xxx()"):error:('Vim:E117: Unknown function: xxx_unknown_function_xxx',)
3727 vim.bindeval("Exe('xxx_non_existent_command_xxx')"):error:('Vim:E492: Not an editor command: xxx_non_existent_command_xxx',)
3728 END
3729 call assert_equal(expected, getline(2, '$'))
3730 close!
3731endfunc
3732
3733" Regression: interrupting vim.command propagates to next vim.command
3734func Test_python_keyboard_interrupt()
3735 new
3736 py cb = vim.current.buffer
3737 py << trim EOF
3738 def test_keyboard_interrupt():
3739 try:
3740 vim.command('while 1 | endwhile')
3741 except KeyboardInterrupt:
3742 cb.append('Caught KeyboardInterrupt')
3743 except Exception:
3744 cb.append('!!!!!!!! Caught exception: ' + emsg(sys.exc_info()))
3745 else:
3746 cb.append('!!!!!!!! No exception')
3747 try:
3748 vim.command('$ put =\'Running :put\'')
3749 except KeyboardInterrupt:
3750 cb.append('!!!!!!!! Caught KeyboardInterrupt')
3751 except Exception:
3752 cb.append('!!!!!!!! Caught exception: ' + emsg(sys.exc_info()))
3753 else:
3754 cb.append('No exception')
3755 EOF
3756
3757 debuggreedy
3758 call inputsave()
3759 call feedkeys("s\ns\ns\ns\nq\n")
3760 redir => output
3761 debug silent! py test_keyboard_interrupt()
3762 redir END
3763 0 debuggreedy
3764 call inputrestore()
3765 py del test_keyboard_interrupt
3766
3767 let expected =<< trim END
3768 Caught KeyboardInterrupt
3769 Running :put
3770 No exception
3771 END
3772 call assert_equal(expected, getline(2, '$'))
3773 call assert_equal('', output)
3774 close!
3775endfunc
3776
Bram Moolenaar6c2b7b82020-04-14 20:15:49 +02003777" vim: shiftwidth=2 sts=2 expandtab