blob: 066b4bd88f453669f6e9cbfa903ab0e56b4138f9 [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
Bram Moolenaar9b7bf9e2020-07-11 22:14:59 +020076 call assert_fails('pydo toupper(line)', 'E21:')
Bram Moolenaarab589462020-07-06 21:03:06 +020077 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))
Yegappan Lakshmanan611728f2021-05-24 15:15:47 +0200317 py vim.current.window.height = 3.2
318 call assert_equal(3, winheight(0))
Bram Moolenaarab589462020-07-06 21:03:06 +0200319
320 " Test for setting the window width
321 10vnew
322 py vim.current.window.width = 6
323 call assert_equal(6, winwidth(0))
324
325 " Try accessing a closed window
Bram Moolenaar92fdd1e2020-07-03 18:00:05 +0200326 py w = vim.current.window
Bram Moolenaarab589462020-07-06 21:03:06 +0200327 py wopts = w.options
Bram Moolenaar92fdd1e2020-07-03 18:00:05 +0200328 close
Bram Moolenaarab589462020-07-06 21:03:06 +0200329 " Access the attributes of a closed window
330 call AssertException(["let n = pyeval('w.number')"],
331 \ 'Vim(let):vim.error: attempt to refer to deleted window')
332 call AssertException(["py w.height = 5"],
333 \ 'Vim(python):vim.error: attempt to refer to deleted window')
334 call AssertException(["py vim.current.window = w"],
335 \ 'Vim(python):vim.error: attempt to refer to deleted window')
336 " Try to set one of the options of the closed window
Bram Moolenaarbb790dc2020-07-07 20:12:54 +0200337 " The following caused an ASAN failure
338 call AssertException(["py wopts['list'] = False"],
339 \ 'vim.error: attempt to refer to deleted window')
Bram Moolenaarab589462020-07-06 21:03:06 +0200340 call assert_match('<window object (deleted)', pyeval("repr(w)"))
341 %bw!
Bram Moolenaar92fdd1e2020-07-03 18:00:05 +0200342endfunc
343
344" Test for the python List object
345func Test_python_list()
346 let l = [1, 2]
347 py pl = vim.bindeval('l')
348 call assert_equal(['locked', '__members__'], pyeval('pl.__members__'))
349
Bram Moolenaarab589462020-07-06 21:03:06 +0200350 " Try to convert a null List
351 call AssertException(["py t = vim.eval('test_null_list()')"],
352 \ 'Vim(python):SystemError: error return without exception set')
353
354 " Try to convert a List with a null List item
355 call AssertException(["py t = vim.eval('[test_null_list()]')"],
356 \ 'Vim(python):SystemError: error return without exception set')
357
Bram Moolenaar64ffa9b2020-11-04 12:23:06 +0100358 " Try to bind a null List variable (works because an empty list is used)
Bram Moolenaarab589462020-07-06 21:03:06 +0200359 let cmds =<< trim END
360 let l = test_null_list()
361 py ll = vim.bindeval('l')
362 END
Bram Moolenaar64ffa9b2020-11-04 12:23:06 +0100363 call AssertException(cmds, '')
Bram Moolenaarab589462020-07-06 21:03:06 +0200364
Bram Moolenaar92fdd1e2020-07-03 18:00:05 +0200365 let l = []
366 py l = vim.bindeval('l')
367 py f = vim.bindeval('function("strlen")')
368 " Extending List directly with different types
369 py l.extend([1, "as'd", [1, 2, f, {'a': 1}]])
370 call assert_equal([1, "as'd", [1, 2, function("strlen"), {'a': 1}]], l)
371 call assert_equal([1, 2, function("strlen"), {'a': 1}], l[-1])
372 call assert_fails('echo l[-4]', 'E684:')
373
374 " List assignment
375 py l[0] = 0
376 call assert_equal([0, "as'd", [1, 2, function("strlen"), {'a': 1}]], l)
377 py l[-2] = f
378 call assert_equal([0, function("strlen"), [1, 2, function("strlen"), {'a': 1}]], l)
Bram Moolenaarab589462020-07-06 21:03:06 +0200379
380 " appending to a list
381 let l = [1, 2]
382 py ll = vim.bindeval('l')
383 py ll[2] = 8
384 call assert_equal([1, 2, 8], l)
385
386 " Using dict as an index
387 call AssertException(['py ll[{}] = 10'],
388 \ 'Vim(python):TypeError: index must be int or slice, not dict')
Bram Moolenaar92fdd1e2020-07-03 18:00:05 +0200389endfunc
390
391" Test for the python Dict object
392func Test_python_dict()
393 let d = {}
394 py pd = vim.bindeval('d')
395 call assert_equal(['locked', 'scope', '__members__'],
396 \ pyeval('pd.__members__'))
Bram Moolenaarab589462020-07-06 21:03:06 +0200397
398 " Try to convert a null Dict
399 call AssertException(["py t = vim.eval('test_null_dict()')"],
400 \ 'Vim(python):SystemError: error return without exception set')
401
402 " Try to convert a Dict with a null List value
403 call AssertException(["py t = vim.eval(\"{'a' : test_null_list()}\")"],
404 \ 'Vim(python):SystemError: error return without exception set')
405
406 " Try to convert a Dict with a null string key
407 py t = vim.eval("{test_null_string() : 10}")
408 call assert_fails("let d = pyeval('t')", 'E859:')
409
410 " Dict length
411 let d = {'a' : 10, 'b' : 20}
412 py d = vim.bindeval('d')
413 call assert_equal(2, pyeval('len(d)'))
414
Dominique Pelle923dce22021-11-21 11:36:04 +0000415 " Deleting a non-existing key
Bram Moolenaarab589462020-07-06 21:03:06 +0200416 call AssertException(["py del d['c']"], "Vim(python):KeyError: 'c'")
Bram Moolenaar92fdd1e2020-07-03 18:00:05 +0200417endfunc
418
419" Extending Dictionary directly with different types
420func Test_python_dict_extend()
421 let d = {}
422 func d.f()
423 return 1
424 endfunc
425
426 py f = vim.bindeval('function("strlen")')
427 py << trim EOF
428 d = vim.bindeval('d')
429 d['1'] = 'asd'
430 d.update() # Must not do anything, including throwing errors
431 d.update(b = [1, 2, f])
432 d.update((('-1', {'a': 1}),))
433 d.update({'0': -1})
434 dk = d.keys()
435 dv = d.values()
436 di = d.items()
437 cmpfun = lambda a, b: cmp(repr(a), repr(b))
438 dk.sort(cmpfun)
439 dv.sort(cmpfun)
440 di.sort(cmpfun)
441 EOF
442
Bram Moolenaarab589462020-07-06 21:03:06 +0200443 " Try extending a locked dictionary
444 lockvar d
445 call AssertException(["py d.update({'b' : 20})"],
446 \ 'Vim(python):vim.error: dictionary is locked')
447 unlockvar d
448
Bram Moolenaar92fdd1e2020-07-03 18:00:05 +0200449 call assert_equal(1, pyeval("d['f'](self={})"))
450 call assert_equal("['-1', '0', '1', 'b', 'f']", pyeval('repr(dk)'))
451 call assert_equal("['asd', -1L, <vim.Function '1'>, <vim.dictionary object at >, <vim.list object at >]", substitute(pyeval('repr(dv)'),'0x\x\+','','g'))
452 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'))
453 call assert_equal(['0', '1', 'b', 'f', '-1'], keys(d))
454 call assert_equal("[-1, 'asd', [1, 2, function('strlen')], function('1'), {'a': 1}]", string(values(d)))
455 py del dk
456 py del di
457 py del dv
458endfunc
459
460func Test_python_list_del_items()
461 " removing items with del
462 let l = [0, function("strlen"), [1, 2, function("strlen"), {'a': 1}]]
463 py l = vim.bindeval('l')
464 py del l[2]
465 call assert_equal("[0, function('strlen')]", string(l))
466
467 let l = range(8)
468 py l = vim.bindeval('l')
469 py del l[:3]
470 py del l[1:]
471 call assert_equal([3], l)
472
473 " removing items out of range: silently skip items that don't exist
474
475 " The following two ranges delete nothing as they match empty list:
476 let l = [0, 1, 2, 3]
477 py l = vim.bindeval('l')
478 py del l[2:1]
479 call assert_equal([0, 1, 2, 3], l)
480 py del l[2:2]
481 call assert_equal([0, 1, 2, 3], l)
482 py del l[2:3]
483 call assert_equal([0, 1, 3], l)
484
485 let l = [0, 1, 2, 3]
486 py l = vim.bindeval('l')
487 py del l[2:4]
488 call assert_equal([0, 1], l)
489
490 let l = [0, 1, 2, 3]
491 py l = vim.bindeval('l')
492 py del l[2:5]
493 call assert_equal([0, 1], l)
494
495 let l = [0, 1, 2, 3]
496 py l = vim.bindeval('l')
497 py del l[2:6]
498 call assert_equal([0, 1], l)
499
500 " The following two ranges delete nothing as they match empty list:
501 let l = [0, 1, 2, 3]
502 py l = vim.bindeval('l')
503 py del l[-1:2]
504 call assert_equal([0, 1, 2, 3], l)
505 py del l[-2:2]
506 call assert_equal([0, 1, 2, 3], l)
507 py del l[-3:2]
508 call assert_equal([0, 2, 3], l)
509
510 let l = [0, 1, 2, 3]
511 py l = vim.bindeval('l')
512 py del l[-4:2]
513 call assert_equal([2, 3], l)
514
515 let l = [0, 1, 2, 3]
516 py l = vim.bindeval('l')
517 py del l[-5:2]
518 call assert_equal([2, 3], l)
519
520 let l = [0, 1, 2, 3]
521 py l = vim.bindeval('l')
522 py del l[-6:2]
523 call assert_equal([2, 3], l)
524
525 let l = [0, 1, 2, 3]
526 py l = vim.bindeval('l')
527 py del l[::2]
528 call assert_equal([1, 3], l)
529
530 let l = [0, 1, 2, 3]
531 py l = vim.bindeval('l')
532 py del l[3:0:-2]
533 call assert_equal([0, 2], l)
534
535 let l = [0, 1, 2, 3]
536 py l = vim.bindeval('l')
537 py del l[2:4:-2]
538 let l = [0, 1, 2, 3]
539endfunc
540
541func Test_python_dict_del_items()
542 let d = eval("{'0' : -1, '1' : 'asd', 'b' : [1, 2, function('strlen')], 'f' : function('min'), '-1' : {'a': 1}}")
543 py d = vim.bindeval('d')
544 py del d['-1']
545 py del d['f']
546 call assert_equal([1, 2, function('strlen')], pyeval('d.get(''b'', 1)'))
547 call assert_equal([1, 2, function('strlen')], pyeval('d.pop(''b'')'))
548 call assert_equal(1, pyeval('d.get(''b'', 1)'))
549 call assert_equal('asd', pyeval('d.pop(''1'', 2)'))
550 call assert_equal(2, pyeval('d.pop(''1'', 2)'))
551 call assert_equal('True', pyeval('repr(d.has_key(''0''))'))
552 call assert_equal('False', pyeval('repr(d.has_key(''1''))'))
553 call assert_equal('True', pyeval('repr(''0'' in d)'))
554 call assert_equal('False', pyeval('repr(''1'' in d)'))
555 call assert_equal("['0']", pyeval('repr(list(iter(d)))'))
556 call assert_equal({'0' : -1}, d)
557 call assert_equal("('0', -1L)", pyeval('repr(d.popitem())'))
558 call assert_equal('None', pyeval('repr(d.get(''0''))'))
559 call assert_equal('[]', pyeval('repr(list(iter(d)))'))
560endfunc
561
562" Slice assignment to a list
563func Test_python_slice_assignment()
564 let l = [0, 1, 2, 3]
565 py l = vim.bindeval('l')
566 py l[0:0] = ['a']
567 call assert_equal(['a', 0, 1, 2, 3], l)
568
569 let l = [0, 1, 2, 3]
570 py l = vim.bindeval('l')
571 py l[1:2] = ['b']
572 call assert_equal([0, 'b', 2, 3], l)
573
574 let l = [0, 1, 2, 3]
575 py l = vim.bindeval('l')
576 py l[2:4] = ['c']
577 call assert_equal([0, 1, 'c'], l)
578
579 let l = [0, 1, 2, 3]
580 py l = vim.bindeval('l')
581 py l[4:4] = ['d']
582 call assert_equal([0, 1, 2, 3, 'd'], l)
583
584 let l = [0, 1, 2, 3]
585 py l = vim.bindeval('l')
586 py l[-1:2] = ['e']
587 call assert_equal([0, 1, 2, 'e', 3], l)
588
589 let l = [0, 1, 2, 3]
590 py l = vim.bindeval('l')
591 py l[-10:2] = ['f']
592 call assert_equal(['f', 2, 3], l)
593
594 let l = [0, 1, 2, 3]
595 py l = vim.bindeval('l')
596 py l[2:-10] = ['g']
597 call assert_equal([0, 1, 'g', 2, 3], l)
598
599 let l = []
600 py l = vim.bindeval('l')
601 py l[0:0] = ['h']
602 call assert_equal(['h'], l)
603
604 let l = range(8)
605 py l = vim.bindeval('l')
606 py l[2:6:2] = [10, 20]
607 call assert_equal([0, 1, 10, 3, 20, 5, 6, 7], l)
608
609 let l = range(8)
610 py l = vim.bindeval('l')
611 py l[6:2:-2] = [10, 20]
612 call assert_equal([0, 1, 2, 3, 20, 5, 10, 7], l)
613
614 let l = range(8)
615 py l = vim.bindeval('l')
616 py l[6:2] = ()
617 call assert_equal([0, 1, 2, 3, 4, 5, 6, 7], l)
618
619 let l = range(8)
620 py l = vim.bindeval('l')
621 py l[6:2:1] = ()
622 call assert_equal([0, 1, 2, 3, 4, 5, 6, 7], l)
623
624 let l = range(8)
625 py l = vim.bindeval('l')
626 py l[2:2:1] = ()
627 call assert_equal([0, 1, 2, 3, 4, 5, 6, 7], l)
Bram Moolenaar0ab55d62020-07-07 20:50:39 +0200628
629 call AssertException(["py x = l[10:11:0]"],
630 \ "Vim(python):ValueError: slice step cannot be zero")
Bram Moolenaar92fdd1e2020-07-03 18:00:05 +0200631endfunc
632
633" Locked variables
634func Test_python_lockedvar()
635 new
636 py cb = vim.current.buffer
637 let l = [0, 1, 2, 3]
638 py l = vim.bindeval('l')
639 lockvar! l
640 py << trim EOF
641 try:
642 l[2]='i'
643 except vim.error:
644 cb.append('l[2] threw vim.error: ' + emsg(sys.exc_info()))
645 EOF
646 call assert_equal(['', "l[2] threw vim.error: error:('list is locked',)"],
647 \ getline(1, '$'))
Bram Moolenaarab589462020-07-06 21:03:06 +0200648
649 " Try to concatenate a locked list
650 call AssertException(['py l += [4, 5]'],
651 \ 'Vim(python):vim.error: list is locked')
652
Bram Moolenaar92fdd1e2020-07-03 18:00:05 +0200653 call assert_equal([0, 1, 2, 3], l)
654 unlockvar! l
655 close!
656endfunc
657
658" Test for calling a function
659func Test_python_function_call()
660 func New(...)
Bram Moolenaareffb0cd2020-07-03 21:17:34 +0200661 return ['NewStart'] + a:000 + ['NewEnd']
Bram Moolenaar92fdd1e2020-07-03 18:00:05 +0200662 endfunc
663
664 func DictNew(...) dict
Bram Moolenaareffb0cd2020-07-03 21:17:34 +0200665 return ['DictNewStart'] + a:000 + ['DictNewEnd', self]
Bram Moolenaar92fdd1e2020-07-03 18:00:05 +0200666 endfunc
667
668 new
669 let l = [function('New'), function('DictNew')]
670 py l = vim.bindeval('l')
671 py l.extend(list(l[0](1, 2, 3)))
672 call assert_equal([function('New'), function('DictNew'), 'NewStart', 1, 2, 3, 'NewEnd'], l)
673 py l.extend(list(l[1](1, 2, 3, self={'a': 'b'})))
674 call assert_equal([function('New'), function('DictNew'), 'NewStart', 1, 2, 3, 'NewEnd', 'DictNewStart', 1, 2, 3, 'DictNewEnd', {'a': 'b'}], l)
675 py l.extend([l[0].name])
676 call assert_equal([function('New'), function('DictNew'), 'NewStart', 1, 2, 3, 'NewEnd', 'DictNewStart', 1, 2, 3, 'DictNewEnd', {'a': 'b'}, 'New'], l)
677 py ee('l[1](1, 2, 3)')
678 call assert_equal("l[1](1, 2, 3):error:('Vim:E725: Calling dict function without Dictionary: DictNew',)", getline(2))
679 %d
680 py f = l[0]
681 delfunction New
682 py ee('f(1, 2, 3)')
683 call assert_equal("f(1, 2, 3):error:('Vim:E117: Unknown function: New',)", getline(2))
684 close!
685 delfunction DictNew
686endfunc
687
688func Test_python_float()
Bram Moolenaar92fdd1e2020-07-03 18:00:05 +0200689 let l = [0.0]
690 py l = vim.bindeval('l')
691 py l.extend([0.0])
692 call assert_equal([0.0, 0.0], l)
693endfunc
694
695" Test for Dict key errors
696func Test_python_dict_key_error()
697 let messages = []
698 py << trim EOF
699 d = vim.bindeval('{}')
700 m = vim.bindeval('messages')
701 def em(expr, g=globals(), l=locals()):
702 try:
703 exec(expr, g, l)
704 except:
705 m.extend([sys.exc_type.__name__])
706
707 em('d["abc1"]')
708 em('d["abc1"]="\\0"')
709 em('d["abc1"]=vim')
710 em('d[""]=1')
711 em('d["a\\0b"]=1')
712 em('d[u"a\\0b"]=1')
713 em('d.pop("abc1")')
714 em('d.popitem()')
715 del em
716 del m
717 EOF
718
719 call assert_equal(['KeyError', 'TypeError', 'TypeError', 'ValueError',
720 \ 'TypeError', 'TypeError', 'KeyError', 'KeyError'], messages)
721 unlet messages
722endfunc
723
724" Test for locked and scope attributes
725func Test_python_lock_scope_attr()
726 let d = {} | let dl = {} | lockvar dl
727 let res = []
728 for s in split("d dl v: g:")
729 let name = tr(s, ':', 's')
730 execute 'py ' .. name .. ' = vim.bindeval("' .. s .. '")'
731 call add(res, s .. ' : ' .. join(map(['locked', 'scope'],
732 \ 'v:val .. ":" .. pyeval(name .. "." .. v:val)'), ';'))
733 endfor
734 call assert_equal(['d : locked:0;scope:0', 'dl : locked:1;scope:0',
735 \ 'v: : locked:2;scope:1', 'g: : locked:0;scope:2'], res)
736
737 silent! let d.abc2 = 1
738 silent! let dl.abc3 = 1
739 py d.locked = True
740 py dl.locked = False
741 silent! let d.def = 1
742 silent! let dl.def = 1
743 call assert_equal({'abc2': 1}, d)
744 call assert_equal({'def': 1}, dl)
745 unlet d dl
746
747 let l = [] | let ll = [] | lockvar ll
748 let res = []
749 for s in split("l ll")
750 let name = tr(s, ':', 's')
751 execute 'py ' .. name .. '=vim.bindeval("' .. s .. '")'
752 call add(res, s .. ' : locked:' .. pyeval(name .. '.locked'))
753 endfor
754 call assert_equal(['l : locked:0', 'll : locked:1'], res)
755
756 silent! call extend(l, [0])
757 silent! call extend(ll, [0])
758 py l.locked = True
759 py ll.locked = False
760 silent! call extend(l, [1])
761 silent! call extend(ll, [1])
762 call assert_equal([0], l)
763 call assert_equal([1], ll)
764 unlet l ll
Bram Moolenaarab589462020-07-06 21:03:06 +0200765
766 " Try changing an attribute of a fixed list
767 py a = vim.bindeval('v:argv')
768 call AssertException(['py a.locked = 0'],
769 \ 'Vim(python):TypeError: cannot modify fixed list')
Bram Moolenaar92fdd1e2020-07-03 18:00:05 +0200770endfunc
771
772" Test for pyeval()
773func Test_python_pyeval()
774 let l = pyeval('range(3)')
775 call assert_equal([0, 1, 2], l)
776
777 let d = pyeval('{"a": "b", "c": 1, "d": ["e"]}')
778 call assert_equal([['a', 'b'], ['c', 1], ['d', ['e']]], sort(items(d)))
779
780 let v:errmsg = ''
781 call assert_equal(v:none, pyeval('None'))
782 call assert_equal('', v:errmsg)
783
Bram Moolenaarab589462020-07-06 21:03:06 +0200784 py v = vim.eval('test_null_function()')
785 call assert_equal(v:none, pyeval('v'))
786
Bram Moolenaar73e28dc2022-09-17 21:08:33 +0100787 call assert_equal(0.0, pyeval('0.0'))
Bram Moolenaar92fdd1e2020-07-03 18:00:05 +0200788
Bram Moolenaarab589462020-07-06 21:03:06 +0200789 " Evaluate an invalid values
790 call AssertException(['let v = pyeval(''"\0"'')'], 'E859:')
791 call AssertException(['let v = pyeval(''{"\0" : 1}'')'], 'E859:')
792 call AssertException(['let v = pyeval("undefined_name")'],
793 \ "Vim(let):NameError: name 'undefined_name' is not defined")
794 call AssertException(['let v = pyeval("vim")'], 'E859:')
795endfunc
Bram Moolenaar92fdd1e2020-07-03 18:00:05 +0200796
Bram Moolenaarab589462020-07-06 21:03:06 +0200797" Test for vim.bindeval()
798func Test_python_vim_bindeval()
799 " Float
800 let f = 3.14
801 py f = vim.bindeval('f')
802 call assert_equal(3.14, pyeval('f'))
Bram Moolenaar92fdd1e2020-07-03 18:00:05 +0200803
Bram Moolenaarab589462020-07-06 21:03:06 +0200804 " Blob
805 let b = 0z12
806 py b = vim.bindeval('b')
807 call assert_equal("\x12", pyeval('b'))
Bram Moolenaar92fdd1e2020-07-03 18:00:05 +0200808
Bram Moolenaarab589462020-07-06 21:03:06 +0200809 " Bool
810 call assert_equal(1, pyeval("vim.bindeval('v:true')"))
811 call assert_equal(0, pyeval("vim.bindeval('v:false')"))
812 call assert_equal(v:none, pyeval("vim.bindeval('v:null')"))
813 call assert_equal(v:none, pyeval("vim.bindeval('v:none')"))
Bram Moolenaar0ab55d62020-07-07 20:50:39 +0200814
815 " channel/job
Dominique Pelle56c9fd02021-05-19 00:16:14 +0200816 if has('channel')
817 call assert_equal(v:none, pyeval("vim.bindeval('test_null_channel()')"))
818 endif
819 if has('job')
820 call assert_equal(v:none, pyeval("vim.bindeval('test_null_job()')"))
821 endif
Bram Moolenaar92fdd1e2020-07-03 18:00:05 +0200822endfunc
823
824" threading
825" Running pydo command (Test_pydo) before this test, stops the python thread
826" from running. So this test should be run before the pydo test
827func Test_aaa_python_threading()
828 let l = [0]
829 py l = vim.bindeval('l')
830 py << trim EOF
831 import threading
832 import time
833
834 class T(threading.Thread):
835 def __init__(self):
836 threading.Thread.__init__(self)
837 self.t = 0
838 self.running = True
839
840 def run(self):
841 while self.running:
842 self.t += 1
843 time.sleep(0.1)
844
845 t = T()
846 del T
847 t.start()
848 EOF
849
850 sleep 1
851 py t.running = False
852 py t.join()
853
854 " Check if the background thread is working. Count should be 10, but on a
855 " busy system (AppVeyor) it can be much lower.
856 py l[0] = t.t > 4
857 py del time
858 py del threading
859 py del t
860 call assert_equal([1], l)
861endfunc
862
863" settrace
864func Test_python_settrace()
865 let l = []
866 py l = vim.bindeval('l')
867 py << trim EOF
868 import sys
869
870 def traceit(frame, event, arg):
871 global l
872 if event == "line":
873 l.extend([frame.f_lineno])
874 return traceit
875
876 def trace_main():
877 for i in range(5):
878 pass
879 EOF
880 py sys.settrace(traceit)
881 py trace_main()
882 py sys.settrace(None)
883 py del traceit
884 py del trace_main
885 call assert_equal([1, 10, 11, 10, 11, 10, 11, 10, 11, 10, 11, 10, 1], l)
886endfunc
887
888" Slice
889func Test_python_list_slice()
890 py ll = vim.bindeval('[0, 1, 2, 3, 4, 5]')
891 py l = ll[:4]
892 call assert_equal([0, 1, 2, 3], pyeval('l'))
893 py l = ll[2:]
894 call assert_equal([2, 3, 4, 5], pyeval('l'))
895 py l = ll[:-4]
896 call assert_equal([0, 1], pyeval('l'))
897 py l = ll[-2:]
898 call assert_equal([4, 5], pyeval('l'))
899 py l = ll[2:4]
900 call assert_equal([2, 3], pyeval('l'))
901 py l = ll[4:2]
902 call assert_equal([], pyeval('l'))
903 py l = ll[-4:-2]
904 call assert_equal([2, 3], pyeval('l'))
905 py l = ll[-2:-4]
906 call assert_equal([], pyeval('l'))
907 py l = ll[:]
908 call assert_equal([0, 1, 2, 3, 4, 5], pyeval('l'))
909 py l = ll[0:6]
910 call assert_equal([0, 1, 2, 3, 4, 5], pyeval('l'))
911 py l = ll[-10:10]
912 call assert_equal([0, 1, 2, 3, 4, 5], pyeval('l'))
913 py l = ll[4:2:-1]
914 call assert_equal([4, 3], pyeval('l'))
915 py l = ll[::2]
916 call assert_equal([0, 2, 4], pyeval('l'))
917 py l = ll[4:2:1]
918 call assert_equal([], pyeval('l'))
Bram Moolenaarab589462020-07-06 21:03:06 +0200919
920 " Error case: Use an invalid index
921 call AssertException(['py ll[-10] = 5'], 'Vim(python):vim.error: internal error:')
922
923 " Use a step value of 0
924 call AssertException(['py ll[0:3:0] = [1, 2, 3]'],
925 \ 'Vim(python):ValueError: slice step cannot be zero')
926
927 " Error case: Invalid slice type
928 call AssertException(["py x = ll['abc']"],
929 \ 'Vim(python):TypeError: index must be int or slice, not str')
Bram Moolenaar92fdd1e2020-07-03 18:00:05 +0200930 py del l
Bram Moolenaarab589462020-07-06 21:03:06 +0200931
932 " Error case: List with a null list item
933 let l = [test_null_list()]
934 py ll = vim.bindeval('l')
935 call AssertException(["py x = ll[:]"],
936 \ 'Vim(python):SystemError: error return without exception set')
Bram Moolenaar92fdd1e2020-07-03 18:00:05 +0200937endfunc
938
939" Vars
940func Test_python_vars()
941 let g:foo = 'bac'
942 let w:abc3 = 'def'
943 let b:baz = 'bar'
944 let t:bar = 'jkl'
945 try
946 throw "Abc"
947 catch /Abc/
948 call assert_equal('Abc', pyeval('vim.vvars[''exception'']'))
949 endtry
950 call assert_equal('bac', pyeval('vim.vars[''foo'']'))
951 call assert_equal('def', pyeval('vim.current.window.vars[''abc3'']'))
952 call assert_equal('bar', pyeval('vim.current.buffer.vars[''baz'']'))
953 call assert_equal('jkl', pyeval('vim.current.tabpage.vars[''bar'']'))
954endfunc
955
956" Options
957" paste: boolean, global
958" previewheight number, global
959" operatorfunc: string, global
960" number: boolean, window-local
961" numberwidth: number, window-local
962" colorcolumn: string, window-local
963" statusline: string, window-local/global
964" autoindent: boolean, buffer-local
965" shiftwidth: number, buffer-local
966" omnifunc: string, buffer-local
967" preserveindent: boolean, buffer-local/global
968" path: string, buffer-local/global
969func Test_python_opts()
970 let g:res = []
971 let g:bufs = [bufnr('%')]
972 new
973 let g:bufs += [bufnr('%')]
974 vnew
975 let g:bufs += [bufnr('%')]
976 wincmd j
977 vnew
978 let g:bufs += [bufnr('%')]
979 wincmd l
980
981 func RecVars(opt)
982 let gval = string(eval('&g:' .. a:opt))
983 let wvals = join(map(range(1, 4),
984 \ 'v:val .. ":" .. string(getwinvar(v:val, "&" .. a:opt))'))
985 let bvals = join(map(copy(g:bufs),
986 \ 'v:val .. ":" .. string(getbufvar(v:val, "&" .. a:opt))'))
987 call add(g:res, ' G: ' .. gval)
988 call add(g:res, ' W: ' .. wvals)
989 call add(g:res, ' B: ' .. wvals)
990 endfunc
991
992 py << trim EOF
993 def e(s, g=globals(), l=locals()):
994 try:
995 exec(s, g, l)
996 except:
997 vim.command('return ' + repr(sys.exc_type.__name__))
998
999 def ev(s, g=globals(), l=locals()):
1000 try:
1001 return eval(s, g, l)
1002 except:
1003 vim.command('let exc=' + repr(sys.exc_type.__name__))
1004 return 0
1005 EOF
1006
1007 func E(s)
1008 python e(vim.eval('a:s'))
1009 endfunc
1010
1011 func Ev(s)
1012 let r = pyeval('ev(vim.eval("a:s"))')
1013 if exists('exc')
1014 throw exc
1015 endif
1016 return r
1017 endfunc
1018
1019 py gopts1 = vim.options
1020 py wopts1 = vim.windows[2].options
1021 py wopts2 = vim.windows[0].options
1022 py wopts3 = vim.windows[1].options
1023 py bopts1 = vim.buffers[vim.bindeval("g:bufs")[2]].options
1024 py bopts2 = vim.buffers[vim.bindeval("g:bufs")[1]].options
1025 py bopts3 = vim.buffers[vim.bindeval("g:bufs")[0]].options
1026 call add(g:res, 'wopts iters equal: ' ..
1027 \ pyeval('list(wopts1) == list(wopts2)'))
1028 call add(g:res, 'bopts iters equal: ' ..
1029 \ pyeval('list(bopts1) == list(bopts2)'))
1030 py gset = set(iter(gopts1))
1031 py wset = set(iter(wopts1))
1032 py bset = set(iter(bopts1))
1033
1034 set path=.,..,,
1035 let lst = []
1036 let lst += [['paste', 1, 0, 1, 2, 1, 1, 0]]
1037 let lst += [['previewheight', 5, 1, 6, 'a', 0, 1, 0]]
1038 let lst += [['operatorfunc', 'A', 'B', 'C', 2, 0, 1, 0]]
1039 let lst += [['number', 0, 1, 1, 0, 1, 0, 1]]
1040 let lst += [['numberwidth', 2, 3, 5, -100, 0, 0, 1]]
1041 let lst += [['colorcolumn', '+1', '+2', '+3', 'abc4', 0, 0, 1]]
1042 let lst += [['statusline', '1', '2', '4', 0, 0, 1, 1]]
1043 let lst += [['autoindent', 0, 1, 1, 2, 1, 0, 2]]
1044 let lst += [['shiftwidth', 0, 2, 1, 3, 0, 0, 2]]
1045 let lst += [['omnifunc', 'A', 'B', 'C', 1, 0, 0, 2]]
1046 let lst += [['preserveindent', 0, 1, 1, 2, 1, 1, 2]]
1047 let lst += [['path', '.,,', ',,', '.', 0, 0, 1, 2]]
1048 for [oname, oval1, oval2, oval3, invval, bool, global, local] in lst
1049 py oname = vim.eval('oname')
1050 py oval1 = vim.bindeval('oval1')
1051 py oval2 = vim.bindeval('oval2')
1052 py oval3 = vim.bindeval('oval3')
1053 if invval is 0 || invval is 1
1054 py invval = bool(vim.bindeval('invval'))
1055 else
1056 py invval = vim.bindeval('invval')
1057 endif
1058 if bool
1059 py oval1 = bool(oval1)
1060 py oval2 = bool(oval2)
1061 py oval3 = bool(oval3)
1062 endif
1063 call add(g:res, '>>> ' .. oname)
1064 call add(g:res, ' g/w/b:' .. pyeval('oname in gset') .. '/' ..
1065 \ pyeval('oname in wset') .. '/' .. pyeval('oname in bset'))
1066 call add(g:res, ' g/w/b (in):' .. pyeval('oname in gopts1') .. '/' ..
1067 \ pyeval('oname in wopts1') .. '/' .. pyeval('oname in bopts1'))
1068 for v in ['gopts1', 'wopts1', 'bopts1']
1069 try
1070 call add(g:res, ' p/' .. v .. ': ' .. Ev('repr(' .. v .. '[''' .. oname .. '''])'))
1071 catch
1072 call add(g:res, ' p/' .. v .. '! ' .. v:exception)
1073 endtry
1074 let r = E(v .. '[''' .. oname .. ''']=invval')
1075 if r isnot 0
1076 call add(g:res, ' inv: ' .. string(invval) .. '! ' .. r)
1077 endif
1078 for vv in (v is# 'gopts1' ? [v] : [v, v[:-2] .. '2', v[:-2] .. '3'])
1079 let val = substitute(vv, '^.opts', 'oval', '')
1080 let r = E(vv .. '[''' .. oname .. ''']=' .. val)
1081 if r isnot 0
1082 call add(g:res, ' ' .. vv .. '! ' .. r)
1083 endif
1084 endfor
1085 endfor
1086 call RecVars(oname)
1087 for v in ['wopts3', 'bopts3']
1088 let r = E('del ' .. v .. '["' .. oname .. '"]')
1089 if r isnot 0
1090 call add(g:res, ' del ' .. v .. '! ' .. r)
1091 endif
1092 endfor
1093 call RecVars(oname)
1094 endfor
1095 delfunction RecVars
1096 delfunction E
1097 delfunction Ev
1098 py del ev
1099 py del e
1100 only
1101 for buf in g:bufs[1:]
1102 execute 'bwipeout!' buf
1103 endfor
1104 py del gopts1
1105 py del wopts1
1106 py del wopts2
1107 py del wopts3
1108 py del bopts1
1109 py del bopts2
1110 py del bopts3
1111 py del oval1
1112 py del oval2
1113 py del oval3
1114 py del oname
1115 py del invval
1116
1117 let expected =<< trim END
1118 wopts iters equal: 1
1119 bopts iters equal: 1
1120 >>> paste
1121 g/w/b:1/0/0
1122 g/w/b (in):1/0/0
1123 p/gopts1: False
1124 p/wopts1! KeyError
1125 inv: 2! KeyError
1126 wopts1! KeyError
1127 wopts2! KeyError
1128 wopts3! KeyError
1129 p/bopts1! KeyError
1130 inv: 2! KeyError
1131 bopts1! KeyError
1132 bopts2! KeyError
1133 bopts3! KeyError
1134 G: 1
1135 W: 1:1 2:1 3:1 4:1
1136 B: 1:1 2:1 3:1 4:1
1137 del wopts3! KeyError
1138 del bopts3! KeyError
1139 G: 1
1140 W: 1:1 2:1 3:1 4:1
1141 B: 1:1 2:1 3:1 4:1
1142 >>> previewheight
1143 g/w/b:1/0/0
1144 g/w/b (in):1/0/0
1145 p/gopts1: 12
1146 inv: 'a'! TypeError
1147 p/wopts1! KeyError
1148 inv: 'a'! KeyError
1149 wopts1! KeyError
1150 wopts2! KeyError
1151 wopts3! KeyError
1152 p/bopts1! KeyError
1153 inv: 'a'! KeyError
1154 bopts1! KeyError
1155 bopts2! KeyError
1156 bopts3! KeyError
1157 G: 5
1158 W: 1:5 2:5 3:5 4:5
1159 B: 1:5 2:5 3:5 4:5
1160 del wopts3! KeyError
1161 del bopts3! KeyError
1162 G: 5
1163 W: 1:5 2:5 3:5 4:5
1164 B: 1:5 2:5 3:5 4:5
1165 >>> operatorfunc
1166 g/w/b:1/0/0
1167 g/w/b (in):1/0/0
1168 p/gopts1: ''
1169 inv: 2! TypeError
1170 p/wopts1! KeyError
1171 inv: 2! KeyError
1172 wopts1! KeyError
1173 wopts2! KeyError
1174 wopts3! KeyError
1175 p/bopts1! KeyError
1176 inv: 2! KeyError
1177 bopts1! KeyError
1178 bopts2! KeyError
1179 bopts3! KeyError
1180 G: 'A'
1181 W: 1:'A' 2:'A' 3:'A' 4:'A'
1182 B: 1:'A' 2:'A' 3:'A' 4:'A'
1183 del wopts3! KeyError
1184 del bopts3! KeyError
1185 G: 'A'
1186 W: 1:'A' 2:'A' 3:'A' 4:'A'
1187 B: 1:'A' 2:'A' 3:'A' 4:'A'
1188 >>> number
1189 g/w/b:0/1/0
1190 g/w/b (in):0/1/0
1191 p/gopts1! KeyError
1192 inv: 0! KeyError
1193 gopts1! KeyError
1194 p/wopts1: False
1195 p/bopts1! KeyError
1196 inv: 0! KeyError
1197 bopts1! KeyError
1198 bopts2! KeyError
1199 bopts3! KeyError
1200 G: 0
1201 W: 1:1 2:1 3:0 4:0
1202 B: 1:1 2:1 3:0 4:0
1203 del wopts3! ValueError
1204 del bopts3! KeyError
1205 G: 0
1206 W: 1:1 2:1 3:0 4:0
1207 B: 1:1 2:1 3:0 4:0
1208 >>> numberwidth
1209 g/w/b:0/1/0
1210 g/w/b (in):0/1/0
1211 p/gopts1! KeyError
1212 inv: -100! KeyError
1213 gopts1! KeyError
1214 p/wopts1: 4
1215 inv: -100! error
1216 p/bopts1! KeyError
1217 inv: -100! KeyError
1218 bopts1! KeyError
1219 bopts2! KeyError
1220 bopts3! KeyError
1221 G: 4
1222 W: 1:3 2:5 3:2 4:4
1223 B: 1:3 2:5 3:2 4:4
1224 del wopts3! ValueError
1225 del bopts3! KeyError
1226 G: 4
1227 W: 1:3 2:5 3:2 4:4
1228 B: 1:3 2:5 3:2 4:4
1229 >>> colorcolumn
1230 g/w/b:0/1/0
1231 g/w/b (in):0/1/0
1232 p/gopts1! KeyError
1233 inv: 'abc4'! KeyError
1234 gopts1! KeyError
1235 p/wopts1: ''
1236 inv: 'abc4'! error
1237 p/bopts1! KeyError
1238 inv: 'abc4'! KeyError
1239 bopts1! KeyError
1240 bopts2! KeyError
1241 bopts3! KeyError
1242 G: ''
1243 W: 1:'+2' 2:'+3' 3:'+1' 4:''
1244 B: 1:'+2' 2:'+3' 3:'+1' 4:''
1245 del wopts3! ValueError
1246 del bopts3! KeyError
1247 G: ''
1248 W: 1:'+2' 2:'+3' 3:'+1' 4:''
1249 B: 1:'+2' 2:'+3' 3:'+1' 4:''
1250 >>> statusline
1251 g/w/b:1/1/0
1252 g/w/b (in):1/1/0
1253 p/gopts1: ''
1254 inv: 0! TypeError
1255 p/wopts1: None
1256 inv: 0! TypeError
1257 p/bopts1! KeyError
1258 inv: 0! KeyError
1259 bopts1! KeyError
1260 bopts2! KeyError
1261 bopts3! KeyError
1262 G: '1'
1263 W: 1:'2' 2:'4' 3:'1' 4:'1'
1264 B: 1:'2' 2:'4' 3:'1' 4:'1'
1265 del bopts3! KeyError
1266 G: '1'
1267 W: 1:'2' 2:'1' 3:'1' 4:'1'
1268 B: 1:'2' 2:'1' 3:'1' 4:'1'
1269 >>> autoindent
1270 g/w/b:0/0/1
1271 g/w/b (in):0/0/1
1272 p/gopts1! KeyError
1273 inv: 2! KeyError
1274 gopts1! KeyError
1275 p/wopts1! KeyError
1276 inv: 2! KeyError
1277 wopts1! KeyError
1278 wopts2! KeyError
1279 wopts3! KeyError
1280 p/bopts1: False
1281 G: 0
1282 W: 1:0 2:1 3:0 4:1
1283 B: 1:0 2:1 3:0 4:1
1284 del wopts3! KeyError
1285 del bopts3! ValueError
1286 G: 0
1287 W: 1:0 2:1 3:0 4:1
1288 B: 1:0 2:1 3:0 4:1
1289 >>> shiftwidth
1290 g/w/b:0/0/1
1291 g/w/b (in):0/0/1
1292 p/gopts1! KeyError
1293 inv: 3! KeyError
1294 gopts1! KeyError
1295 p/wopts1! KeyError
1296 inv: 3! KeyError
1297 wopts1! KeyError
1298 wopts2! KeyError
1299 wopts3! KeyError
1300 p/bopts1: 8
1301 G: 8
1302 W: 1:0 2:2 3:8 4:1
1303 B: 1:0 2:2 3:8 4:1
1304 del wopts3! KeyError
1305 del bopts3! ValueError
1306 G: 8
1307 W: 1:0 2:2 3:8 4:1
1308 B: 1:0 2:2 3:8 4:1
1309 >>> omnifunc
1310 g/w/b:0/0/1
1311 g/w/b (in):0/0/1
1312 p/gopts1! KeyError
1313 inv: 1! KeyError
1314 gopts1! KeyError
1315 p/wopts1! KeyError
1316 inv: 1! KeyError
1317 wopts1! KeyError
1318 wopts2! KeyError
1319 wopts3! KeyError
1320 p/bopts1: ''
1321 inv: 1! TypeError
1322 G: ''
1323 W: 1:'A' 2:'B' 3:'' 4:'C'
1324 B: 1:'A' 2:'B' 3:'' 4:'C'
1325 del wopts3! KeyError
1326 del bopts3! ValueError
1327 G: ''
1328 W: 1:'A' 2:'B' 3:'' 4:'C'
1329 B: 1:'A' 2:'B' 3:'' 4:'C'
1330 >>> preserveindent
1331 g/w/b:0/0/1
1332 g/w/b (in):0/0/1
1333 p/gopts1! KeyError
1334 inv: 2! KeyError
1335 gopts1! KeyError
1336 p/wopts1! KeyError
1337 inv: 2! KeyError
1338 wopts1! KeyError
1339 wopts2! KeyError
1340 wopts3! KeyError
1341 p/bopts1: False
1342 G: 0
1343 W: 1:0 2:1 3:0 4:1
1344 B: 1:0 2:1 3:0 4:1
1345 del wopts3! KeyError
1346 del bopts3! ValueError
1347 G: 0
1348 W: 1:0 2:1 3:0 4:1
1349 B: 1:0 2:1 3:0 4:1
1350 >>> path
1351 g/w/b:1/0/1
1352 g/w/b (in):1/0/1
1353 p/gopts1: '.,..,,'
1354 inv: 0! TypeError
1355 p/wopts1! KeyError
1356 inv: 0! KeyError
1357 wopts1! KeyError
1358 wopts2! KeyError
1359 wopts3! KeyError
1360 p/bopts1: None
1361 inv: 0! TypeError
1362 G: '.,,'
1363 W: 1:'.,,' 2:',,' 3:'.,,' 4:'.'
1364 B: 1:'.,,' 2:',,' 3:'.,,' 4:'.'
1365 del wopts3! KeyError
1366 G: '.,,'
1367 W: 1:'.,,' 2:',,' 3:'.,,' 4:'.,,'
1368 B: 1:'.,,' 2:',,' 3:'.,,' 4:'.,,'
1369 END
1370
1371 call assert_equal(expected, g:res)
1372 unlet g:res
Bram Moolenaarab589462020-07-06 21:03:06 +02001373
1374 call assert_equal(0, pyeval("'' in vim.options"))
1375
1376 " use an empty key to index vim.options
1377 call AssertException(["let v = pyeval(\"vim.options['']\")"],
1378 \ 'Vim(let):ValueError: empty keys are not allowed')
1379 call AssertException(["py vim.current.window.options[''] = 0"],
1380 \ 'Vim(python):ValueError: empty keys are not allowed')
1381 call AssertException(["py vim.current.window.options[{}] = 0"],
1382 \ 'Vim(python):TypeError: expected str() or unicode() instance, but got dict')
1383
1384 " set one of the number options to a very large number
1385 let cmd = ["py vim.options['previewheight'] = 9999999999999999"]
1386 call AssertException(cmd, 'OverflowError:')
1387
1388 " unset a global-local string option
1389 call AssertException(["py del vim.options['errorformat']"],
1390 \ 'Vim(python):ValueError: unable to unset global option errorformat')
Bram Moolenaar92fdd1e2020-07-03 18:00:05 +02001391endfunc
1392
1393" Test for vim.buffer object
1394func Test_python_buffer()
1395 new
1396 call setline(1, "Hello\nWorld")
1397 call assert_fails("let x = pyeval('vim.current.buffer[0]')", 'E859:')
1398 %bw!
1399
1400 edit Xfile1
1401 let bnr1 = bufnr()
1402 py cb = vim.current.buffer
1403 vnew Xfile2
1404 let bnr2 = bufnr()
1405 call setline(1, ['First line', 'Second line', 'Third line'])
1406 py b = vim.current.buffer
1407 wincmd w
1408
Bram Moolenaarab589462020-07-06 21:03:06 +02001409 " Test for getting lines from the buffer using a slice
1410 call assert_equal(['First line'], pyeval('b[-10:1]'))
1411 call assert_equal(['Third line'], pyeval('b[2:10]'))
1412 call assert_equal([], pyeval('b[2:0]'))
1413 call assert_equal([], pyeval('b[10:12]'))
1414 call assert_equal([], pyeval('b[-10:-8]'))
Bram Moolenaar0ab55d62020-07-07 20:50:39 +02001415 call AssertException(["py x = b[0:3:0]"],
1416 \ "Vim(python):TypeError: sequence index must be integer, not 'slice'")
1417 call AssertException(["py b[0:3:0] = 'abc'"],
1418 \ "Vim(python):TypeError: sequence index must be integer, not 'slice'")
1419 call AssertException(["py x = b[{}]"],
1420 \ "Vim(python):TypeError: sequence index must be integer, not 'dict'")
1421 call AssertException(["py b[{}] = 'abc'"],
1422 \ "Vim(python):TypeError: sequence index must be integer, not 'dict'")
1423
1424 " Test for getting lines using a range
1425 call AssertException(["py x = b.range(0,3)[0:2:0]"],
1426 \ "Vim(python):TypeError: sequence index must be integer, not 'slice'")
1427 call AssertException(["py b.range(0,3)[0:2:0] = 'abc'"],
1428 \ "Vim(python):TypeError: sequence index must be integer, not 'slice'")
Bram Moolenaarab589462020-07-06 21:03:06 +02001429
Bram Moolenaar92fdd1e2020-07-03 18:00:05 +02001430 " Tests BufferAppend and BufferItem
1431 py cb.append(b[0])
1432 call assert_equal(['First line'], getbufline(bnr1, 2))
1433 %d
1434
Bram Moolenaarab589462020-07-06 21:03:06 +02001435 " Try to append using out-of-range line number
1436 call AssertException(["py b.append('abc', 10)"],
1437 \ 'Vim(python):IndexError: line number out of range')
1438
1439 " Append a non-string item
1440 call AssertException(["py b.append([22])"],
1441 \ 'Vim(python):TypeError: expected str() or unicode() instance, but got int')
1442
Bram Moolenaar92fdd1e2020-07-03 18:00:05 +02001443 " Tests BufferSlice and BufferAssSlice
1444 py cb.append('abc5') # Will be overwritten
1445 py cb[-1:] = b[:-2]
1446 call assert_equal(['First line'], getbufline(bnr1, 2))
1447 %d
1448
1449 " Test BufferLength and BufferAssSlice
1450 py cb.append('def') # Will not be overwritten
1451 py cb[len(cb):] = b[:]
1452 call assert_equal(['def', 'First line', 'Second line', 'Third line'],
1453 \ getbufline(bnr1, 2, '$'))
1454 %d
1455
1456 " Test BufferAssItem and BufferMark
1457 call setbufline(bnr1, 1, ['one', 'two', 'three'])
1458 call cursor(1, 3)
1459 normal ma
1460 py cb.append('ghi') # Will be overwritten
1461 py cb[-1] = repr((len(cb) - cb.mark('a')[0], cb.mark('a')[1]))
1462 call assert_equal(['(3, 2)'], getbufline(bnr1, 4))
1463 %d
1464
1465 " Test BufferRepr
1466 py cb.append(repr(cb) + repr(b))
1467 call assert_equal(['<buffer Xfile1><buffer Xfile2>'], getbufline(bnr1, 2))
1468 %d
1469
1470 " Modify foreign buffer
1471 py << trim EOF
1472 b.append('foo')
1473 b[0]='bar'
1474 b[0:0]=['baz']
1475 vim.command('call append("$", getbufline(%i, 1, "$"))' % b.number)
1476 EOF
1477 call assert_equal(['baz', 'bar', 'Second line', 'Third line', 'foo'],
1478 \ getbufline(bnr2, 1, '$'))
1479 %d
1480
1481 " Test assigning to name property
1482 augroup BUFS
Bram Moolenaareffb0cd2020-07-03 21:17:34 +02001483 autocmd BufFilePost * python cb.append(vim.eval('expand("<abuf>")') + ':BufFilePost:' + vim.eval('bufnr("%")'))
1484 autocmd BufFilePre * python cb.append(vim.eval('expand("<abuf>")') + ':BufFilePre:' + vim.eval('bufnr("%")'))
Bram Moolenaar92fdd1e2020-07-03 18:00:05 +02001485 augroup END
1486 py << trim EOF
1487 import os
1488 old_name = cb.name
1489 cb.name = 'foo'
1490 cb.append(cb.name[-11:].replace(os.path.sep, '/'))
1491 b.name = 'bar'
1492 cb.append(b.name[-11:].replace(os.path.sep, '/'))
1493 cb.name = old_name
1494 cb.append(cb.name[-14:].replace(os.path.sep, '/'))
1495 del old_name
1496 EOF
1497 call assert_equal([bnr1 .. ':BufFilePre:' .. bnr1,
1498 \ bnr1 .. ':BufFilePost:' .. bnr1,
1499 \ 'testdir/foo',
1500 \ bnr2 .. ':BufFilePre:' .. bnr2,
1501 \ bnr2 .. ':BufFilePost:' .. bnr2,
1502 \ 'testdir/bar',
1503 \ bnr1 .. ':BufFilePre:' .. bnr1,
1504 \ bnr1 .. ':BufFilePost:' .. bnr1,
1505 \ 'testdir/Xfile1'], getbufline(bnr1, 2, '$'))
1506 %d
1507
1508 " Test CheckBuffer
1509 py << trim EOF
1510 for _b in vim.buffers:
1511 if _b is not cb:
1512 vim.command('bwipeout! ' + str(_b.number))
1513 del _b
1514 cb.append('valid: b:%s, cb:%s' % (repr(b.valid), repr(cb.valid)))
1515 EOF
1516 call assert_equal('valid: b:False, cb:True', getline(2))
1517 %d
1518
1519 py << trim EOF
1520 for expr in ('b[1]','b[:] = ["A", "B"]','b[:]','b.append("abc6")', 'b.name = "!"'):
1521 try:
1522 exec(expr)
1523 except vim.error:
1524 pass
1525 else:
1526 # Usually a SEGV here
1527 # Should not happen in any case
1528 cb.append('No exception for ' + expr)
1529 vim.command('cd .')
1530 del b
1531 EOF
1532 call assert_equal([''], getline(1, '$'))
1533
Bram Moolenaarab589462020-07-06 21:03:06 +02001534 " Delete all the lines in a buffer
1535 call setline(1, ['a', 'b', 'c'])
1536 py vim.current.buffer[:] = []
1537 call assert_equal([''], getline(1, '$'))
1538
Bram Moolenaar0ab55d62020-07-07 20:50:39 +02001539 " Test for buffer marks
1540 call assert_equal(v:none, pyeval("vim.current.buffer.mark('r')"))
1541
Bram Moolenaarab589462020-07-06 21:03:06 +02001542 " Test for modifying a 'nomodifiable' buffer
1543 setlocal nomodifiable
1544 call AssertException(["py vim.current.buffer[0] = 'abc'"],
1545 \ "Vim(python):vim.error: Vim:E21: Cannot make changes, 'modifiable' is off")
1546 call AssertException(["py vim.current.buffer[0] = None"],
1547 \ "Vim(python):vim.error: Vim:E21: Cannot make changes, 'modifiable' is off")
1548 call AssertException(["py vim.current.buffer[:] = None"],
1549 \ "Vim(python):vim.error: Vim:E21: Cannot make changes, 'modifiable' is off")
1550 call AssertException(["py vim.current.buffer[:] = []"],
1551 \ "Vim(python):vim.error: Vim:E21: Cannot make changes, 'modifiable' is off")
1552 call AssertException(["py vim.current.buffer.append('abc')"],
1553 \ "Vim(python):vim.error: Vim:E21: Cannot make changes, 'modifiable' is off")
1554 call AssertException(["py vim.current.buffer.append([])"],
1555 \ "Vim(python):vim.error: Vim:E21: Cannot make changes, 'modifiable' is off")
1556 setlocal modifiable
1557
Bram Moolenaar92fdd1e2020-07-03 18:00:05 +02001558 augroup BUFS
Bram Moolenaareffb0cd2020-07-03 21:17:34 +02001559 autocmd!
Bram Moolenaar92fdd1e2020-07-03 18:00:05 +02001560 augroup END
1561 augroup! BUFS
1562 %bw!
Bram Moolenaarab589462020-07-06 21:03:06 +02001563
1564 " Range object for a deleted buffer
Bram Moolenaarb18b4962022-09-02 21:55:50 +01001565 new Xpbuffile
Bram Moolenaarab589462020-07-06 21:03:06 +02001566 call setline(1, ['one', 'two', 'three'])
1567 py b = vim.current.buffer
1568 py r = vim.current.buffer.range(0, 2)
Bram Moolenaarb18b4962022-09-02 21:55:50 +01001569 call assert_equal('<range Xpbuffile (0:2)>', pyeval('repr(r)'))
Bram Moolenaarab589462020-07-06 21:03:06 +02001570 %bw!
1571 call AssertException(['py r[:] = []'],
1572 \ 'Vim(python):vim.error: attempt to refer to deleted buffer')
1573 call assert_match('<buffer object (deleted)', pyeval('repr(b)'))
1574 call assert_match('<range object (for deleted buffer)', pyeval('repr(r)'))
1575 call AssertException(["let n = pyeval('len(r)')"],
1576 \ 'Vim(let):vim.error: attempt to refer to deleted buffer')
1577 call AssertException(["py r.append('abc')"],
1578 \ 'Vim(python):vim.error: attempt to refer to deleted buffer')
1579
1580 " object for a deleted buffer
1581 call AssertException(["py b[0] = 'one'"],
1582 \ 'Vim(python):vim.error: attempt to refer to deleted buffer')
1583 call AssertException(["py b.append('one')"],
1584 \ 'Vim(python):vim.error: attempt to refer to deleted buffer')
1585 call AssertException(["let n = pyeval('len(b)')"],
1586 \ 'Vim(let):vim.error: attempt to refer to deleted buffer')
1587 call AssertException(["py pos = b.mark('a')"],
1588 \ 'Vim(python):vim.error: attempt to refer to deleted buffer')
1589 call AssertException(["py vim.current.buffer = b"],
1590 \ 'Vim(python):vim.error: attempt to refer to deleted buffer')
1591 call AssertException(["py rn = b.range(0, 2)"],
1592 \ 'Vim(python):vim.error: attempt to refer to deleted buffer')
Bram Moolenaar92fdd1e2020-07-03 18:00:05 +02001593endfunc
1594
1595" Test vim.buffers object
1596func Test_python_buffers()
1597 %bw!
Bram Moolenaarb18b4962022-09-02 21:55:50 +01001598 edit Xpbuffile
Bram Moolenaar92fdd1e2020-07-03 18:00:05 +02001599 py cb = vim.current.buffer
1600 set hidden
1601 edit a
1602 buffer #
1603 edit b
1604 buffer #
1605 edit c
1606 buffer #
1607 py << trim EOF
1608 try:
1609 from __builtin__ import next
1610 except ImportError:
1611 next = lambda o: o.next()
1612 # Check GCing iterator that was not fully exhausted
1613 i = iter(vim.buffers)
1614 cb.append('i:' + str(next(i)))
1615 # and also check creating more than one iterator at a time
1616 i2 = iter(vim.buffers)
1617 cb.append('i2:' + str(next(i2)))
1618 cb.append('i:' + str(next(i)))
1619 # The following should trigger GC and not cause any problems
1620 del i
1621 del i2
1622 i3 = iter(vim.buffers)
1623 cb.append('i3:' + str(next(i3)))
1624 del i3
1625 EOF
Bram Moolenaarb18b4962022-09-02 21:55:50 +01001626 call assert_equal(['i:<buffer Xpbuffile>',
1627 \ 'i2:<buffer Xpbuffile>', 'i:<buffer a>', 'i3:<buffer Xpbuffile>'],
Bram Moolenaar92fdd1e2020-07-03 18:00:05 +02001628 \ getline(2, '$'))
1629 %d
1630
1631 py << trim EOF
1632 prevnum = 0
1633 for b in vim.buffers:
1634 # Check buffer order
1635 if prevnum >= b.number:
1636 cb.append('!!! Buffer numbers not in strictly ascending order')
1637 # Check indexing: vim.buffers[number].number == number
1638 cb.append(str(b.number) + ':' + repr(vim.buffers[b.number]) + \
1639 '=' + repr(b))
1640 prevnum = b.number
1641 del prevnum
1642
1643 cb.append(str(len(vim.buffers)))
1644 EOF
Bram Moolenaarb18b4962022-09-02 21:55:50 +01001645 call assert_equal([bufnr('Xpbuffile') .. ':<buffer Xpbuffile>=<buffer Xpbuffile>',
Bram Moolenaar92fdd1e2020-07-03 18:00:05 +02001646 \ bufnr('a') .. ':<buffer a>=<buffer a>',
1647 \ bufnr('b') .. ':<buffer b>=<buffer b>',
1648 \ bufnr('c') .. ':<buffer c>=<buffer c>', '4'], getline(2, '$'))
1649 %d
1650
1651 py << trim EOF
1652 bnums = list(map(lambda b: b.number, vim.buffers))[1:]
1653
1654 # Test wiping out buffer with existing iterator
1655 i4 = iter(vim.buffers)
1656 cb.append('i4:' + str(next(i4)))
1657 vim.command('bwipeout! ' + str(bnums.pop(0)))
1658 try:
1659 next(i4)
1660 except vim.error:
1661 pass
1662 else:
1663 cb.append('!!!! No vim.error')
1664 i4 = iter(vim.buffers)
1665 vim.command('bwipeout! ' + str(bnums.pop(-1)))
1666 vim.command('bwipeout! ' + str(bnums.pop(-1)))
1667 cb.append('i4:' + str(next(i4)))
1668 try:
1669 next(i4)
1670 except StopIteration:
1671 cb.append('StopIteration')
1672 del i4
1673 del bnums
1674 EOF
Bram Moolenaarb18b4962022-09-02 21:55:50 +01001675 call assert_equal(['i4:<buffer Xpbuffile>',
1676 \ 'i4:<buffer Xpbuffile>', 'StopIteration'], getline(2, '$'))
Bram Moolenaar92fdd1e2020-07-03 18:00:05 +02001677 %bw!
1678endfunc
1679
1680" Test vim.{tabpage,window}list and vim.{tabpage,window} objects
1681func Test_python_tabpage_window()
1682 %bw
Bram Moolenaarb18b4962022-09-02 21:55:50 +01001683 edit Xpbuffile
Bram Moolenaar92fdd1e2020-07-03 18:00:05 +02001684 py cb = vim.current.buffer
1685 tabnew 0
1686 tabnew 1
1687 vnew a.1
1688 tabnew 2
1689 vnew a.2
1690 vnew b.2
1691 vnew c.2
1692
Bram Moolenaarab589462020-07-06 21:03:06 +02001693 call assert_equal(4, pyeval('vim.current.window.tabpage.number'))
1694
Bram Moolenaar92fdd1e2020-07-03 18:00:05 +02001695 py << trim EOF
1696 cb.append('Number of tabs: ' + str(len(vim.tabpages)))
1697 cb.append('Current tab pages:')
1698 def W(w):
1699 if repr(w).find('(unknown)') != -1:
1700 return '<window object (unknown)>'
1701 else:
1702 return repr(w)
1703
1704 start = len(cb)
1705
1706 def Cursor(w):
1707 if w.buffer is cb:
1708 return repr((start - w.cursor[0], w.cursor[1]))
1709 else:
1710 return repr(w.cursor)
1711
1712 for t in vim.tabpages:
1713 cb.append(' ' + repr(t) + '(' + str(t.number) + ')' + ': ' + \
1714 str(len(t.windows)) + ' windows, current is ' + W(t.window))
1715 cb.append(' Windows:')
1716 for w in t.windows:
1717 cb.append(' ' + W(w) + '(' + str(w.number) + ')' + \
1718 ': displays buffer ' + repr(w.buffer) + \
1719 '; cursor is at ' + Cursor(w))
1720 # Other values depend on the size of the terminal, so they are checked
1721 # partly:
1722 for attr in ('height', 'row', 'width', 'col'):
1723 try:
1724 aval = getattr(w, attr)
1725 if type(aval) is not long:
1726 raise TypeError
1727 if aval < 0:
1728 raise ValueError
1729 except Exception:
1730 cb.append('!!!!!! Error while getting attribute ' + attr + \
1731 ': ' + sys.exc_type.__name__)
1732 del aval
1733 del attr
1734 w.cursor = (len(w.buffer), 0)
1735 del W
1736 del Cursor
1737 cb.append('Number of windows in current tab page: ' + \
1738 str(len(vim.windows)))
1739 if list(vim.windows) != list(vim.current.tabpage.windows):
1740 cb.append('!!!!!! Windows differ')
1741 EOF
1742
Bram Moolenaareffb0cd2020-07-03 21:17:34 +02001743 let expected =<< trim END
Bram Moolenaar92fdd1e2020-07-03 18:00:05 +02001744 Number of tabs: 4
1745 Current tab pages:
1746 <tabpage 0>(1): 1 windows, current is <window object (unknown)>
1747 Windows:
Bram Moolenaarb18b4962022-09-02 21:55:50 +01001748 <window object (unknown)>(1): displays buffer <buffer Xpbuffile>; cursor is at (2, 0)
Bram Moolenaar92fdd1e2020-07-03 18:00:05 +02001749 <tabpage 1>(2): 1 windows, current is <window object (unknown)>
1750 Windows:
1751 <window object (unknown)>(1): displays buffer <buffer 0>; cursor is at (1, 0)
1752 <tabpage 2>(3): 2 windows, current is <window object (unknown)>
1753 Windows:
1754 <window object (unknown)>(1): displays buffer <buffer a.1>; cursor is at (1, 0)
1755 <window object (unknown)>(2): displays buffer <buffer 1>; cursor is at (1, 0)
1756 <tabpage 3>(4): 4 windows, current is <window 0>
1757 Windows:
1758 <window 0>(1): displays buffer <buffer c.2>; cursor is at (1, 0)
1759 <window 1>(2): displays buffer <buffer b.2>; cursor is at (1, 0)
1760 <window 2>(3): displays buffer <buffer a.2>; cursor is at (1, 0)
1761 <window 3>(4): displays buffer <buffer 2>; cursor is at (1, 0)
1762 Number of windows in current tab page: 4
1763 END
Bram Moolenaarb18b4962022-09-02 21:55:50 +01001764 call assert_equal(expected, getbufline(bufnr('Xpbuffile'), 2, '$'))
Bram Moolenaar92fdd1e2020-07-03 18:00:05 +02001765 %bw!
1766endfunc
1767
1768" Test vim.current
1769func Test_python_vim_current()
1770 %bw
Bram Moolenaarb18b4962022-09-02 21:55:50 +01001771 edit Xpbuffile
Bram Moolenaar92fdd1e2020-07-03 18:00:05 +02001772 py cb = vim.current.buffer
1773 tabnew 0
1774 tabnew 1
1775 vnew a.1
1776 tabnew 2
1777 vnew a.2
1778 vnew b.2
1779 vnew c.2
1780
1781 py << trim EOF
1782 def H(o):
1783 return repr(o)
1784 cb.append('Current tab page: ' + repr(vim.current.tabpage))
1785 cb.append('Current window: ' + repr(vim.current.window) + ': ' + \
1786 H(vim.current.window) + ' is ' + H(vim.current.tabpage.window))
1787 cb.append('Current buffer: ' + repr(vim.current.buffer) + ': ' + \
1788 H(vim.current.buffer) + ' is ' + H(vim.current.window.buffer)+ \
1789 ' is ' + H(vim.current.tabpage.window.buffer))
1790 del H
1791 EOF
1792 let expected =<< trim END
1793 Current tab page: <tabpage 3>
1794 Current window: <window 0>: <window 0> is <window 0>
1795 Current buffer: <buffer c.2>: <buffer c.2> is <buffer c.2> is <buffer c.2>
1796 END
Bram Moolenaarb18b4962022-09-02 21:55:50 +01001797 call assert_equal(expected, getbufline(bufnr('Xpbuffile'), 2, '$'))
1798 call deletebufline(bufnr('Xpbuffile'), 1, '$')
Bram Moolenaar92fdd1e2020-07-03 18:00:05 +02001799
1800 " Assigning: fails
1801 py << trim EOF
1802 try:
1803 vim.current.window = vim.tabpages[0].window
1804 except ValueError:
1805 cb.append('ValueError at assigning foreign tab window')
1806
1807 for attr in ('window', 'tabpage', 'buffer'):
1808 try:
1809 setattr(vim.current, attr, None)
1810 except TypeError:
1811 cb.append('Type error at assigning None to vim.current.' + attr)
1812 del attr
1813 EOF
1814
1815 let expected =<< trim END
1816 ValueError at assigning foreign tab window
1817 Type error at assigning None to vim.current.window
1818 Type error at assigning None to vim.current.tabpage
1819 Type error at assigning None to vim.current.buffer
1820 END
Bram Moolenaarb18b4962022-09-02 21:55:50 +01001821 call assert_equal(expected, getbufline(bufnr('Xpbuffile'), 2, '$'))
1822 call deletebufline(bufnr('Xpbuffile'), 1, '$')
Bram Moolenaar92fdd1e2020-07-03 18:00:05 +02001823
Bram Moolenaarb18b4962022-09-02 21:55:50 +01001824 call setbufline(bufnr('Xpbuffile'), 1, 'python interface')
Bram Moolenaar92fdd1e2020-07-03 18:00:05 +02001825 py << trim EOF
1826 # Assigning: success
1827 vim.current.tabpage = vim.tabpages[-2]
1828 vim.current.buffer = cb
1829 vim.current.window = vim.windows[0]
1830 vim.current.window.cursor = (len(vim.current.buffer), 0)
1831 cb.append('Current tab page: ' + repr(vim.current.tabpage))
1832 cb.append('Current window: ' + repr(vim.current.window))
1833 cb.append('Current buffer: ' + repr(vim.current.buffer))
1834 cb.append('Current line: ' + repr(vim.current.line))
1835 EOF
1836
1837 let expected =<< trim END
1838 Current tab page: <tabpage 2>
1839 Current window: <window 0>
Bram Moolenaarb18b4962022-09-02 21:55:50 +01001840 Current buffer: <buffer Xpbuffile>
Bram Moolenaar92fdd1e2020-07-03 18:00:05 +02001841 Current line: 'python interface'
1842 END
Bram Moolenaarb18b4962022-09-02 21:55:50 +01001843 call assert_equal(expected, getbufline(bufnr('Xpbuffile'), 2, '$'))
Bram Moolenaarab589462020-07-06 21:03:06 +02001844 py vim.current.line = 'one line'
1845 call assert_equal('one line', getline('.'))
Bram Moolenaarb18b4962022-09-02 21:55:50 +01001846 call deletebufline(bufnr('Xpbuffile'), 1, '$')
Bram Moolenaar92fdd1e2020-07-03 18:00:05 +02001847
1848 py << trim EOF
1849 ws = list(vim.windows)
1850 ts = list(vim.tabpages)
1851 for b in vim.buffers:
1852 if b is not cb:
1853 vim.command('bwipeout! ' + str(b.number))
1854 del b
1855 cb.append('w.valid: ' + repr([w.valid for w in ws]))
1856 cb.append('t.valid: ' + repr([t.valid for t in ts]))
1857 del w
1858 del t
1859 del ts
1860 del ws
1861 EOF
1862 let expected =<< trim END
1863 w.valid: [True, False]
1864 t.valid: [True, False, True, False]
1865 END
Bram Moolenaarb18b4962022-09-02 21:55:50 +01001866 call assert_equal(expected, getbufline(bufnr('Xpbuffile'), 2, '$'))
Bram Moolenaar92fdd1e2020-07-03 18:00:05 +02001867 %bw!
1868endfunc
1869
1870" Test types
1871func Test_python_types()
1872 %d
1873 py cb = vim.current.buffer
1874 py << trim EOF
1875 for expr, attr in (
1876 ('vim.vars', 'Dictionary'),
1877 ('vim.options', 'Options'),
1878 ('vim.bindeval("{}")', 'Dictionary'),
1879 ('vim.bindeval("[]")', 'List'),
1880 ('vim.bindeval("function(\'tr\')")', 'Function'),
1881 ('vim.current.buffer', 'Buffer'),
1882 ('vim.current.range', 'Range'),
1883 ('vim.current.window', 'Window'),
1884 ('vim.current.tabpage', 'TabPage'),
1885 ):
1886 cb.append(expr + ':' + attr + ':' + \
1887 repr(type(eval(expr)) is getattr(vim, attr)))
1888 del expr
1889 del attr
1890 EOF
1891 let expected =<< trim END
1892 vim.vars:Dictionary:True
1893 vim.options:Options:True
1894 vim.bindeval("{}"):Dictionary:True
1895 vim.bindeval("[]"):List:True
1896 vim.bindeval("function('tr')"):Function:True
1897 vim.current.buffer:Buffer:True
1898 vim.current.range:Range:True
1899 vim.current.window:Window:True
1900 vim.current.tabpage:TabPage:True
1901 END
1902 call assert_equal(expected, getline(2, '$'))
1903endfunc
1904
1905" Test __dir__() method
1906func Test_python_dir_method()
1907 %d
1908 py cb = vim.current.buffer
1909 py << trim EOF
1910 for name, o in (
1911 ('current', vim.current),
1912 ('buffer', vim.current.buffer),
1913 ('window', vim.current.window),
1914 ('tabpage', vim.current.tabpage),
1915 ('range', vim.current.range),
1916 ('dictionary', vim.bindeval('{}')),
1917 ('list', vim.bindeval('[]')),
1918 ('function', vim.bindeval('function("tr")')),
1919 ('output', sys.stdout),
1920 ):
1921 cb.append(name + ':' + ','.join(dir(o)))
1922 del name
1923 del o
1924 EOF
1925 let expected =<< trim END
1926 current:__dir__,__members__,buffer,line,range,tabpage,window
1927 buffer:__dir__,__members__,append,mark,name,number,options,range,valid,vars
1928 window:__dir__,__members__,buffer,col,cursor,height,number,options,row,tabpage,valid,vars,width
1929 tabpage:__dir__,__members__,number,valid,vars,window,windows
1930 range:__dir__,__members__,append,end,start
1931 dictionary:__dir__,__members__,get,has_key,items,keys,locked,pop,popitem,scope,update,values
1932 list:__dir__,__members__,extend,locked
1933 function:__dir__,__members__,args,auto_rebind,self,softspace
1934 output:__dir__,__members__,close,closed,flush,isatty,readable,seekable,softspace,writable,write,writelines
1935 END
1936 call assert_equal(expected, getline(2, '$'))
1937endfunc
1938
1939" Test vim.*.__new__
1940func Test_python_new()
1941 call assert_equal({}, pyeval('vim.Dictionary({})'))
1942 call assert_equal({'a': 1}, pyeval('vim.Dictionary(a=1)'))
1943 call assert_equal({'a': 1}, pyeval('vim.Dictionary(((''a'', 1),))'))
1944 call assert_equal([], pyeval('vim.List()'))
1945 call assert_equal(['a', 'b', 'c', '7'], pyeval('vim.List(iter(''abc7''))'))
1946 call assert_equal(function('tr'), pyeval('vim.Function(''tr'')'))
1947 call assert_equal(function('tr', [123, 3, 4]),
1948 \ pyeval('vim.Function(''tr'', args=[123, 3, 4])'))
1949 call assert_equal(function('tr'), pyeval('vim.Function(''tr'', args=[])'))
1950 call assert_equal(function('tr', {}),
1951 \ pyeval('vim.Function(''tr'', self={})'))
1952 call assert_equal(function('tr', [123, 3, 4], {}),
1953 \ pyeval('vim.Function(''tr'', args=[123, 3, 4], self={})'))
1954 call assert_equal(function('tr'),
1955 \ pyeval('vim.Function(''tr'', auto_rebind=False)'))
1956 call assert_equal(function('tr', [123, 3, 4]),
1957 \ pyeval('vim.Function(''tr'', args=[123, 3, 4], auto_rebind=False)'))
1958 call assert_equal(function('tr'),
1959 \ pyeval('vim.Function(''tr'', args=[], auto_rebind=False)'))
1960 call assert_equal(function('tr', {}),
1961 \ pyeval('vim.Function(''tr'', self={}, auto_rebind=False)'))
1962 call assert_equal(function('tr', [123, 3, 4], {}),
1963 \ pyeval('vim.Function(''tr'', args=[123, 3, 4], self={}, auto_rebind=False)'))
1964endfunc
1965
1966" Test vim.Function
1967func Test_python_vim_func()
Bram Moolenaarab589462020-07-06 21:03:06 +02001968 func Args(...)
Bram Moolenaar92fdd1e2020-07-03 18:00:05 +02001969 return a:000
Bram Moolenaarab589462020-07-06 21:03:06 +02001970 endfunc
Bram Moolenaar92fdd1e2020-07-03 18:00:05 +02001971
Bram Moolenaarab589462020-07-06 21:03:06 +02001972 func SelfArgs(...) dict
Bram Moolenaar92fdd1e2020-07-03 18:00:05 +02001973 return [a:000, self]
Bram Moolenaarab589462020-07-06 21:03:06 +02001974 endfunc
Bram Moolenaar92fdd1e2020-07-03 18:00:05 +02001975
1976 " The following four lines should not crash
1977 let Pt = function('tr', [[]], {'l': []})
1978 py Pt = vim.bindeval('Pt')
1979 unlet Pt
1980 py del Pt
1981
Bram Moolenaarab589462020-07-06 21:03:06 +02001982 call assert_equal(3, pyeval('vim.strwidth("a\tb")'))
1983
Bram Moolenaar92fdd1e2020-07-03 18:00:05 +02001984 %bw!
1985 py cb = vim.current.buffer
1986 py << trim EOF
1987 def ecall(out_prefix, func, *args, **kwargs):
1988 line = out_prefix + ': '
1989 try:
1990 ret = func(*args, **kwargs)
1991 except Exception:
1992 line += '!exception: ' + emsg(sys.exc_info())
1993 else:
1994 line += '!result: ' + vim.Function('string')(ret)
1995 cb.append(line)
1996 a = vim.Function('Args')
1997 pa1 = vim.Function('Args', args=['abcArgsPA1'])
1998 pa2 = vim.Function('Args', args=[])
1999 pa3 = vim.Function('Args', args=['abcArgsPA3'], self={'abcSelfPA3': 'abcSelfPA3Val'})
2000 pa4 = vim.Function('Args', self={'abcSelfPA4': 'abcSelfPA4Val'})
2001 cb.append('a: ' + repr(a))
2002 cb.append('pa1: ' + repr(pa1))
2003 cb.append('pa2: ' + repr(pa2))
2004 cb.append('pa3: ' + repr(pa3))
2005 cb.append('pa4: ' + repr(pa4))
2006 sa = vim.Function('SelfArgs')
2007 psa1 = vim.Function('SelfArgs', args=['abcArgsPSA1'])
2008 psa2 = vim.Function('SelfArgs', args=[])
2009 psa3 = vim.Function('SelfArgs', args=['abcArgsPSA3'], self={'abcSelfPSA3': 'abcSelfPSA3Val'})
2010 psa4 = vim.Function('SelfArgs', self={'abcSelfPSA4': 'abcSelfPSA4Val'})
2011 psa5 = vim.Function('SelfArgs', self={'abcSelfPSA5': 'abcSelfPSA5Val'}, auto_rebind=0)
2012 psa6 = vim.Function('SelfArgs', args=['abcArgsPSA6'], self={'abcSelfPSA6': 'abcSelfPSA6Val'}, auto_rebind=())
2013 psa7 = vim.Function('SelfArgs', args=['abcArgsPSA7'], auto_rebind=[])
2014 psa8 = vim.Function('SelfArgs', auto_rebind=False)
2015 psa9 = vim.Function('SelfArgs', self={'abcSelfPSA9': 'abcSelfPSA9Val'}, auto_rebind=True)
2016 psaA = vim.Function('SelfArgs', args=['abcArgsPSAA'], self={'abcSelfPSAA': 'abcSelfPSAAVal'}, auto_rebind=1)
2017 psaB = vim.Function('SelfArgs', args=['abcArgsPSAB'], auto_rebind={'abcARPSAB': 'abcARPSABVal'})
2018 psaC = vim.Function('SelfArgs', auto_rebind=['abcARPSAC'])
2019 cb.append('sa: ' + repr(sa))
2020 cb.append('psa1: ' + repr(psa1))
2021 cb.append('psa2: ' + repr(psa2))
2022 cb.append('psa3: ' + repr(psa3))
2023 cb.append('psa4: ' + repr(psa4))
2024 cb.append('psa5: ' + repr(psa5))
2025 cb.append('psa6: ' + repr(psa6))
2026 cb.append('psa7: ' + repr(psa7))
2027 cb.append('psa8: ' + repr(psa8))
2028 cb.append('psa9: ' + repr(psa9))
2029 cb.append('psaA: ' + repr(psaA))
2030 cb.append('psaB: ' + repr(psaB))
2031 cb.append('psaC: ' + repr(psaC))
Bram Moolenaareffb0cd2020-07-03 21:17:34 +02002032
Bram Moolenaar92fdd1e2020-07-03 18:00:05 +02002033 psar = vim.Function('SelfArgs', args=[{'abcArgsPSAr': 'abcArgsPSArVal'}], self={'abcSelfPSAr': 'abcSelfPSArVal'})
2034 psar.args[0]['abcArgsPSAr2'] = [psar.self, psar.args[0]]
2035 psar.self['rec'] = psar
2036 psar.self['self'] = psar.self
2037 psar.self['args'] = psar.args
Bram Moolenaareffb0cd2020-07-03 21:17:34 +02002038
Bram Moolenaar92fdd1e2020-07-03 18:00:05 +02002039 try:
2040 cb.append('psar: ' + repr(psar))
2041 except Exception:
2042 cb.append('!!!!!!!! Caught exception: ' + emsg(sys.exc_info()))
2043 EOF
2044
2045 let expected =<< trim END
2046 a: <vim.Function 'Args'>
2047 pa1: <vim.Function 'Args', args=['abcArgsPA1']>
2048 pa2: <vim.Function 'Args'>
2049 pa3: <vim.Function 'Args', args=['abcArgsPA3'], self={'abcSelfPA3': 'abcSelfPA3Val'}>
2050 pa4: <vim.Function 'Args', self={'abcSelfPA4': 'abcSelfPA4Val'}>
2051 sa: <vim.Function 'SelfArgs'>
2052 psa1: <vim.Function 'SelfArgs', args=['abcArgsPSA1']>
2053 psa2: <vim.Function 'SelfArgs'>
2054 psa3: <vim.Function 'SelfArgs', args=['abcArgsPSA3'], self={'abcSelfPSA3': 'abcSelfPSA3Val'}>
2055 psa4: <vim.Function 'SelfArgs', self={'abcSelfPSA4': 'abcSelfPSA4Val'}>
2056 psa5: <vim.Function 'SelfArgs', self={'abcSelfPSA5': 'abcSelfPSA5Val'}>
2057 psa6: <vim.Function 'SelfArgs', args=['abcArgsPSA6'], self={'abcSelfPSA6': 'abcSelfPSA6Val'}>
2058 psa7: <vim.Function 'SelfArgs', args=['abcArgsPSA7']>
2059 psa8: <vim.Function 'SelfArgs'>
2060 psa9: <vim.Function 'SelfArgs', self={'abcSelfPSA9': 'abcSelfPSA9Val'}, auto_rebind=True>
2061 psaA: <vim.Function 'SelfArgs', args=['abcArgsPSAA'], self={'abcSelfPSAA': 'abcSelfPSAAVal'}, auto_rebind=True>
2062 psaB: <vim.Function 'SelfArgs', args=['abcArgsPSAB']>
2063 psaC: <vim.Function 'SelfArgs'>
2064 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'}]}>
2065 END
2066 call assert_equal(expected, getline(2, '$'))
2067 %d
2068
2069 call assert_equal(function('Args'), pyeval('a'))
2070 call assert_equal(function('Args', ['abcArgsPA1']), pyeval('pa1'))
2071 call assert_equal(function('Args'), pyeval('pa2'))
2072 call assert_equal(function('Args', ['abcArgsPA3'], {'abcSelfPA3': 'abcSelfPA3Val'}), pyeval('pa3'))
2073 call assert_equal(function('Args', {'abcSelfPA4': 'abcSelfPA4Val'}), pyeval('pa4'))
2074 call assert_equal(function('SelfArgs'), pyeval('sa'))
2075 call assert_equal(function('SelfArgs', ['abcArgsPSA1']), pyeval('psa1'))
2076 call assert_equal(function('SelfArgs'), pyeval('psa2'))
2077 call assert_equal(function('SelfArgs', ['abcArgsPSA3'], {'abcSelfPSA3': 'abcSelfPSA3Val'}), pyeval('psa3'))
2078 call assert_equal(function('SelfArgs', {'abcSelfPSA4': 'abcSelfPSA4Val'}), pyeval('psa4'))
2079 call assert_equal(function('SelfArgs', {'abcSelfPSA5': 'abcSelfPSA5Val'}), pyeval('psa5'))
2080 call assert_equal(function('SelfArgs', ['abcArgsPSA6'], {'abcSelfPSA6': 'abcSelfPSA6Val'}), pyeval('psa6'))
2081 call assert_equal(function('SelfArgs', ['abcArgsPSA7']), pyeval('psa7'))
2082 call assert_equal(function('SelfArgs'), pyeval('psa8'))
2083 call assert_equal(function('SelfArgs', {'abcSelfPSA9': 'abcSelfPSA9Val'}), pyeval('psa9'))
2084 call assert_equal(function('SelfArgs', ['abcArgsPSAA'], {'abcSelfPSAA': 'abcSelfPSAAVal'}), pyeval('psaA'))
2085 call assert_equal(function('SelfArgs', ['abcArgsPSAB']), pyeval('psaB'))
2086 call assert_equal(function('SelfArgs'), pyeval('psaC'))
2087
2088 let res = []
2089 for v in ['sa', 'psa1', 'psa2', 'psa3', 'psa4', 'psa5', 'psa6', 'psa7',
2090 \ 'psa8', 'psa9', 'psaA', 'psaB', 'psaC']
2091 let d = {'f': pyeval(v)}
2092 call add(res, 'd.' .. v .. '(): ' .. string(d.f()))
2093 endfor
2094
2095 let expected =<< trim END
2096 d.sa(): [[], {'f': function('SelfArgs')}]
2097 d.psa1(): [['abcArgsPSA1'], {'f': function('SelfArgs', ['abcArgsPSA1'])}]
2098 d.psa2(): [[], {'f': function('SelfArgs')}]
2099 d.psa3(): [['abcArgsPSA3'], {'abcSelfPSA3': 'abcSelfPSA3Val'}]
2100 d.psa4(): [[], {'abcSelfPSA4': 'abcSelfPSA4Val'}]
2101 d.psa5(): [[], {'abcSelfPSA5': 'abcSelfPSA5Val'}]
2102 d.psa6(): [['abcArgsPSA6'], {'abcSelfPSA6': 'abcSelfPSA6Val'}]
2103 d.psa7(): [['abcArgsPSA7'], {'f': function('SelfArgs', ['abcArgsPSA7'])}]
2104 d.psa8(): [[], {'f': function('SelfArgs')}]
2105 d.psa9(): [[], {'f': function('SelfArgs', {'abcSelfPSA9': 'abcSelfPSA9Val'})}]
2106 d.psaA(): [['abcArgsPSAA'], {'f': function('SelfArgs', ['abcArgsPSAA'], {'abcSelfPSAA': 'abcSelfPSAAVal'})}]
2107 d.psaB(): [['abcArgsPSAB'], {'f': function('SelfArgs', ['abcArgsPSAB'])}]
2108 d.psaC(): [[], {'f': function('SelfArgs')}]
2109 END
2110 call assert_equal(expected, res)
2111
2112 py ecall('a()', a, )
2113 py ecall('pa1()', pa1, )
2114 py ecall('pa2()', pa2, )
2115 py ecall('pa3()', pa3, )
2116 py ecall('pa4()', pa4, )
2117 py ecall('sa()', sa, )
2118 py ecall('psa1()', psa1, )
2119 py ecall('psa2()', psa2, )
2120 py ecall('psa3()', psa3, )
2121 py ecall('psa4()', psa4, )
2122
2123 py ecall('a(42, 43)', a, 42, 43)
2124 py ecall('pa1(42, 43)', pa1, 42, 43)
2125 py ecall('pa2(42, 43)', pa2, 42, 43)
2126 py ecall('pa3(42, 43)', pa3, 42, 43)
2127 py ecall('pa4(42, 43)', pa4, 42, 43)
2128 py ecall('sa(42, 43)', sa, 42, 43)
2129 py ecall('psa1(42, 43)', psa1, 42, 43)
2130 py ecall('psa2(42, 43)', psa2, 42, 43)
2131 py ecall('psa3(42, 43)', psa3, 42, 43)
2132 py ecall('psa4(42, 43)', psa4, 42, 43)
2133
2134 py ecall('a(42, self={"20": 1})', a, 42, self={'20': 1})
2135 py ecall('pa1(42, self={"20": 1})', pa1, 42, self={'20': 1})
2136 py ecall('pa2(42, self={"20": 1})', pa2, 42, self={'20': 1})
2137 py ecall('pa3(42, self={"20": 1})', pa3, 42, self={'20': 1})
2138 py ecall('pa4(42, self={"20": 1})', pa4, 42, self={'20': 1})
2139 py ecall('sa(42, self={"20": 1})', sa, 42, self={'20': 1})
2140 py ecall('psa1(42, self={"20": 1})', psa1, 42, self={'20': 1})
2141 py ecall('psa2(42, self={"20": 1})', psa2, 42, self={'20': 1})
2142 py ecall('psa3(42, self={"20": 1})', psa3, 42, self={'20': 1})
2143 py ecall('psa4(42, self={"20": 1})', psa4, 42, self={'20': 1})
2144
2145 py ecall('a(self={"20": 1})', a, self={'20': 1})
2146 py ecall('pa1(self={"20": 1})', pa1, self={'20': 1})
2147 py ecall('pa2(self={"20": 1})', pa2, self={'20': 1})
2148 py ecall('pa3(self={"20": 1})', pa3, self={'20': 1})
2149 py ecall('pa4(self={"20": 1})', pa4, self={'20': 1})
2150 py ecall('sa(self={"20": 1})', sa, self={'20': 1})
2151 py ecall('psa1(self={"20": 1})', psa1, self={'20': 1})
2152 py ecall('psa2(self={"20": 1})', psa2, self={'20': 1})
2153 py ecall('psa3(self={"20": 1})', psa3, self={'20': 1})
2154 py ecall('psa4(self={"20": 1})', psa4, self={'20': 1})
2155
2156 py << trim EOF
2157 def s(v):
2158 if v is None:
2159 return repr(v)
2160 else:
2161 return vim.Function('string')(v)
Bram Moolenaareffb0cd2020-07-03 21:17:34 +02002162
Bram Moolenaar92fdd1e2020-07-03 18:00:05 +02002163 cb.append('a.args: ' + s(a.args))
2164 cb.append('pa1.args: ' + s(pa1.args))
2165 cb.append('pa2.args: ' + s(pa2.args))
2166 cb.append('pa3.args: ' + s(pa3.args))
2167 cb.append('pa4.args: ' + s(pa4.args))
2168 cb.append('sa.args: ' + s(sa.args))
2169 cb.append('psa1.args: ' + s(psa1.args))
2170 cb.append('psa2.args: ' + s(psa2.args))
2171 cb.append('psa3.args: ' + s(psa3.args))
2172 cb.append('psa4.args: ' + s(psa4.args))
Bram Moolenaareffb0cd2020-07-03 21:17:34 +02002173
Bram Moolenaar92fdd1e2020-07-03 18:00:05 +02002174 cb.append('a.self: ' + s(a.self))
2175 cb.append('pa1.self: ' + s(pa1.self))
2176 cb.append('pa2.self: ' + s(pa2.self))
2177 cb.append('pa3.self: ' + s(pa3.self))
2178 cb.append('pa4.self: ' + s(pa4.self))
2179 cb.append('sa.self: ' + s(sa.self))
2180 cb.append('psa1.self: ' + s(psa1.self))
2181 cb.append('psa2.self: ' + s(psa2.self))
2182 cb.append('psa3.self: ' + s(psa3.self))
2183 cb.append('psa4.self: ' + s(psa4.self))
Bram Moolenaareffb0cd2020-07-03 21:17:34 +02002184
Bram Moolenaar92fdd1e2020-07-03 18:00:05 +02002185 cb.append('a.name: ' + s(a.name))
2186 cb.append('pa1.name: ' + s(pa1.name))
2187 cb.append('pa2.name: ' + s(pa2.name))
2188 cb.append('pa3.name: ' + s(pa3.name))
2189 cb.append('pa4.name: ' + s(pa4.name))
2190 cb.append('sa.name: ' + s(sa.name))
2191 cb.append('psa1.name: ' + s(psa1.name))
2192 cb.append('psa2.name: ' + s(psa2.name))
2193 cb.append('psa3.name: ' + s(psa3.name))
2194 cb.append('psa4.name: ' + s(psa4.name))
Bram Moolenaareffb0cd2020-07-03 21:17:34 +02002195
Bram Moolenaar92fdd1e2020-07-03 18:00:05 +02002196 cb.append('a.auto_rebind: ' + s(a.auto_rebind))
2197 cb.append('pa1.auto_rebind: ' + s(pa1.auto_rebind))
2198 cb.append('pa2.auto_rebind: ' + s(pa2.auto_rebind))
2199 cb.append('pa3.auto_rebind: ' + s(pa3.auto_rebind))
2200 cb.append('pa4.auto_rebind: ' + s(pa4.auto_rebind))
2201 cb.append('sa.auto_rebind: ' + s(sa.auto_rebind))
2202 cb.append('psa1.auto_rebind: ' + s(psa1.auto_rebind))
2203 cb.append('psa2.auto_rebind: ' + s(psa2.auto_rebind))
2204 cb.append('psa3.auto_rebind: ' + s(psa3.auto_rebind))
2205 cb.append('psa4.auto_rebind: ' + s(psa4.auto_rebind))
2206 cb.append('psa5.auto_rebind: ' + s(psa5.auto_rebind))
2207 cb.append('psa6.auto_rebind: ' + s(psa6.auto_rebind))
2208 cb.append('psa7.auto_rebind: ' + s(psa7.auto_rebind))
2209 cb.append('psa8.auto_rebind: ' + s(psa8.auto_rebind))
2210 cb.append('psa9.auto_rebind: ' + s(psa9.auto_rebind))
2211 cb.append('psaA.auto_rebind: ' + s(psaA.auto_rebind))
2212 cb.append('psaB.auto_rebind: ' + s(psaB.auto_rebind))
2213 cb.append('psaC.auto_rebind: ' + s(psaC.auto_rebind))
Bram Moolenaareffb0cd2020-07-03 21:17:34 +02002214
Bram Moolenaar92fdd1e2020-07-03 18:00:05 +02002215 del s
Bram Moolenaareffb0cd2020-07-03 21:17:34 +02002216
Bram Moolenaar92fdd1e2020-07-03 18:00:05 +02002217 del a
2218 del pa1
2219 del pa2
2220 del pa3
2221 del pa4
2222 del sa
2223 del psa1
2224 del psa2
2225 del psa3
2226 del psa4
2227 del psa5
2228 del psa6
2229 del psa7
2230 del psa8
2231 del psa9
2232 del psaA
2233 del psaB
2234 del psaC
2235 del psar
Bram Moolenaareffb0cd2020-07-03 21:17:34 +02002236
Bram Moolenaar92fdd1e2020-07-03 18:00:05 +02002237 del ecall
2238 EOF
2239
2240 let expected =<< trim END
2241 a(): !result: []
2242 pa1(): !result: ['abcArgsPA1']
2243 pa2(): !result: []
2244 pa3(): !result: ['abcArgsPA3']
2245 pa4(): !result: []
2246 sa(): !exception: error:('Vim:E725: Calling dict function without Dictionary: SelfArgs',)
2247 psa1(): !exception: error:('Vim:E725: Calling dict function without Dictionary: SelfArgs',)
2248 psa2(): !exception: error:('Vim:E725: Calling dict function without Dictionary: SelfArgs',)
2249 psa3(): !result: [['abcArgsPSA3'], {'abcSelfPSA3': 'abcSelfPSA3Val'}]
2250 psa4(): !result: [[], {'abcSelfPSA4': 'abcSelfPSA4Val'}]
2251 a(42, 43): !result: [42, 43]
2252 pa1(42, 43): !result: ['abcArgsPA1', 42, 43]
2253 pa2(42, 43): !result: [42, 43]
2254 pa3(42, 43): !result: ['abcArgsPA3', 42, 43]
2255 pa4(42, 43): !result: [42, 43]
2256 sa(42, 43): !exception: error:('Vim:E725: Calling dict function without Dictionary: SelfArgs',)
2257 psa1(42, 43): !exception: error:('Vim:E725: Calling dict function without Dictionary: SelfArgs',)
2258 psa2(42, 43): !exception: error:('Vim:E725: Calling dict function without Dictionary: SelfArgs',)
2259 psa3(42, 43): !result: [['abcArgsPSA3', 42, 43], {'abcSelfPSA3': 'abcSelfPSA3Val'}]
2260 psa4(42, 43): !result: [[42, 43], {'abcSelfPSA4': 'abcSelfPSA4Val'}]
2261 a(42, self={"20": 1}): !result: [42]
2262 pa1(42, self={"20": 1}): !result: ['abcArgsPA1', 42]
2263 pa2(42, self={"20": 1}): !result: [42]
2264 pa3(42, self={"20": 1}): !result: ['abcArgsPA3', 42]
2265 pa4(42, self={"20": 1}): !result: [42]
2266 sa(42, self={"20": 1}): !result: [[42], {'20': 1}]
2267 psa1(42, self={"20": 1}): !result: [['abcArgsPSA1', 42], {'20': 1}]
2268 psa2(42, self={"20": 1}): !result: [[42], {'20': 1}]
2269 psa3(42, self={"20": 1}): !result: [['abcArgsPSA3', 42], {'20': 1}]
2270 psa4(42, self={"20": 1}): !result: [[42], {'20': 1}]
2271 a(self={"20": 1}): !result: []
2272 pa1(self={"20": 1}): !result: ['abcArgsPA1']
2273 pa2(self={"20": 1}): !result: []
2274 pa3(self={"20": 1}): !result: ['abcArgsPA3']
2275 pa4(self={"20": 1}): !result: []
2276 sa(self={"20": 1}): !result: [[], {'20': 1}]
2277 psa1(self={"20": 1}): !result: [['abcArgsPSA1'], {'20': 1}]
2278 psa2(self={"20": 1}): !result: [[], {'20': 1}]
2279 psa3(self={"20": 1}): !result: [['abcArgsPSA3'], {'20': 1}]
2280 psa4(self={"20": 1}): !result: [[], {'20': 1}]
2281 a.args: None
2282 pa1.args: ['abcArgsPA1']
2283 pa2.args: None
2284 pa3.args: ['abcArgsPA3']
2285 pa4.args: None
2286 sa.args: None
2287 psa1.args: ['abcArgsPSA1']
2288 psa2.args: None
2289 psa3.args: ['abcArgsPSA3']
2290 psa4.args: None
2291 a.self: None
2292 pa1.self: None
2293 pa2.self: None
2294 pa3.self: {'abcSelfPA3': 'abcSelfPA3Val'}
2295 pa4.self: {'abcSelfPA4': 'abcSelfPA4Val'}
2296 sa.self: None
2297 psa1.self: None
2298 psa2.self: None
2299 psa3.self: {'abcSelfPSA3': 'abcSelfPSA3Val'}
2300 psa4.self: {'abcSelfPSA4': 'abcSelfPSA4Val'}
2301 a.name: 'Args'
2302 pa1.name: 'Args'
2303 pa2.name: 'Args'
2304 pa3.name: 'Args'
2305 pa4.name: 'Args'
2306 sa.name: 'SelfArgs'
2307 psa1.name: 'SelfArgs'
2308 psa2.name: 'SelfArgs'
2309 psa3.name: 'SelfArgs'
2310 psa4.name: 'SelfArgs'
2311 a.auto_rebind: 1
2312 pa1.auto_rebind: 1
2313 pa2.auto_rebind: 1
2314 pa3.auto_rebind: 0
2315 pa4.auto_rebind: 0
2316 sa.auto_rebind: 1
2317 psa1.auto_rebind: 1
2318 psa2.auto_rebind: 1
2319 psa3.auto_rebind: 0
2320 psa4.auto_rebind: 0
2321 psa5.auto_rebind: 0
2322 psa6.auto_rebind: 0
2323 psa7.auto_rebind: 1
2324 psa8.auto_rebind: 1
2325 psa9.auto_rebind: 1
2326 psaA.auto_rebind: 1
2327 psaB.auto_rebind: 1
2328 psaC.auto_rebind: 1
2329 END
2330 call assert_equal(expected, getline(2, '$'))
2331 %bw!
2332endfunc
2333
2334" Test stdout/stderr
2335func Test_python_stdin_stderr()
2336 let caught_writeerr = 0
2337 let caught_writelineerr = 0
2338 redir => messages
2339 py sys.stdout.write('abc8') ; sys.stdout.write('def')
2340 try
2341 py sys.stderr.write('abc9') ; sys.stderr.write('def')
2342 catch /abc9def/
2343 let caught_writeerr = 1
2344 endtry
2345 py sys.stdout.writelines(iter('abcA'))
2346 try
2347 py sys.stderr.writelines(iter('abcB'))
2348 catch /abcB/
2349 let caught_writelineerr = 1
2350 endtry
2351 redir END
2352 call assert_equal("\nabc8def\nabcA", messages)
2353 call assert_equal(1, caught_writeerr)
2354 call assert_equal(1, caught_writelineerr)
2355endfunc
2356
2357" Test subclassing
2358func Test_python_subclass()
2359 new
Bram Moolenaarab589462020-07-06 21:03:06 +02002360 func Put(...)
2361 return a:000
2362 endfunc
Bram Moolenaar92fdd1e2020-07-03 18:00:05 +02002363
2364 py << trim EOF
2365 class DupDict(vim.Dictionary):
2366 def __setitem__(self, key, value):
2367 super(DupDict, self).__setitem__(key, value)
2368 super(DupDict, self).__setitem__('dup_' + key, value)
2369 dd = DupDict()
2370 dd['a'] = 'b'
Bram Moolenaareffb0cd2020-07-03 21:17:34 +02002371
Bram Moolenaar92fdd1e2020-07-03 18:00:05 +02002372 class DupList(vim.List):
2373 def __getitem__(self, idx):
2374 return [super(DupList, self).__getitem__(idx)] * 2
Bram Moolenaareffb0cd2020-07-03 21:17:34 +02002375
Bram Moolenaar92fdd1e2020-07-03 18:00:05 +02002376 dl = DupList()
2377 dl2 = DupList(iter('abcC'))
2378 dl.extend(dl2[0])
Bram Moolenaareffb0cd2020-07-03 21:17:34 +02002379
Bram Moolenaar92fdd1e2020-07-03 18:00:05 +02002380 class DupFun(vim.Function):
2381 def __call__(self, arg):
2382 return super(DupFun, self).__call__(arg, arg)
Bram Moolenaareffb0cd2020-07-03 21:17:34 +02002383
Bram Moolenaar92fdd1e2020-07-03 18:00:05 +02002384 df = DupFun('Put')
2385 EOF
2386
2387 call assert_equal(['a', 'dup_a'], sort(keys(pyeval('dd'))))
2388 call assert_equal(['a', 'a'], pyeval('dl'))
2389 call assert_equal(['a', 'b', 'c', 'C'], pyeval('dl2'))
2390 call assert_equal([2, 2], pyeval('df(2)'))
2391 call assert_equal(1, pyeval('dl') is# pyeval('dl'))
2392 call assert_equal(1, pyeval('dd') is# pyeval('dd'))
2393 call assert_equal(function('Put'), pyeval('df'))
2394 delfunction Put
2395 py << trim EOF
2396 del DupDict
2397 del DupList
2398 del DupFun
2399 del dd
2400 del dl
2401 del dl2
2402 del df
2403 EOF
2404 close!
2405endfunc
2406
2407" Test chdir
2408func Test_python_chdir()
Bram Moolenaarb18b4962022-09-02 21:55:50 +01002409 new Xpycfile
Bram Moolenaar92fdd1e2020-07-03 18:00:05 +02002410 py cb = vim.current.buffer
2411 py << trim EOF
2412 import os
2413 fnamemodify = vim.Function('fnamemodify')
2414 cb.append(fnamemodify('.', ':p:h:t'))
2415 cb.append(vim.eval('@%'))
2416 os.chdir('..')
2417 path = fnamemodify('.', ':p:h:t')
Bram Moolenaar7d697962020-08-31 21:30:32 +02002418 if path != 'src' and path != 'src2':
Bram Moolenaar92fdd1e2020-07-03 18:00:05 +02002419 # Running tests from a shadow directory, so move up another level
Bram Moolenaarb18b4962022-09-02 21:55:50 +01002420 # This will result in @% looking like shadow/testdir/Xpycfile, hence the
Bram Moolenaar92fdd1e2020-07-03 18:00:05 +02002421 # extra fnamemodify
2422 os.chdir('..')
2423 cb.append(fnamemodify('.', ':p:h:t'))
2424 cb.append(fnamemodify(vim.eval('@%'), ':s?^%s.??' % path).replace(os.path.sep, '/'))
2425 os.chdir(path)
2426 del path
2427 else:
Bram Moolenaar7d697962020-08-31 21:30:32 +02002428 # Also accept running from src2/testdir/ for MS-Windows CI.
2429 cb.append(fnamemodify('.', ':p:h:t').replace('src2', 'src'))
Bram Moolenaar92fdd1e2020-07-03 18:00:05 +02002430 cb.append(vim.eval('@%').replace(os.path.sep, '/'))
2431 os.chdir('testdir')
2432 cb.append(fnamemodify('.', ':p:h:t'))
2433 cb.append(vim.eval('@%'))
2434 del fnamemodify
2435 EOF
Bram Moolenaarb18b4962022-09-02 21:55:50 +01002436 call assert_equal(['testdir', 'Xpycfile', 'src', 'testdir/Xpycfile', 'testdir',
2437 \ 'Xpycfile'], getline(2, '$'))
Bram Moolenaar92fdd1e2020-07-03 18:00:05 +02002438 close!
Bram Moolenaar0ab55d62020-07-07 20:50:39 +02002439 call AssertException(["py vim.chdir(None)"], "Vim(python):TypeError:")
Bram Moolenaar92fdd1e2020-07-03 18:00:05 +02002440endfunc
2441
2442" Test errors
2443func Test_python_errors()
Bram Moolenaarab589462020-07-06 21:03:06 +02002444 func F() dict
2445 endfunc
Bram Moolenaar92fdd1e2020-07-03 18:00:05 +02002446
Bram Moolenaarab589462020-07-06 21:03:06 +02002447 func D()
2448 endfunc
Bram Moolenaar92fdd1e2020-07-03 18:00:05 +02002449
2450 new
2451 py cb = vim.current.buffer
2452
2453 py << trim EOF
2454 d = vim.Dictionary()
2455 ned = vim.Dictionary(foo='bar', baz='abcD')
2456 dl = vim.Dictionary(a=1)
2457 dl.locked = True
2458 l = vim.List()
2459 ll = vim.List('abcE')
2460 ll.locked = True
2461 nel = vim.List('abcO')
2462 f = vim.Function('string')
2463 fd = vim.Function('F')
2464 fdel = vim.Function('D')
2465 vim.command('delfunction D')
Bram Moolenaareffb0cd2020-07-03 21:17:34 +02002466
Bram Moolenaar92fdd1e2020-07-03 18:00:05 +02002467 def subexpr_test(expr, name, subexprs):
2468 cb.append('>>> Testing %s using %s' % (name, expr))
2469 for subexpr in subexprs:
2470 ee(expr % subexpr)
2471 cb.append('<<< Finished')
Bram Moolenaareffb0cd2020-07-03 21:17:34 +02002472
Bram Moolenaar92fdd1e2020-07-03 18:00:05 +02002473 def stringtochars_test(expr):
2474 return subexpr_test(expr, 'StringToChars', (
2475 '1', # Fail type checks
2476 'u"\\0"', # Fail PyString_AsStringAndSize(bytes, , NULL) check
2477 '"\\0"', # Fail PyString_AsStringAndSize(object, , NULL) check
2478 ))
Bram Moolenaareffb0cd2020-07-03 21:17:34 +02002479
Bram Moolenaar92fdd1e2020-07-03 18:00:05 +02002480 class Mapping(object):
2481 def __init__(self, d):
2482 self.d = d
Bram Moolenaareffb0cd2020-07-03 21:17:34 +02002483
Bram Moolenaar92fdd1e2020-07-03 18:00:05 +02002484 def __getitem__(self, key):
2485 return self.d[key]
Bram Moolenaareffb0cd2020-07-03 21:17:34 +02002486
Bram Moolenaar92fdd1e2020-07-03 18:00:05 +02002487 def keys(self):
2488 return self.d.keys()
Bram Moolenaareffb0cd2020-07-03 21:17:34 +02002489
Bram Moolenaar92fdd1e2020-07-03 18:00:05 +02002490 def items(self):
2491 return self.d.items()
Bram Moolenaareffb0cd2020-07-03 21:17:34 +02002492
Bram Moolenaar92fdd1e2020-07-03 18:00:05 +02002493 def convertfrompyobject_test(expr, recurse=True):
2494 # pydict_to_tv
2495 stringtochars_test(expr % '{%s : 1}')
2496 if recurse:
2497 convertfrompyobject_test(expr % '{"abcF" : %s}', False)
2498 # pymap_to_tv
2499 stringtochars_test(expr % 'Mapping({%s : 1})')
2500 if recurse:
2501 convertfrompyobject_test(expr % 'Mapping({"abcG" : %s})', False)
2502 # pyseq_to_tv
2503 iter_test(expr)
2504 return subexpr_test(expr, 'ConvertFromPyObject', (
2505 'None', # Not conversible
2506 '{"": 1}', # Empty key not allowed
2507 '{u"": 1}', # Same, but with unicode object
2508 'FailingMapping()', #
2509 'FailingMappingKey()', #
2510 'FailingNumber()', #
2511 ))
Bram Moolenaareffb0cd2020-07-03 21:17:34 +02002512
Bram Moolenaar92fdd1e2020-07-03 18:00:05 +02002513 def convertfrompymapping_test(expr):
2514 convertfrompyobject_test(expr)
2515 return subexpr_test(expr, 'ConvertFromPyMapping', (
2516 '[]',
2517 ))
Bram Moolenaareffb0cd2020-07-03 21:17:34 +02002518
Bram Moolenaar92fdd1e2020-07-03 18:00:05 +02002519 def iter_test(expr):
2520 return subexpr_test(expr, '*Iter*', (
2521 'FailingIter()',
2522 'FailingIterNext()',
2523 ))
Bram Moolenaareffb0cd2020-07-03 21:17:34 +02002524
Bram Moolenaar92fdd1e2020-07-03 18:00:05 +02002525 def number_test(expr, natural=False, unsigned=False):
2526 if natural:
2527 unsigned = True
2528 return subexpr_test(expr, 'NumberToLong', (
2529 '[]',
2530 'None',
2531 ) + (unsigned and ('-1',) or ())
2532 + (natural and ('0',) or ()))
Bram Moolenaareffb0cd2020-07-03 21:17:34 +02002533
Bram Moolenaar92fdd1e2020-07-03 18:00:05 +02002534 class FailingTrue(object):
2535 def __nonzero__(self):
2536 raise NotImplementedError('bool')
Bram Moolenaareffb0cd2020-07-03 21:17:34 +02002537
Bram Moolenaar92fdd1e2020-07-03 18:00:05 +02002538 class FailingIter(object):
2539 def __iter__(self):
2540 raise NotImplementedError('iter')
Bram Moolenaareffb0cd2020-07-03 21:17:34 +02002541
Bram Moolenaar92fdd1e2020-07-03 18:00:05 +02002542 class FailingIterNext(object):
2543 def __iter__(self):
2544 return self
Bram Moolenaareffb0cd2020-07-03 21:17:34 +02002545
Bram Moolenaar92fdd1e2020-07-03 18:00:05 +02002546 def next(self):
2547 raise NotImplementedError('next')
Bram Moolenaareffb0cd2020-07-03 21:17:34 +02002548
Bram Moolenaar92fdd1e2020-07-03 18:00:05 +02002549 class FailingIterNextN(object):
2550 def __init__(self, n):
2551 self.n = n
Bram Moolenaareffb0cd2020-07-03 21:17:34 +02002552
Bram Moolenaar92fdd1e2020-07-03 18:00:05 +02002553 def __iter__(self):
2554 return self
Bram Moolenaareffb0cd2020-07-03 21:17:34 +02002555
Bram Moolenaar92fdd1e2020-07-03 18:00:05 +02002556 def next(self):
2557 if self.n:
2558 self.n -= 1
2559 return 1
2560 else:
2561 raise NotImplementedError('next N')
Bram Moolenaareffb0cd2020-07-03 21:17:34 +02002562
Bram Moolenaar92fdd1e2020-07-03 18:00:05 +02002563 class FailingMappingKey(object):
2564 def __getitem__(self, item):
2565 raise NotImplementedError('getitem:mappingkey')
Bram Moolenaareffb0cd2020-07-03 21:17:34 +02002566
Bram Moolenaar92fdd1e2020-07-03 18:00:05 +02002567 def keys(self):
2568 return list("abcH")
Bram Moolenaareffb0cd2020-07-03 21:17:34 +02002569
Bram Moolenaar92fdd1e2020-07-03 18:00:05 +02002570 class FailingMapping(object):
2571 def __getitem__(self):
2572 raise NotImplementedError('getitem:mapping')
Bram Moolenaareffb0cd2020-07-03 21:17:34 +02002573
Bram Moolenaar92fdd1e2020-07-03 18:00:05 +02002574 def keys(self):
2575 raise NotImplementedError('keys')
Bram Moolenaareffb0cd2020-07-03 21:17:34 +02002576
Bram Moolenaar92fdd1e2020-07-03 18:00:05 +02002577 class FailingList(list):
2578 def __getitem__(self, idx):
2579 if i == 2:
2580 raise NotImplementedError('getitem:list')
2581 else:
2582 return super(FailingList, self).__getitem__(idx)
Bram Moolenaareffb0cd2020-07-03 21:17:34 +02002583
Bram Moolenaar92fdd1e2020-07-03 18:00:05 +02002584 class NoArgsCall(object):
2585 def __call__(self):
2586 pass
Bram Moolenaareffb0cd2020-07-03 21:17:34 +02002587
Bram Moolenaar92fdd1e2020-07-03 18:00:05 +02002588 class FailingCall(object):
2589 def __call__(self, path):
2590 raise NotImplementedError('call')
Bram Moolenaareffb0cd2020-07-03 21:17:34 +02002591
Bram Moolenaar92fdd1e2020-07-03 18:00:05 +02002592 class FailingNumber(object):
2593 def __int__(self):
2594 raise NotImplementedError('int')
Bram Moolenaareffb0cd2020-07-03 21:17:34 +02002595
Bram Moolenaar92fdd1e2020-07-03 18:00:05 +02002596 cb.append("> Output")
2597 cb.append(">> OutputSetattr")
2598 ee('del sys.stdout.softspace')
2599 number_test('sys.stdout.softspace = %s', unsigned=True)
2600 number_test('sys.stderr.softspace = %s', unsigned=True)
2601 ee('assert sys.stdout.isatty()==False')
2602 ee('assert sys.stdout.seekable()==False')
2603 ee('sys.stdout.close()')
2604 ee('sys.stdout.flush()')
2605 ee('assert sys.stderr.isatty()==False')
2606 ee('assert sys.stderr.seekable()==False')
2607 ee('sys.stderr.close()')
2608 ee('sys.stderr.flush()')
2609 ee('sys.stdout.attr = None')
2610 cb.append(">> OutputWrite")
2611 ee('assert sys.stdout.writable()==True')
2612 ee('assert sys.stdout.readable()==False')
2613 ee('assert sys.stderr.writable()==True')
2614 ee('assert sys.stderr.readable()==False')
2615 ee('assert sys.stdout.closed()==False')
2616 ee('assert sys.stderr.closed()==False')
2617 ee('assert sys.stdout.errors=="strict"')
2618 ee('assert sys.stderr.errors=="strict"')
2619 ee('assert sys.stdout.encoding==sys.stderr.encoding')
2620 ee('sys.stdout.write(None)')
2621 cb.append(">> OutputWriteLines")
2622 ee('sys.stdout.writelines(None)')
2623 ee('sys.stdout.writelines([1])')
2624 iter_test('sys.stdout.writelines(%s)')
2625 cb.append("> VimCommand")
2626 stringtochars_test('vim.command(%s)')
2627 ee('vim.command("", 2)')
2628 #! Not checked: vim->python exceptions translating: checked later
2629 cb.append("> VimToPython")
2630 #! Not checked: everything: needs errors in internal python functions
2631 cb.append("> VimEval")
2632 stringtochars_test('vim.eval(%s)')
2633 ee('vim.eval("", FailingTrue())')
2634 #! Not checked: everything: needs errors in internal python functions
2635 cb.append("> VimEvalPy")
2636 stringtochars_test('vim.bindeval(%s)')
2637 ee('vim.eval("", 2)')
2638 #! Not checked: vim->python exceptions translating: checked later
2639 cb.append("> VimStrwidth")
2640 stringtochars_test('vim.strwidth(%s)')
2641 cb.append("> VimForeachRTP")
2642 ee('vim.foreach_rtp(None)')
2643 ee('vim.foreach_rtp(NoArgsCall())')
2644 ee('vim.foreach_rtp(FailingCall())')
2645 ee('vim.foreach_rtp(int, 2)')
2646 cb.append('> import')
2647 old_rtp = vim.options['rtp']
2648 vim.options['rtp'] = os.getcwd().replace('\\', '\\\\').replace(',', '\\,')
2649 ee('import xxx_no_such_module_xxx')
2650 ee('import failing_import')
2651 ee('import failing')
2652 vim.options['rtp'] = old_rtp
2653 del old_rtp
2654 cb.append("> Options")
2655 cb.append(">> OptionsItem")
2656 ee('vim.options["abcQ"]')
2657 ee('vim.options[""]')
2658 stringtochars_test('vim.options[%s]')
2659 cb.append(">> OptionsContains")
2660 stringtochars_test('%s in vim.options')
2661 cb.append("> Dictionary")
2662 cb.append(">> DictionaryConstructor")
2663 ee('vim.Dictionary("abcI")')
2664 ##! Not checked: py_dict_alloc failure
2665 cb.append(">> DictionarySetattr")
2666 ee('del d.locked')
2667 ee('d.locked = FailingTrue()')
2668 ee('vim.vvars.locked = False')
2669 ee('d.scope = True')
2670 ee('d.xxx = True')
2671 cb.append(">> _DictionaryItem")
2672 ee('d.get("a", 2, 3)')
2673 stringtochars_test('d.get(%s)')
2674 ee('d.pop("a")')
2675 ee('dl.pop("a")')
2676 cb.append(">> DictionaryContains")
2677 ee('"" in d')
2678 ee('0 in d')
2679 cb.append(">> DictionaryIterNext")
2680 ee('for i in ned: ned["a"] = 1')
2681 del i
2682 cb.append(">> DictionaryAssItem")
2683 ee('dl["b"] = 1')
2684 stringtochars_test('d[%s] = 1')
2685 convertfrompyobject_test('d["a"] = %s')
2686 cb.append(">> DictionaryUpdate")
2687 cb.append(">>> kwargs")
2688 cb.append(">>> iter")
2689 ee('d.update(FailingMapping())')
2690 ee('d.update([FailingIterNext()])')
2691 ee('d.update([FailingIterNextN(1)])')
2692 iter_test('d.update(%s)')
2693 convertfrompyobject_test('d.update(%s)')
2694 stringtochars_test('d.update(((%s, 0),))')
2695 convertfrompyobject_test('d.update((("a", %s),))')
2696 cb.append(">> DictionaryPopItem")
2697 ee('d.popitem(1, 2)')
2698 cb.append(">> DictionaryHasKey")
2699 ee('d.has_key()')
2700 cb.append("> List")
2701 cb.append(">> ListConstructor")
2702 ee('vim.List(1, 2)')
2703 ee('vim.List(a=1)')
2704 iter_test('vim.List(%s)')
2705 convertfrompyobject_test('vim.List([%s])')
2706 cb.append(">> ListItem")
2707 ee('l[1000]')
2708 cb.append(">> ListAssItem")
2709 ee('ll[1] = 2')
2710 ee('l[1000] = 3')
2711 cb.append(">> ListAssSlice")
2712 ee('ll[1:100] = "abcJ"')
2713 iter_test('l[:] = %s')
2714 ee('nel[1:10:2] = "abcK"')
2715 cb.append(repr(tuple(nel)))
2716 ee('nel[1:10:2] = "a"')
2717 cb.append(repr(tuple(nel)))
2718 ee('nel[1:1:-1] = "a"')
2719 cb.append(repr(tuple(nel)))
2720 ee('nel[:] = FailingIterNextN(2)')
2721 cb.append(repr(tuple(nel)))
2722 convertfrompyobject_test('l[:] = [%s]')
2723 cb.append(">> ListConcatInPlace")
2724 iter_test('l.extend(%s)')
2725 convertfrompyobject_test('l.extend([%s])')
2726 cb.append(">> ListSetattr")
2727 ee('del l.locked')
2728 ee('l.locked = FailingTrue()')
2729 ee('l.xxx = True')
2730 cb.append("> Function")
2731 cb.append(">> FunctionConstructor")
2732 cb.append(">>> FunctionConstructor")
2733 ee('vim.Function("123")')
2734 ee('vim.Function("xxx_non_existent_function_xxx")')
2735 ee('vim.Function("xxx#non#existent#function#xxx")')
2736 ee('vim.Function("xxx_non_existent_function_xxx2", args=[])')
2737 ee('vim.Function("xxx_non_existent_function_xxx3", self={})')
2738 ee('vim.Function("xxx_non_existent_function_xxx4", args=[], self={})')
2739 cb.append(">>> FunctionNew")
2740 ee('vim.Function("tr", self="abcFuncSelf")')
2741 ee('vim.Function("tr", args=427423)')
2742 ee('vim.Function("tr", self="abcFuncSelf2", args="abcFuncArgs2")')
2743 ee('vim.Function(self="abcFuncSelf2", args="abcFuncArgs2")')
2744 ee('vim.Function("tr", "", self="abcFuncSelf2", args="abcFuncArgs2")')
2745 ee('vim.Function("tr", "")')
2746 cb.append(">> FunctionCall")
2747 convertfrompyobject_test('f(%s)')
2748 convertfrompymapping_test('fd(self=%s)')
2749 cb.append("> TabPage")
2750 cb.append(">> TabPageAttr")
2751 ee('vim.current.tabpage.xxx')
2752 cb.append("> TabList")
2753 cb.append(">> TabListItem")
2754 ee('vim.tabpages[1000]')
2755 cb.append("> Window")
2756 cb.append(">> WindowAttr")
2757 ee('vim.current.window.xxx')
2758 cb.append(">> WindowSetattr")
2759 ee('vim.current.window.buffer = 0')
2760 ee('vim.current.window.cursor = (100000000, 100000000)')
2761 ee('vim.current.window.cursor = True')
2762 number_test('vim.current.window.height = %s', unsigned=True)
2763 number_test('vim.current.window.width = %s', unsigned=True)
2764 ee('vim.current.window.xxxxxx = True')
2765 cb.append("> WinList")
2766 cb.append(">> WinListItem")
2767 ee('vim.windows[1000]')
2768 cb.append("> Buffer")
2769 cb.append(">> StringToLine (indirect)")
Bram Moolenaar92fdd1e2020-07-03 18:00:05 +02002770 ee('vim.current.buffer[0] = "\\na"')
Bram Moolenaarab589462020-07-06 21:03:06 +02002771 ee('vim.current.buffer[0] = u"\\na"')
Bram Moolenaar92fdd1e2020-07-03 18:00:05 +02002772 cb.append(">> SetBufferLine (indirect)")
2773 ee('vim.current.buffer[0] = True')
2774 cb.append(">> SetBufferLineList (indirect)")
2775 ee('vim.current.buffer[:] = True')
2776 ee('vim.current.buffer[:] = ["\\na", "bc"]')
2777 cb.append(">> InsertBufferLines (indirect)")
2778 ee('vim.current.buffer.append(None)')
2779 ee('vim.current.buffer.append(["\\na", "bc"])')
2780 ee('vim.current.buffer.append("\\nbc")')
2781 cb.append(">> RBItem")
2782 ee('vim.current.buffer[100000000]')
2783 cb.append(">> RBAsItem")
2784 ee('vim.current.buffer[100000000] = ""')
2785 cb.append(">> BufferAttr")
2786 ee('vim.current.buffer.xxx')
2787 cb.append(">> BufferSetattr")
2788 ee('vim.current.buffer.name = True')
2789 ee('vim.current.buffer.xxx = True')
2790 cb.append(">> BufferMark")
2791 ee('vim.current.buffer.mark(0)')
2792 ee('vim.current.buffer.mark("abcM")')
2793 ee('vim.current.buffer.mark("!")')
2794 cb.append(">> BufferRange")
2795 ee('vim.current.buffer.range(1, 2, 3)')
2796 cb.append("> BufMap")
2797 cb.append(">> BufMapItem")
2798 ee('vim.buffers[100000000]')
2799 number_test('vim.buffers[%s]', natural=True)
2800 cb.append("> Current")
2801 cb.append(">> CurrentGetattr")
2802 ee('vim.current.xxx')
2803 cb.append(">> CurrentSetattr")
2804 ee('vim.current.line = True')
2805 ee('vim.current.buffer = True')
2806 ee('vim.current.window = True')
2807 ee('vim.current.tabpage = True')
2808 ee('vim.current.xxx = True')
2809 del d
2810 del ned
2811 del dl
2812 del l
2813 del ll
2814 del nel
2815 del f
2816 del fd
2817 del fdel
2818 del subexpr_test
2819 del stringtochars_test
2820 del Mapping
2821 del convertfrompyobject_test
2822 del convertfrompymapping_test
2823 del iter_test
2824 del number_test
2825 del FailingTrue
2826 del FailingIter
2827 del FailingIterNext
2828 del FailingIterNextN
2829 del FailingMapping
2830 del FailingMappingKey
2831 del FailingList
2832 del NoArgsCall
2833 del FailingCall
2834 del FailingNumber
2835 EOF
2836 delfunction F
2837
2838 let expected =<< trim END
2839 > Output
2840 >> OutputSetattr
2841 del sys.stdout.softspace:AttributeError:('cannot delete OutputObject attributes',)
2842 >>> Testing NumberToLong using sys.stdout.softspace = %s
2843 sys.stdout.softspace = []:TypeError:('expected int(), long() or something supporting coercing to long(), but got list',)
2844 sys.stdout.softspace = None:TypeError:('expected int(), long() or something supporting coercing to long(), but got NoneType',)
2845 sys.stdout.softspace = -1:ValueError:('number must be greater or equal to zero',)
2846 <<< Finished
2847 >>> Testing NumberToLong using sys.stderr.softspace = %s
2848 sys.stderr.softspace = []:TypeError:('expected int(), long() or something supporting coercing to long(), but got list',)
2849 sys.stderr.softspace = None:TypeError:('expected int(), long() or something supporting coercing to long(), but got NoneType',)
2850 sys.stderr.softspace = -1:ValueError:('number must be greater or equal to zero',)
2851 <<< Finished
2852 assert sys.stdout.isatty()==False:NOT FAILED
2853 assert sys.stdout.seekable()==False:NOT FAILED
2854 sys.stdout.close():NOT FAILED
2855 sys.stdout.flush():NOT FAILED
2856 assert sys.stderr.isatty()==False:NOT FAILED
2857 assert sys.stderr.seekable()==False:NOT FAILED
2858 sys.stderr.close():NOT FAILED
2859 sys.stderr.flush():NOT FAILED
2860 sys.stdout.attr = None:AttributeError:('invalid attribute: attr',)
2861 >> OutputWrite
2862 assert sys.stdout.writable()==True:NOT FAILED
2863 assert sys.stdout.readable()==False:NOT FAILED
2864 assert sys.stderr.writable()==True:NOT FAILED
2865 assert sys.stderr.readable()==False:NOT FAILED
2866 assert sys.stdout.closed()==False:NOT FAILED
2867 assert sys.stderr.closed()==False:NOT FAILED
2868 assert sys.stdout.errors=="strict":NOT FAILED
2869 assert sys.stderr.errors=="strict":NOT FAILED
2870 assert sys.stdout.encoding==sys.stderr.encoding:NOT FAILED
2871 sys.stdout.write(None):TypeError:('coercing to Unicode: need string or buffer, NoneType found',)
2872 >> OutputWriteLines
2873 sys.stdout.writelines(None):TypeError:("'NoneType' object is not iterable",)
2874 sys.stdout.writelines([1]):TypeError:('coercing to Unicode: need string or buffer, int found',)
2875 >>> Testing *Iter* using sys.stdout.writelines(%s)
2876 sys.stdout.writelines(FailingIter()):NotImplementedError:('iter',)
2877 sys.stdout.writelines(FailingIterNext()):NotImplementedError:('next',)
2878 <<< Finished
2879 > VimCommand
2880 >>> Testing StringToChars using vim.command(%s)
2881 vim.command(1):TypeError:('expected str() or unicode() instance, but got int',)
2882 vim.command(u"\0"):TypeError:('expected string without null bytes',)
2883 vim.command("\0"):TypeError:('expected string without null bytes',)
2884 <<< Finished
2885 vim.command("", 2):TypeError:('command() takes exactly one argument (2 given)',)
2886 > VimToPython
2887 > VimEval
2888 >>> Testing StringToChars using vim.eval(%s)
2889 vim.eval(1):TypeError:('expected str() or unicode() instance, but got int',)
2890 vim.eval(u"\0"):TypeError:('expected string without null bytes',)
2891 vim.eval("\0"):TypeError:('expected string without null bytes',)
2892 <<< Finished
2893 vim.eval("", FailingTrue()):TypeError:('function takes exactly 1 argument (2 given)',)
2894 > VimEvalPy
2895 >>> Testing StringToChars using vim.bindeval(%s)
2896 vim.bindeval(1):TypeError:('expected str() or unicode() instance, but got int',)
2897 vim.bindeval(u"\0"):TypeError:('expected string without null bytes',)
2898 vim.bindeval("\0"):TypeError:('expected string without null bytes',)
2899 <<< Finished
2900 vim.eval("", 2):TypeError:('function takes exactly 1 argument (2 given)',)
2901 > VimStrwidth
2902 >>> Testing StringToChars using vim.strwidth(%s)
2903 vim.strwidth(1):TypeError:('expected str() or unicode() instance, but got int',)
2904 vim.strwidth(u"\0"):TypeError:('expected string without null bytes',)
2905 vim.strwidth("\0"):TypeError:('expected string without null bytes',)
2906 <<< Finished
2907 > VimForeachRTP
2908 vim.foreach_rtp(None):TypeError:("'NoneType' object is not callable",)
2909 vim.foreach_rtp(NoArgsCall()):TypeError:('__call__() takes exactly 1 argument (2 given)',)
2910 vim.foreach_rtp(FailingCall()):NotImplementedError:('call',)
2911 vim.foreach_rtp(int, 2):TypeError:('foreach_rtp() takes exactly one argument (2 given)',)
2912 > import
2913 import xxx_no_such_module_xxx:ImportError:('No module named xxx_no_such_module_xxx',)
2914 import failing_import:ImportError:()
2915 import failing:NotImplementedError:()
2916 > Options
2917 >> OptionsItem
2918 vim.options["abcQ"]:KeyError:('abcQ',)
2919 vim.options[""]:ValueError:('empty keys are not allowed',)
2920 >>> Testing StringToChars using vim.options[%s]
2921 vim.options[1]:TypeError:('expected str() or unicode() instance, but got int',)
2922 vim.options[u"\0"]:TypeError:('expected string without null bytes',)
2923 vim.options["\0"]:TypeError:('expected string without null bytes',)
2924 <<< Finished
2925 >> OptionsContains
2926 >>> Testing StringToChars using %s in vim.options
2927 1 in vim.options:TypeError:('expected str() or unicode() instance, but got int',)
2928 u"\0" in vim.options:TypeError:('expected string without null bytes',)
2929 "\0" in vim.options:TypeError:('expected string without null bytes',)
2930 <<< Finished
2931 > Dictionary
2932 >> DictionaryConstructor
2933 vim.Dictionary("abcI"):ValueError:('expected sequence element of size 2, but got sequence of size 1',)
2934 >> DictionarySetattr
2935 del d.locked:AttributeError:('cannot delete vim.Dictionary attributes',)
2936 d.locked = FailingTrue():NotImplementedError:('bool',)
2937 vim.vvars.locked = False:TypeError:('cannot modify fixed dictionary',)
2938 d.scope = True:AttributeError:('cannot set attribute scope',)
2939 d.xxx = True:AttributeError:('cannot set attribute xxx',)
2940 >> _DictionaryItem
2941 d.get("a", 2, 3):TypeError:('function takes at most 2 arguments (3 given)',)
2942 >>> Testing StringToChars using d.get(%s)
2943 d.get(1):TypeError:('expected str() or unicode() instance, but got int',)
2944 d.get(u"\0"):TypeError:('expected string without null bytes',)
2945 d.get("\0"):TypeError:('expected string without null bytes',)
2946 <<< Finished
2947 d.pop("a"):KeyError:('a',)
2948 dl.pop("a"):error:('dictionary is locked',)
2949 >> DictionaryContains
2950 "" in d:ValueError:('empty keys are not allowed',)
2951 0 in d:TypeError:('expected str() or unicode() instance, but got int',)
2952 >> DictionaryIterNext
2953 for i in ned: ned["a"] = 1:RuntimeError:('hashtab changed during iteration',)
2954 >> DictionaryAssItem
2955 dl["b"] = 1:error:('dictionary is locked',)
2956 >>> Testing StringToChars using d[%s] = 1
2957 d[1] = 1:TypeError:('expected str() or unicode() instance, but got int',)
2958 d[u"\0"] = 1:TypeError:('expected string without null bytes',)
2959 d["\0"] = 1:TypeError:('expected string without null bytes',)
2960 <<< Finished
2961 >>> Testing StringToChars using d["a"] = {%s : 1}
2962 d["a"] = {1 : 1}:TypeError:('expected str() or unicode() instance, but got int',)
2963 d["a"] = {u"\0" : 1}:TypeError:('expected string without null bytes',)
2964 d["a"] = {"\0" : 1}:TypeError:('expected string without null bytes',)
2965 <<< Finished
2966 >>> Testing StringToChars using d["a"] = {"abcF" : {%s : 1}}
2967 d["a"] = {"abcF" : {1 : 1}}:TypeError:('expected str() or unicode() instance, but got int',)
2968 d["a"] = {"abcF" : {u"\0" : 1}}:TypeError:('expected string without null bytes',)
2969 d["a"] = {"abcF" : {"\0" : 1}}:TypeError:('expected string without null bytes',)
2970 <<< Finished
2971 >>> Testing StringToChars using d["a"] = {"abcF" : Mapping({%s : 1})}
2972 d["a"] = {"abcF" : Mapping({1 : 1})}:TypeError:('expected str() or unicode() instance, but got int',)
2973 d["a"] = {"abcF" : Mapping({u"\0" : 1})}:TypeError:('expected string without null bytes',)
2974 d["a"] = {"abcF" : Mapping({"\0" : 1})}:TypeError:('expected string without null bytes',)
2975 <<< Finished
2976 >>> Testing *Iter* using d["a"] = {"abcF" : %s}
2977 d["a"] = {"abcF" : FailingIter()}:TypeError:('unable to convert FailingIter to a Vim structure',)
2978 d["a"] = {"abcF" : FailingIterNext()}:NotImplementedError:('next',)
2979 <<< Finished
2980 >>> Testing ConvertFromPyObject using d["a"] = {"abcF" : %s}
2981 d["a"] = {"abcF" : None}:NOT FAILED
2982 d["a"] = {"abcF" : {"": 1}}:ValueError:('empty keys are not allowed',)
2983 d["a"] = {"abcF" : {u"": 1}}:ValueError:('empty keys are not allowed',)
2984 d["a"] = {"abcF" : FailingMapping()}:NotImplementedError:('keys',)
2985 d["a"] = {"abcF" : FailingMappingKey()}:NotImplementedError:('getitem:mappingkey',)
2986 d["a"] = {"abcF" : FailingNumber()}:TypeError:('long() argument must be a string or a number',)
2987 <<< Finished
2988 >>> Testing StringToChars using d["a"] = Mapping({%s : 1})
2989 d["a"] = Mapping({1 : 1}):TypeError:('expected str() or unicode() instance, but got int',)
2990 d["a"] = Mapping({u"\0" : 1}):TypeError:('expected string without null bytes',)
2991 d["a"] = Mapping({"\0" : 1}):TypeError:('expected string without null bytes',)
2992 <<< Finished
2993 >>> Testing StringToChars using d["a"] = Mapping({"abcG" : {%s : 1}})
2994 d["a"] = Mapping({"abcG" : {1 : 1}}):TypeError:('expected str() or unicode() instance, but got int',)
2995 d["a"] = Mapping({"abcG" : {u"\0" : 1}}):TypeError:('expected string without null bytes',)
2996 d["a"] = Mapping({"abcG" : {"\0" : 1}}):TypeError:('expected string without null bytes',)
2997 <<< Finished
2998 >>> Testing StringToChars using d["a"] = Mapping({"abcG" : Mapping({%s : 1})})
2999 d["a"] = Mapping({"abcG" : Mapping({1 : 1})}):TypeError:('expected str() or unicode() instance, but got int',)
3000 d["a"] = Mapping({"abcG" : Mapping({u"\0" : 1})}):TypeError:('expected string without null bytes',)
3001 d["a"] = Mapping({"abcG" : Mapping({"\0" : 1})}):TypeError:('expected string without null bytes',)
3002 <<< Finished
3003 >>> Testing *Iter* using d["a"] = Mapping({"abcG" : %s})
3004 d["a"] = Mapping({"abcG" : FailingIter()}):TypeError:('unable to convert FailingIter to a Vim structure',)
3005 d["a"] = Mapping({"abcG" : FailingIterNext()}):NotImplementedError:('next',)
3006 <<< Finished
3007 >>> Testing ConvertFromPyObject using d["a"] = Mapping({"abcG" : %s})
3008 d["a"] = Mapping({"abcG" : None}):NOT FAILED
3009 d["a"] = Mapping({"abcG" : {"": 1}}):ValueError:('empty keys are not allowed',)
3010 d["a"] = Mapping({"abcG" : {u"": 1}}):ValueError:('empty keys are not allowed',)
3011 d["a"] = Mapping({"abcG" : FailingMapping()}):NotImplementedError:('keys',)
3012 d["a"] = Mapping({"abcG" : FailingMappingKey()}):NotImplementedError:('getitem:mappingkey',)
3013 d["a"] = Mapping({"abcG" : FailingNumber()}):TypeError:('long() argument must be a string or a number',)
3014 <<< Finished
3015 >>> Testing *Iter* using d["a"] = %s
3016 d["a"] = FailingIter():TypeError:('unable to convert FailingIter to a Vim structure',)
3017 d["a"] = FailingIterNext():NotImplementedError:('next',)
3018 <<< Finished
3019 >>> Testing ConvertFromPyObject using d["a"] = %s
3020 d["a"] = None:NOT FAILED
3021 d["a"] = {"": 1}:ValueError:('empty keys are not allowed',)
3022 d["a"] = {u"": 1}:ValueError:('empty keys are not allowed',)
3023 d["a"] = FailingMapping():NotImplementedError:('keys',)
3024 d["a"] = FailingMappingKey():NotImplementedError:('getitem:mappingkey',)
3025 d["a"] = FailingNumber():TypeError:('long() argument must be a string or a number',)
3026 <<< Finished
3027 >> DictionaryUpdate
3028 >>> kwargs
3029 >>> iter
3030 d.update(FailingMapping()):NotImplementedError:('keys',)
3031 d.update([FailingIterNext()]):NotImplementedError:('next',)
3032 d.update([FailingIterNextN(1)]):NotImplementedError:('next N',)
3033 >>> Testing *Iter* using d.update(%s)
3034 d.update(FailingIter()):NotImplementedError:('iter',)
3035 d.update(FailingIterNext()):NotImplementedError:('next',)
3036 <<< Finished
3037 >>> Testing StringToChars using d.update({%s : 1})
3038 d.update({1 : 1}):TypeError:('expected str() or unicode() instance, but got int',)
3039 d.update({u"\0" : 1}):TypeError:('expected string without null bytes',)
3040 d.update({"\0" : 1}):TypeError:('expected string without null bytes',)
3041 <<< Finished
3042 >>> Testing StringToChars using d.update({"abcF" : {%s : 1}})
3043 d.update({"abcF" : {1 : 1}}):TypeError:('expected str() or unicode() instance, but got int',)
3044 d.update({"abcF" : {u"\0" : 1}}):TypeError:('expected string without null bytes',)
3045 d.update({"abcF" : {"\0" : 1}}):TypeError:('expected string without null bytes',)
3046 <<< Finished
3047 >>> Testing StringToChars using d.update({"abcF" : Mapping({%s : 1})})
3048 d.update({"abcF" : Mapping({1 : 1})}):TypeError:('expected str() or unicode() instance, but got int',)
3049 d.update({"abcF" : Mapping({u"\0" : 1})}):TypeError:('expected string without null bytes',)
3050 d.update({"abcF" : Mapping({"\0" : 1})}):TypeError:('expected string without null bytes',)
3051 <<< Finished
3052 >>> Testing *Iter* using d.update({"abcF" : %s})
3053 d.update({"abcF" : FailingIter()}):TypeError:('unable to convert FailingIter to a Vim structure',)
3054 d.update({"abcF" : FailingIterNext()}):NotImplementedError:('next',)
3055 <<< Finished
3056 >>> Testing ConvertFromPyObject using d.update({"abcF" : %s})
3057 d.update({"abcF" : None}):NOT FAILED
3058 d.update({"abcF" : {"": 1}}):ValueError:('empty keys are not allowed',)
3059 d.update({"abcF" : {u"": 1}}):ValueError:('empty keys are not allowed',)
3060 d.update({"abcF" : FailingMapping()}):NotImplementedError:('keys',)
3061 d.update({"abcF" : FailingMappingKey()}):NotImplementedError:('getitem:mappingkey',)
3062 d.update({"abcF" : FailingNumber()}):TypeError:('long() argument must be a string or a number',)
3063 <<< Finished
3064 >>> Testing StringToChars using d.update(Mapping({%s : 1}))
3065 d.update(Mapping({1 : 1})):TypeError:('expected str() or unicode() instance, but got int',)
3066 d.update(Mapping({u"\0" : 1})):TypeError:('expected string without null bytes',)
3067 d.update(Mapping({"\0" : 1})):TypeError:('expected string without null bytes',)
3068 <<< Finished
3069 >>> Testing StringToChars using d.update(Mapping({"abcG" : {%s : 1}}))
3070 d.update(Mapping({"abcG" : {1 : 1}})):TypeError:('expected str() or unicode() instance, but got int',)
3071 d.update(Mapping({"abcG" : {u"\0" : 1}})):TypeError:('expected string without null bytes',)
3072 d.update(Mapping({"abcG" : {"\0" : 1}})):TypeError:('expected string without null bytes',)
3073 <<< Finished
3074 >>> Testing StringToChars using d.update(Mapping({"abcG" : Mapping({%s : 1})}))
3075 d.update(Mapping({"abcG" : Mapping({1 : 1})})):TypeError:('expected str() or unicode() instance, but got int',)
3076 d.update(Mapping({"abcG" : Mapping({u"\0" : 1})})):TypeError:('expected string without null bytes',)
3077 d.update(Mapping({"abcG" : Mapping({"\0" : 1})})):TypeError:('expected string without null bytes',)
3078 <<< Finished
3079 >>> Testing *Iter* using d.update(Mapping({"abcG" : %s}))
3080 d.update(Mapping({"abcG" : FailingIter()})):TypeError:('unable to convert FailingIter to a Vim structure',)
3081 d.update(Mapping({"abcG" : FailingIterNext()})):NotImplementedError:('next',)
3082 <<< Finished
3083 >>> Testing ConvertFromPyObject using d.update(Mapping({"abcG" : %s}))
3084 d.update(Mapping({"abcG" : None})):NOT FAILED
3085 d.update(Mapping({"abcG" : {"": 1}})):ValueError:('empty keys are not allowed',)
3086 d.update(Mapping({"abcG" : {u"": 1}})):ValueError:('empty keys are not allowed',)
3087 d.update(Mapping({"abcG" : FailingMapping()})):NotImplementedError:('keys',)
3088 d.update(Mapping({"abcG" : FailingMappingKey()})):NotImplementedError:('getitem:mappingkey',)
3089 d.update(Mapping({"abcG" : FailingNumber()})):TypeError:('long() argument must be a string or a number',)
3090 <<< Finished
3091 >>> Testing *Iter* using d.update(%s)
3092 d.update(FailingIter()):NotImplementedError:('iter',)
3093 d.update(FailingIterNext()):NotImplementedError:('next',)
3094 <<< Finished
3095 >>> Testing ConvertFromPyObject using d.update(%s)
3096 d.update(None):TypeError:("'NoneType' object is not iterable",)
3097 d.update({"": 1}):ValueError:('empty keys are not allowed',)
3098 d.update({u"": 1}):ValueError:('empty keys are not allowed',)
3099 d.update(FailingMapping()):NotImplementedError:('keys',)
3100 d.update(FailingMappingKey()):NotImplementedError:('getitem:mappingkey',)
3101 d.update(FailingNumber()):TypeError:("'FailingNumber' object is not iterable",)
3102 <<< Finished
3103 >>> Testing StringToChars using d.update(((%s, 0),))
3104 d.update(((1, 0),)):TypeError:('expected str() or unicode() instance, but got int',)
3105 d.update(((u"\0", 0),)):TypeError:('expected string without null bytes',)
3106 d.update((("\0", 0),)):TypeError:('expected string without null bytes',)
3107 <<< Finished
3108 >>> Testing StringToChars using d.update((("a", {%s : 1}),))
3109 d.update((("a", {1 : 1}),)):TypeError:('expected str() or unicode() instance, but got int',)
3110 d.update((("a", {u"\0" : 1}),)):TypeError:('expected string without null bytes',)
3111 d.update((("a", {"\0" : 1}),)):TypeError:('expected string without null bytes',)
3112 <<< Finished
3113 >>> Testing StringToChars using d.update((("a", {"abcF" : {%s : 1}}),))
3114 d.update((("a", {"abcF" : {1 : 1}}),)):TypeError:('expected str() or unicode() instance, but got int',)
3115 d.update((("a", {"abcF" : {u"\0" : 1}}),)):TypeError:('expected string without null bytes',)
3116 d.update((("a", {"abcF" : {"\0" : 1}}),)):TypeError:('expected string without null bytes',)
3117 <<< Finished
3118 >>> Testing StringToChars using d.update((("a", {"abcF" : Mapping({%s : 1})}),))
3119 d.update((("a", {"abcF" : Mapping({1 : 1})}),)):TypeError:('expected str() or unicode() instance, but got int',)
3120 d.update((("a", {"abcF" : Mapping({u"\0" : 1})}),)):TypeError:('expected string without null bytes',)
3121 d.update((("a", {"abcF" : Mapping({"\0" : 1})}),)):TypeError:('expected string without null bytes',)
3122 <<< Finished
3123 >>> Testing *Iter* using d.update((("a", {"abcF" : %s}),))
3124 d.update((("a", {"abcF" : FailingIter()}),)):TypeError:('unable to convert FailingIter to a Vim structure',)
3125 d.update((("a", {"abcF" : FailingIterNext()}),)):NotImplementedError:('next',)
3126 <<< Finished
3127 >>> Testing ConvertFromPyObject using d.update((("a", {"abcF" : %s}),))
3128 d.update((("a", {"abcF" : None}),)):error:("failed to add key 'a' to dictionary",)
3129 d.update((("a", {"abcF" : {"": 1}}),)):ValueError:('empty keys are not allowed',)
3130 d.update((("a", {"abcF" : {u"": 1}}),)):ValueError:('empty keys are not allowed',)
3131 d.update((("a", {"abcF" : FailingMapping()}),)):NotImplementedError:('keys',)
3132 d.update((("a", {"abcF" : FailingMappingKey()}),)):NotImplementedError:('getitem:mappingkey',)
3133 d.update((("a", {"abcF" : FailingNumber()}),)):TypeError:('long() argument must be a string or a number',)
3134 <<< Finished
3135 >>> Testing StringToChars using d.update((("a", Mapping({%s : 1})),))
3136 d.update((("a", Mapping({1 : 1})),)):TypeError:('expected str() or unicode() instance, but got int',)
3137 d.update((("a", Mapping({u"\0" : 1})),)):TypeError:('expected string without null bytes',)
3138 d.update((("a", Mapping({"\0" : 1})),)):TypeError:('expected string without null bytes',)
3139 <<< Finished
3140 >>> Testing StringToChars using d.update((("a", Mapping({"abcG" : {%s : 1}})),))
3141 d.update((("a", Mapping({"abcG" : {1 : 1}})),)):TypeError:('expected str() or unicode() instance, but got int',)
3142 d.update((("a", Mapping({"abcG" : {u"\0" : 1}})),)):TypeError:('expected string without null bytes',)
3143 d.update((("a", Mapping({"abcG" : {"\0" : 1}})),)):TypeError:('expected string without null bytes',)
3144 <<< Finished
3145 >>> Testing StringToChars using d.update((("a", Mapping({"abcG" : Mapping({%s : 1})})),))
3146 d.update((("a", Mapping({"abcG" : Mapping({1 : 1})})),)):TypeError:('expected str() or unicode() instance, but got int',)
3147 d.update((("a", Mapping({"abcG" : Mapping({u"\0" : 1})})),)):TypeError:('expected string without null bytes',)
3148 d.update((("a", Mapping({"abcG" : Mapping({"\0" : 1})})),)):TypeError:('expected string without null bytes',)
3149 <<< Finished
3150 >>> Testing *Iter* using d.update((("a", Mapping({"abcG" : %s})),))
3151 d.update((("a", Mapping({"abcG" : FailingIter()})),)):TypeError:('unable to convert FailingIter to a Vim structure',)
3152 d.update((("a", Mapping({"abcG" : FailingIterNext()})),)):NotImplementedError:('next',)
3153 <<< Finished
3154 >>> Testing ConvertFromPyObject using d.update((("a", Mapping({"abcG" : %s})),))
3155 d.update((("a", Mapping({"abcG" : None})),)):error:("failed to add key 'a' to dictionary",)
3156 d.update((("a", Mapping({"abcG" : {"": 1}})),)):ValueError:('empty keys are not allowed',)
3157 d.update((("a", Mapping({"abcG" : {u"": 1}})),)):ValueError:('empty keys are not allowed',)
3158 d.update((("a", Mapping({"abcG" : FailingMapping()})),)):NotImplementedError:('keys',)
3159 d.update((("a", Mapping({"abcG" : FailingMappingKey()})),)):NotImplementedError:('getitem:mappingkey',)
3160 d.update((("a", Mapping({"abcG" : FailingNumber()})),)):TypeError:('long() argument must be a string or a number',)
3161 <<< Finished
3162 >>> Testing *Iter* using d.update((("a", %s),))
3163 d.update((("a", FailingIter()),)):TypeError:('unable to convert FailingIter to a Vim structure',)
3164 d.update((("a", FailingIterNext()),)):NotImplementedError:('next',)
3165 <<< Finished
3166 >>> Testing ConvertFromPyObject using d.update((("a", %s),))
3167 d.update((("a", None),)):error:("failed to add key 'a' to dictionary",)
3168 d.update((("a", {"": 1}),)):ValueError:('empty keys are not allowed',)
3169 d.update((("a", {u"": 1}),)):ValueError:('empty keys are not allowed',)
3170 d.update((("a", FailingMapping()),)):NotImplementedError:('keys',)
3171 d.update((("a", FailingMappingKey()),)):NotImplementedError:('getitem:mappingkey',)
3172 d.update((("a", FailingNumber()),)):TypeError:('long() argument must be a string or a number',)
3173 <<< Finished
3174 >> DictionaryPopItem
3175 d.popitem(1, 2):TypeError:('popitem() takes no arguments (2 given)',)
3176 >> DictionaryHasKey
3177 d.has_key():TypeError:('has_key() takes exactly one argument (0 given)',)
3178 > List
3179 >> ListConstructor
3180 vim.List(1, 2):TypeError:('function takes at most 1 argument (2 given)',)
3181 vim.List(a=1):TypeError:('list constructor does not accept keyword arguments',)
3182 >>> Testing *Iter* using vim.List(%s)
3183 vim.List(FailingIter()):NotImplementedError:('iter',)
3184 vim.List(FailingIterNext()):NotImplementedError:('next',)
3185 <<< Finished
3186 >>> Testing StringToChars using vim.List([{%s : 1}])
3187 vim.List([{1 : 1}]):TypeError:('expected str() or unicode() instance, but got int',)
3188 vim.List([{u"\0" : 1}]):TypeError:('expected string without null bytes',)
3189 vim.List([{"\0" : 1}]):TypeError:('expected string without null bytes',)
3190 <<< Finished
3191 >>> Testing StringToChars using vim.List([{"abcF" : {%s : 1}}])
3192 vim.List([{"abcF" : {1 : 1}}]):TypeError:('expected str() or unicode() instance, but got int',)
3193 vim.List([{"abcF" : {u"\0" : 1}}]):TypeError:('expected string without null bytes',)
3194 vim.List([{"abcF" : {"\0" : 1}}]):TypeError:('expected string without null bytes',)
3195 <<< Finished
3196 >>> Testing StringToChars using vim.List([{"abcF" : Mapping({%s : 1})}])
3197 vim.List([{"abcF" : Mapping({1 : 1})}]):TypeError:('expected str() or unicode() instance, but got int',)
3198 vim.List([{"abcF" : Mapping({u"\0" : 1})}]):TypeError:('expected string without null bytes',)
3199 vim.List([{"abcF" : Mapping({"\0" : 1})}]):TypeError:('expected string without null bytes',)
3200 <<< Finished
3201 >>> Testing *Iter* using vim.List([{"abcF" : %s}])
3202 vim.List([{"abcF" : FailingIter()}]):TypeError:('unable to convert FailingIter to a Vim structure',)
3203 vim.List([{"abcF" : FailingIterNext()}]):NotImplementedError:('next',)
3204 <<< Finished
3205 >>> Testing ConvertFromPyObject using vim.List([{"abcF" : %s}])
3206 vim.List([{"abcF" : None}]):NOT FAILED
3207 vim.List([{"abcF" : {"": 1}}]):ValueError:('empty keys are not allowed',)
3208 vim.List([{"abcF" : {u"": 1}}]):ValueError:('empty keys are not allowed',)
3209 vim.List([{"abcF" : FailingMapping()}]):NotImplementedError:('keys',)
3210 vim.List([{"abcF" : FailingMappingKey()}]):NotImplementedError:('getitem:mappingkey',)
3211 vim.List([{"abcF" : FailingNumber()}]):TypeError:('long() argument must be a string or a number',)
3212 <<< Finished
3213 >>> Testing StringToChars using vim.List([Mapping({%s : 1})])
3214 vim.List([Mapping({1 : 1})]):TypeError:('expected str() or unicode() instance, but got int',)
3215 vim.List([Mapping({u"\0" : 1})]):TypeError:('expected string without null bytes',)
3216 vim.List([Mapping({"\0" : 1})]):TypeError:('expected string without null bytes',)
3217 <<< Finished
3218 >>> Testing StringToChars using vim.List([Mapping({"abcG" : {%s : 1}})])
3219 vim.List([Mapping({"abcG" : {1 : 1}})]):TypeError:('expected str() or unicode() instance, but got int',)
3220 vim.List([Mapping({"abcG" : {u"\0" : 1}})]):TypeError:('expected string without null bytes',)
3221 vim.List([Mapping({"abcG" : {"\0" : 1}})]):TypeError:('expected string without null bytes',)
3222 <<< Finished
3223 >>> Testing StringToChars using vim.List([Mapping({"abcG" : Mapping({%s : 1})})])
3224 vim.List([Mapping({"abcG" : Mapping({1 : 1})})]):TypeError:('expected str() or unicode() instance, but got int',)
3225 vim.List([Mapping({"abcG" : Mapping({u"\0" : 1})})]):TypeError:('expected string without null bytes',)
3226 vim.List([Mapping({"abcG" : Mapping({"\0" : 1})})]):TypeError:('expected string without null bytes',)
3227 <<< Finished
3228 >>> Testing *Iter* using vim.List([Mapping({"abcG" : %s})])
3229 vim.List([Mapping({"abcG" : FailingIter()})]):TypeError:('unable to convert FailingIter to a Vim structure',)
3230 vim.List([Mapping({"abcG" : FailingIterNext()})]):NotImplementedError:('next',)
3231 <<< Finished
3232 >>> Testing ConvertFromPyObject using vim.List([Mapping({"abcG" : %s})])
3233 vim.List([Mapping({"abcG" : None})]):NOT FAILED
3234 vim.List([Mapping({"abcG" : {"": 1}})]):ValueError:('empty keys are not allowed',)
3235 vim.List([Mapping({"abcG" : {u"": 1}})]):ValueError:('empty keys are not allowed',)
3236 vim.List([Mapping({"abcG" : FailingMapping()})]):NotImplementedError:('keys',)
3237 vim.List([Mapping({"abcG" : FailingMappingKey()})]):NotImplementedError:('getitem:mappingkey',)
3238 vim.List([Mapping({"abcG" : FailingNumber()})]):TypeError:('long() argument must be a string or a number',)
3239 <<< Finished
3240 >>> Testing *Iter* using vim.List([%s])
3241 vim.List([FailingIter()]):TypeError:('unable to convert FailingIter to a Vim structure',)
3242 vim.List([FailingIterNext()]):NotImplementedError:('next',)
3243 <<< Finished
3244 >>> Testing ConvertFromPyObject using vim.List([%s])
3245 vim.List([None]):NOT FAILED
3246 vim.List([{"": 1}]):ValueError:('empty keys are not allowed',)
3247 vim.List([{u"": 1}]):ValueError:('empty keys are not allowed',)
3248 vim.List([FailingMapping()]):NotImplementedError:('keys',)
3249 vim.List([FailingMappingKey()]):NotImplementedError:('getitem:mappingkey',)
3250 vim.List([FailingNumber()]):TypeError:('long() argument must be a string or a number',)
3251 <<< Finished
3252 >> ListItem
3253 l[1000]:IndexError:('list index out of range',)
3254 >> ListAssItem
3255 ll[1] = 2:error:('list is locked',)
3256 l[1000] = 3:IndexError:('list index out of range',)
3257 >> ListAssSlice
3258 ll[1:100] = "abcJ":error:('list is locked',)
3259 >>> Testing *Iter* using l[:] = %s
3260 l[:] = FailingIter():NotImplementedError:('iter',)
3261 l[:] = FailingIterNext():NotImplementedError:('next',)
3262 <<< Finished
3263 nel[1:10:2] = "abcK":ValueError:('attempt to assign sequence of size greater than 2 to extended slice',)
3264 ('a', 'b', 'c', 'O')
3265 nel[1:10:2] = "a":ValueError:('attempt to assign sequence of size 1 to extended slice of size 2',)
3266 ('a', 'b', 'c', 'O')
3267 nel[1:1:-1] = "a":ValueError:('attempt to assign sequence of size greater than 0 to extended slice',)
3268 ('a', 'b', 'c', 'O')
3269 nel[:] = FailingIterNextN(2):NotImplementedError:('next N',)
3270 ('a', 'b', 'c', 'O')
3271 >>> Testing StringToChars using l[:] = [{%s : 1}]
3272 l[:] = [{1 : 1}]:TypeError:('expected str() or unicode() instance, but got int',)
3273 l[:] = [{u"\0" : 1}]:TypeError:('expected string without null bytes',)
3274 l[:] = [{"\0" : 1}]:TypeError:('expected string without null bytes',)
3275 <<< Finished
3276 >>> Testing StringToChars using l[:] = [{"abcF" : {%s : 1}}]
3277 l[:] = [{"abcF" : {1 : 1}}]:TypeError:('expected str() or unicode() instance, but got int',)
3278 l[:] = [{"abcF" : {u"\0" : 1}}]:TypeError:('expected string without null bytes',)
3279 l[:] = [{"abcF" : {"\0" : 1}}]:TypeError:('expected string without null bytes',)
3280 <<< Finished
3281 >>> Testing StringToChars using l[:] = [{"abcF" : Mapping({%s : 1})}]
3282 l[:] = [{"abcF" : Mapping({1 : 1})}]:TypeError:('expected str() or unicode() instance, but got int',)
3283 l[:] = [{"abcF" : Mapping({u"\0" : 1})}]:TypeError:('expected string without null bytes',)
3284 l[:] = [{"abcF" : Mapping({"\0" : 1})}]:TypeError:('expected string without null bytes',)
3285 <<< Finished
3286 >>> Testing *Iter* using l[:] = [{"abcF" : %s}]
3287 l[:] = [{"abcF" : FailingIter()}]:TypeError:('unable to convert FailingIter to a Vim structure',)
3288 l[:] = [{"abcF" : FailingIterNext()}]:NotImplementedError:('next',)
3289 <<< Finished
3290 >>> Testing ConvertFromPyObject using l[:] = [{"abcF" : %s}]
3291 l[:] = [{"abcF" : None}]:NOT FAILED
3292 l[:] = [{"abcF" : {"": 1}}]:ValueError:('empty keys are not allowed',)
3293 l[:] = [{"abcF" : {u"": 1}}]:ValueError:('empty keys are not allowed',)
3294 l[:] = [{"abcF" : FailingMapping()}]:NotImplementedError:('keys',)
3295 l[:] = [{"abcF" : FailingMappingKey()}]:NotImplementedError:('getitem:mappingkey',)
3296 l[:] = [{"abcF" : FailingNumber()}]:TypeError:('long() argument must be a string or a number',)
3297 <<< Finished
3298 >>> Testing StringToChars using l[:] = [Mapping({%s : 1})]
3299 l[:] = [Mapping({1 : 1})]:TypeError:('expected str() or unicode() instance, but got int',)
3300 l[:] = [Mapping({u"\0" : 1})]:TypeError:('expected string without null bytes',)
3301 l[:] = [Mapping({"\0" : 1})]:TypeError:('expected string without null bytes',)
3302 <<< Finished
3303 >>> Testing StringToChars using l[:] = [Mapping({"abcG" : {%s : 1}})]
3304 l[:] = [Mapping({"abcG" : {1 : 1}})]:TypeError:('expected str() or unicode() instance, but got int',)
3305 l[:] = [Mapping({"abcG" : {u"\0" : 1}})]:TypeError:('expected string without null bytes',)
3306 l[:] = [Mapping({"abcG" : {"\0" : 1}})]:TypeError:('expected string without null bytes',)
3307 <<< Finished
3308 >>> Testing StringToChars using l[:] = [Mapping({"abcG" : Mapping({%s : 1})})]
3309 l[:] = [Mapping({"abcG" : Mapping({1 : 1})})]:TypeError:('expected str() or unicode() instance, but got int',)
3310 l[:] = [Mapping({"abcG" : Mapping({u"\0" : 1})})]:TypeError:('expected string without null bytes',)
3311 l[:] = [Mapping({"abcG" : Mapping({"\0" : 1})})]:TypeError:('expected string without null bytes',)
3312 <<< Finished
3313 >>> Testing *Iter* using l[:] = [Mapping({"abcG" : %s})]
3314 l[:] = [Mapping({"abcG" : FailingIter()})]:TypeError:('unable to convert FailingIter to a Vim structure',)
3315 l[:] = [Mapping({"abcG" : FailingIterNext()})]:NotImplementedError:('next',)
3316 <<< Finished
3317 >>> Testing ConvertFromPyObject using l[:] = [Mapping({"abcG" : %s})]
3318 l[:] = [Mapping({"abcG" : None})]:NOT FAILED
3319 l[:] = [Mapping({"abcG" : {"": 1}})]:ValueError:('empty keys are not allowed',)
3320 l[:] = [Mapping({"abcG" : {u"": 1}})]:ValueError:('empty keys are not allowed',)
3321 l[:] = [Mapping({"abcG" : FailingMapping()})]:NotImplementedError:('keys',)
3322 l[:] = [Mapping({"abcG" : FailingMappingKey()})]:NotImplementedError:('getitem:mappingkey',)
3323 l[:] = [Mapping({"abcG" : FailingNumber()})]:TypeError:('long() argument must be a string or a number',)
3324 <<< Finished
3325 >>> Testing *Iter* using l[:] = [%s]
3326 l[:] = [FailingIter()]:TypeError:('unable to convert FailingIter to a Vim structure',)
3327 l[:] = [FailingIterNext()]:NotImplementedError:('next',)
3328 <<< Finished
3329 >>> Testing ConvertFromPyObject using l[:] = [%s]
3330 l[:] = [None]:NOT FAILED
3331 l[:] = [{"": 1}]:ValueError:('empty keys are not allowed',)
3332 l[:] = [{u"": 1}]:ValueError:('empty keys are not allowed',)
3333 l[:] = [FailingMapping()]:NotImplementedError:('keys',)
3334 l[:] = [FailingMappingKey()]:NotImplementedError:('getitem:mappingkey',)
3335 l[:] = [FailingNumber()]:TypeError:('long() argument must be a string or a number',)
3336 <<< Finished
3337 >> ListConcatInPlace
3338 >>> Testing *Iter* using l.extend(%s)
3339 l.extend(FailingIter()):NotImplementedError:('iter',)
3340 l.extend(FailingIterNext()):NotImplementedError:('next',)
3341 <<< Finished
3342 >>> Testing StringToChars using l.extend([{%s : 1}])
3343 l.extend([{1 : 1}]):TypeError:('expected str() or unicode() instance, but got int',)
3344 l.extend([{u"\0" : 1}]):TypeError:('expected string without null bytes',)
3345 l.extend([{"\0" : 1}]):TypeError:('expected string without null bytes',)
3346 <<< Finished
3347 >>> Testing StringToChars using l.extend([{"abcF" : {%s : 1}}])
3348 l.extend([{"abcF" : {1 : 1}}]):TypeError:('expected str() or unicode() instance, but got int',)
3349 l.extend([{"abcF" : {u"\0" : 1}}]):TypeError:('expected string without null bytes',)
3350 l.extend([{"abcF" : {"\0" : 1}}]):TypeError:('expected string without null bytes',)
3351 <<< Finished
3352 >>> Testing StringToChars using l.extend([{"abcF" : Mapping({%s : 1})}])
3353 l.extend([{"abcF" : Mapping({1 : 1})}]):TypeError:('expected str() or unicode() instance, but got int',)
3354 l.extend([{"abcF" : Mapping({u"\0" : 1})}]):TypeError:('expected string without null bytes',)
3355 l.extend([{"abcF" : Mapping({"\0" : 1})}]):TypeError:('expected string without null bytes',)
3356 <<< Finished
3357 >>> Testing *Iter* using l.extend([{"abcF" : %s}])
3358 l.extend([{"abcF" : FailingIter()}]):TypeError:('unable to convert FailingIter to a Vim structure',)
3359 l.extend([{"abcF" : FailingIterNext()}]):NotImplementedError:('next',)
3360 <<< Finished
3361 >>> Testing ConvertFromPyObject using l.extend([{"abcF" : %s}])
3362 l.extend([{"abcF" : None}]):NOT FAILED
3363 l.extend([{"abcF" : {"": 1}}]):ValueError:('empty keys are not allowed',)
3364 l.extend([{"abcF" : {u"": 1}}]):ValueError:('empty keys are not allowed',)
3365 l.extend([{"abcF" : FailingMapping()}]):NotImplementedError:('keys',)
3366 l.extend([{"abcF" : FailingMappingKey()}]):NotImplementedError:('getitem:mappingkey',)
3367 l.extend([{"abcF" : FailingNumber()}]):TypeError:('long() argument must be a string or a number',)
3368 <<< Finished
3369 >>> Testing StringToChars using l.extend([Mapping({%s : 1})])
3370 l.extend([Mapping({1 : 1})]):TypeError:('expected str() or unicode() instance, but got int',)
3371 l.extend([Mapping({u"\0" : 1})]):TypeError:('expected string without null bytes',)
3372 l.extend([Mapping({"\0" : 1})]):TypeError:('expected string without null bytes',)
3373 <<< Finished
3374 >>> Testing StringToChars using l.extend([Mapping({"abcG" : {%s : 1}})])
3375 l.extend([Mapping({"abcG" : {1 : 1}})]):TypeError:('expected str() or unicode() instance, but got int',)
3376 l.extend([Mapping({"abcG" : {u"\0" : 1}})]):TypeError:('expected string without null bytes',)
3377 l.extend([Mapping({"abcG" : {"\0" : 1}})]):TypeError:('expected string without null bytes',)
3378 <<< Finished
3379 >>> Testing StringToChars using l.extend([Mapping({"abcG" : Mapping({%s : 1})})])
3380 l.extend([Mapping({"abcG" : Mapping({1 : 1})})]):TypeError:('expected str() or unicode() instance, but got int',)
3381 l.extend([Mapping({"abcG" : Mapping({u"\0" : 1})})]):TypeError:('expected string without null bytes',)
3382 l.extend([Mapping({"abcG" : Mapping({"\0" : 1})})]):TypeError:('expected string without null bytes',)
3383 <<< Finished
3384 >>> Testing *Iter* using l.extend([Mapping({"abcG" : %s})])
3385 l.extend([Mapping({"abcG" : FailingIter()})]):TypeError:('unable to convert FailingIter to a Vim structure',)
3386 l.extend([Mapping({"abcG" : FailingIterNext()})]):NotImplementedError:('next',)
3387 <<< Finished
3388 >>> Testing ConvertFromPyObject using l.extend([Mapping({"abcG" : %s})])
3389 l.extend([Mapping({"abcG" : None})]):NOT FAILED
3390 l.extend([Mapping({"abcG" : {"": 1}})]):ValueError:('empty keys are not allowed',)
3391 l.extend([Mapping({"abcG" : {u"": 1}})]):ValueError:('empty keys are not allowed',)
3392 l.extend([Mapping({"abcG" : FailingMapping()})]):NotImplementedError:('keys',)
3393 l.extend([Mapping({"abcG" : FailingMappingKey()})]):NotImplementedError:('getitem:mappingkey',)
3394 l.extend([Mapping({"abcG" : FailingNumber()})]):TypeError:('long() argument must be a string or a number',)
3395 <<< Finished
3396 >>> Testing *Iter* using l.extend([%s])
3397 l.extend([FailingIter()]):TypeError:('unable to convert FailingIter to a Vim structure',)
3398 l.extend([FailingIterNext()]):NotImplementedError:('next',)
3399 <<< Finished
3400 >>> Testing ConvertFromPyObject using l.extend([%s])
3401 l.extend([None]):NOT FAILED
3402 l.extend([{"": 1}]):ValueError:('empty keys are not allowed',)
3403 l.extend([{u"": 1}]):ValueError:('empty keys are not allowed',)
3404 l.extend([FailingMapping()]):NotImplementedError:('keys',)
3405 l.extend([FailingMappingKey()]):NotImplementedError:('getitem:mappingkey',)
3406 l.extend([FailingNumber()]):TypeError:('long() argument must be a string or a number',)
3407 <<< Finished
3408 >> ListSetattr
3409 del l.locked:AttributeError:('cannot delete vim.List attributes',)
3410 l.locked = FailingTrue():NotImplementedError:('bool',)
3411 l.xxx = True:AttributeError:('cannot set attribute xxx',)
3412 > Function
3413 >> FunctionConstructor
3414 >>> FunctionConstructor
3415 vim.Function("123"):ValueError:('unnamed function 123 does not exist',)
3416 vim.Function("xxx_non_existent_function_xxx"):ValueError:('function xxx_non_existent_function_xxx does not exist',)
3417 vim.Function("xxx#non#existent#function#xxx"):NOT FAILED
3418 vim.Function("xxx_non_existent_function_xxx2", args=[]):ValueError:('function xxx_non_existent_function_xxx2 does not exist',)
3419 vim.Function("xxx_non_existent_function_xxx3", self={}):ValueError:('function xxx_non_existent_function_xxx3 does not exist',)
3420 vim.Function("xxx_non_existent_function_xxx4", args=[], self={}):ValueError:('function xxx_non_existent_function_xxx4 does not exist',)
3421 >>> FunctionNew
3422 vim.Function("tr", self="abcFuncSelf"):TypeError:('unable to convert str to a Vim dictionary',)
3423 vim.Function("tr", args=427423):TypeError:('unable to convert int to a Vim list',)
3424 vim.Function("tr", self="abcFuncSelf2", args="abcFuncArgs2"):TypeError:('unable to convert str to a Vim dictionary',)
3425 vim.Function(self="abcFuncSelf2", args="abcFuncArgs2"):TypeError:('unable to convert str to a Vim dictionary',)
3426 vim.Function("tr", "", self="abcFuncSelf2", args="abcFuncArgs2"):TypeError:('unable to convert str to a Vim dictionary',)
3427 vim.Function("tr", ""):TypeError:('function takes exactly 1 argument (2 given)',)
3428 >> FunctionCall
3429 >>> Testing StringToChars using f({%s : 1})
3430 f({1 : 1}):TypeError:('expected str() or unicode() instance, but got int',)
3431 f({u"\0" : 1}):TypeError:('expected string without null bytes',)
3432 f({"\0" : 1}):TypeError:('expected string without null bytes',)
3433 <<< Finished
3434 >>> Testing StringToChars using f({"abcF" : {%s : 1}})
3435 f({"abcF" : {1 : 1}}):TypeError:('expected str() or unicode() instance, but got int',)
3436 f({"abcF" : {u"\0" : 1}}):TypeError:('expected string without null bytes',)
3437 f({"abcF" : {"\0" : 1}}):TypeError:('expected string without null bytes',)
3438 <<< Finished
3439 >>> Testing StringToChars using f({"abcF" : Mapping({%s : 1})})
3440 f({"abcF" : Mapping({1 : 1})}):TypeError:('expected str() or unicode() instance, but got int',)
3441 f({"abcF" : Mapping({u"\0" : 1})}):TypeError:('expected string without null bytes',)
3442 f({"abcF" : Mapping({"\0" : 1})}):TypeError:('expected string without null bytes',)
3443 <<< Finished
3444 >>> Testing *Iter* using f({"abcF" : %s})
3445 f({"abcF" : FailingIter()}):TypeError:('unable to convert FailingIter to a Vim structure',)
3446 f({"abcF" : FailingIterNext()}):NotImplementedError:('next',)
3447 <<< Finished
3448 >>> Testing ConvertFromPyObject using f({"abcF" : %s})
3449 f({"abcF" : None}):NOT FAILED
3450 f({"abcF" : {"": 1}}):ValueError:('empty keys are not allowed',)
3451 f({"abcF" : {u"": 1}}):ValueError:('empty keys are not allowed',)
3452 f({"abcF" : FailingMapping()}):NotImplementedError:('keys',)
3453 f({"abcF" : FailingMappingKey()}):NotImplementedError:('getitem:mappingkey',)
3454 f({"abcF" : FailingNumber()}):TypeError:('long() argument must be a string or a number',)
3455 <<< Finished
3456 >>> Testing StringToChars using f(Mapping({%s : 1}))
3457 f(Mapping({1 : 1})):TypeError:('expected str() or unicode() instance, but got int',)
3458 f(Mapping({u"\0" : 1})):TypeError:('expected string without null bytes',)
3459 f(Mapping({"\0" : 1})):TypeError:('expected string without null bytes',)
3460 <<< Finished
3461 >>> Testing StringToChars using f(Mapping({"abcG" : {%s : 1}}))
3462 f(Mapping({"abcG" : {1 : 1}})):TypeError:('expected str() or unicode() instance, but got int',)
3463 f(Mapping({"abcG" : {u"\0" : 1}})):TypeError:('expected string without null bytes',)
3464 f(Mapping({"abcG" : {"\0" : 1}})):TypeError:('expected string without null bytes',)
3465 <<< Finished
3466 >>> Testing StringToChars using f(Mapping({"abcG" : Mapping({%s : 1})}))
3467 f(Mapping({"abcG" : Mapping({1 : 1})})):TypeError:('expected str() or unicode() instance, but got int',)
3468 f(Mapping({"abcG" : Mapping({u"\0" : 1})})):TypeError:('expected string without null bytes',)
3469 f(Mapping({"abcG" : Mapping({"\0" : 1})})):TypeError:('expected string without null bytes',)
3470 <<< Finished
3471 >>> Testing *Iter* using f(Mapping({"abcG" : %s}))
3472 f(Mapping({"abcG" : FailingIter()})):TypeError:('unable to convert FailingIter to a Vim structure',)
3473 f(Mapping({"abcG" : FailingIterNext()})):NotImplementedError:('next',)
3474 <<< Finished
3475 >>> Testing ConvertFromPyObject using f(Mapping({"abcG" : %s}))
3476 f(Mapping({"abcG" : None})):NOT FAILED
3477 f(Mapping({"abcG" : {"": 1}})):ValueError:('empty keys are not allowed',)
3478 f(Mapping({"abcG" : {u"": 1}})):ValueError:('empty keys are not allowed',)
3479 f(Mapping({"abcG" : FailingMapping()})):NotImplementedError:('keys',)
3480 f(Mapping({"abcG" : FailingMappingKey()})):NotImplementedError:('getitem:mappingkey',)
3481 f(Mapping({"abcG" : FailingNumber()})):TypeError:('long() argument must be a string or a number',)
3482 <<< Finished
3483 >>> Testing *Iter* using f(%s)
3484 f(FailingIter()):TypeError:('unable to convert FailingIter to a Vim structure',)
3485 f(FailingIterNext()):NotImplementedError:('next',)
3486 <<< Finished
3487 >>> Testing ConvertFromPyObject using f(%s)
3488 f(None):NOT FAILED
3489 f({"": 1}):ValueError:('empty keys are not allowed',)
3490 f({u"": 1}):ValueError:('empty keys are not allowed',)
3491 f(FailingMapping()):NotImplementedError:('keys',)
3492 f(FailingMappingKey()):NotImplementedError:('getitem:mappingkey',)
3493 f(FailingNumber()):TypeError:('long() argument must be a string or a number',)
3494 <<< Finished
3495 >>> Testing StringToChars using fd(self={%s : 1})
3496 fd(self={1 : 1}):TypeError:('expected str() or unicode() instance, but got int',)
3497 fd(self={u"\0" : 1}):TypeError:('expected string without null bytes',)
3498 fd(self={"\0" : 1}):TypeError:('expected string without null bytes',)
3499 <<< Finished
3500 >>> Testing StringToChars using fd(self={"abcF" : {%s : 1}})
3501 fd(self={"abcF" : {1 : 1}}):TypeError:('expected str() or unicode() instance, but got int',)
3502 fd(self={"abcF" : {u"\0" : 1}}):TypeError:('expected string without null bytes',)
3503 fd(self={"abcF" : {"\0" : 1}}):TypeError:('expected string without null bytes',)
3504 <<< Finished
3505 >>> Testing StringToChars using fd(self={"abcF" : Mapping({%s : 1})})
3506 fd(self={"abcF" : Mapping({1 : 1})}):TypeError:('expected str() or unicode() instance, but got int',)
3507 fd(self={"abcF" : Mapping({u"\0" : 1})}):TypeError:('expected string without null bytes',)
3508 fd(self={"abcF" : Mapping({"\0" : 1})}):TypeError:('expected string without null bytes',)
3509 <<< Finished
3510 >>> Testing *Iter* using fd(self={"abcF" : %s})
3511 fd(self={"abcF" : FailingIter()}):TypeError:('unable to convert FailingIter to a Vim structure',)
3512 fd(self={"abcF" : FailingIterNext()}):NotImplementedError:('next',)
3513 <<< Finished
3514 >>> Testing ConvertFromPyObject using fd(self={"abcF" : %s})
3515 fd(self={"abcF" : None}):NOT FAILED
3516 fd(self={"abcF" : {"": 1}}):ValueError:('empty keys are not allowed',)
3517 fd(self={"abcF" : {u"": 1}}):ValueError:('empty keys are not allowed',)
3518 fd(self={"abcF" : FailingMapping()}):NotImplementedError:('keys',)
3519 fd(self={"abcF" : FailingMappingKey()}):NotImplementedError:('getitem:mappingkey',)
3520 fd(self={"abcF" : FailingNumber()}):TypeError:('long() argument must be a string or a number',)
3521 <<< Finished
3522 >>> Testing StringToChars using fd(self=Mapping({%s : 1}))
3523 fd(self=Mapping({1 : 1})):TypeError:('expected str() or unicode() instance, but got int',)
3524 fd(self=Mapping({u"\0" : 1})):TypeError:('expected string without null bytes',)
3525 fd(self=Mapping({"\0" : 1})):TypeError:('expected string without null bytes',)
3526 <<< Finished
3527 >>> Testing StringToChars using fd(self=Mapping({"abcG" : {%s : 1}}))
3528 fd(self=Mapping({"abcG" : {1 : 1}})):TypeError:('expected str() or unicode() instance, but got int',)
3529 fd(self=Mapping({"abcG" : {u"\0" : 1}})):TypeError:('expected string without null bytes',)
3530 fd(self=Mapping({"abcG" : {"\0" : 1}})):TypeError:('expected string without null bytes',)
3531 <<< Finished
3532 >>> Testing StringToChars using fd(self=Mapping({"abcG" : Mapping({%s : 1})}))
3533 fd(self=Mapping({"abcG" : Mapping({1 : 1})})):TypeError:('expected str() or unicode() instance, but got int',)
3534 fd(self=Mapping({"abcG" : Mapping({u"\0" : 1})})):TypeError:('expected string without null bytes',)
3535 fd(self=Mapping({"abcG" : Mapping({"\0" : 1})})):TypeError:('expected string without null bytes',)
3536 <<< Finished
3537 >>> Testing *Iter* using fd(self=Mapping({"abcG" : %s}))
3538 fd(self=Mapping({"abcG" : FailingIter()})):TypeError:('unable to convert FailingIter to a Vim structure',)
3539 fd(self=Mapping({"abcG" : FailingIterNext()})):NotImplementedError:('next',)
3540 <<< Finished
3541 >>> Testing ConvertFromPyObject using fd(self=Mapping({"abcG" : %s}))
3542 fd(self=Mapping({"abcG" : None})):NOT FAILED
3543 fd(self=Mapping({"abcG" : {"": 1}})):ValueError:('empty keys are not allowed',)
3544 fd(self=Mapping({"abcG" : {u"": 1}})):ValueError:('empty keys are not allowed',)
3545 fd(self=Mapping({"abcG" : FailingMapping()})):NotImplementedError:('keys',)
3546 fd(self=Mapping({"abcG" : FailingMappingKey()})):NotImplementedError:('getitem:mappingkey',)
3547 fd(self=Mapping({"abcG" : FailingNumber()})):TypeError:('long() argument must be a string or a number',)
3548 <<< Finished
3549 >>> Testing *Iter* using fd(self=%s)
3550 fd(self=FailingIter()):TypeError:('unable to convert FailingIter to a Vim dictionary',)
3551 fd(self=FailingIterNext()):TypeError:('unable to convert FailingIterNext to a Vim dictionary',)
3552 <<< Finished
3553 >>> Testing ConvertFromPyObject using fd(self=%s)
3554 fd(self=None):TypeError:('unable to convert NoneType to a Vim dictionary',)
3555 fd(self={"": 1}):ValueError:('empty keys are not allowed',)
3556 fd(self={u"": 1}):ValueError:('empty keys are not allowed',)
3557 fd(self=FailingMapping()):NotImplementedError:('keys',)
3558 fd(self=FailingMappingKey()):NotImplementedError:('getitem:mappingkey',)
3559 fd(self=FailingNumber()):TypeError:('unable to convert FailingNumber to a Vim dictionary',)
3560 <<< Finished
3561 >>> Testing ConvertFromPyMapping using fd(self=%s)
3562 fd(self=[]):TypeError:('unable to convert list to a Vim dictionary',)
3563 <<< Finished
3564 > TabPage
3565 >> TabPageAttr
3566 vim.current.tabpage.xxx:AttributeError:('xxx',)
3567 > TabList
3568 >> TabListItem
3569 vim.tabpages[1000]:IndexError:('no such tab page',)
3570 > Window
3571 >> WindowAttr
3572 vim.current.window.xxx:AttributeError:('xxx',)
3573 >> WindowSetattr
3574 vim.current.window.buffer = 0:TypeError:('readonly attribute: buffer',)
3575 vim.current.window.cursor = (100000000, 100000000):error:('cursor position outside buffer',)
3576 vim.current.window.cursor = True:TypeError:('argument must be 2-item sequence, not bool',)
3577 >>> Testing NumberToLong using vim.current.window.height = %s
3578 vim.current.window.height = []:TypeError:('expected int(), long() or something supporting coercing to long(), but got list',)
3579 vim.current.window.height = None:TypeError:('expected int(), long() or something supporting coercing to long(), but got NoneType',)
3580 vim.current.window.height = -1:ValueError:('number must be greater or equal to zero',)
3581 <<< Finished
3582 >>> Testing NumberToLong using vim.current.window.width = %s
3583 vim.current.window.width = []:TypeError:('expected int(), long() or something supporting coercing to long(), but got list',)
3584 vim.current.window.width = None:TypeError:('expected int(), long() or something supporting coercing to long(), but got NoneType',)
3585 vim.current.window.width = -1:ValueError:('number must be greater or equal to zero',)
3586 <<< Finished
3587 vim.current.window.xxxxxx = True:AttributeError:('xxxxxx',)
3588 > WinList
3589 >> WinListItem
3590 vim.windows[1000]:IndexError:('no such window',)
3591 > Buffer
3592 >> StringToLine (indirect)
Bram Moolenaar92fdd1e2020-07-03 18:00:05 +02003593 vim.current.buffer[0] = "\na":error:('string cannot contain newlines',)
Bram Moolenaarab589462020-07-06 21:03:06 +02003594 vim.current.buffer[0] = u"\na":error:('string cannot contain newlines',)
Bram Moolenaar92fdd1e2020-07-03 18:00:05 +02003595 >> SetBufferLine (indirect)
3596 vim.current.buffer[0] = True:TypeError:('bad argument type for built-in operation',)
3597 >> SetBufferLineList (indirect)
3598 vim.current.buffer[:] = True:TypeError:('bad argument type for built-in operation',)
3599 vim.current.buffer[:] = ["\na", "bc"]:error:('string cannot contain newlines',)
3600 >> InsertBufferLines (indirect)
3601 vim.current.buffer.append(None):TypeError:('bad argument type for built-in operation',)
3602 vim.current.buffer.append(["\na", "bc"]):error:('string cannot contain newlines',)
3603 vim.current.buffer.append("\nbc"):error:('string cannot contain newlines',)
3604 >> RBItem
3605 vim.current.buffer[100000000]:IndexError:('line number out of range',)
3606 >> RBAsItem
3607 vim.current.buffer[100000000] = "":IndexError:('line number out of range',)
3608 >> BufferAttr
3609 vim.current.buffer.xxx:AttributeError:('xxx',)
3610 >> BufferSetattr
3611 vim.current.buffer.name = True:TypeError:('expected str() or unicode() instance, but got bool',)
3612 vim.current.buffer.xxx = True:AttributeError:('xxx',)
3613 >> BufferMark
3614 vim.current.buffer.mark(0):TypeError:('expected str() or unicode() instance, but got int',)
3615 vim.current.buffer.mark("abcM"):ValueError:('mark name must be a single character',)
3616 vim.current.buffer.mark("!"):error:('invalid mark name',)
3617 >> BufferRange
3618 vim.current.buffer.range(1, 2, 3):TypeError:('function takes exactly 2 arguments (3 given)',)
3619 > BufMap
3620 >> BufMapItem
3621 vim.buffers[100000000]:KeyError:(100000000,)
3622 >>> Testing NumberToLong using vim.buffers[%s]
3623 vim.buffers[[]]:TypeError:('expected int(), long() or something supporting coercing to long(), but got list',)
3624 vim.buffers[None]:TypeError:('expected int(), long() or something supporting coercing to long(), but got NoneType',)
3625 vim.buffers[-1]:ValueError:('number must be greater than zero',)
3626 vim.buffers[0]:ValueError:('number must be greater than zero',)
3627 <<< Finished
3628 > Current
3629 >> CurrentGetattr
3630 vim.current.xxx:AttributeError:('xxx',)
3631 >> CurrentSetattr
3632 vim.current.line = True:TypeError:('bad argument type for built-in operation',)
3633 vim.current.buffer = True:TypeError:('expected vim.Buffer object, but got bool',)
3634 vim.current.window = True:TypeError:('expected vim.Window object, but got bool',)
3635 vim.current.tabpage = True:TypeError:('expected vim.TabPage object, but got bool',)
3636 vim.current.xxx = True:AttributeError:('xxx',)
3637 END
3638
3639 call assert_equal(expected, getline(2, '$'))
3640 close!
3641endfunc
3642
3643" Test import
3644func Test_python_import()
3645 new
3646 py cb = vim.current.buffer
3647
3648 py << trim EOF
3649 sys.path.insert(0, os.path.join(os.getcwd(), 'python_before'))
3650 sys.path.append(os.path.join(os.getcwd(), 'python_after'))
3651 vim.options['rtp'] = os.getcwd().replace(',', '\\,').replace('\\', '\\\\')
3652 l = []
3653 def callback(path):
3654 l.append(path[-len('/testdir'):].replace(os.path.sep, '/'))
3655 vim.foreach_rtp(callback)
3656 cb.append(repr(l))
3657 del l
3658 def callback(path):
3659 return path[-len('/testdir'):].replace(os.path.sep, '/')
3660 cb.append(repr(vim.foreach_rtp(callback)))
3661 del callback
3662 from module import dir as d
3663 from modulex import ddir
3664 cb.append(d + ',' + ddir)
3665 import before
3666 cb.append(before.dir)
3667 import after
3668 cb.append(after.dir)
3669 import topmodule as tm
3670 import topmodule.submodule as tms
3671 import topmodule.submodule.subsubmodule.subsubsubmodule as tmsss
3672 cb.append(tm.__file__.replace('.pyc', '.py').replace(os.path.sep, '/')[-len('modulex/topmodule/__init__.py'):])
3673 cb.append(tms.__file__.replace('.pyc', '.py').replace(os.path.sep, '/')[-len('modulex/topmodule/submodule/__init__.py'):])
3674 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 +02003675
Bram Moolenaar92fdd1e2020-07-03 18:00:05 +02003676 del before
3677 del after
3678 del d
3679 del ddir
3680 del tm
3681 del tms
3682 del tmsss
3683 EOF
3684
3685 let expected =<< trim END
3686 ['/testdir']
3687 '/testdir'
3688 2,xx
3689 before
3690 after
3691 pythonx/topmodule/__init__.py
3692 pythonx/topmodule/submodule/__init__.py
3693 pythonx/topmodule/submodule/subsubmodule/subsubsubmodule.py
3694 END
3695 call assert_equal(expected, getline(2, '$'))
3696 close!
Bram Moolenaarab589462020-07-06 21:03:06 +02003697
Bram Moolenaar8e7d6222020-12-18 19:49:56 +01003698 " Try to import a non-existing module with a dot (.)
Bram Moolenaarab589462020-07-06 21:03:06 +02003699 call AssertException(['py import a.b.c'], 'ImportError:')
Bram Moolenaar92fdd1e2020-07-03 18:00:05 +02003700endfunc
3701
3702" Test exceptions
3703func Test_python_exception()
Bram Moolenaarab589462020-07-06 21:03:06 +02003704 func Exe(e)
Bram Moolenaar92fdd1e2020-07-03 18:00:05 +02003705 execute a:e
Bram Moolenaarab589462020-07-06 21:03:06 +02003706 endfunc
Bram Moolenaar92fdd1e2020-07-03 18:00:05 +02003707
3708 new
3709 py cb = vim.current.buffer
3710
3711 py << trim EOF
3712 Exe = vim.bindeval('function("Exe")')
3713 ee('vim.command("throw \'abcN\'")')
3714 ee('Exe("throw \'def\'")')
3715 ee('vim.eval("Exe(\'throw \'\'ghi\'\'\')")')
3716 ee('vim.eval("Exe(\'echoerr \'\'jkl\'\'\')")')
3717 ee('vim.eval("Exe(\'xxx_non_existent_command_xxx\')")')
3718 ee('vim.eval("xxx_unknown_function_xxx()")')
3719 ee('vim.bindeval("Exe(\'xxx_non_existent_command_xxx\')")')
3720 del Exe
3721 EOF
3722 delfunction Exe
3723
3724 let expected =<< trim END
3725 vim.command("throw 'abcN'"):error:('abcN',)
3726 Exe("throw 'def'"):error:('def',)
3727 vim.eval("Exe('throw ''ghi''')"):error:('ghi',)
3728 vim.eval("Exe('echoerr ''jkl''')"):error:('Vim(echoerr):jkl',)
3729 vim.eval("Exe('xxx_non_existent_command_xxx')"):error:('Vim:E492: Not an editor command: xxx_non_existent_command_xxx',)
3730 vim.eval("xxx_unknown_function_xxx()"):error:('Vim:E117: Unknown function: xxx_unknown_function_xxx',)
3731 vim.bindeval("Exe('xxx_non_existent_command_xxx')"):error:('Vim:E492: Not an editor command: xxx_non_existent_command_xxx',)
3732 END
3733 call assert_equal(expected, getline(2, '$'))
3734 close!
3735endfunc
3736
3737" Regression: interrupting vim.command propagates to next vim.command
3738func Test_python_keyboard_interrupt()
3739 new
3740 py cb = vim.current.buffer
3741 py << trim EOF
3742 def test_keyboard_interrupt():
3743 try:
3744 vim.command('while 1 | endwhile')
3745 except KeyboardInterrupt:
3746 cb.append('Caught KeyboardInterrupt')
3747 except Exception:
3748 cb.append('!!!!!!!! Caught exception: ' + emsg(sys.exc_info()))
3749 else:
3750 cb.append('!!!!!!!! No exception')
3751 try:
3752 vim.command('$ put =\'Running :put\'')
3753 except KeyboardInterrupt:
3754 cb.append('!!!!!!!! Caught KeyboardInterrupt')
3755 except Exception:
3756 cb.append('!!!!!!!! Caught exception: ' + emsg(sys.exc_info()))
3757 else:
3758 cb.append('No exception')
3759 EOF
3760
3761 debuggreedy
3762 call inputsave()
3763 call feedkeys("s\ns\ns\ns\nq\n")
3764 redir => output
3765 debug silent! py test_keyboard_interrupt()
3766 redir END
3767 0 debuggreedy
3768 call inputrestore()
3769 py del test_keyboard_interrupt
3770
3771 let expected =<< trim END
3772 Caught KeyboardInterrupt
3773 Running :put
3774 No exception
3775 END
3776 call assert_equal(expected, getline(2, '$'))
3777 call assert_equal('', output)
3778 close!
3779endfunc
3780
Bram Moolenaar2e2f52a2020-12-21 16:03:02 +01003781func Test_python_non_utf8_string()
3782 smap <Esc>@ <A-@>
3783 python vim.command('redir => _tmp_smaps | smap | redir END')
3784 python vim.eval('_tmp_smaps').splitlines()
3785 sunmap <Esc>@
3786endfunc
3787
Bram Moolenaar6c2b7b82020-04-14 20:15:49 +02003788" vim: shiftwidth=2 sts=2 expandtab