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