blob: ac43e6053090efaeaa1405c90ab83501b71f0546 [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
Bram Moolenaarab589462020-07-06 21:03:06 +0200812" Test for vim.bindeval()
813func Test_python_vim_bindeval()
814 " Float
815 let f = 3.14
816 py f = vim.bindeval('f')
817 call assert_equal(3.14, pyeval('f'))
Bram Moolenaar92fdd1e2020-07-03 18:00:05 +0200818
Bram Moolenaarab589462020-07-06 21:03:06 +0200819 " Blob
820 let b = 0z12
821 py b = vim.bindeval('b')
822 call assert_equal("\x12", pyeval('b'))
Bram Moolenaar92fdd1e2020-07-03 18:00:05 +0200823
Bram Moolenaarab589462020-07-06 21:03:06 +0200824 " Bool
825 call assert_equal(1, pyeval("vim.bindeval('v:true')"))
826 call assert_equal(0, pyeval("vim.bindeval('v:false')"))
827 call assert_equal(v:none, pyeval("vim.bindeval('v:null')"))
828 call assert_equal(v:none, pyeval("vim.bindeval('v:none')"))
Bram Moolenaar0ab55d62020-07-07 20:50:39 +0200829
830 " channel/job
Dominique Pelle56c9fd02021-05-19 00:16:14 +0200831 if has('channel')
832 call assert_equal(v:none, pyeval("vim.bindeval('test_null_channel()')"))
833 endif
834 if has('job')
835 call assert_equal(v:none, pyeval("vim.bindeval('test_null_job()')"))
836 endif
Bram Moolenaar92fdd1e2020-07-03 18:00:05 +0200837endfunc
838
839" threading
840" Running pydo command (Test_pydo) before this test, stops the python thread
841" from running. So this test should be run before the pydo test
842func Test_aaa_python_threading()
843 let l = [0]
844 py l = vim.bindeval('l')
845 py << trim EOF
846 import threading
847 import time
848
849 class T(threading.Thread):
850 def __init__(self):
851 threading.Thread.__init__(self)
852 self.t = 0
853 self.running = True
854
855 def run(self):
856 while self.running:
857 self.t += 1
858 time.sleep(0.1)
859
860 t = T()
861 del T
862 t.start()
863 EOF
864
865 sleep 1
866 py t.running = False
867 py t.join()
868
869 " Check if the background thread is working. Count should be 10, but on a
870 " busy system (AppVeyor) it can be much lower.
871 py l[0] = t.t > 4
872 py del time
873 py del threading
874 py del t
875 call assert_equal([1], l)
876endfunc
877
878" settrace
879func Test_python_settrace()
880 let l = []
881 py l = vim.bindeval('l')
882 py << trim EOF
883 import sys
884
885 def traceit(frame, event, arg):
886 global l
887 if event == "line":
888 l.extend([frame.f_lineno])
889 return traceit
890
891 def trace_main():
892 for i in range(5):
893 pass
894 EOF
895 py sys.settrace(traceit)
896 py trace_main()
897 py sys.settrace(None)
898 py del traceit
899 py del trace_main
900 call assert_equal([1, 10, 11, 10, 11, 10, 11, 10, 11, 10, 11, 10, 1], l)
901endfunc
902
903" Slice
904func Test_python_list_slice()
905 py ll = vim.bindeval('[0, 1, 2, 3, 4, 5]')
906 py l = ll[:4]
907 call assert_equal([0, 1, 2, 3], pyeval('l'))
908 py l = ll[2:]
909 call assert_equal([2, 3, 4, 5], pyeval('l'))
910 py l = ll[:-4]
911 call assert_equal([0, 1], pyeval('l'))
912 py l = ll[-2:]
913 call assert_equal([4, 5], pyeval('l'))
914 py l = ll[2:4]
915 call assert_equal([2, 3], pyeval('l'))
916 py l = ll[4:2]
917 call assert_equal([], pyeval('l'))
918 py l = ll[-4:-2]
919 call assert_equal([2, 3], pyeval('l'))
920 py l = ll[-2:-4]
921 call assert_equal([], pyeval('l'))
922 py l = ll[:]
923 call assert_equal([0, 1, 2, 3, 4, 5], pyeval('l'))
924 py l = ll[0:6]
925 call assert_equal([0, 1, 2, 3, 4, 5], pyeval('l'))
926 py l = ll[-10:10]
927 call assert_equal([0, 1, 2, 3, 4, 5], pyeval('l'))
928 py l = ll[4:2:-1]
929 call assert_equal([4, 3], pyeval('l'))
930 py l = ll[::2]
931 call assert_equal([0, 2, 4], pyeval('l'))
932 py l = ll[4:2:1]
933 call assert_equal([], pyeval('l'))
Bram Moolenaarab589462020-07-06 21:03:06 +0200934
935 " Error case: Use an invalid index
936 call AssertException(['py ll[-10] = 5'], 'Vim(python):vim.error: internal error:')
937
938 " Use a step value of 0
939 call AssertException(['py ll[0:3:0] = [1, 2, 3]'],
940 \ 'Vim(python):ValueError: slice step cannot be zero')
941
942 " Error case: Invalid slice type
943 call AssertException(["py x = ll['abc']"],
944 \ 'Vim(python):TypeError: index must be int or slice, not str')
Bram Moolenaar92fdd1e2020-07-03 18:00:05 +0200945 py del l
Bram Moolenaarab589462020-07-06 21:03:06 +0200946
947 " Error case: List with a null list item
948 let l = [test_null_list()]
949 py ll = vim.bindeval('l')
950 call AssertException(["py x = ll[:]"],
951 \ 'Vim(python):SystemError: error return without exception set')
Bram Moolenaar92fdd1e2020-07-03 18:00:05 +0200952endfunc
953
954" Vars
955func Test_python_vars()
956 let g:foo = 'bac'
957 let w:abc3 = 'def'
958 let b:baz = 'bar'
959 let t:bar = 'jkl'
960 try
961 throw "Abc"
962 catch /Abc/
963 call assert_equal('Abc', pyeval('vim.vvars[''exception'']'))
964 endtry
965 call assert_equal('bac', pyeval('vim.vars[''foo'']'))
966 call assert_equal('def', pyeval('vim.current.window.vars[''abc3'']'))
967 call assert_equal('bar', pyeval('vim.current.buffer.vars[''baz'']'))
968 call assert_equal('jkl', pyeval('vim.current.tabpage.vars[''bar'']'))
969endfunc
970
971" Options
972" paste: boolean, global
973" previewheight number, global
974" operatorfunc: string, global
975" number: boolean, window-local
976" numberwidth: number, window-local
977" colorcolumn: string, window-local
978" statusline: string, window-local/global
979" autoindent: boolean, buffer-local
980" shiftwidth: number, buffer-local
981" omnifunc: string, buffer-local
982" preserveindent: boolean, buffer-local/global
983" path: string, buffer-local/global
984func Test_python_opts()
985 let g:res = []
986 let g:bufs = [bufnr('%')]
987 new
988 let g:bufs += [bufnr('%')]
989 vnew
990 let g:bufs += [bufnr('%')]
991 wincmd j
992 vnew
993 let g:bufs += [bufnr('%')]
994 wincmd l
995
996 func RecVars(opt)
997 let gval = string(eval('&g:' .. a:opt))
998 let wvals = join(map(range(1, 4),
999 \ 'v:val .. ":" .. string(getwinvar(v:val, "&" .. a:opt))'))
1000 let bvals = join(map(copy(g:bufs),
1001 \ 'v:val .. ":" .. string(getbufvar(v:val, "&" .. a:opt))'))
1002 call add(g:res, ' G: ' .. gval)
1003 call add(g:res, ' W: ' .. wvals)
1004 call add(g:res, ' B: ' .. wvals)
1005 endfunc
1006
1007 py << trim EOF
1008 def e(s, g=globals(), l=locals()):
1009 try:
1010 exec(s, g, l)
1011 except:
1012 vim.command('return ' + repr(sys.exc_type.__name__))
1013
1014 def ev(s, g=globals(), l=locals()):
1015 try:
1016 return eval(s, g, l)
1017 except:
1018 vim.command('let exc=' + repr(sys.exc_type.__name__))
1019 return 0
1020 EOF
1021
1022 func E(s)
1023 python e(vim.eval('a:s'))
1024 endfunc
1025
1026 func Ev(s)
1027 let r = pyeval('ev(vim.eval("a:s"))')
1028 if exists('exc')
1029 throw exc
1030 endif
1031 return r
1032 endfunc
1033
1034 py gopts1 = vim.options
1035 py wopts1 = vim.windows[2].options
1036 py wopts2 = vim.windows[0].options
1037 py wopts3 = vim.windows[1].options
1038 py bopts1 = vim.buffers[vim.bindeval("g:bufs")[2]].options
1039 py bopts2 = vim.buffers[vim.bindeval("g:bufs")[1]].options
1040 py bopts3 = vim.buffers[vim.bindeval("g:bufs")[0]].options
1041 call add(g:res, 'wopts iters equal: ' ..
1042 \ pyeval('list(wopts1) == list(wopts2)'))
1043 call add(g:res, 'bopts iters equal: ' ..
1044 \ pyeval('list(bopts1) == list(bopts2)'))
1045 py gset = set(iter(gopts1))
1046 py wset = set(iter(wopts1))
1047 py bset = set(iter(bopts1))
1048
1049 set path=.,..,,
1050 let lst = []
1051 let lst += [['paste', 1, 0, 1, 2, 1, 1, 0]]
1052 let lst += [['previewheight', 5, 1, 6, 'a', 0, 1, 0]]
1053 let lst += [['operatorfunc', 'A', 'B', 'C', 2, 0, 1, 0]]
1054 let lst += [['number', 0, 1, 1, 0, 1, 0, 1]]
1055 let lst += [['numberwidth', 2, 3, 5, -100, 0, 0, 1]]
1056 let lst += [['colorcolumn', '+1', '+2', '+3', 'abc4', 0, 0, 1]]
1057 let lst += [['statusline', '1', '2', '4', 0, 0, 1, 1]]
1058 let lst += [['autoindent', 0, 1, 1, 2, 1, 0, 2]]
1059 let lst += [['shiftwidth', 0, 2, 1, 3, 0, 0, 2]]
1060 let lst += [['omnifunc', 'A', 'B', 'C', 1, 0, 0, 2]]
1061 let lst += [['preserveindent', 0, 1, 1, 2, 1, 1, 2]]
1062 let lst += [['path', '.,,', ',,', '.', 0, 0, 1, 2]]
1063 for [oname, oval1, oval2, oval3, invval, bool, global, local] in lst
1064 py oname = vim.eval('oname')
1065 py oval1 = vim.bindeval('oval1')
1066 py oval2 = vim.bindeval('oval2')
1067 py oval3 = vim.bindeval('oval3')
1068 if invval is 0 || invval is 1
1069 py invval = bool(vim.bindeval('invval'))
1070 else
1071 py invval = vim.bindeval('invval')
1072 endif
1073 if bool
1074 py oval1 = bool(oval1)
1075 py oval2 = bool(oval2)
1076 py oval3 = bool(oval3)
1077 endif
1078 call add(g:res, '>>> ' .. oname)
1079 call add(g:res, ' g/w/b:' .. pyeval('oname in gset') .. '/' ..
1080 \ pyeval('oname in wset') .. '/' .. pyeval('oname in bset'))
1081 call add(g:res, ' g/w/b (in):' .. pyeval('oname in gopts1') .. '/' ..
1082 \ pyeval('oname in wopts1') .. '/' .. pyeval('oname in bopts1'))
1083 for v in ['gopts1', 'wopts1', 'bopts1']
1084 try
1085 call add(g:res, ' p/' .. v .. ': ' .. Ev('repr(' .. v .. '[''' .. oname .. '''])'))
1086 catch
1087 call add(g:res, ' p/' .. v .. '! ' .. v:exception)
1088 endtry
1089 let r = E(v .. '[''' .. oname .. ''']=invval')
1090 if r isnot 0
1091 call add(g:res, ' inv: ' .. string(invval) .. '! ' .. r)
1092 endif
1093 for vv in (v is# 'gopts1' ? [v] : [v, v[:-2] .. '2', v[:-2] .. '3'])
1094 let val = substitute(vv, '^.opts', 'oval', '')
1095 let r = E(vv .. '[''' .. oname .. ''']=' .. val)
1096 if r isnot 0
1097 call add(g:res, ' ' .. vv .. '! ' .. r)
1098 endif
1099 endfor
1100 endfor
1101 call RecVars(oname)
1102 for v in ['wopts3', 'bopts3']
1103 let r = E('del ' .. v .. '["' .. oname .. '"]')
1104 if r isnot 0
1105 call add(g:res, ' del ' .. v .. '! ' .. r)
1106 endif
1107 endfor
1108 call RecVars(oname)
1109 endfor
1110 delfunction RecVars
1111 delfunction E
1112 delfunction Ev
1113 py del ev
1114 py del e
1115 only
1116 for buf in g:bufs[1:]
1117 execute 'bwipeout!' buf
1118 endfor
1119 py del gopts1
1120 py del wopts1
1121 py del wopts2
1122 py del wopts3
1123 py del bopts1
1124 py del bopts2
1125 py del bopts3
1126 py del oval1
1127 py del oval2
1128 py del oval3
1129 py del oname
1130 py del invval
1131
1132 let expected =<< trim END
1133 wopts iters equal: 1
1134 bopts iters equal: 1
1135 >>> paste
1136 g/w/b:1/0/0
1137 g/w/b (in):1/0/0
1138 p/gopts1: False
1139 p/wopts1! KeyError
1140 inv: 2! KeyError
1141 wopts1! KeyError
1142 wopts2! KeyError
1143 wopts3! KeyError
1144 p/bopts1! KeyError
1145 inv: 2! KeyError
1146 bopts1! KeyError
1147 bopts2! KeyError
1148 bopts3! KeyError
1149 G: 1
1150 W: 1:1 2:1 3:1 4:1
1151 B: 1:1 2:1 3:1 4:1
1152 del wopts3! KeyError
1153 del bopts3! KeyError
1154 G: 1
1155 W: 1:1 2:1 3:1 4:1
1156 B: 1:1 2:1 3:1 4:1
1157 >>> previewheight
1158 g/w/b:1/0/0
1159 g/w/b (in):1/0/0
1160 p/gopts1: 12
1161 inv: 'a'! TypeError
1162 p/wopts1! KeyError
1163 inv: 'a'! KeyError
1164 wopts1! KeyError
1165 wopts2! KeyError
1166 wopts3! KeyError
1167 p/bopts1! KeyError
1168 inv: 'a'! KeyError
1169 bopts1! KeyError
1170 bopts2! KeyError
1171 bopts3! KeyError
1172 G: 5
1173 W: 1:5 2:5 3:5 4:5
1174 B: 1:5 2:5 3:5 4:5
1175 del wopts3! KeyError
1176 del bopts3! KeyError
1177 G: 5
1178 W: 1:5 2:5 3:5 4:5
1179 B: 1:5 2:5 3:5 4:5
1180 >>> operatorfunc
1181 g/w/b:1/0/0
1182 g/w/b (in):1/0/0
1183 p/gopts1: ''
1184 inv: 2! TypeError
1185 p/wopts1! KeyError
1186 inv: 2! KeyError
1187 wopts1! KeyError
1188 wopts2! KeyError
1189 wopts3! KeyError
1190 p/bopts1! KeyError
1191 inv: 2! KeyError
1192 bopts1! KeyError
1193 bopts2! KeyError
1194 bopts3! KeyError
1195 G: 'A'
1196 W: 1:'A' 2:'A' 3:'A' 4:'A'
1197 B: 1:'A' 2:'A' 3:'A' 4:'A'
1198 del wopts3! KeyError
1199 del bopts3! KeyError
1200 G: 'A'
1201 W: 1:'A' 2:'A' 3:'A' 4:'A'
1202 B: 1:'A' 2:'A' 3:'A' 4:'A'
1203 >>> number
1204 g/w/b:0/1/0
1205 g/w/b (in):0/1/0
1206 p/gopts1! KeyError
1207 inv: 0! KeyError
1208 gopts1! KeyError
1209 p/wopts1: False
1210 p/bopts1! KeyError
1211 inv: 0! KeyError
1212 bopts1! KeyError
1213 bopts2! KeyError
1214 bopts3! KeyError
1215 G: 0
1216 W: 1:1 2:1 3:0 4:0
1217 B: 1:1 2:1 3:0 4:0
1218 del wopts3! ValueError
1219 del bopts3! KeyError
1220 G: 0
1221 W: 1:1 2:1 3:0 4:0
1222 B: 1:1 2:1 3:0 4:0
1223 >>> numberwidth
1224 g/w/b:0/1/0
1225 g/w/b (in):0/1/0
1226 p/gopts1! KeyError
1227 inv: -100! KeyError
1228 gopts1! KeyError
1229 p/wopts1: 4
1230 inv: -100! error
1231 p/bopts1! KeyError
1232 inv: -100! KeyError
1233 bopts1! KeyError
1234 bopts2! KeyError
1235 bopts3! KeyError
1236 G: 4
1237 W: 1:3 2:5 3:2 4:4
1238 B: 1:3 2:5 3:2 4:4
1239 del wopts3! ValueError
1240 del bopts3! KeyError
1241 G: 4
1242 W: 1:3 2:5 3:2 4:4
1243 B: 1:3 2:5 3:2 4:4
1244 >>> colorcolumn
1245 g/w/b:0/1/0
1246 g/w/b (in):0/1/0
1247 p/gopts1! KeyError
1248 inv: 'abc4'! KeyError
1249 gopts1! KeyError
1250 p/wopts1: ''
1251 inv: 'abc4'! error
1252 p/bopts1! KeyError
1253 inv: 'abc4'! KeyError
1254 bopts1! KeyError
1255 bopts2! KeyError
1256 bopts3! KeyError
1257 G: ''
1258 W: 1:'+2' 2:'+3' 3:'+1' 4:''
1259 B: 1:'+2' 2:'+3' 3:'+1' 4:''
1260 del wopts3! ValueError
1261 del bopts3! KeyError
1262 G: ''
1263 W: 1:'+2' 2:'+3' 3:'+1' 4:''
1264 B: 1:'+2' 2:'+3' 3:'+1' 4:''
1265 >>> statusline
1266 g/w/b:1/1/0
1267 g/w/b (in):1/1/0
1268 p/gopts1: ''
1269 inv: 0! TypeError
1270 p/wopts1: None
1271 inv: 0! TypeError
1272 p/bopts1! KeyError
1273 inv: 0! KeyError
1274 bopts1! KeyError
1275 bopts2! KeyError
1276 bopts3! KeyError
1277 G: '1'
1278 W: 1:'2' 2:'4' 3:'1' 4:'1'
1279 B: 1:'2' 2:'4' 3:'1' 4:'1'
1280 del bopts3! KeyError
1281 G: '1'
1282 W: 1:'2' 2:'1' 3:'1' 4:'1'
1283 B: 1:'2' 2:'1' 3:'1' 4:'1'
1284 >>> autoindent
1285 g/w/b:0/0/1
1286 g/w/b (in):0/0/1
1287 p/gopts1! KeyError
1288 inv: 2! KeyError
1289 gopts1! KeyError
1290 p/wopts1! KeyError
1291 inv: 2! KeyError
1292 wopts1! KeyError
1293 wopts2! KeyError
1294 wopts3! KeyError
1295 p/bopts1: False
1296 G: 0
1297 W: 1:0 2:1 3:0 4:1
1298 B: 1:0 2:1 3:0 4:1
1299 del wopts3! KeyError
1300 del bopts3! ValueError
1301 G: 0
1302 W: 1:0 2:1 3:0 4:1
1303 B: 1:0 2:1 3:0 4:1
1304 >>> shiftwidth
1305 g/w/b:0/0/1
1306 g/w/b (in):0/0/1
1307 p/gopts1! KeyError
1308 inv: 3! KeyError
1309 gopts1! KeyError
1310 p/wopts1! KeyError
1311 inv: 3! KeyError
1312 wopts1! KeyError
1313 wopts2! KeyError
1314 wopts3! KeyError
1315 p/bopts1: 8
1316 G: 8
1317 W: 1:0 2:2 3:8 4:1
1318 B: 1:0 2:2 3:8 4:1
1319 del wopts3! KeyError
1320 del bopts3! ValueError
1321 G: 8
1322 W: 1:0 2:2 3:8 4:1
1323 B: 1:0 2:2 3:8 4:1
1324 >>> omnifunc
1325 g/w/b:0/0/1
1326 g/w/b (in):0/0/1
1327 p/gopts1! KeyError
1328 inv: 1! KeyError
1329 gopts1! KeyError
1330 p/wopts1! KeyError
1331 inv: 1! KeyError
1332 wopts1! KeyError
1333 wopts2! KeyError
1334 wopts3! KeyError
1335 p/bopts1: ''
1336 inv: 1! TypeError
1337 G: ''
1338 W: 1:'A' 2:'B' 3:'' 4:'C'
1339 B: 1:'A' 2:'B' 3:'' 4:'C'
1340 del wopts3! KeyError
1341 del bopts3! ValueError
1342 G: ''
1343 W: 1:'A' 2:'B' 3:'' 4:'C'
1344 B: 1:'A' 2:'B' 3:'' 4:'C'
1345 >>> preserveindent
1346 g/w/b:0/0/1
1347 g/w/b (in):0/0/1
1348 p/gopts1! KeyError
1349 inv: 2! KeyError
1350 gopts1! KeyError
1351 p/wopts1! KeyError
1352 inv: 2! KeyError
1353 wopts1! KeyError
1354 wopts2! KeyError
1355 wopts3! KeyError
1356 p/bopts1: False
1357 G: 0
1358 W: 1:0 2:1 3:0 4:1
1359 B: 1:0 2:1 3:0 4:1
1360 del wopts3! KeyError
1361 del bopts3! ValueError
1362 G: 0
1363 W: 1:0 2:1 3:0 4:1
1364 B: 1:0 2:1 3:0 4:1
1365 >>> path
1366 g/w/b:1/0/1
1367 g/w/b (in):1/0/1
1368 p/gopts1: '.,..,,'
1369 inv: 0! TypeError
1370 p/wopts1! KeyError
1371 inv: 0! KeyError
1372 wopts1! KeyError
1373 wopts2! KeyError
1374 wopts3! KeyError
1375 p/bopts1: None
1376 inv: 0! TypeError
1377 G: '.,,'
1378 W: 1:'.,,' 2:',,' 3:'.,,' 4:'.'
1379 B: 1:'.,,' 2:',,' 3:'.,,' 4:'.'
1380 del wopts3! KeyError
1381 G: '.,,'
1382 W: 1:'.,,' 2:',,' 3:'.,,' 4:'.,,'
1383 B: 1:'.,,' 2:',,' 3:'.,,' 4:'.,,'
1384 END
1385
1386 call assert_equal(expected, g:res)
1387 unlet g:res
Bram Moolenaarab589462020-07-06 21:03:06 +02001388
1389 call assert_equal(0, pyeval("'' in vim.options"))
1390
1391 " use an empty key to index vim.options
1392 call AssertException(["let v = pyeval(\"vim.options['']\")"],
1393 \ 'Vim(let):ValueError: empty keys are not allowed')
1394 call AssertException(["py vim.current.window.options[''] = 0"],
1395 \ 'Vim(python):ValueError: empty keys are not allowed')
1396 call AssertException(["py vim.current.window.options[{}] = 0"],
1397 \ 'Vim(python):TypeError: expected str() or unicode() instance, but got dict')
1398
1399 " set one of the number options to a very large number
1400 let cmd = ["py vim.options['previewheight'] = 9999999999999999"]
1401 call AssertException(cmd, 'OverflowError:')
1402
1403 " unset a global-local string option
1404 call AssertException(["py del vim.options['errorformat']"],
1405 \ 'Vim(python):ValueError: unable to unset global option errorformat')
Bram Moolenaar92fdd1e2020-07-03 18:00:05 +02001406endfunc
1407
1408" Test for vim.buffer object
1409func Test_python_buffer()
1410 new
1411 call setline(1, "Hello\nWorld")
1412 call assert_fails("let x = pyeval('vim.current.buffer[0]')", 'E859:')
1413 %bw!
1414
1415 edit Xfile1
1416 let bnr1 = bufnr()
1417 py cb = vim.current.buffer
1418 vnew Xfile2
1419 let bnr2 = bufnr()
1420 call setline(1, ['First line', 'Second line', 'Third line'])
1421 py b = vim.current.buffer
1422 wincmd w
1423
Bram Moolenaarab589462020-07-06 21:03:06 +02001424 " Test for getting lines from the buffer using a slice
1425 call assert_equal(['First line'], pyeval('b[-10:1]'))
1426 call assert_equal(['Third line'], pyeval('b[2:10]'))
1427 call assert_equal([], pyeval('b[2:0]'))
1428 call assert_equal([], pyeval('b[10:12]'))
1429 call assert_equal([], pyeval('b[-10:-8]'))
Bram Moolenaar0ab55d62020-07-07 20:50:39 +02001430 call AssertException(["py x = b[0:3:0]"],
1431 \ "Vim(python):TypeError: sequence index must be integer, not 'slice'")
1432 call AssertException(["py b[0:3:0] = 'abc'"],
1433 \ "Vim(python):TypeError: sequence index must be integer, not 'slice'")
1434 call AssertException(["py x = b[{}]"],
1435 \ "Vim(python):TypeError: sequence index must be integer, not 'dict'")
1436 call AssertException(["py b[{}] = 'abc'"],
1437 \ "Vim(python):TypeError: sequence index must be integer, not 'dict'")
1438
1439 " Test for getting lines using a range
1440 call AssertException(["py x = b.range(0,3)[0:2:0]"],
1441 \ "Vim(python):TypeError: sequence index must be integer, not 'slice'")
1442 call AssertException(["py b.range(0,3)[0:2:0] = 'abc'"],
1443 \ "Vim(python):TypeError: sequence index must be integer, not 'slice'")
Bram Moolenaarab589462020-07-06 21:03:06 +02001444
Bram Moolenaar92fdd1e2020-07-03 18:00:05 +02001445 " Tests BufferAppend and BufferItem
1446 py cb.append(b[0])
1447 call assert_equal(['First line'], getbufline(bnr1, 2))
1448 %d
1449
Bram Moolenaarab589462020-07-06 21:03:06 +02001450 " Try to append using out-of-range line number
1451 call AssertException(["py b.append('abc', 10)"],
1452 \ 'Vim(python):IndexError: line number out of range')
1453
1454 " Append a non-string item
1455 call AssertException(["py b.append([22])"],
1456 \ 'Vim(python):TypeError: expected str() or unicode() instance, but got int')
1457
Bram Moolenaar92fdd1e2020-07-03 18:00:05 +02001458 " Tests BufferSlice and BufferAssSlice
1459 py cb.append('abc5') # Will be overwritten
1460 py cb[-1:] = b[:-2]
1461 call assert_equal(['First line'], getbufline(bnr1, 2))
1462 %d
1463
1464 " Test BufferLength and BufferAssSlice
1465 py cb.append('def') # Will not be overwritten
1466 py cb[len(cb):] = b[:]
1467 call assert_equal(['def', 'First line', 'Second line', 'Third line'],
1468 \ getbufline(bnr1, 2, '$'))
1469 %d
1470
1471 " Test BufferAssItem and BufferMark
1472 call setbufline(bnr1, 1, ['one', 'two', 'three'])
1473 call cursor(1, 3)
1474 normal ma
1475 py cb.append('ghi') # Will be overwritten
1476 py cb[-1] = repr((len(cb) - cb.mark('a')[0], cb.mark('a')[1]))
1477 call assert_equal(['(3, 2)'], getbufline(bnr1, 4))
1478 %d
1479
1480 " Test BufferRepr
1481 py cb.append(repr(cb) + repr(b))
1482 call assert_equal(['<buffer Xfile1><buffer Xfile2>'], getbufline(bnr1, 2))
1483 %d
1484
1485 " Modify foreign buffer
1486 py << trim EOF
1487 b.append('foo')
1488 b[0]='bar'
1489 b[0:0]=['baz']
1490 vim.command('call append("$", getbufline(%i, 1, "$"))' % b.number)
1491 EOF
1492 call assert_equal(['baz', 'bar', 'Second line', 'Third line', 'foo'],
1493 \ getbufline(bnr2, 1, '$'))
1494 %d
1495
1496 " Test assigning to name property
1497 augroup BUFS
Bram Moolenaareffb0cd2020-07-03 21:17:34 +02001498 autocmd BufFilePost * python cb.append(vim.eval('expand("<abuf>")') + ':BufFilePost:' + vim.eval('bufnr("%")'))
1499 autocmd BufFilePre * python cb.append(vim.eval('expand("<abuf>")') + ':BufFilePre:' + vim.eval('bufnr("%")'))
Bram Moolenaar92fdd1e2020-07-03 18:00:05 +02001500 augroup END
1501 py << trim EOF
1502 import os
1503 old_name = cb.name
1504 cb.name = 'foo'
1505 cb.append(cb.name[-11:].replace(os.path.sep, '/'))
1506 b.name = 'bar'
1507 cb.append(b.name[-11:].replace(os.path.sep, '/'))
1508 cb.name = old_name
1509 cb.append(cb.name[-14:].replace(os.path.sep, '/'))
1510 del old_name
1511 EOF
1512 call assert_equal([bnr1 .. ':BufFilePre:' .. bnr1,
1513 \ bnr1 .. ':BufFilePost:' .. bnr1,
1514 \ 'testdir/foo',
1515 \ bnr2 .. ':BufFilePre:' .. bnr2,
1516 \ bnr2 .. ':BufFilePost:' .. bnr2,
1517 \ 'testdir/bar',
1518 \ bnr1 .. ':BufFilePre:' .. bnr1,
1519 \ bnr1 .. ':BufFilePost:' .. bnr1,
1520 \ 'testdir/Xfile1'], getbufline(bnr1, 2, '$'))
1521 %d
1522
1523 " Test CheckBuffer
1524 py << trim EOF
1525 for _b in vim.buffers:
1526 if _b is not cb:
1527 vim.command('bwipeout! ' + str(_b.number))
1528 del _b
1529 cb.append('valid: b:%s, cb:%s' % (repr(b.valid), repr(cb.valid)))
1530 EOF
1531 call assert_equal('valid: b:False, cb:True', getline(2))
1532 %d
1533
1534 py << trim EOF
1535 for expr in ('b[1]','b[:] = ["A", "B"]','b[:]','b.append("abc6")', 'b.name = "!"'):
1536 try:
1537 exec(expr)
1538 except vim.error:
1539 pass
1540 else:
1541 # Usually a SEGV here
1542 # Should not happen in any case
1543 cb.append('No exception for ' + expr)
1544 vim.command('cd .')
1545 del b
1546 EOF
1547 call assert_equal([''], getline(1, '$'))
1548
Bram Moolenaarab589462020-07-06 21:03:06 +02001549 " Delete all the lines in a buffer
1550 call setline(1, ['a', 'b', 'c'])
1551 py vim.current.buffer[:] = []
1552 call assert_equal([''], getline(1, '$'))
1553
Bram Moolenaar0ab55d62020-07-07 20:50:39 +02001554 " Test for buffer marks
1555 call assert_equal(v:none, pyeval("vim.current.buffer.mark('r')"))
1556
Bram Moolenaarab589462020-07-06 21:03:06 +02001557 " Test for modifying a 'nomodifiable' buffer
1558 setlocal nomodifiable
1559 call AssertException(["py vim.current.buffer[0] = 'abc'"],
1560 \ "Vim(python):vim.error: Vim:E21: Cannot make changes, 'modifiable' is off")
1561 call AssertException(["py vim.current.buffer[0] = None"],
1562 \ "Vim(python):vim.error: Vim:E21: Cannot make changes, 'modifiable' is off")
1563 call AssertException(["py vim.current.buffer[:] = None"],
1564 \ "Vim(python):vim.error: Vim:E21: Cannot make changes, 'modifiable' is off")
1565 call AssertException(["py vim.current.buffer[:] = []"],
1566 \ "Vim(python):vim.error: Vim:E21: Cannot make changes, 'modifiable' is off")
1567 call AssertException(["py vim.current.buffer.append('abc')"],
1568 \ "Vim(python):vim.error: Vim:E21: Cannot make changes, 'modifiable' is off")
1569 call AssertException(["py vim.current.buffer.append([])"],
1570 \ "Vim(python):vim.error: Vim:E21: Cannot make changes, 'modifiable' is off")
1571 setlocal modifiable
1572
Bram Moolenaar92fdd1e2020-07-03 18:00:05 +02001573 augroup BUFS
Bram Moolenaareffb0cd2020-07-03 21:17:34 +02001574 autocmd!
Bram Moolenaar92fdd1e2020-07-03 18:00:05 +02001575 augroup END
1576 augroup! BUFS
1577 %bw!
Bram Moolenaarab589462020-07-06 21:03:06 +02001578
1579 " Range object for a deleted buffer
Bram Moolenaarb18b4962022-09-02 21:55:50 +01001580 new Xpbuffile
Bram Moolenaarab589462020-07-06 21:03:06 +02001581 call setline(1, ['one', 'two', 'three'])
1582 py b = vim.current.buffer
1583 py r = vim.current.buffer.range(0, 2)
Bram Moolenaarb18b4962022-09-02 21:55:50 +01001584 call assert_equal('<range Xpbuffile (0:2)>', pyeval('repr(r)'))
Bram Moolenaarab589462020-07-06 21:03:06 +02001585 %bw!
1586 call AssertException(['py r[:] = []'],
1587 \ 'Vim(python):vim.error: attempt to refer to deleted buffer')
1588 call assert_match('<buffer object (deleted)', pyeval('repr(b)'))
1589 call assert_match('<range object (for deleted buffer)', pyeval('repr(r)'))
1590 call AssertException(["let n = pyeval('len(r)')"],
1591 \ 'Vim(let):vim.error: attempt to refer to deleted buffer')
1592 call AssertException(["py r.append('abc')"],
1593 \ 'Vim(python):vim.error: attempt to refer to deleted buffer')
1594
1595 " object for a deleted buffer
1596 call AssertException(["py b[0] = 'one'"],
1597 \ 'Vim(python):vim.error: attempt to refer to deleted buffer')
1598 call AssertException(["py b.append('one')"],
1599 \ 'Vim(python):vim.error: attempt to refer to deleted buffer')
1600 call AssertException(["let n = pyeval('len(b)')"],
1601 \ 'Vim(let):vim.error: attempt to refer to deleted buffer')
1602 call AssertException(["py pos = b.mark('a')"],
1603 \ 'Vim(python):vim.error: attempt to refer to deleted buffer')
1604 call AssertException(["py vim.current.buffer = b"],
1605 \ 'Vim(python):vim.error: attempt to refer to deleted buffer')
1606 call AssertException(["py rn = b.range(0, 2)"],
1607 \ 'Vim(python):vim.error: attempt to refer to deleted buffer')
Bram Moolenaar92fdd1e2020-07-03 18:00:05 +02001608endfunc
1609
1610" Test vim.buffers object
1611func Test_python_buffers()
1612 %bw!
Bram Moolenaarb18b4962022-09-02 21:55:50 +01001613 edit Xpbuffile
Bram Moolenaar92fdd1e2020-07-03 18:00:05 +02001614 py cb = vim.current.buffer
1615 set hidden
1616 edit a
1617 buffer #
1618 edit b
1619 buffer #
1620 edit c
1621 buffer #
1622 py << trim EOF
1623 try:
1624 from __builtin__ import next
1625 except ImportError:
1626 next = lambda o: o.next()
1627 # Check GCing iterator that was not fully exhausted
1628 i = iter(vim.buffers)
1629 cb.append('i:' + str(next(i)))
1630 # and also check creating more than one iterator at a time
1631 i2 = iter(vim.buffers)
1632 cb.append('i2:' + str(next(i2)))
1633 cb.append('i:' + str(next(i)))
1634 # The following should trigger GC and not cause any problems
1635 del i
1636 del i2
1637 i3 = iter(vim.buffers)
1638 cb.append('i3:' + str(next(i3)))
1639 del i3
1640 EOF
Bram Moolenaarb18b4962022-09-02 21:55:50 +01001641 call assert_equal(['i:<buffer Xpbuffile>',
1642 \ 'i2:<buffer Xpbuffile>', 'i:<buffer a>', 'i3:<buffer Xpbuffile>'],
Bram Moolenaar92fdd1e2020-07-03 18:00:05 +02001643 \ getline(2, '$'))
1644 %d
1645
1646 py << trim EOF
1647 prevnum = 0
1648 for b in vim.buffers:
1649 # Check buffer order
1650 if prevnum >= b.number:
1651 cb.append('!!! Buffer numbers not in strictly ascending order')
1652 # Check indexing: vim.buffers[number].number == number
1653 cb.append(str(b.number) + ':' + repr(vim.buffers[b.number]) + \
1654 '=' + repr(b))
1655 prevnum = b.number
1656 del prevnum
1657
1658 cb.append(str(len(vim.buffers)))
1659 EOF
Bram Moolenaarb18b4962022-09-02 21:55:50 +01001660 call assert_equal([bufnr('Xpbuffile') .. ':<buffer Xpbuffile>=<buffer Xpbuffile>',
Bram Moolenaar92fdd1e2020-07-03 18:00:05 +02001661 \ bufnr('a') .. ':<buffer a>=<buffer a>',
1662 \ bufnr('b') .. ':<buffer b>=<buffer b>',
1663 \ bufnr('c') .. ':<buffer c>=<buffer c>', '4'], getline(2, '$'))
1664 %d
1665
1666 py << trim EOF
1667 bnums = list(map(lambda b: b.number, vim.buffers))[1:]
1668
1669 # Test wiping out buffer with existing iterator
1670 i4 = iter(vim.buffers)
1671 cb.append('i4:' + str(next(i4)))
1672 vim.command('bwipeout! ' + str(bnums.pop(0)))
1673 try:
1674 next(i4)
1675 except vim.error:
1676 pass
1677 else:
1678 cb.append('!!!! No vim.error')
1679 i4 = iter(vim.buffers)
1680 vim.command('bwipeout! ' + str(bnums.pop(-1)))
1681 vim.command('bwipeout! ' + str(bnums.pop(-1)))
1682 cb.append('i4:' + str(next(i4)))
1683 try:
1684 next(i4)
1685 except StopIteration:
1686 cb.append('StopIteration')
1687 del i4
1688 del bnums
1689 EOF
Bram Moolenaarb18b4962022-09-02 21:55:50 +01001690 call assert_equal(['i4:<buffer Xpbuffile>',
1691 \ 'i4:<buffer Xpbuffile>', 'StopIteration'], getline(2, '$'))
Bram Moolenaar92fdd1e2020-07-03 18:00:05 +02001692 %bw!
1693endfunc
1694
1695" Test vim.{tabpage,window}list and vim.{tabpage,window} objects
1696func Test_python_tabpage_window()
1697 %bw
Bram Moolenaarb18b4962022-09-02 21:55:50 +01001698 edit Xpbuffile
Bram Moolenaar92fdd1e2020-07-03 18:00:05 +02001699 py cb = vim.current.buffer
1700 tabnew 0
1701 tabnew 1
1702 vnew a.1
1703 tabnew 2
1704 vnew a.2
1705 vnew b.2
1706 vnew c.2
1707
Bram Moolenaarab589462020-07-06 21:03:06 +02001708 call assert_equal(4, pyeval('vim.current.window.tabpage.number'))
1709
Bram Moolenaar92fdd1e2020-07-03 18:00:05 +02001710 py << trim EOF
1711 cb.append('Number of tabs: ' + str(len(vim.tabpages)))
1712 cb.append('Current tab pages:')
1713 def W(w):
1714 if repr(w).find('(unknown)') != -1:
1715 return '<window object (unknown)>'
1716 else:
1717 return repr(w)
1718
1719 start = len(cb)
1720
1721 def Cursor(w):
1722 if w.buffer is cb:
1723 return repr((start - w.cursor[0], w.cursor[1]))
1724 else:
1725 return repr(w.cursor)
1726
1727 for t in vim.tabpages:
1728 cb.append(' ' + repr(t) + '(' + str(t.number) + ')' + ': ' + \
1729 str(len(t.windows)) + ' windows, current is ' + W(t.window))
1730 cb.append(' Windows:')
1731 for w in t.windows:
1732 cb.append(' ' + W(w) + '(' + str(w.number) + ')' + \
1733 ': displays buffer ' + repr(w.buffer) + \
1734 '; cursor is at ' + Cursor(w))
1735 # Other values depend on the size of the terminal, so they are checked
1736 # partly:
1737 for attr in ('height', 'row', 'width', 'col'):
1738 try:
1739 aval = getattr(w, attr)
1740 if type(aval) is not long:
1741 raise TypeError
1742 if aval < 0:
1743 raise ValueError
1744 except Exception:
1745 cb.append('!!!!!! Error while getting attribute ' + attr + \
1746 ': ' + sys.exc_type.__name__)
1747 del aval
1748 del attr
1749 w.cursor = (len(w.buffer), 0)
1750 del W
1751 del Cursor
1752 cb.append('Number of windows in current tab page: ' + \
1753 str(len(vim.windows)))
1754 if list(vim.windows) != list(vim.current.tabpage.windows):
1755 cb.append('!!!!!! Windows differ')
1756 EOF
1757
Bram Moolenaareffb0cd2020-07-03 21:17:34 +02001758 let expected =<< trim END
Bram Moolenaar92fdd1e2020-07-03 18:00:05 +02001759 Number of tabs: 4
1760 Current tab pages:
1761 <tabpage 0>(1): 1 windows, current is <window object (unknown)>
1762 Windows:
Bram Moolenaarb18b4962022-09-02 21:55:50 +01001763 <window object (unknown)>(1): displays buffer <buffer Xpbuffile>; cursor is at (2, 0)
Bram Moolenaar92fdd1e2020-07-03 18:00:05 +02001764 <tabpage 1>(2): 1 windows, current is <window object (unknown)>
1765 Windows:
1766 <window object (unknown)>(1): displays buffer <buffer 0>; cursor is at (1, 0)
1767 <tabpage 2>(3): 2 windows, current is <window object (unknown)>
1768 Windows:
1769 <window object (unknown)>(1): displays buffer <buffer a.1>; cursor is at (1, 0)
1770 <window object (unknown)>(2): displays buffer <buffer 1>; cursor is at (1, 0)
1771 <tabpage 3>(4): 4 windows, current is <window 0>
1772 Windows:
1773 <window 0>(1): displays buffer <buffer c.2>; cursor is at (1, 0)
1774 <window 1>(2): displays buffer <buffer b.2>; cursor is at (1, 0)
1775 <window 2>(3): displays buffer <buffer a.2>; cursor is at (1, 0)
1776 <window 3>(4): displays buffer <buffer 2>; cursor is at (1, 0)
1777 Number of windows in current tab page: 4
1778 END
Bram Moolenaarb18b4962022-09-02 21:55:50 +01001779 call assert_equal(expected, getbufline(bufnr('Xpbuffile'), 2, '$'))
Bram Moolenaar92fdd1e2020-07-03 18:00:05 +02001780 %bw!
1781endfunc
1782
1783" Test vim.current
1784func Test_python_vim_current()
1785 %bw
Bram Moolenaarb18b4962022-09-02 21:55:50 +01001786 edit Xpbuffile
Bram Moolenaar92fdd1e2020-07-03 18:00:05 +02001787 py cb = vim.current.buffer
1788 tabnew 0
1789 tabnew 1
1790 vnew a.1
1791 tabnew 2
1792 vnew a.2
1793 vnew b.2
1794 vnew c.2
1795
1796 py << trim EOF
1797 def H(o):
1798 return repr(o)
1799 cb.append('Current tab page: ' + repr(vim.current.tabpage))
1800 cb.append('Current window: ' + repr(vim.current.window) + ': ' + \
1801 H(vim.current.window) + ' is ' + H(vim.current.tabpage.window))
1802 cb.append('Current buffer: ' + repr(vim.current.buffer) + ': ' + \
1803 H(vim.current.buffer) + ' is ' + H(vim.current.window.buffer)+ \
1804 ' is ' + H(vim.current.tabpage.window.buffer))
1805 del H
1806 EOF
1807 let expected =<< trim END
1808 Current tab page: <tabpage 3>
1809 Current window: <window 0>: <window 0> is <window 0>
1810 Current buffer: <buffer c.2>: <buffer c.2> is <buffer c.2> is <buffer c.2>
1811 END
Bram Moolenaarb18b4962022-09-02 21:55:50 +01001812 call assert_equal(expected, getbufline(bufnr('Xpbuffile'), 2, '$'))
1813 call deletebufline(bufnr('Xpbuffile'), 1, '$')
Bram Moolenaar92fdd1e2020-07-03 18:00:05 +02001814
1815 " Assigning: fails
1816 py << trim EOF
1817 try:
1818 vim.current.window = vim.tabpages[0].window
1819 except ValueError:
1820 cb.append('ValueError at assigning foreign tab window')
1821
1822 for attr in ('window', 'tabpage', 'buffer'):
1823 try:
1824 setattr(vim.current, attr, None)
1825 except TypeError:
1826 cb.append('Type error at assigning None to vim.current.' + attr)
1827 del attr
1828 EOF
1829
1830 let expected =<< trim END
1831 ValueError at assigning foreign tab window
1832 Type error at assigning None to vim.current.window
1833 Type error at assigning None to vim.current.tabpage
1834 Type error at assigning None to vim.current.buffer
1835 END
Bram Moolenaarb18b4962022-09-02 21:55:50 +01001836 call assert_equal(expected, getbufline(bufnr('Xpbuffile'), 2, '$'))
1837 call deletebufline(bufnr('Xpbuffile'), 1, '$')
Bram Moolenaar92fdd1e2020-07-03 18:00:05 +02001838
Bram Moolenaarb18b4962022-09-02 21:55:50 +01001839 call setbufline(bufnr('Xpbuffile'), 1, 'python interface')
Bram Moolenaar92fdd1e2020-07-03 18:00:05 +02001840 py << trim EOF
1841 # Assigning: success
1842 vim.current.tabpage = vim.tabpages[-2]
1843 vim.current.buffer = cb
1844 vim.current.window = vim.windows[0]
1845 vim.current.window.cursor = (len(vim.current.buffer), 0)
1846 cb.append('Current tab page: ' + repr(vim.current.tabpage))
1847 cb.append('Current window: ' + repr(vim.current.window))
1848 cb.append('Current buffer: ' + repr(vim.current.buffer))
1849 cb.append('Current line: ' + repr(vim.current.line))
1850 EOF
1851
1852 let expected =<< trim END
1853 Current tab page: <tabpage 2>
1854 Current window: <window 0>
Bram Moolenaarb18b4962022-09-02 21:55:50 +01001855 Current buffer: <buffer Xpbuffile>
Bram Moolenaar92fdd1e2020-07-03 18:00:05 +02001856 Current line: 'python interface'
1857 END
Bram Moolenaarb18b4962022-09-02 21:55:50 +01001858 call assert_equal(expected, getbufline(bufnr('Xpbuffile'), 2, '$'))
Bram Moolenaarab589462020-07-06 21:03:06 +02001859 py vim.current.line = 'one line'
1860 call assert_equal('one line', getline('.'))
Bram Moolenaarb18b4962022-09-02 21:55:50 +01001861 call deletebufline(bufnr('Xpbuffile'), 1, '$')
Bram Moolenaar92fdd1e2020-07-03 18:00:05 +02001862
1863 py << trim EOF
1864 ws = list(vim.windows)
1865 ts = list(vim.tabpages)
1866 for b in vim.buffers:
1867 if b is not cb:
1868 vim.command('bwipeout! ' + str(b.number))
1869 del b
1870 cb.append('w.valid: ' + repr([w.valid for w in ws]))
1871 cb.append('t.valid: ' + repr([t.valid for t in ts]))
1872 del w
1873 del t
1874 del ts
1875 del ws
1876 EOF
1877 let expected =<< trim END
1878 w.valid: [True, False]
1879 t.valid: [True, False, True, False]
1880 END
Bram Moolenaarb18b4962022-09-02 21:55:50 +01001881 call assert_equal(expected, getbufline(bufnr('Xpbuffile'), 2, '$'))
Bram Moolenaar92fdd1e2020-07-03 18:00:05 +02001882 %bw!
1883endfunc
1884
1885" Test types
1886func Test_python_types()
1887 %d
1888 py cb = vim.current.buffer
1889 py << trim EOF
1890 for expr, attr in (
1891 ('vim.vars', 'Dictionary'),
1892 ('vim.options', 'Options'),
1893 ('vim.bindeval("{}")', 'Dictionary'),
1894 ('vim.bindeval("[]")', 'List'),
1895 ('vim.bindeval("function(\'tr\')")', 'Function'),
1896 ('vim.current.buffer', 'Buffer'),
1897 ('vim.current.range', 'Range'),
1898 ('vim.current.window', 'Window'),
1899 ('vim.current.tabpage', 'TabPage'),
1900 ):
1901 cb.append(expr + ':' + attr + ':' + \
1902 repr(type(eval(expr)) is getattr(vim, attr)))
1903 del expr
1904 del attr
1905 EOF
1906 let expected =<< trim END
1907 vim.vars:Dictionary:True
1908 vim.options:Options:True
1909 vim.bindeval("{}"):Dictionary:True
1910 vim.bindeval("[]"):List:True
1911 vim.bindeval("function('tr')"):Function:True
1912 vim.current.buffer:Buffer:True
1913 vim.current.range:Range:True
1914 vim.current.window:Window:True
1915 vim.current.tabpage:TabPage:True
1916 END
1917 call assert_equal(expected, getline(2, '$'))
1918endfunc
1919
1920" Test __dir__() method
1921func Test_python_dir_method()
1922 %d
1923 py cb = vim.current.buffer
1924 py << trim EOF
1925 for name, o in (
1926 ('current', vim.current),
1927 ('buffer', vim.current.buffer),
1928 ('window', vim.current.window),
1929 ('tabpage', vim.current.tabpage),
1930 ('range', vim.current.range),
1931 ('dictionary', vim.bindeval('{}')),
1932 ('list', vim.bindeval('[]')),
1933 ('function', vim.bindeval('function("tr")')),
1934 ('output', sys.stdout),
1935 ):
1936 cb.append(name + ':' + ','.join(dir(o)))
1937 del name
1938 del o
1939 EOF
1940 let expected =<< trim END
1941 current:__dir__,__members__,buffer,line,range,tabpage,window
1942 buffer:__dir__,__members__,append,mark,name,number,options,range,valid,vars
1943 window:__dir__,__members__,buffer,col,cursor,height,number,options,row,tabpage,valid,vars,width
1944 tabpage:__dir__,__members__,number,valid,vars,window,windows
1945 range:__dir__,__members__,append,end,start
1946 dictionary:__dir__,__members__,get,has_key,items,keys,locked,pop,popitem,scope,update,values
1947 list:__dir__,__members__,extend,locked
1948 function:__dir__,__members__,args,auto_rebind,self,softspace
1949 output:__dir__,__members__,close,closed,flush,isatty,readable,seekable,softspace,writable,write,writelines
1950 END
1951 call assert_equal(expected, getline(2, '$'))
1952endfunc
1953
1954" Test vim.*.__new__
1955func Test_python_new()
1956 call assert_equal({}, pyeval('vim.Dictionary({})'))
1957 call assert_equal({'a': 1}, pyeval('vim.Dictionary(a=1)'))
1958 call assert_equal({'a': 1}, pyeval('vim.Dictionary(((''a'', 1),))'))
1959 call assert_equal([], pyeval('vim.List()'))
1960 call assert_equal(['a', 'b', 'c', '7'], pyeval('vim.List(iter(''abc7''))'))
1961 call assert_equal(function('tr'), pyeval('vim.Function(''tr'')'))
1962 call assert_equal(function('tr', [123, 3, 4]),
1963 \ pyeval('vim.Function(''tr'', args=[123, 3, 4])'))
1964 call assert_equal(function('tr'), pyeval('vim.Function(''tr'', args=[])'))
1965 call assert_equal(function('tr', {}),
1966 \ pyeval('vim.Function(''tr'', self={})'))
1967 call assert_equal(function('tr', [123, 3, 4], {}),
1968 \ pyeval('vim.Function(''tr'', args=[123, 3, 4], self={})'))
1969 call assert_equal(function('tr'),
1970 \ pyeval('vim.Function(''tr'', auto_rebind=False)'))
1971 call assert_equal(function('tr', [123, 3, 4]),
1972 \ pyeval('vim.Function(''tr'', args=[123, 3, 4], auto_rebind=False)'))
1973 call assert_equal(function('tr'),
1974 \ pyeval('vim.Function(''tr'', args=[], auto_rebind=False)'))
1975 call assert_equal(function('tr', {}),
1976 \ pyeval('vim.Function(''tr'', self={}, auto_rebind=False)'))
1977 call assert_equal(function('tr', [123, 3, 4], {}),
1978 \ pyeval('vim.Function(''tr'', args=[123, 3, 4], self={}, auto_rebind=False)'))
1979endfunc
1980
1981" Test vim.Function
1982func Test_python_vim_func()
Bram Moolenaarab589462020-07-06 21:03:06 +02001983 func Args(...)
Bram Moolenaar92fdd1e2020-07-03 18:00:05 +02001984 return a:000
Bram Moolenaarab589462020-07-06 21:03:06 +02001985 endfunc
Bram Moolenaar92fdd1e2020-07-03 18:00:05 +02001986
Bram Moolenaarab589462020-07-06 21:03:06 +02001987 func SelfArgs(...) dict
Bram Moolenaar92fdd1e2020-07-03 18:00:05 +02001988 return [a:000, self]
Bram Moolenaarab589462020-07-06 21:03:06 +02001989 endfunc
Bram Moolenaar92fdd1e2020-07-03 18:00:05 +02001990
1991 " The following four lines should not crash
1992 let Pt = function('tr', [[]], {'l': []})
1993 py Pt = vim.bindeval('Pt')
1994 unlet Pt
1995 py del Pt
1996
Bram Moolenaarab589462020-07-06 21:03:06 +02001997 call assert_equal(3, pyeval('vim.strwidth("a\tb")'))
1998
Bram Moolenaar92fdd1e2020-07-03 18:00:05 +02001999 %bw!
2000 py cb = vim.current.buffer
2001 py << trim EOF
2002 def ecall(out_prefix, func, *args, **kwargs):
2003 line = out_prefix + ': '
2004 try:
2005 ret = func(*args, **kwargs)
2006 except Exception:
2007 line += '!exception: ' + emsg(sys.exc_info())
2008 else:
2009 line += '!result: ' + vim.Function('string')(ret)
2010 cb.append(line)
2011 a = vim.Function('Args')
2012 pa1 = vim.Function('Args', args=['abcArgsPA1'])
2013 pa2 = vim.Function('Args', args=[])
2014 pa3 = vim.Function('Args', args=['abcArgsPA3'], self={'abcSelfPA3': 'abcSelfPA3Val'})
2015 pa4 = vim.Function('Args', self={'abcSelfPA4': 'abcSelfPA4Val'})
2016 cb.append('a: ' + repr(a))
2017 cb.append('pa1: ' + repr(pa1))
2018 cb.append('pa2: ' + repr(pa2))
2019 cb.append('pa3: ' + repr(pa3))
2020 cb.append('pa4: ' + repr(pa4))
2021 sa = vim.Function('SelfArgs')
2022 psa1 = vim.Function('SelfArgs', args=['abcArgsPSA1'])
2023 psa2 = vim.Function('SelfArgs', args=[])
2024 psa3 = vim.Function('SelfArgs', args=['abcArgsPSA3'], self={'abcSelfPSA3': 'abcSelfPSA3Val'})
2025 psa4 = vim.Function('SelfArgs', self={'abcSelfPSA4': 'abcSelfPSA4Val'})
2026 psa5 = vim.Function('SelfArgs', self={'abcSelfPSA5': 'abcSelfPSA5Val'}, auto_rebind=0)
2027 psa6 = vim.Function('SelfArgs', args=['abcArgsPSA6'], self={'abcSelfPSA6': 'abcSelfPSA6Val'}, auto_rebind=())
2028 psa7 = vim.Function('SelfArgs', args=['abcArgsPSA7'], auto_rebind=[])
2029 psa8 = vim.Function('SelfArgs', auto_rebind=False)
2030 psa9 = vim.Function('SelfArgs', self={'abcSelfPSA9': 'abcSelfPSA9Val'}, auto_rebind=True)
2031 psaA = vim.Function('SelfArgs', args=['abcArgsPSAA'], self={'abcSelfPSAA': 'abcSelfPSAAVal'}, auto_rebind=1)
2032 psaB = vim.Function('SelfArgs', args=['abcArgsPSAB'], auto_rebind={'abcARPSAB': 'abcARPSABVal'})
2033 psaC = vim.Function('SelfArgs', auto_rebind=['abcARPSAC'])
2034 cb.append('sa: ' + repr(sa))
2035 cb.append('psa1: ' + repr(psa1))
2036 cb.append('psa2: ' + repr(psa2))
2037 cb.append('psa3: ' + repr(psa3))
2038 cb.append('psa4: ' + repr(psa4))
2039 cb.append('psa5: ' + repr(psa5))
2040 cb.append('psa6: ' + repr(psa6))
2041 cb.append('psa7: ' + repr(psa7))
2042 cb.append('psa8: ' + repr(psa8))
2043 cb.append('psa9: ' + repr(psa9))
2044 cb.append('psaA: ' + repr(psaA))
2045 cb.append('psaB: ' + repr(psaB))
2046 cb.append('psaC: ' + repr(psaC))
Bram Moolenaareffb0cd2020-07-03 21:17:34 +02002047
Bram Moolenaar92fdd1e2020-07-03 18:00:05 +02002048 psar = vim.Function('SelfArgs', args=[{'abcArgsPSAr': 'abcArgsPSArVal'}], self={'abcSelfPSAr': 'abcSelfPSArVal'})
2049 psar.args[0]['abcArgsPSAr2'] = [psar.self, psar.args[0]]
2050 psar.self['rec'] = psar
2051 psar.self['self'] = psar.self
2052 psar.self['args'] = psar.args
Bram Moolenaareffb0cd2020-07-03 21:17:34 +02002053
Bram Moolenaar92fdd1e2020-07-03 18:00:05 +02002054 try:
2055 cb.append('psar: ' + repr(psar))
2056 except Exception:
2057 cb.append('!!!!!!!! Caught exception: ' + emsg(sys.exc_info()))
2058 EOF
2059
2060 let expected =<< trim END
2061 a: <vim.Function 'Args'>
2062 pa1: <vim.Function 'Args', args=['abcArgsPA1']>
2063 pa2: <vim.Function 'Args'>
2064 pa3: <vim.Function 'Args', args=['abcArgsPA3'], self={'abcSelfPA3': 'abcSelfPA3Val'}>
2065 pa4: <vim.Function 'Args', self={'abcSelfPA4': 'abcSelfPA4Val'}>
2066 sa: <vim.Function 'SelfArgs'>
2067 psa1: <vim.Function 'SelfArgs', args=['abcArgsPSA1']>
2068 psa2: <vim.Function 'SelfArgs'>
2069 psa3: <vim.Function 'SelfArgs', args=['abcArgsPSA3'], self={'abcSelfPSA3': 'abcSelfPSA3Val'}>
2070 psa4: <vim.Function 'SelfArgs', self={'abcSelfPSA4': 'abcSelfPSA4Val'}>
2071 psa5: <vim.Function 'SelfArgs', self={'abcSelfPSA5': 'abcSelfPSA5Val'}>
2072 psa6: <vim.Function 'SelfArgs', args=['abcArgsPSA6'], self={'abcSelfPSA6': 'abcSelfPSA6Val'}>
2073 psa7: <vim.Function 'SelfArgs', args=['abcArgsPSA7']>
2074 psa8: <vim.Function 'SelfArgs'>
2075 psa9: <vim.Function 'SelfArgs', self={'abcSelfPSA9': 'abcSelfPSA9Val'}, auto_rebind=True>
2076 psaA: <vim.Function 'SelfArgs', args=['abcArgsPSAA'], self={'abcSelfPSAA': 'abcSelfPSAAVal'}, auto_rebind=True>
2077 psaB: <vim.Function 'SelfArgs', args=['abcArgsPSAB']>
2078 psaC: <vim.Function 'SelfArgs'>
2079 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'}]}>
2080 END
2081 call assert_equal(expected, getline(2, '$'))
2082 %d
2083
2084 call assert_equal(function('Args'), pyeval('a'))
2085 call assert_equal(function('Args', ['abcArgsPA1']), pyeval('pa1'))
2086 call assert_equal(function('Args'), pyeval('pa2'))
2087 call assert_equal(function('Args', ['abcArgsPA3'], {'abcSelfPA3': 'abcSelfPA3Val'}), pyeval('pa3'))
2088 call assert_equal(function('Args', {'abcSelfPA4': 'abcSelfPA4Val'}), pyeval('pa4'))
2089 call assert_equal(function('SelfArgs'), pyeval('sa'))
2090 call assert_equal(function('SelfArgs', ['abcArgsPSA1']), pyeval('psa1'))
2091 call assert_equal(function('SelfArgs'), pyeval('psa2'))
2092 call assert_equal(function('SelfArgs', ['abcArgsPSA3'], {'abcSelfPSA3': 'abcSelfPSA3Val'}), pyeval('psa3'))
2093 call assert_equal(function('SelfArgs', {'abcSelfPSA4': 'abcSelfPSA4Val'}), pyeval('psa4'))
2094 call assert_equal(function('SelfArgs', {'abcSelfPSA5': 'abcSelfPSA5Val'}), pyeval('psa5'))
2095 call assert_equal(function('SelfArgs', ['abcArgsPSA6'], {'abcSelfPSA6': 'abcSelfPSA6Val'}), pyeval('psa6'))
2096 call assert_equal(function('SelfArgs', ['abcArgsPSA7']), pyeval('psa7'))
2097 call assert_equal(function('SelfArgs'), pyeval('psa8'))
2098 call assert_equal(function('SelfArgs', {'abcSelfPSA9': 'abcSelfPSA9Val'}), pyeval('psa9'))
2099 call assert_equal(function('SelfArgs', ['abcArgsPSAA'], {'abcSelfPSAA': 'abcSelfPSAAVal'}), pyeval('psaA'))
2100 call assert_equal(function('SelfArgs', ['abcArgsPSAB']), pyeval('psaB'))
2101 call assert_equal(function('SelfArgs'), pyeval('psaC'))
2102
2103 let res = []
2104 for v in ['sa', 'psa1', 'psa2', 'psa3', 'psa4', 'psa5', 'psa6', 'psa7',
2105 \ 'psa8', 'psa9', 'psaA', 'psaB', 'psaC']
2106 let d = {'f': pyeval(v)}
2107 call add(res, 'd.' .. v .. '(): ' .. string(d.f()))
2108 endfor
2109
2110 let expected =<< trim END
2111 d.sa(): [[], {'f': function('SelfArgs')}]
2112 d.psa1(): [['abcArgsPSA1'], {'f': function('SelfArgs', ['abcArgsPSA1'])}]
2113 d.psa2(): [[], {'f': function('SelfArgs')}]
2114 d.psa3(): [['abcArgsPSA3'], {'abcSelfPSA3': 'abcSelfPSA3Val'}]
2115 d.psa4(): [[], {'abcSelfPSA4': 'abcSelfPSA4Val'}]
2116 d.psa5(): [[], {'abcSelfPSA5': 'abcSelfPSA5Val'}]
2117 d.psa6(): [['abcArgsPSA6'], {'abcSelfPSA6': 'abcSelfPSA6Val'}]
2118 d.psa7(): [['abcArgsPSA7'], {'f': function('SelfArgs', ['abcArgsPSA7'])}]
2119 d.psa8(): [[], {'f': function('SelfArgs')}]
2120 d.psa9(): [[], {'f': function('SelfArgs', {'abcSelfPSA9': 'abcSelfPSA9Val'})}]
2121 d.psaA(): [['abcArgsPSAA'], {'f': function('SelfArgs', ['abcArgsPSAA'], {'abcSelfPSAA': 'abcSelfPSAAVal'})}]
2122 d.psaB(): [['abcArgsPSAB'], {'f': function('SelfArgs', ['abcArgsPSAB'])}]
2123 d.psaC(): [[], {'f': function('SelfArgs')}]
2124 END
2125 call assert_equal(expected, res)
2126
2127 py ecall('a()', a, )
2128 py ecall('pa1()', pa1, )
2129 py ecall('pa2()', pa2, )
2130 py ecall('pa3()', pa3, )
2131 py ecall('pa4()', pa4, )
2132 py ecall('sa()', sa, )
2133 py ecall('psa1()', psa1, )
2134 py ecall('psa2()', psa2, )
2135 py ecall('psa3()', psa3, )
2136 py ecall('psa4()', psa4, )
2137
2138 py ecall('a(42, 43)', a, 42, 43)
2139 py ecall('pa1(42, 43)', pa1, 42, 43)
2140 py ecall('pa2(42, 43)', pa2, 42, 43)
2141 py ecall('pa3(42, 43)', pa3, 42, 43)
2142 py ecall('pa4(42, 43)', pa4, 42, 43)
2143 py ecall('sa(42, 43)', sa, 42, 43)
2144 py ecall('psa1(42, 43)', psa1, 42, 43)
2145 py ecall('psa2(42, 43)', psa2, 42, 43)
2146 py ecall('psa3(42, 43)', psa3, 42, 43)
2147 py ecall('psa4(42, 43)', psa4, 42, 43)
2148
2149 py ecall('a(42, self={"20": 1})', a, 42, self={'20': 1})
2150 py ecall('pa1(42, self={"20": 1})', pa1, 42, self={'20': 1})
2151 py ecall('pa2(42, self={"20": 1})', pa2, 42, self={'20': 1})
2152 py ecall('pa3(42, self={"20": 1})', pa3, 42, self={'20': 1})
2153 py ecall('pa4(42, self={"20": 1})', pa4, 42, self={'20': 1})
2154 py ecall('sa(42, self={"20": 1})', sa, 42, self={'20': 1})
2155 py ecall('psa1(42, self={"20": 1})', psa1, 42, self={'20': 1})
2156 py ecall('psa2(42, self={"20": 1})', psa2, 42, self={'20': 1})
2157 py ecall('psa3(42, self={"20": 1})', psa3, 42, self={'20': 1})
2158 py ecall('psa4(42, self={"20": 1})', psa4, 42, self={'20': 1})
2159
2160 py ecall('a(self={"20": 1})', a, self={'20': 1})
2161 py ecall('pa1(self={"20": 1})', pa1, self={'20': 1})
2162 py ecall('pa2(self={"20": 1})', pa2, self={'20': 1})
2163 py ecall('pa3(self={"20": 1})', pa3, self={'20': 1})
2164 py ecall('pa4(self={"20": 1})', pa4, self={'20': 1})
2165 py ecall('sa(self={"20": 1})', sa, self={'20': 1})
2166 py ecall('psa1(self={"20": 1})', psa1, self={'20': 1})
2167 py ecall('psa2(self={"20": 1})', psa2, self={'20': 1})
2168 py ecall('psa3(self={"20": 1})', psa3, self={'20': 1})
2169 py ecall('psa4(self={"20": 1})', psa4, self={'20': 1})
2170
2171 py << trim EOF
2172 def s(v):
2173 if v is None:
2174 return repr(v)
2175 else:
2176 return vim.Function('string')(v)
Bram Moolenaareffb0cd2020-07-03 21:17:34 +02002177
Bram Moolenaar92fdd1e2020-07-03 18:00:05 +02002178 cb.append('a.args: ' + s(a.args))
2179 cb.append('pa1.args: ' + s(pa1.args))
2180 cb.append('pa2.args: ' + s(pa2.args))
2181 cb.append('pa3.args: ' + s(pa3.args))
2182 cb.append('pa4.args: ' + s(pa4.args))
2183 cb.append('sa.args: ' + s(sa.args))
2184 cb.append('psa1.args: ' + s(psa1.args))
2185 cb.append('psa2.args: ' + s(psa2.args))
2186 cb.append('psa3.args: ' + s(psa3.args))
2187 cb.append('psa4.args: ' + s(psa4.args))
Bram Moolenaareffb0cd2020-07-03 21:17:34 +02002188
Bram Moolenaar92fdd1e2020-07-03 18:00:05 +02002189 cb.append('a.self: ' + s(a.self))
2190 cb.append('pa1.self: ' + s(pa1.self))
2191 cb.append('pa2.self: ' + s(pa2.self))
2192 cb.append('pa3.self: ' + s(pa3.self))
2193 cb.append('pa4.self: ' + s(pa4.self))
2194 cb.append('sa.self: ' + s(sa.self))
2195 cb.append('psa1.self: ' + s(psa1.self))
2196 cb.append('psa2.self: ' + s(psa2.self))
2197 cb.append('psa3.self: ' + s(psa3.self))
2198 cb.append('psa4.self: ' + s(psa4.self))
Bram Moolenaareffb0cd2020-07-03 21:17:34 +02002199
Bram Moolenaar92fdd1e2020-07-03 18:00:05 +02002200 cb.append('a.name: ' + s(a.name))
2201 cb.append('pa1.name: ' + s(pa1.name))
2202 cb.append('pa2.name: ' + s(pa2.name))
2203 cb.append('pa3.name: ' + s(pa3.name))
2204 cb.append('pa4.name: ' + s(pa4.name))
2205 cb.append('sa.name: ' + s(sa.name))
2206 cb.append('psa1.name: ' + s(psa1.name))
2207 cb.append('psa2.name: ' + s(psa2.name))
2208 cb.append('psa3.name: ' + s(psa3.name))
2209 cb.append('psa4.name: ' + s(psa4.name))
Bram Moolenaareffb0cd2020-07-03 21:17:34 +02002210
Bram Moolenaar92fdd1e2020-07-03 18:00:05 +02002211 cb.append('a.auto_rebind: ' + s(a.auto_rebind))
2212 cb.append('pa1.auto_rebind: ' + s(pa1.auto_rebind))
2213 cb.append('pa2.auto_rebind: ' + s(pa2.auto_rebind))
2214 cb.append('pa3.auto_rebind: ' + s(pa3.auto_rebind))
2215 cb.append('pa4.auto_rebind: ' + s(pa4.auto_rebind))
2216 cb.append('sa.auto_rebind: ' + s(sa.auto_rebind))
2217 cb.append('psa1.auto_rebind: ' + s(psa1.auto_rebind))
2218 cb.append('psa2.auto_rebind: ' + s(psa2.auto_rebind))
2219 cb.append('psa3.auto_rebind: ' + s(psa3.auto_rebind))
2220 cb.append('psa4.auto_rebind: ' + s(psa4.auto_rebind))
2221 cb.append('psa5.auto_rebind: ' + s(psa5.auto_rebind))
2222 cb.append('psa6.auto_rebind: ' + s(psa6.auto_rebind))
2223 cb.append('psa7.auto_rebind: ' + s(psa7.auto_rebind))
2224 cb.append('psa8.auto_rebind: ' + s(psa8.auto_rebind))
2225 cb.append('psa9.auto_rebind: ' + s(psa9.auto_rebind))
2226 cb.append('psaA.auto_rebind: ' + s(psaA.auto_rebind))
2227 cb.append('psaB.auto_rebind: ' + s(psaB.auto_rebind))
2228 cb.append('psaC.auto_rebind: ' + s(psaC.auto_rebind))
Bram Moolenaareffb0cd2020-07-03 21:17:34 +02002229
Bram Moolenaar92fdd1e2020-07-03 18:00:05 +02002230 del s
Bram Moolenaareffb0cd2020-07-03 21:17:34 +02002231
Bram Moolenaar92fdd1e2020-07-03 18:00:05 +02002232 del a
2233 del pa1
2234 del pa2
2235 del pa3
2236 del pa4
2237 del sa
2238 del psa1
2239 del psa2
2240 del psa3
2241 del psa4
2242 del psa5
2243 del psa6
2244 del psa7
2245 del psa8
2246 del psa9
2247 del psaA
2248 del psaB
2249 del psaC
2250 del psar
Bram Moolenaareffb0cd2020-07-03 21:17:34 +02002251
Bram Moolenaar92fdd1e2020-07-03 18:00:05 +02002252 del ecall
2253 EOF
2254
2255 let expected =<< trim END
2256 a(): !result: []
2257 pa1(): !result: ['abcArgsPA1']
2258 pa2(): !result: []
2259 pa3(): !result: ['abcArgsPA3']
2260 pa4(): !result: []
2261 sa(): !exception: error:('Vim:E725: Calling dict function without Dictionary: SelfArgs',)
2262 psa1(): !exception: error:('Vim:E725: Calling dict function without Dictionary: SelfArgs',)
2263 psa2(): !exception: error:('Vim:E725: Calling dict function without Dictionary: SelfArgs',)
2264 psa3(): !result: [['abcArgsPSA3'], {'abcSelfPSA3': 'abcSelfPSA3Val'}]
2265 psa4(): !result: [[], {'abcSelfPSA4': 'abcSelfPSA4Val'}]
2266 a(42, 43): !result: [42, 43]
2267 pa1(42, 43): !result: ['abcArgsPA1', 42, 43]
2268 pa2(42, 43): !result: [42, 43]
2269 pa3(42, 43): !result: ['abcArgsPA3', 42, 43]
2270 pa4(42, 43): !result: [42, 43]
2271 sa(42, 43): !exception: error:('Vim:E725: Calling dict function without Dictionary: SelfArgs',)
2272 psa1(42, 43): !exception: error:('Vim:E725: Calling dict function without Dictionary: SelfArgs',)
2273 psa2(42, 43): !exception: error:('Vim:E725: Calling dict function without Dictionary: SelfArgs',)
2274 psa3(42, 43): !result: [['abcArgsPSA3', 42, 43], {'abcSelfPSA3': 'abcSelfPSA3Val'}]
2275 psa4(42, 43): !result: [[42, 43], {'abcSelfPSA4': 'abcSelfPSA4Val'}]
2276 a(42, self={"20": 1}): !result: [42]
2277 pa1(42, self={"20": 1}): !result: ['abcArgsPA1', 42]
2278 pa2(42, self={"20": 1}): !result: [42]
2279 pa3(42, self={"20": 1}): !result: ['abcArgsPA3', 42]
2280 pa4(42, self={"20": 1}): !result: [42]
2281 sa(42, self={"20": 1}): !result: [[42], {'20': 1}]
2282 psa1(42, self={"20": 1}): !result: [['abcArgsPSA1', 42], {'20': 1}]
2283 psa2(42, self={"20": 1}): !result: [[42], {'20': 1}]
2284 psa3(42, self={"20": 1}): !result: [['abcArgsPSA3', 42], {'20': 1}]
2285 psa4(42, self={"20": 1}): !result: [[42], {'20': 1}]
2286 a(self={"20": 1}): !result: []
2287 pa1(self={"20": 1}): !result: ['abcArgsPA1']
2288 pa2(self={"20": 1}): !result: []
2289 pa3(self={"20": 1}): !result: ['abcArgsPA3']
2290 pa4(self={"20": 1}): !result: []
2291 sa(self={"20": 1}): !result: [[], {'20': 1}]
2292 psa1(self={"20": 1}): !result: [['abcArgsPSA1'], {'20': 1}]
2293 psa2(self={"20": 1}): !result: [[], {'20': 1}]
2294 psa3(self={"20": 1}): !result: [['abcArgsPSA3'], {'20': 1}]
2295 psa4(self={"20": 1}): !result: [[], {'20': 1}]
2296 a.args: None
2297 pa1.args: ['abcArgsPA1']
2298 pa2.args: None
2299 pa3.args: ['abcArgsPA3']
2300 pa4.args: None
2301 sa.args: None
2302 psa1.args: ['abcArgsPSA1']
2303 psa2.args: None
2304 psa3.args: ['abcArgsPSA3']
2305 psa4.args: None
2306 a.self: None
2307 pa1.self: None
2308 pa2.self: None
2309 pa3.self: {'abcSelfPA3': 'abcSelfPA3Val'}
2310 pa4.self: {'abcSelfPA4': 'abcSelfPA4Val'}
2311 sa.self: None
2312 psa1.self: None
2313 psa2.self: None
2314 psa3.self: {'abcSelfPSA3': 'abcSelfPSA3Val'}
2315 psa4.self: {'abcSelfPSA4': 'abcSelfPSA4Val'}
2316 a.name: 'Args'
2317 pa1.name: 'Args'
2318 pa2.name: 'Args'
2319 pa3.name: 'Args'
2320 pa4.name: 'Args'
2321 sa.name: 'SelfArgs'
2322 psa1.name: 'SelfArgs'
2323 psa2.name: 'SelfArgs'
2324 psa3.name: 'SelfArgs'
2325 psa4.name: 'SelfArgs'
2326 a.auto_rebind: 1
2327 pa1.auto_rebind: 1
2328 pa2.auto_rebind: 1
2329 pa3.auto_rebind: 0
2330 pa4.auto_rebind: 0
2331 sa.auto_rebind: 1
2332 psa1.auto_rebind: 1
2333 psa2.auto_rebind: 1
2334 psa3.auto_rebind: 0
2335 psa4.auto_rebind: 0
2336 psa5.auto_rebind: 0
2337 psa6.auto_rebind: 0
2338 psa7.auto_rebind: 1
2339 psa8.auto_rebind: 1
2340 psa9.auto_rebind: 1
2341 psaA.auto_rebind: 1
2342 psaB.auto_rebind: 1
2343 psaC.auto_rebind: 1
2344 END
2345 call assert_equal(expected, getline(2, '$'))
2346 %bw!
2347endfunc
2348
2349" Test stdout/stderr
2350func Test_python_stdin_stderr()
2351 let caught_writeerr = 0
2352 let caught_writelineerr = 0
2353 redir => messages
2354 py sys.stdout.write('abc8') ; sys.stdout.write('def')
2355 try
2356 py sys.stderr.write('abc9') ; sys.stderr.write('def')
2357 catch /abc9def/
2358 let caught_writeerr = 1
2359 endtry
2360 py sys.stdout.writelines(iter('abcA'))
2361 try
2362 py sys.stderr.writelines(iter('abcB'))
2363 catch /abcB/
2364 let caught_writelineerr = 1
2365 endtry
2366 redir END
2367 call assert_equal("\nabc8def\nabcA", messages)
2368 call assert_equal(1, caught_writeerr)
2369 call assert_equal(1, caught_writelineerr)
2370endfunc
2371
2372" Test subclassing
2373func Test_python_subclass()
2374 new
Bram Moolenaarab589462020-07-06 21:03:06 +02002375 func Put(...)
2376 return a:000
2377 endfunc
Bram Moolenaar92fdd1e2020-07-03 18:00:05 +02002378
2379 py << trim EOF
2380 class DupDict(vim.Dictionary):
2381 def __setitem__(self, key, value):
2382 super(DupDict, self).__setitem__(key, value)
2383 super(DupDict, self).__setitem__('dup_' + key, value)
2384 dd = DupDict()
2385 dd['a'] = 'b'
Bram Moolenaareffb0cd2020-07-03 21:17:34 +02002386
Bram Moolenaar92fdd1e2020-07-03 18:00:05 +02002387 class DupList(vim.List):
2388 def __getitem__(self, idx):
2389 return [super(DupList, self).__getitem__(idx)] * 2
Bram Moolenaareffb0cd2020-07-03 21:17:34 +02002390
Bram Moolenaar92fdd1e2020-07-03 18:00:05 +02002391 dl = DupList()
2392 dl2 = DupList(iter('abcC'))
2393 dl.extend(dl2[0])
Bram Moolenaareffb0cd2020-07-03 21:17:34 +02002394
Bram Moolenaar92fdd1e2020-07-03 18:00:05 +02002395 class DupFun(vim.Function):
2396 def __call__(self, arg):
2397 return super(DupFun, self).__call__(arg, arg)
Bram Moolenaareffb0cd2020-07-03 21:17:34 +02002398
Bram Moolenaar92fdd1e2020-07-03 18:00:05 +02002399 df = DupFun('Put')
2400 EOF
2401
2402 call assert_equal(['a', 'dup_a'], sort(keys(pyeval('dd'))))
2403 call assert_equal(['a', 'a'], pyeval('dl'))
2404 call assert_equal(['a', 'b', 'c', 'C'], pyeval('dl2'))
2405 call assert_equal([2, 2], pyeval('df(2)'))
2406 call assert_equal(1, pyeval('dl') is# pyeval('dl'))
2407 call assert_equal(1, pyeval('dd') is# pyeval('dd'))
2408 call assert_equal(function('Put'), pyeval('df'))
2409 delfunction Put
2410 py << trim EOF
2411 del DupDict
2412 del DupList
2413 del DupFun
2414 del dd
2415 del dl
2416 del dl2
2417 del df
2418 EOF
2419 close!
2420endfunc
2421
2422" Test chdir
2423func Test_python_chdir()
Bram Moolenaarb18b4962022-09-02 21:55:50 +01002424 new Xpycfile
Bram Moolenaar92fdd1e2020-07-03 18:00:05 +02002425 py cb = vim.current.buffer
2426 py << trim EOF
2427 import os
2428 fnamemodify = vim.Function('fnamemodify')
2429 cb.append(fnamemodify('.', ':p:h:t'))
2430 cb.append(vim.eval('@%'))
2431 os.chdir('..')
2432 path = fnamemodify('.', ':p:h:t')
Bram Moolenaar7d697962020-08-31 21:30:32 +02002433 if path != 'src' and path != 'src2':
Bram Moolenaar92fdd1e2020-07-03 18:00:05 +02002434 # Running tests from a shadow directory, so move up another level
Bram Moolenaarb18b4962022-09-02 21:55:50 +01002435 # This will result in @% looking like shadow/testdir/Xpycfile, hence the
Bram Moolenaar92fdd1e2020-07-03 18:00:05 +02002436 # extra fnamemodify
2437 os.chdir('..')
2438 cb.append(fnamemodify('.', ':p:h:t'))
2439 cb.append(fnamemodify(vim.eval('@%'), ':s?^%s.??' % path).replace(os.path.sep, '/'))
2440 os.chdir(path)
2441 del path
2442 else:
Bram Moolenaar7d697962020-08-31 21:30:32 +02002443 # Also accept running from src2/testdir/ for MS-Windows CI.
2444 cb.append(fnamemodify('.', ':p:h:t').replace('src2', 'src'))
Bram Moolenaar92fdd1e2020-07-03 18:00:05 +02002445 cb.append(vim.eval('@%').replace(os.path.sep, '/'))
2446 os.chdir('testdir')
2447 cb.append(fnamemodify('.', ':p:h:t'))
2448 cb.append(vim.eval('@%'))
2449 del fnamemodify
2450 EOF
Bram Moolenaarb18b4962022-09-02 21:55:50 +01002451 call assert_equal(['testdir', 'Xpycfile', 'src', 'testdir/Xpycfile', 'testdir',
2452 \ 'Xpycfile'], getline(2, '$'))
Bram Moolenaar92fdd1e2020-07-03 18:00:05 +02002453 close!
Bram Moolenaar0ab55d62020-07-07 20:50:39 +02002454 call AssertException(["py vim.chdir(None)"], "Vim(python):TypeError:")
Bram Moolenaar92fdd1e2020-07-03 18:00:05 +02002455endfunc
2456
2457" Test errors
2458func Test_python_errors()
Bram Moolenaarab589462020-07-06 21:03:06 +02002459 func F() dict
2460 endfunc
Bram Moolenaar92fdd1e2020-07-03 18:00:05 +02002461
Bram Moolenaarab589462020-07-06 21:03:06 +02002462 func D()
2463 endfunc
Bram Moolenaar92fdd1e2020-07-03 18:00:05 +02002464
2465 new
2466 py cb = vim.current.buffer
2467
2468 py << trim EOF
2469 d = vim.Dictionary()
2470 ned = vim.Dictionary(foo='bar', baz='abcD')
2471 dl = vim.Dictionary(a=1)
2472 dl.locked = True
2473 l = vim.List()
2474 ll = vim.List('abcE')
2475 ll.locked = True
2476 nel = vim.List('abcO')
2477 f = vim.Function('string')
2478 fd = vim.Function('F')
2479 fdel = vim.Function('D')
2480 vim.command('delfunction D')
Bram Moolenaareffb0cd2020-07-03 21:17:34 +02002481
Bram Moolenaar92fdd1e2020-07-03 18:00:05 +02002482 def subexpr_test(expr, name, subexprs):
2483 cb.append('>>> Testing %s using %s' % (name, expr))
2484 for subexpr in subexprs:
2485 ee(expr % subexpr)
2486 cb.append('<<< Finished')
Bram Moolenaareffb0cd2020-07-03 21:17:34 +02002487
Bram Moolenaar92fdd1e2020-07-03 18:00:05 +02002488 def stringtochars_test(expr):
2489 return subexpr_test(expr, 'StringToChars', (
2490 '1', # Fail type checks
2491 'u"\\0"', # Fail PyString_AsStringAndSize(bytes, , NULL) check
2492 '"\\0"', # Fail PyString_AsStringAndSize(object, , NULL) check
2493 ))
Bram Moolenaareffb0cd2020-07-03 21:17:34 +02002494
Bram Moolenaar92fdd1e2020-07-03 18:00:05 +02002495 class Mapping(object):
2496 def __init__(self, d):
2497 self.d = d
Bram Moolenaareffb0cd2020-07-03 21:17:34 +02002498
Bram Moolenaar92fdd1e2020-07-03 18:00:05 +02002499 def __getitem__(self, key):
2500 return self.d[key]
Bram Moolenaareffb0cd2020-07-03 21:17:34 +02002501
Bram Moolenaar92fdd1e2020-07-03 18:00:05 +02002502 def keys(self):
2503 return self.d.keys()
Bram Moolenaareffb0cd2020-07-03 21:17:34 +02002504
Bram Moolenaar92fdd1e2020-07-03 18:00:05 +02002505 def items(self):
2506 return self.d.items()
Bram Moolenaareffb0cd2020-07-03 21:17:34 +02002507
Bram Moolenaar92fdd1e2020-07-03 18:00:05 +02002508 def convertfrompyobject_test(expr, recurse=True):
2509 # pydict_to_tv
2510 stringtochars_test(expr % '{%s : 1}')
2511 if recurse:
2512 convertfrompyobject_test(expr % '{"abcF" : %s}', False)
2513 # pymap_to_tv
2514 stringtochars_test(expr % 'Mapping({%s : 1})')
2515 if recurse:
2516 convertfrompyobject_test(expr % 'Mapping({"abcG" : %s})', False)
2517 # pyseq_to_tv
2518 iter_test(expr)
2519 return subexpr_test(expr, 'ConvertFromPyObject', (
2520 'None', # Not conversible
2521 '{"": 1}', # Empty key not allowed
2522 '{u"": 1}', # Same, but with unicode object
2523 'FailingMapping()', #
2524 'FailingMappingKey()', #
2525 'FailingNumber()', #
2526 ))
Bram Moolenaareffb0cd2020-07-03 21:17:34 +02002527
Bram Moolenaar92fdd1e2020-07-03 18:00:05 +02002528 def convertfrompymapping_test(expr):
2529 convertfrompyobject_test(expr)
2530 return subexpr_test(expr, 'ConvertFromPyMapping', (
2531 '[]',
2532 ))
Bram Moolenaareffb0cd2020-07-03 21:17:34 +02002533
Bram Moolenaar92fdd1e2020-07-03 18:00:05 +02002534 def iter_test(expr):
2535 return subexpr_test(expr, '*Iter*', (
2536 'FailingIter()',
2537 'FailingIterNext()',
2538 ))
Bram Moolenaareffb0cd2020-07-03 21:17:34 +02002539
Bram Moolenaar92fdd1e2020-07-03 18:00:05 +02002540 def number_test(expr, natural=False, unsigned=False):
2541 if natural:
2542 unsigned = True
2543 return subexpr_test(expr, 'NumberToLong', (
2544 '[]',
2545 'None',
2546 ) + (unsigned and ('-1',) or ())
2547 + (natural and ('0',) or ()))
Bram Moolenaareffb0cd2020-07-03 21:17:34 +02002548
Bram Moolenaar92fdd1e2020-07-03 18:00:05 +02002549 class FailingTrue(object):
2550 def __nonzero__(self):
2551 raise NotImplementedError('bool')
Bram Moolenaareffb0cd2020-07-03 21:17:34 +02002552
Bram Moolenaar92fdd1e2020-07-03 18:00:05 +02002553 class FailingIter(object):
2554 def __iter__(self):
2555 raise NotImplementedError('iter')
Bram Moolenaareffb0cd2020-07-03 21:17:34 +02002556
Bram Moolenaar92fdd1e2020-07-03 18:00:05 +02002557 class FailingIterNext(object):
2558 def __iter__(self):
2559 return self
Bram Moolenaareffb0cd2020-07-03 21:17:34 +02002560
Bram Moolenaar92fdd1e2020-07-03 18:00:05 +02002561 def next(self):
2562 raise NotImplementedError('next')
Bram Moolenaareffb0cd2020-07-03 21:17:34 +02002563
Bram Moolenaar92fdd1e2020-07-03 18:00:05 +02002564 class FailingIterNextN(object):
2565 def __init__(self, n):
2566 self.n = n
Bram Moolenaareffb0cd2020-07-03 21:17:34 +02002567
Bram Moolenaar92fdd1e2020-07-03 18:00:05 +02002568 def __iter__(self):
2569 return self
Bram Moolenaareffb0cd2020-07-03 21:17:34 +02002570
Bram Moolenaar92fdd1e2020-07-03 18:00:05 +02002571 def next(self):
2572 if self.n:
2573 self.n -= 1
2574 return 1
2575 else:
2576 raise NotImplementedError('next N')
Bram Moolenaareffb0cd2020-07-03 21:17:34 +02002577
Bram Moolenaar92fdd1e2020-07-03 18:00:05 +02002578 class FailingMappingKey(object):
2579 def __getitem__(self, item):
2580 raise NotImplementedError('getitem:mappingkey')
Bram Moolenaareffb0cd2020-07-03 21:17:34 +02002581
Bram Moolenaar92fdd1e2020-07-03 18:00:05 +02002582 def keys(self):
2583 return list("abcH")
Bram Moolenaareffb0cd2020-07-03 21:17:34 +02002584
Bram Moolenaar92fdd1e2020-07-03 18:00:05 +02002585 class FailingMapping(object):
2586 def __getitem__(self):
2587 raise NotImplementedError('getitem:mapping')
Bram Moolenaareffb0cd2020-07-03 21:17:34 +02002588
Bram Moolenaar92fdd1e2020-07-03 18:00:05 +02002589 def keys(self):
2590 raise NotImplementedError('keys')
Bram Moolenaareffb0cd2020-07-03 21:17:34 +02002591
Bram Moolenaar92fdd1e2020-07-03 18:00:05 +02002592 class FailingList(list):
2593 def __getitem__(self, idx):
2594 if i == 2:
2595 raise NotImplementedError('getitem:list')
2596 else:
2597 return super(FailingList, self).__getitem__(idx)
Bram Moolenaareffb0cd2020-07-03 21:17:34 +02002598
Bram Moolenaar92fdd1e2020-07-03 18:00:05 +02002599 class NoArgsCall(object):
2600 def __call__(self):
2601 pass
Bram Moolenaareffb0cd2020-07-03 21:17:34 +02002602
Bram Moolenaar92fdd1e2020-07-03 18:00:05 +02002603 class FailingCall(object):
2604 def __call__(self, path):
2605 raise NotImplementedError('call')
Bram Moolenaareffb0cd2020-07-03 21:17:34 +02002606
Bram Moolenaar92fdd1e2020-07-03 18:00:05 +02002607 class FailingNumber(object):
2608 def __int__(self):
2609 raise NotImplementedError('int')
Bram Moolenaareffb0cd2020-07-03 21:17:34 +02002610
Bram Moolenaar92fdd1e2020-07-03 18:00:05 +02002611 cb.append("> Output")
2612 cb.append(">> OutputSetattr")
2613 ee('del sys.stdout.softspace')
2614 number_test('sys.stdout.softspace = %s', unsigned=True)
2615 number_test('sys.stderr.softspace = %s', unsigned=True)
2616 ee('assert sys.stdout.isatty()==False')
2617 ee('assert sys.stdout.seekable()==False')
2618 ee('sys.stdout.close()')
2619 ee('sys.stdout.flush()')
2620 ee('assert sys.stderr.isatty()==False')
2621 ee('assert sys.stderr.seekable()==False')
2622 ee('sys.stderr.close()')
2623 ee('sys.stderr.flush()')
2624 ee('sys.stdout.attr = None')
2625 cb.append(">> OutputWrite")
2626 ee('assert sys.stdout.writable()==True')
2627 ee('assert sys.stdout.readable()==False')
2628 ee('assert sys.stderr.writable()==True')
2629 ee('assert sys.stderr.readable()==False')
2630 ee('assert sys.stdout.closed()==False')
2631 ee('assert sys.stderr.closed()==False')
2632 ee('assert sys.stdout.errors=="strict"')
2633 ee('assert sys.stderr.errors=="strict"')
2634 ee('assert sys.stdout.encoding==sys.stderr.encoding')
2635 ee('sys.stdout.write(None)')
2636 cb.append(">> OutputWriteLines")
2637 ee('sys.stdout.writelines(None)')
2638 ee('sys.stdout.writelines([1])')
2639 iter_test('sys.stdout.writelines(%s)')
2640 cb.append("> VimCommand")
2641 stringtochars_test('vim.command(%s)')
2642 ee('vim.command("", 2)')
2643 #! Not checked: vim->python exceptions translating: checked later
2644 cb.append("> VimToPython")
2645 #! Not checked: everything: needs errors in internal python functions
2646 cb.append("> VimEval")
2647 stringtochars_test('vim.eval(%s)')
2648 ee('vim.eval("", FailingTrue())')
2649 #! Not checked: everything: needs errors in internal python functions
2650 cb.append("> VimEvalPy")
2651 stringtochars_test('vim.bindeval(%s)')
2652 ee('vim.eval("", 2)')
2653 #! Not checked: vim->python exceptions translating: checked later
2654 cb.append("> VimStrwidth")
2655 stringtochars_test('vim.strwidth(%s)')
2656 cb.append("> VimForeachRTP")
2657 ee('vim.foreach_rtp(None)')
2658 ee('vim.foreach_rtp(NoArgsCall())')
2659 ee('vim.foreach_rtp(FailingCall())')
2660 ee('vim.foreach_rtp(int, 2)')
2661 cb.append('> import')
2662 old_rtp = vim.options['rtp']
2663 vim.options['rtp'] = os.getcwd().replace('\\', '\\\\').replace(',', '\\,')
2664 ee('import xxx_no_such_module_xxx')
2665 ee('import failing_import')
2666 ee('import failing')
2667 vim.options['rtp'] = old_rtp
2668 del old_rtp
2669 cb.append("> Options")
2670 cb.append(">> OptionsItem")
2671 ee('vim.options["abcQ"]')
2672 ee('vim.options[""]')
2673 stringtochars_test('vim.options[%s]')
2674 cb.append(">> OptionsContains")
2675 stringtochars_test('%s in vim.options')
2676 cb.append("> Dictionary")
2677 cb.append(">> DictionaryConstructor")
2678 ee('vim.Dictionary("abcI")')
2679 ##! Not checked: py_dict_alloc failure
2680 cb.append(">> DictionarySetattr")
2681 ee('del d.locked')
2682 ee('d.locked = FailingTrue()')
2683 ee('vim.vvars.locked = False')
2684 ee('d.scope = True')
2685 ee('d.xxx = True')
2686 cb.append(">> _DictionaryItem")
2687 ee('d.get("a", 2, 3)')
2688 stringtochars_test('d.get(%s)')
2689 ee('d.pop("a")')
2690 ee('dl.pop("a")')
2691 cb.append(">> DictionaryContains")
2692 ee('"" in d')
2693 ee('0 in d')
2694 cb.append(">> DictionaryIterNext")
2695 ee('for i in ned: ned["a"] = 1')
2696 del i
2697 cb.append(">> DictionaryAssItem")
2698 ee('dl["b"] = 1')
2699 stringtochars_test('d[%s] = 1')
2700 convertfrompyobject_test('d["a"] = %s')
2701 cb.append(">> DictionaryUpdate")
2702 cb.append(">>> kwargs")
2703 cb.append(">>> iter")
2704 ee('d.update(FailingMapping())')
2705 ee('d.update([FailingIterNext()])')
2706 ee('d.update([FailingIterNextN(1)])')
2707 iter_test('d.update(%s)')
2708 convertfrompyobject_test('d.update(%s)')
2709 stringtochars_test('d.update(((%s, 0),))')
2710 convertfrompyobject_test('d.update((("a", %s),))')
2711 cb.append(">> DictionaryPopItem")
2712 ee('d.popitem(1, 2)')
2713 cb.append(">> DictionaryHasKey")
2714 ee('d.has_key()')
2715 cb.append("> List")
2716 cb.append(">> ListConstructor")
2717 ee('vim.List(1, 2)')
2718 ee('vim.List(a=1)')
2719 iter_test('vim.List(%s)')
2720 convertfrompyobject_test('vim.List([%s])')
2721 cb.append(">> ListItem")
2722 ee('l[1000]')
2723 cb.append(">> ListAssItem")
2724 ee('ll[1] = 2')
2725 ee('l[1000] = 3')
2726 cb.append(">> ListAssSlice")
2727 ee('ll[1:100] = "abcJ"')
2728 iter_test('l[:] = %s')
2729 ee('nel[1:10:2] = "abcK"')
2730 cb.append(repr(tuple(nel)))
2731 ee('nel[1:10:2] = "a"')
2732 cb.append(repr(tuple(nel)))
2733 ee('nel[1:1:-1] = "a"')
2734 cb.append(repr(tuple(nel)))
2735 ee('nel[:] = FailingIterNextN(2)')
2736 cb.append(repr(tuple(nel)))
2737 convertfrompyobject_test('l[:] = [%s]')
2738 cb.append(">> ListConcatInPlace")
2739 iter_test('l.extend(%s)')
2740 convertfrompyobject_test('l.extend([%s])')
2741 cb.append(">> ListSetattr")
2742 ee('del l.locked')
2743 ee('l.locked = FailingTrue()')
2744 ee('l.xxx = True')
2745 cb.append("> Function")
2746 cb.append(">> FunctionConstructor")
2747 cb.append(">>> FunctionConstructor")
2748 ee('vim.Function("123")')
2749 ee('vim.Function("xxx_non_existent_function_xxx")')
2750 ee('vim.Function("xxx#non#existent#function#xxx")')
2751 ee('vim.Function("xxx_non_existent_function_xxx2", args=[])')
2752 ee('vim.Function("xxx_non_existent_function_xxx3", self={})')
2753 ee('vim.Function("xxx_non_existent_function_xxx4", args=[], self={})')
2754 cb.append(">>> FunctionNew")
2755 ee('vim.Function("tr", self="abcFuncSelf")')
2756 ee('vim.Function("tr", args=427423)')
2757 ee('vim.Function("tr", self="abcFuncSelf2", args="abcFuncArgs2")')
2758 ee('vim.Function(self="abcFuncSelf2", args="abcFuncArgs2")')
2759 ee('vim.Function("tr", "", self="abcFuncSelf2", args="abcFuncArgs2")')
2760 ee('vim.Function("tr", "")')
2761 cb.append(">> FunctionCall")
2762 convertfrompyobject_test('f(%s)')
2763 convertfrompymapping_test('fd(self=%s)')
2764 cb.append("> TabPage")
2765 cb.append(">> TabPageAttr")
2766 ee('vim.current.tabpage.xxx')
2767 cb.append("> TabList")
2768 cb.append(">> TabListItem")
2769 ee('vim.tabpages[1000]')
2770 cb.append("> Window")
2771 cb.append(">> WindowAttr")
2772 ee('vim.current.window.xxx')
2773 cb.append(">> WindowSetattr")
2774 ee('vim.current.window.buffer = 0')
2775 ee('vim.current.window.cursor = (100000000, 100000000)')
2776 ee('vim.current.window.cursor = True')
2777 number_test('vim.current.window.height = %s', unsigned=True)
2778 number_test('vim.current.window.width = %s', unsigned=True)
2779 ee('vim.current.window.xxxxxx = True')
2780 cb.append("> WinList")
2781 cb.append(">> WinListItem")
2782 ee('vim.windows[1000]')
2783 cb.append("> Buffer")
2784 cb.append(">> StringToLine (indirect)")
Bram Moolenaar92fdd1e2020-07-03 18:00:05 +02002785 ee('vim.current.buffer[0] = "\\na"')
Bram Moolenaarab589462020-07-06 21:03:06 +02002786 ee('vim.current.buffer[0] = u"\\na"')
Bram Moolenaar92fdd1e2020-07-03 18:00:05 +02002787 cb.append(">> SetBufferLine (indirect)")
2788 ee('vim.current.buffer[0] = True')
2789 cb.append(">> SetBufferLineList (indirect)")
2790 ee('vim.current.buffer[:] = True')
2791 ee('vim.current.buffer[:] = ["\\na", "bc"]')
2792 cb.append(">> InsertBufferLines (indirect)")
2793 ee('vim.current.buffer.append(None)')
2794 ee('vim.current.buffer.append(["\\na", "bc"])')
2795 ee('vim.current.buffer.append("\\nbc")')
2796 cb.append(">> RBItem")
2797 ee('vim.current.buffer[100000000]')
2798 cb.append(">> RBAsItem")
2799 ee('vim.current.buffer[100000000] = ""')
2800 cb.append(">> BufferAttr")
2801 ee('vim.current.buffer.xxx')
2802 cb.append(">> BufferSetattr")
2803 ee('vim.current.buffer.name = True')
2804 ee('vim.current.buffer.xxx = True')
2805 cb.append(">> BufferMark")
2806 ee('vim.current.buffer.mark(0)')
2807 ee('vim.current.buffer.mark("abcM")')
2808 ee('vim.current.buffer.mark("!")')
2809 cb.append(">> BufferRange")
2810 ee('vim.current.buffer.range(1, 2, 3)')
2811 cb.append("> BufMap")
2812 cb.append(">> BufMapItem")
2813 ee('vim.buffers[100000000]')
2814 number_test('vim.buffers[%s]', natural=True)
2815 cb.append("> Current")
2816 cb.append(">> CurrentGetattr")
2817 ee('vim.current.xxx')
2818 cb.append(">> CurrentSetattr")
2819 ee('vim.current.line = True')
2820 ee('vim.current.buffer = True')
2821 ee('vim.current.window = True')
2822 ee('vim.current.tabpage = True')
2823 ee('vim.current.xxx = True')
2824 del d
2825 del ned
2826 del dl
2827 del l
2828 del ll
2829 del nel
2830 del f
2831 del fd
2832 del fdel
2833 del subexpr_test
2834 del stringtochars_test
2835 del Mapping
2836 del convertfrompyobject_test
2837 del convertfrompymapping_test
2838 del iter_test
2839 del number_test
2840 del FailingTrue
2841 del FailingIter
2842 del FailingIterNext
2843 del FailingIterNextN
2844 del FailingMapping
2845 del FailingMappingKey
2846 del FailingList
2847 del NoArgsCall
2848 del FailingCall
2849 del FailingNumber
2850 EOF
2851 delfunction F
2852
2853 let expected =<< trim END
2854 > Output
2855 >> OutputSetattr
2856 del sys.stdout.softspace:AttributeError:('cannot delete OutputObject attributes',)
2857 >>> Testing NumberToLong using sys.stdout.softspace = %s
2858 sys.stdout.softspace = []:TypeError:('expected int(), long() or something supporting coercing to long(), but got list',)
2859 sys.stdout.softspace = None:TypeError:('expected int(), long() or something supporting coercing to long(), but got NoneType',)
2860 sys.stdout.softspace = -1:ValueError:('number must be greater or equal to zero',)
2861 <<< Finished
2862 >>> Testing NumberToLong using sys.stderr.softspace = %s
2863 sys.stderr.softspace = []:TypeError:('expected int(), long() or something supporting coercing to long(), but got list',)
2864 sys.stderr.softspace = None:TypeError:('expected int(), long() or something supporting coercing to long(), but got NoneType',)
2865 sys.stderr.softspace = -1:ValueError:('number must be greater or equal to zero',)
2866 <<< Finished
2867 assert sys.stdout.isatty()==False:NOT FAILED
2868 assert sys.stdout.seekable()==False:NOT FAILED
2869 sys.stdout.close():NOT FAILED
2870 sys.stdout.flush():NOT FAILED
2871 assert sys.stderr.isatty()==False:NOT FAILED
2872 assert sys.stderr.seekable()==False:NOT FAILED
2873 sys.stderr.close():NOT FAILED
2874 sys.stderr.flush():NOT FAILED
2875 sys.stdout.attr = None:AttributeError:('invalid attribute: attr',)
2876 >> OutputWrite
2877 assert sys.stdout.writable()==True:NOT FAILED
2878 assert sys.stdout.readable()==False:NOT FAILED
2879 assert sys.stderr.writable()==True:NOT FAILED
2880 assert sys.stderr.readable()==False:NOT FAILED
2881 assert sys.stdout.closed()==False:NOT FAILED
2882 assert sys.stderr.closed()==False:NOT FAILED
2883 assert sys.stdout.errors=="strict":NOT FAILED
2884 assert sys.stderr.errors=="strict":NOT FAILED
2885 assert sys.stdout.encoding==sys.stderr.encoding:NOT FAILED
2886 sys.stdout.write(None):TypeError:('coercing to Unicode: need string or buffer, NoneType found',)
2887 >> OutputWriteLines
2888 sys.stdout.writelines(None):TypeError:("'NoneType' object is not iterable",)
2889 sys.stdout.writelines([1]):TypeError:('coercing to Unicode: need string or buffer, int found',)
2890 >>> Testing *Iter* using sys.stdout.writelines(%s)
2891 sys.stdout.writelines(FailingIter()):NotImplementedError:('iter',)
2892 sys.stdout.writelines(FailingIterNext()):NotImplementedError:('next',)
2893 <<< Finished
2894 > VimCommand
2895 >>> Testing StringToChars using vim.command(%s)
2896 vim.command(1):TypeError:('expected str() or unicode() instance, but got int',)
2897 vim.command(u"\0"):TypeError:('expected string without null bytes',)
2898 vim.command("\0"):TypeError:('expected string without null bytes',)
2899 <<< Finished
2900 vim.command("", 2):TypeError:('command() takes exactly one argument (2 given)',)
2901 > VimToPython
2902 > VimEval
2903 >>> Testing StringToChars using vim.eval(%s)
2904 vim.eval(1):TypeError:('expected str() or unicode() instance, but got int',)
2905 vim.eval(u"\0"):TypeError:('expected string without null bytes',)
2906 vim.eval("\0"):TypeError:('expected string without null bytes',)
2907 <<< Finished
2908 vim.eval("", FailingTrue()):TypeError:('function takes exactly 1 argument (2 given)',)
2909 > VimEvalPy
2910 >>> Testing StringToChars using vim.bindeval(%s)
2911 vim.bindeval(1):TypeError:('expected str() or unicode() instance, but got int',)
2912 vim.bindeval(u"\0"):TypeError:('expected string without null bytes',)
2913 vim.bindeval("\0"):TypeError:('expected string without null bytes',)
2914 <<< Finished
2915 vim.eval("", 2):TypeError:('function takes exactly 1 argument (2 given)',)
2916 > VimStrwidth
2917 >>> Testing StringToChars using vim.strwidth(%s)
2918 vim.strwidth(1):TypeError:('expected str() or unicode() instance, but got int',)
2919 vim.strwidth(u"\0"):TypeError:('expected string without null bytes',)
2920 vim.strwidth("\0"):TypeError:('expected string without null bytes',)
2921 <<< Finished
2922 > VimForeachRTP
2923 vim.foreach_rtp(None):TypeError:("'NoneType' object is not callable",)
2924 vim.foreach_rtp(NoArgsCall()):TypeError:('__call__() takes exactly 1 argument (2 given)',)
2925 vim.foreach_rtp(FailingCall()):NotImplementedError:('call',)
2926 vim.foreach_rtp(int, 2):TypeError:('foreach_rtp() takes exactly one argument (2 given)',)
2927 > import
2928 import xxx_no_such_module_xxx:ImportError:('No module named xxx_no_such_module_xxx',)
2929 import failing_import:ImportError:()
2930 import failing:NotImplementedError:()
2931 > Options
2932 >> OptionsItem
2933 vim.options["abcQ"]:KeyError:('abcQ',)
2934 vim.options[""]:ValueError:('empty keys are not allowed',)
2935 >>> Testing StringToChars using vim.options[%s]
2936 vim.options[1]:TypeError:('expected str() or unicode() instance, but got int',)
2937 vim.options[u"\0"]:TypeError:('expected string without null bytes',)
2938 vim.options["\0"]:TypeError:('expected string without null bytes',)
2939 <<< Finished
2940 >> OptionsContains
2941 >>> Testing StringToChars using %s in vim.options
2942 1 in vim.options:TypeError:('expected str() or unicode() instance, but got int',)
2943 u"\0" in vim.options:TypeError:('expected string without null bytes',)
2944 "\0" in vim.options:TypeError:('expected string without null bytes',)
2945 <<< Finished
2946 > Dictionary
2947 >> DictionaryConstructor
2948 vim.Dictionary("abcI"):ValueError:('expected sequence element of size 2, but got sequence of size 1',)
2949 >> DictionarySetattr
2950 del d.locked:AttributeError:('cannot delete vim.Dictionary attributes',)
2951 d.locked = FailingTrue():NotImplementedError:('bool',)
2952 vim.vvars.locked = False:TypeError:('cannot modify fixed dictionary',)
2953 d.scope = True:AttributeError:('cannot set attribute scope',)
2954 d.xxx = True:AttributeError:('cannot set attribute xxx',)
2955 >> _DictionaryItem
2956 d.get("a", 2, 3):TypeError:('function takes at most 2 arguments (3 given)',)
2957 >>> Testing StringToChars using d.get(%s)
2958 d.get(1):TypeError:('expected str() or unicode() instance, but got int',)
2959 d.get(u"\0"):TypeError:('expected string without null bytes',)
2960 d.get("\0"):TypeError:('expected string without null bytes',)
2961 <<< Finished
2962 d.pop("a"):KeyError:('a',)
2963 dl.pop("a"):error:('dictionary is locked',)
2964 >> DictionaryContains
2965 "" in d:ValueError:('empty keys are not allowed',)
2966 0 in d:TypeError:('expected str() or unicode() instance, but got int',)
2967 >> DictionaryIterNext
2968 for i in ned: ned["a"] = 1:RuntimeError:('hashtab changed during iteration',)
2969 >> DictionaryAssItem
2970 dl["b"] = 1:error:('dictionary is locked',)
2971 >>> Testing StringToChars using d[%s] = 1
2972 d[1] = 1:TypeError:('expected str() or unicode() instance, but got int',)
2973 d[u"\0"] = 1:TypeError:('expected string without null bytes',)
2974 d["\0"] = 1:TypeError:('expected string without null bytes',)
2975 <<< Finished
2976 >>> Testing StringToChars using d["a"] = {%s : 1}
2977 d["a"] = {1 : 1}:TypeError:('expected str() or unicode() instance, but got int',)
2978 d["a"] = {u"\0" : 1}:TypeError:('expected string without null bytes',)
2979 d["a"] = {"\0" : 1}:TypeError:('expected string without null bytes',)
2980 <<< Finished
2981 >>> Testing StringToChars using d["a"] = {"abcF" : {%s : 1}}
2982 d["a"] = {"abcF" : {1 : 1}}:TypeError:('expected str() or unicode() instance, but got int',)
2983 d["a"] = {"abcF" : {u"\0" : 1}}:TypeError:('expected string without null bytes',)
2984 d["a"] = {"abcF" : {"\0" : 1}}:TypeError:('expected string without null bytes',)
2985 <<< Finished
2986 >>> Testing StringToChars using d["a"] = {"abcF" : Mapping({%s : 1})}
2987 d["a"] = {"abcF" : Mapping({1 : 1})}:TypeError:('expected str() or unicode() instance, but got int',)
2988 d["a"] = {"abcF" : Mapping({u"\0" : 1})}:TypeError:('expected string without null bytes',)
2989 d["a"] = {"abcF" : Mapping({"\0" : 1})}:TypeError:('expected string without null bytes',)
2990 <<< Finished
2991 >>> Testing *Iter* using d["a"] = {"abcF" : %s}
2992 d["a"] = {"abcF" : FailingIter()}:TypeError:('unable to convert FailingIter to a Vim structure',)
2993 d["a"] = {"abcF" : FailingIterNext()}:NotImplementedError:('next',)
2994 <<< Finished
2995 >>> Testing ConvertFromPyObject using d["a"] = {"abcF" : %s}
2996 d["a"] = {"abcF" : None}:NOT FAILED
2997 d["a"] = {"abcF" : {"": 1}}:ValueError:('empty keys are not allowed',)
2998 d["a"] = {"abcF" : {u"": 1}}:ValueError:('empty keys are not allowed',)
2999 d["a"] = {"abcF" : FailingMapping()}:NotImplementedError:('keys',)
3000 d["a"] = {"abcF" : FailingMappingKey()}:NotImplementedError:('getitem:mappingkey',)
3001 d["a"] = {"abcF" : FailingNumber()}:TypeError:('long() argument must be a string or a number',)
3002 <<< Finished
3003 >>> Testing StringToChars using d["a"] = Mapping({%s : 1})
3004 d["a"] = Mapping({1 : 1}):TypeError:('expected str() or unicode() instance, but got int',)
3005 d["a"] = Mapping({u"\0" : 1}):TypeError:('expected string without null bytes',)
3006 d["a"] = Mapping({"\0" : 1}):TypeError:('expected string without null bytes',)
3007 <<< Finished
3008 >>> Testing StringToChars using d["a"] = Mapping({"abcG" : {%s : 1}})
3009 d["a"] = Mapping({"abcG" : {1 : 1}}):TypeError:('expected str() or unicode() instance, but got int',)
3010 d["a"] = Mapping({"abcG" : {u"\0" : 1}}):TypeError:('expected string without null bytes',)
3011 d["a"] = Mapping({"abcG" : {"\0" : 1}}):TypeError:('expected string without null bytes',)
3012 <<< Finished
3013 >>> Testing StringToChars using d["a"] = Mapping({"abcG" : Mapping({%s : 1})})
3014 d["a"] = Mapping({"abcG" : Mapping({1 : 1})}):TypeError:('expected str() or unicode() instance, but got int',)
3015 d["a"] = Mapping({"abcG" : Mapping({u"\0" : 1})}):TypeError:('expected string without null bytes',)
3016 d["a"] = Mapping({"abcG" : Mapping({"\0" : 1})}):TypeError:('expected string without null bytes',)
3017 <<< Finished
3018 >>> Testing *Iter* using d["a"] = Mapping({"abcG" : %s})
3019 d["a"] = Mapping({"abcG" : FailingIter()}):TypeError:('unable to convert FailingIter to a Vim structure',)
3020 d["a"] = Mapping({"abcG" : FailingIterNext()}):NotImplementedError:('next',)
3021 <<< Finished
3022 >>> Testing ConvertFromPyObject using d["a"] = Mapping({"abcG" : %s})
3023 d["a"] = Mapping({"abcG" : None}):NOT FAILED
3024 d["a"] = Mapping({"abcG" : {"": 1}}):ValueError:('empty keys are not allowed',)
3025 d["a"] = Mapping({"abcG" : {u"": 1}}):ValueError:('empty keys are not allowed',)
3026 d["a"] = Mapping({"abcG" : FailingMapping()}):NotImplementedError:('keys',)
3027 d["a"] = Mapping({"abcG" : FailingMappingKey()}):NotImplementedError:('getitem:mappingkey',)
3028 d["a"] = Mapping({"abcG" : FailingNumber()}):TypeError:('long() argument must be a string or a number',)
3029 <<< Finished
3030 >>> Testing *Iter* using d["a"] = %s
3031 d["a"] = FailingIter():TypeError:('unable to convert FailingIter to a Vim structure',)
3032 d["a"] = FailingIterNext():NotImplementedError:('next',)
3033 <<< Finished
3034 >>> Testing ConvertFromPyObject using d["a"] = %s
3035 d["a"] = None:NOT FAILED
3036 d["a"] = {"": 1}:ValueError:('empty keys are not allowed',)
3037 d["a"] = {u"": 1}:ValueError:('empty keys are not allowed',)
3038 d["a"] = FailingMapping():NotImplementedError:('keys',)
3039 d["a"] = FailingMappingKey():NotImplementedError:('getitem:mappingkey',)
3040 d["a"] = FailingNumber():TypeError:('long() argument must be a string or a number',)
3041 <<< Finished
3042 >> DictionaryUpdate
3043 >>> kwargs
3044 >>> iter
3045 d.update(FailingMapping()):NotImplementedError:('keys',)
3046 d.update([FailingIterNext()]):NotImplementedError:('next',)
3047 d.update([FailingIterNextN(1)]):NotImplementedError:('next N',)
3048 >>> Testing *Iter* using d.update(%s)
3049 d.update(FailingIter()):NotImplementedError:('iter',)
3050 d.update(FailingIterNext()):NotImplementedError:('next',)
3051 <<< Finished
3052 >>> Testing StringToChars using d.update({%s : 1})
3053 d.update({1 : 1}):TypeError:('expected str() or unicode() instance, but got int',)
3054 d.update({u"\0" : 1}):TypeError:('expected string without null bytes',)
3055 d.update({"\0" : 1}):TypeError:('expected string without null bytes',)
3056 <<< Finished
3057 >>> Testing StringToChars using d.update({"abcF" : {%s : 1}})
3058 d.update({"abcF" : {1 : 1}}):TypeError:('expected str() or unicode() instance, but got int',)
3059 d.update({"abcF" : {u"\0" : 1}}):TypeError:('expected string without null bytes',)
3060 d.update({"abcF" : {"\0" : 1}}):TypeError:('expected string without null bytes',)
3061 <<< Finished
3062 >>> Testing StringToChars using d.update({"abcF" : Mapping({%s : 1})})
3063 d.update({"abcF" : Mapping({1 : 1})}):TypeError:('expected str() or unicode() instance, but got int',)
3064 d.update({"abcF" : Mapping({u"\0" : 1})}):TypeError:('expected string without null bytes',)
3065 d.update({"abcF" : Mapping({"\0" : 1})}):TypeError:('expected string without null bytes',)
3066 <<< Finished
3067 >>> Testing *Iter* using d.update({"abcF" : %s})
3068 d.update({"abcF" : FailingIter()}):TypeError:('unable to convert FailingIter to a Vim structure',)
3069 d.update({"abcF" : FailingIterNext()}):NotImplementedError:('next',)
3070 <<< Finished
3071 >>> Testing ConvertFromPyObject using d.update({"abcF" : %s})
3072 d.update({"abcF" : None}):NOT FAILED
3073 d.update({"abcF" : {"": 1}}):ValueError:('empty keys are not allowed',)
3074 d.update({"abcF" : {u"": 1}}):ValueError:('empty keys are not allowed',)
3075 d.update({"abcF" : FailingMapping()}):NotImplementedError:('keys',)
3076 d.update({"abcF" : FailingMappingKey()}):NotImplementedError:('getitem:mappingkey',)
3077 d.update({"abcF" : FailingNumber()}):TypeError:('long() argument must be a string or a number',)
3078 <<< Finished
3079 >>> Testing StringToChars using d.update(Mapping({%s : 1}))
3080 d.update(Mapping({1 : 1})):TypeError:('expected str() or unicode() instance, but got int',)
3081 d.update(Mapping({u"\0" : 1})):TypeError:('expected string without null bytes',)
3082 d.update(Mapping({"\0" : 1})):TypeError:('expected string without null bytes',)
3083 <<< Finished
3084 >>> Testing StringToChars using d.update(Mapping({"abcG" : {%s : 1}}))
3085 d.update(Mapping({"abcG" : {1 : 1}})):TypeError:('expected str() or unicode() instance, but got int',)
3086 d.update(Mapping({"abcG" : {u"\0" : 1}})):TypeError:('expected string without null bytes',)
3087 d.update(Mapping({"abcG" : {"\0" : 1}})):TypeError:('expected string without null bytes',)
3088 <<< Finished
3089 >>> Testing StringToChars using d.update(Mapping({"abcG" : Mapping({%s : 1})}))
3090 d.update(Mapping({"abcG" : Mapping({1 : 1})})):TypeError:('expected str() or unicode() instance, but got int',)
3091 d.update(Mapping({"abcG" : Mapping({u"\0" : 1})})):TypeError:('expected string without null bytes',)
3092 d.update(Mapping({"abcG" : Mapping({"\0" : 1})})):TypeError:('expected string without null bytes',)
3093 <<< Finished
3094 >>> Testing *Iter* using d.update(Mapping({"abcG" : %s}))
3095 d.update(Mapping({"abcG" : FailingIter()})):TypeError:('unable to convert FailingIter to a Vim structure',)
3096 d.update(Mapping({"abcG" : FailingIterNext()})):NotImplementedError:('next',)
3097 <<< Finished
3098 >>> Testing ConvertFromPyObject using d.update(Mapping({"abcG" : %s}))
3099 d.update(Mapping({"abcG" : None})):NOT FAILED
3100 d.update(Mapping({"abcG" : {"": 1}})):ValueError:('empty keys are not allowed',)
3101 d.update(Mapping({"abcG" : {u"": 1}})):ValueError:('empty keys are not allowed',)
3102 d.update(Mapping({"abcG" : FailingMapping()})):NotImplementedError:('keys',)
3103 d.update(Mapping({"abcG" : FailingMappingKey()})):NotImplementedError:('getitem:mappingkey',)
3104 d.update(Mapping({"abcG" : FailingNumber()})):TypeError:('long() argument must be a string or a number',)
3105 <<< Finished
3106 >>> Testing *Iter* using d.update(%s)
3107 d.update(FailingIter()):NotImplementedError:('iter',)
3108 d.update(FailingIterNext()):NotImplementedError:('next',)
3109 <<< Finished
3110 >>> Testing ConvertFromPyObject using d.update(%s)
3111 d.update(None):TypeError:("'NoneType' object is not iterable",)
3112 d.update({"": 1}):ValueError:('empty keys are not allowed',)
3113 d.update({u"": 1}):ValueError:('empty keys are not allowed',)
3114 d.update(FailingMapping()):NotImplementedError:('keys',)
3115 d.update(FailingMappingKey()):NotImplementedError:('getitem:mappingkey',)
3116 d.update(FailingNumber()):TypeError:("'FailingNumber' object is not iterable",)
3117 <<< Finished
3118 >>> Testing StringToChars using d.update(((%s, 0),))
3119 d.update(((1, 0),)):TypeError:('expected str() or unicode() instance, but got int',)
3120 d.update(((u"\0", 0),)):TypeError:('expected string without null bytes',)
3121 d.update((("\0", 0),)):TypeError:('expected string without null bytes',)
3122 <<< Finished
3123 >>> Testing StringToChars using d.update((("a", {%s : 1}),))
3124 d.update((("a", {1 : 1}),)):TypeError:('expected str() or unicode() instance, but got int',)
3125 d.update((("a", {u"\0" : 1}),)):TypeError:('expected string without null bytes',)
3126 d.update((("a", {"\0" : 1}),)):TypeError:('expected string without null bytes',)
3127 <<< Finished
3128 >>> Testing StringToChars using d.update((("a", {"abcF" : {%s : 1}}),))
3129 d.update((("a", {"abcF" : {1 : 1}}),)):TypeError:('expected str() or unicode() instance, but got int',)
3130 d.update((("a", {"abcF" : {u"\0" : 1}}),)):TypeError:('expected string without null bytes',)
3131 d.update((("a", {"abcF" : {"\0" : 1}}),)):TypeError:('expected string without null bytes',)
3132 <<< Finished
3133 >>> Testing StringToChars using d.update((("a", {"abcF" : Mapping({%s : 1})}),))
3134 d.update((("a", {"abcF" : Mapping({1 : 1})}),)):TypeError:('expected str() or unicode() instance, but got int',)
3135 d.update((("a", {"abcF" : Mapping({u"\0" : 1})}),)):TypeError:('expected string without null bytes',)
3136 d.update((("a", {"abcF" : Mapping({"\0" : 1})}),)):TypeError:('expected string without null bytes',)
3137 <<< Finished
3138 >>> Testing *Iter* using d.update((("a", {"abcF" : %s}),))
3139 d.update((("a", {"abcF" : FailingIter()}),)):TypeError:('unable to convert FailingIter to a Vim structure',)
3140 d.update((("a", {"abcF" : FailingIterNext()}),)):NotImplementedError:('next',)
3141 <<< Finished
3142 >>> Testing ConvertFromPyObject using d.update((("a", {"abcF" : %s}),))
3143 d.update((("a", {"abcF" : None}),)):error:("failed to add key 'a' to dictionary",)
3144 d.update((("a", {"abcF" : {"": 1}}),)):ValueError:('empty keys are not allowed',)
3145 d.update((("a", {"abcF" : {u"": 1}}),)):ValueError:('empty keys are not allowed',)
3146 d.update((("a", {"abcF" : FailingMapping()}),)):NotImplementedError:('keys',)
3147 d.update((("a", {"abcF" : FailingMappingKey()}),)):NotImplementedError:('getitem:mappingkey',)
3148 d.update((("a", {"abcF" : FailingNumber()}),)):TypeError:('long() argument must be a string or a number',)
3149 <<< Finished
3150 >>> Testing StringToChars using d.update((("a", Mapping({%s : 1})),))
3151 d.update((("a", Mapping({1 : 1})),)):TypeError:('expected str() or unicode() instance, but got int',)
3152 d.update((("a", Mapping({u"\0" : 1})),)):TypeError:('expected string without null bytes',)
3153 d.update((("a", Mapping({"\0" : 1})),)):TypeError:('expected string without null bytes',)
3154 <<< Finished
3155 >>> Testing StringToChars using d.update((("a", Mapping({"abcG" : {%s : 1}})),))
3156 d.update((("a", Mapping({"abcG" : {1 : 1}})),)):TypeError:('expected str() or unicode() instance, but got int',)
3157 d.update((("a", Mapping({"abcG" : {u"\0" : 1}})),)):TypeError:('expected string without null bytes',)
3158 d.update((("a", Mapping({"abcG" : {"\0" : 1}})),)):TypeError:('expected string without null bytes',)
3159 <<< Finished
3160 >>> Testing StringToChars using d.update((("a", Mapping({"abcG" : Mapping({%s : 1})})),))
3161 d.update((("a", Mapping({"abcG" : Mapping({1 : 1})})),)):TypeError:('expected str() or unicode() instance, but got int',)
3162 d.update((("a", Mapping({"abcG" : Mapping({u"\0" : 1})})),)):TypeError:('expected string without null bytes',)
3163 d.update((("a", Mapping({"abcG" : Mapping({"\0" : 1})})),)):TypeError:('expected string without null bytes',)
3164 <<< Finished
3165 >>> Testing *Iter* using d.update((("a", Mapping({"abcG" : %s})),))
3166 d.update((("a", Mapping({"abcG" : FailingIter()})),)):TypeError:('unable to convert FailingIter to a Vim structure',)
3167 d.update((("a", Mapping({"abcG" : FailingIterNext()})),)):NotImplementedError:('next',)
3168 <<< Finished
3169 >>> Testing ConvertFromPyObject using d.update((("a", Mapping({"abcG" : %s})),))
3170 d.update((("a", Mapping({"abcG" : None})),)):error:("failed to add key 'a' to dictionary",)
3171 d.update((("a", Mapping({"abcG" : {"": 1}})),)):ValueError:('empty keys are not allowed',)
3172 d.update((("a", Mapping({"abcG" : {u"": 1}})),)):ValueError:('empty keys are not allowed',)
3173 d.update((("a", Mapping({"abcG" : FailingMapping()})),)):NotImplementedError:('keys',)
3174 d.update((("a", Mapping({"abcG" : FailingMappingKey()})),)):NotImplementedError:('getitem:mappingkey',)
3175 d.update((("a", Mapping({"abcG" : FailingNumber()})),)):TypeError:('long() argument must be a string or a number',)
3176 <<< Finished
3177 >>> Testing *Iter* using d.update((("a", %s),))
3178 d.update((("a", FailingIter()),)):TypeError:('unable to convert FailingIter to a Vim structure',)
3179 d.update((("a", FailingIterNext()),)):NotImplementedError:('next',)
3180 <<< Finished
3181 >>> Testing ConvertFromPyObject using d.update((("a", %s),))
3182 d.update((("a", None),)):error:("failed to add key 'a' to dictionary",)
3183 d.update((("a", {"": 1}),)):ValueError:('empty keys are not allowed',)
3184 d.update((("a", {u"": 1}),)):ValueError:('empty keys are not allowed',)
3185 d.update((("a", FailingMapping()),)):NotImplementedError:('keys',)
3186 d.update((("a", FailingMappingKey()),)):NotImplementedError:('getitem:mappingkey',)
3187 d.update((("a", FailingNumber()),)):TypeError:('long() argument must be a string or a number',)
3188 <<< Finished
3189 >> DictionaryPopItem
3190 d.popitem(1, 2):TypeError:('popitem() takes no arguments (2 given)',)
3191 >> DictionaryHasKey
3192 d.has_key():TypeError:('has_key() takes exactly one argument (0 given)',)
3193 > List
3194 >> ListConstructor
3195 vim.List(1, 2):TypeError:('function takes at most 1 argument (2 given)',)
3196 vim.List(a=1):TypeError:('list constructor does not accept keyword arguments',)
3197 >>> Testing *Iter* using vim.List(%s)
3198 vim.List(FailingIter()):NotImplementedError:('iter',)
3199 vim.List(FailingIterNext()):NotImplementedError:('next',)
3200 <<< Finished
3201 >>> Testing StringToChars using vim.List([{%s : 1}])
3202 vim.List([{1 : 1}]):TypeError:('expected str() or unicode() instance, but got int',)
3203 vim.List([{u"\0" : 1}]):TypeError:('expected string without null bytes',)
3204 vim.List([{"\0" : 1}]):TypeError:('expected string without null bytes',)
3205 <<< Finished
3206 >>> Testing StringToChars using vim.List([{"abcF" : {%s : 1}}])
3207 vim.List([{"abcF" : {1 : 1}}]):TypeError:('expected str() or unicode() instance, but got int',)
3208 vim.List([{"abcF" : {u"\0" : 1}}]):TypeError:('expected string without null bytes',)
3209 vim.List([{"abcF" : {"\0" : 1}}]):TypeError:('expected string without null bytes',)
3210 <<< Finished
3211 >>> Testing StringToChars using vim.List([{"abcF" : Mapping({%s : 1})}])
3212 vim.List([{"abcF" : Mapping({1 : 1})}]):TypeError:('expected str() or unicode() instance, but got int',)
3213 vim.List([{"abcF" : Mapping({u"\0" : 1})}]):TypeError:('expected string without null bytes',)
3214 vim.List([{"abcF" : Mapping({"\0" : 1})}]):TypeError:('expected string without null bytes',)
3215 <<< Finished
3216 >>> Testing *Iter* using vim.List([{"abcF" : %s}])
3217 vim.List([{"abcF" : FailingIter()}]):TypeError:('unable to convert FailingIter to a Vim structure',)
3218 vim.List([{"abcF" : FailingIterNext()}]):NotImplementedError:('next',)
3219 <<< Finished
3220 >>> Testing ConvertFromPyObject using vim.List([{"abcF" : %s}])
3221 vim.List([{"abcF" : None}]):NOT FAILED
3222 vim.List([{"abcF" : {"": 1}}]):ValueError:('empty keys are not allowed',)
3223 vim.List([{"abcF" : {u"": 1}}]):ValueError:('empty keys are not allowed',)
3224 vim.List([{"abcF" : FailingMapping()}]):NotImplementedError:('keys',)
3225 vim.List([{"abcF" : FailingMappingKey()}]):NotImplementedError:('getitem:mappingkey',)
3226 vim.List([{"abcF" : FailingNumber()}]):TypeError:('long() argument must be a string or a number',)
3227 <<< Finished
3228 >>> Testing StringToChars using vim.List([Mapping({%s : 1})])
3229 vim.List([Mapping({1 : 1})]):TypeError:('expected str() or unicode() instance, but got int',)
3230 vim.List([Mapping({u"\0" : 1})]):TypeError:('expected string without null bytes',)
3231 vim.List([Mapping({"\0" : 1})]):TypeError:('expected string without null bytes',)
3232 <<< Finished
3233 >>> Testing StringToChars using vim.List([Mapping({"abcG" : {%s : 1}})])
3234 vim.List([Mapping({"abcG" : {1 : 1}})]):TypeError:('expected str() or unicode() instance, but got int',)
3235 vim.List([Mapping({"abcG" : {u"\0" : 1}})]):TypeError:('expected string without null bytes',)
3236 vim.List([Mapping({"abcG" : {"\0" : 1}})]):TypeError:('expected string without null bytes',)
3237 <<< Finished
3238 >>> Testing StringToChars using vim.List([Mapping({"abcG" : Mapping({%s : 1})})])
3239 vim.List([Mapping({"abcG" : Mapping({1 : 1})})]):TypeError:('expected str() or unicode() instance, but got int',)
3240 vim.List([Mapping({"abcG" : Mapping({u"\0" : 1})})]):TypeError:('expected string without null bytes',)
3241 vim.List([Mapping({"abcG" : Mapping({"\0" : 1})})]):TypeError:('expected string without null bytes',)
3242 <<< Finished
3243 >>> Testing *Iter* using vim.List([Mapping({"abcG" : %s})])
3244 vim.List([Mapping({"abcG" : FailingIter()})]):TypeError:('unable to convert FailingIter to a Vim structure',)
3245 vim.List([Mapping({"abcG" : FailingIterNext()})]):NotImplementedError:('next',)
3246 <<< Finished
3247 >>> Testing ConvertFromPyObject using vim.List([Mapping({"abcG" : %s})])
3248 vim.List([Mapping({"abcG" : None})]):NOT FAILED
3249 vim.List([Mapping({"abcG" : {"": 1}})]):ValueError:('empty keys are not allowed',)
3250 vim.List([Mapping({"abcG" : {u"": 1}})]):ValueError:('empty keys are not allowed',)
3251 vim.List([Mapping({"abcG" : FailingMapping()})]):NotImplementedError:('keys',)
3252 vim.List([Mapping({"abcG" : FailingMappingKey()})]):NotImplementedError:('getitem:mappingkey',)
3253 vim.List([Mapping({"abcG" : FailingNumber()})]):TypeError:('long() argument must be a string or a number',)
3254 <<< Finished
3255 >>> Testing *Iter* using vim.List([%s])
3256 vim.List([FailingIter()]):TypeError:('unable to convert FailingIter to a Vim structure',)
3257 vim.List([FailingIterNext()]):NotImplementedError:('next',)
3258 <<< Finished
3259 >>> Testing ConvertFromPyObject using vim.List([%s])
3260 vim.List([None]):NOT FAILED
3261 vim.List([{"": 1}]):ValueError:('empty keys are not allowed',)
3262 vim.List([{u"": 1}]):ValueError:('empty keys are not allowed',)
3263 vim.List([FailingMapping()]):NotImplementedError:('keys',)
3264 vim.List([FailingMappingKey()]):NotImplementedError:('getitem:mappingkey',)
3265 vim.List([FailingNumber()]):TypeError:('long() argument must be a string or a number',)
3266 <<< Finished
3267 >> ListItem
3268 l[1000]:IndexError:('list index out of range',)
3269 >> ListAssItem
3270 ll[1] = 2:error:('list is locked',)
3271 l[1000] = 3:IndexError:('list index out of range',)
3272 >> ListAssSlice
3273 ll[1:100] = "abcJ":error:('list is locked',)
3274 >>> Testing *Iter* using l[:] = %s
3275 l[:] = FailingIter():NotImplementedError:('iter',)
3276 l[:] = FailingIterNext():NotImplementedError:('next',)
3277 <<< Finished
3278 nel[1:10:2] = "abcK":ValueError:('attempt to assign sequence of size greater than 2 to extended slice',)
3279 ('a', 'b', 'c', 'O')
3280 nel[1:10:2] = "a":ValueError:('attempt to assign sequence of size 1 to extended slice of size 2',)
3281 ('a', 'b', 'c', 'O')
3282 nel[1:1:-1] = "a":ValueError:('attempt to assign sequence of size greater than 0 to extended slice',)
3283 ('a', 'b', 'c', 'O')
3284 nel[:] = FailingIterNextN(2):NotImplementedError:('next N',)
3285 ('a', 'b', 'c', 'O')
3286 >>> Testing StringToChars using l[:] = [{%s : 1}]
3287 l[:] = [{1 : 1}]:TypeError:('expected str() or unicode() instance, but got int',)
3288 l[:] = [{u"\0" : 1}]:TypeError:('expected string without null bytes',)
3289 l[:] = [{"\0" : 1}]:TypeError:('expected string without null bytes',)
3290 <<< Finished
3291 >>> Testing StringToChars using l[:] = [{"abcF" : {%s : 1}}]
3292 l[:] = [{"abcF" : {1 : 1}}]:TypeError:('expected str() or unicode() instance, but got int',)
3293 l[:] = [{"abcF" : {u"\0" : 1}}]:TypeError:('expected string without null bytes',)
3294 l[:] = [{"abcF" : {"\0" : 1}}]:TypeError:('expected string without null bytes',)
3295 <<< Finished
3296 >>> Testing StringToChars using l[:] = [{"abcF" : Mapping({%s : 1})}]
3297 l[:] = [{"abcF" : Mapping({1 : 1})}]:TypeError:('expected str() or unicode() instance, but got int',)
3298 l[:] = [{"abcF" : Mapping({u"\0" : 1})}]:TypeError:('expected string without null bytes',)
3299 l[:] = [{"abcF" : Mapping({"\0" : 1})}]:TypeError:('expected string without null bytes',)
3300 <<< Finished
3301 >>> Testing *Iter* using l[:] = [{"abcF" : %s}]
3302 l[:] = [{"abcF" : FailingIter()}]:TypeError:('unable to convert FailingIter to a Vim structure',)
3303 l[:] = [{"abcF" : FailingIterNext()}]:NotImplementedError:('next',)
3304 <<< Finished
3305 >>> Testing ConvertFromPyObject using l[:] = [{"abcF" : %s}]
3306 l[:] = [{"abcF" : None}]:NOT FAILED
3307 l[:] = [{"abcF" : {"": 1}}]:ValueError:('empty keys are not allowed',)
3308 l[:] = [{"abcF" : {u"": 1}}]:ValueError:('empty keys are not allowed',)
3309 l[:] = [{"abcF" : FailingMapping()}]:NotImplementedError:('keys',)
3310 l[:] = [{"abcF" : FailingMappingKey()}]:NotImplementedError:('getitem:mappingkey',)
3311 l[:] = [{"abcF" : FailingNumber()}]:TypeError:('long() argument must be a string or a number',)
3312 <<< Finished
3313 >>> Testing StringToChars using l[:] = [Mapping({%s : 1})]
3314 l[:] = [Mapping({1 : 1})]:TypeError:('expected str() or unicode() instance, but got int',)
3315 l[:] = [Mapping({u"\0" : 1})]:TypeError:('expected string without null bytes',)
3316 l[:] = [Mapping({"\0" : 1})]:TypeError:('expected string without null bytes',)
3317 <<< Finished
3318 >>> Testing StringToChars using l[:] = [Mapping({"abcG" : {%s : 1}})]
3319 l[:] = [Mapping({"abcG" : {1 : 1}})]:TypeError:('expected str() or unicode() instance, but got int',)
3320 l[:] = [Mapping({"abcG" : {u"\0" : 1}})]:TypeError:('expected string without null bytes',)
3321 l[:] = [Mapping({"abcG" : {"\0" : 1}})]:TypeError:('expected string without null bytes',)
3322 <<< Finished
3323 >>> Testing StringToChars using l[:] = [Mapping({"abcG" : Mapping({%s : 1})})]
3324 l[:] = [Mapping({"abcG" : Mapping({1 : 1})})]:TypeError:('expected str() or unicode() instance, but got int',)
3325 l[:] = [Mapping({"abcG" : Mapping({u"\0" : 1})})]:TypeError:('expected string without null bytes',)
3326 l[:] = [Mapping({"abcG" : Mapping({"\0" : 1})})]:TypeError:('expected string without null bytes',)
3327 <<< Finished
3328 >>> Testing *Iter* using l[:] = [Mapping({"abcG" : %s})]
3329 l[:] = [Mapping({"abcG" : FailingIter()})]:TypeError:('unable to convert FailingIter to a Vim structure',)
3330 l[:] = [Mapping({"abcG" : FailingIterNext()})]:NotImplementedError:('next',)
3331 <<< Finished
3332 >>> Testing ConvertFromPyObject using l[:] = [Mapping({"abcG" : %s})]
3333 l[:] = [Mapping({"abcG" : None})]:NOT FAILED
3334 l[:] = [Mapping({"abcG" : {"": 1}})]:ValueError:('empty keys are not allowed',)
3335 l[:] = [Mapping({"abcG" : {u"": 1}})]:ValueError:('empty keys are not allowed',)
3336 l[:] = [Mapping({"abcG" : FailingMapping()})]:NotImplementedError:('keys',)
3337 l[:] = [Mapping({"abcG" : FailingMappingKey()})]:NotImplementedError:('getitem:mappingkey',)
3338 l[:] = [Mapping({"abcG" : FailingNumber()})]:TypeError:('long() argument must be a string or a number',)
3339 <<< Finished
3340 >>> Testing *Iter* using l[:] = [%s]
3341 l[:] = [FailingIter()]:TypeError:('unable to convert FailingIter to a Vim structure',)
3342 l[:] = [FailingIterNext()]:NotImplementedError:('next',)
3343 <<< Finished
3344 >>> Testing ConvertFromPyObject using l[:] = [%s]
3345 l[:] = [None]:NOT FAILED
3346 l[:] = [{"": 1}]:ValueError:('empty keys are not allowed',)
3347 l[:] = [{u"": 1}]:ValueError:('empty keys are not allowed',)
3348 l[:] = [FailingMapping()]:NotImplementedError:('keys',)
3349 l[:] = [FailingMappingKey()]:NotImplementedError:('getitem:mappingkey',)
3350 l[:] = [FailingNumber()]:TypeError:('long() argument must be a string or a number',)
3351 <<< Finished
3352 >> ListConcatInPlace
3353 >>> Testing *Iter* using l.extend(%s)
3354 l.extend(FailingIter()):NotImplementedError:('iter',)
3355 l.extend(FailingIterNext()):NotImplementedError:('next',)
3356 <<< Finished
3357 >>> Testing StringToChars using l.extend([{%s : 1}])
3358 l.extend([{1 : 1}]):TypeError:('expected str() or unicode() instance, but got int',)
3359 l.extend([{u"\0" : 1}]):TypeError:('expected string without null bytes',)
3360 l.extend([{"\0" : 1}]):TypeError:('expected string without null bytes',)
3361 <<< Finished
3362 >>> Testing StringToChars using l.extend([{"abcF" : {%s : 1}}])
3363 l.extend([{"abcF" : {1 : 1}}]):TypeError:('expected str() or unicode() instance, but got int',)
3364 l.extend([{"abcF" : {u"\0" : 1}}]):TypeError:('expected string without null bytes',)
3365 l.extend([{"abcF" : {"\0" : 1}}]):TypeError:('expected string without null bytes',)
3366 <<< Finished
3367 >>> Testing StringToChars using l.extend([{"abcF" : Mapping({%s : 1})}])
3368 l.extend([{"abcF" : Mapping({1 : 1})}]):TypeError:('expected str() or unicode() instance, but got int',)
3369 l.extend([{"abcF" : Mapping({u"\0" : 1})}]):TypeError:('expected string without null bytes',)
3370 l.extend([{"abcF" : Mapping({"\0" : 1})}]):TypeError:('expected string without null bytes',)
3371 <<< Finished
3372 >>> Testing *Iter* using l.extend([{"abcF" : %s}])
3373 l.extend([{"abcF" : FailingIter()}]):TypeError:('unable to convert FailingIter to a Vim structure',)
3374 l.extend([{"abcF" : FailingIterNext()}]):NotImplementedError:('next',)
3375 <<< Finished
3376 >>> Testing ConvertFromPyObject using l.extend([{"abcF" : %s}])
3377 l.extend([{"abcF" : None}]):NOT FAILED
3378 l.extend([{"abcF" : {"": 1}}]):ValueError:('empty keys are not allowed',)
3379 l.extend([{"abcF" : {u"": 1}}]):ValueError:('empty keys are not allowed',)
3380 l.extend([{"abcF" : FailingMapping()}]):NotImplementedError:('keys',)
3381 l.extend([{"abcF" : FailingMappingKey()}]):NotImplementedError:('getitem:mappingkey',)
3382 l.extend([{"abcF" : FailingNumber()}]):TypeError:('long() argument must be a string or a number',)
3383 <<< Finished
3384 >>> Testing StringToChars using l.extend([Mapping({%s : 1})])
3385 l.extend([Mapping({1 : 1})]):TypeError:('expected str() or unicode() instance, but got int',)
3386 l.extend([Mapping({u"\0" : 1})]):TypeError:('expected string without null bytes',)
3387 l.extend([Mapping({"\0" : 1})]):TypeError:('expected string without null bytes',)
3388 <<< Finished
3389 >>> Testing StringToChars using l.extend([Mapping({"abcG" : {%s : 1}})])
3390 l.extend([Mapping({"abcG" : {1 : 1}})]):TypeError:('expected str() or unicode() instance, but got int',)
3391 l.extend([Mapping({"abcG" : {u"\0" : 1}})]):TypeError:('expected string without null bytes',)
3392 l.extend([Mapping({"abcG" : {"\0" : 1}})]):TypeError:('expected string without null bytes',)
3393 <<< Finished
3394 >>> Testing StringToChars using l.extend([Mapping({"abcG" : Mapping({%s : 1})})])
3395 l.extend([Mapping({"abcG" : Mapping({1 : 1})})]):TypeError:('expected str() or unicode() instance, but got int',)
3396 l.extend([Mapping({"abcG" : Mapping({u"\0" : 1})})]):TypeError:('expected string without null bytes',)
3397 l.extend([Mapping({"abcG" : Mapping({"\0" : 1})})]):TypeError:('expected string without null bytes',)
3398 <<< Finished
3399 >>> Testing *Iter* using l.extend([Mapping({"abcG" : %s})])
3400 l.extend([Mapping({"abcG" : FailingIter()})]):TypeError:('unable to convert FailingIter to a Vim structure',)
3401 l.extend([Mapping({"abcG" : FailingIterNext()})]):NotImplementedError:('next',)
3402 <<< Finished
3403 >>> Testing ConvertFromPyObject using l.extend([Mapping({"abcG" : %s})])
3404 l.extend([Mapping({"abcG" : None})]):NOT FAILED
3405 l.extend([Mapping({"abcG" : {"": 1}})]):ValueError:('empty keys are not allowed',)
3406 l.extend([Mapping({"abcG" : {u"": 1}})]):ValueError:('empty keys are not allowed',)
3407 l.extend([Mapping({"abcG" : FailingMapping()})]):NotImplementedError:('keys',)
3408 l.extend([Mapping({"abcG" : FailingMappingKey()})]):NotImplementedError:('getitem:mappingkey',)
3409 l.extend([Mapping({"abcG" : FailingNumber()})]):TypeError:('long() argument must be a string or a number',)
3410 <<< Finished
3411 >>> Testing *Iter* using l.extend([%s])
3412 l.extend([FailingIter()]):TypeError:('unable to convert FailingIter to a Vim structure',)
3413 l.extend([FailingIterNext()]):NotImplementedError:('next',)
3414 <<< Finished
3415 >>> Testing ConvertFromPyObject using l.extend([%s])
3416 l.extend([None]):NOT FAILED
3417 l.extend([{"": 1}]):ValueError:('empty keys are not allowed',)
3418 l.extend([{u"": 1}]):ValueError:('empty keys are not allowed',)
3419 l.extend([FailingMapping()]):NotImplementedError:('keys',)
3420 l.extend([FailingMappingKey()]):NotImplementedError:('getitem:mappingkey',)
3421 l.extend([FailingNumber()]):TypeError:('long() argument must be a string or a number',)
3422 <<< Finished
3423 >> ListSetattr
3424 del l.locked:AttributeError:('cannot delete vim.List attributes',)
3425 l.locked = FailingTrue():NotImplementedError:('bool',)
3426 l.xxx = True:AttributeError:('cannot set attribute xxx',)
3427 > Function
3428 >> FunctionConstructor
3429 >>> FunctionConstructor
3430 vim.Function("123"):ValueError:('unnamed function 123 does not exist',)
3431 vim.Function("xxx_non_existent_function_xxx"):ValueError:('function xxx_non_existent_function_xxx does not exist',)
3432 vim.Function("xxx#non#existent#function#xxx"):NOT FAILED
3433 vim.Function("xxx_non_existent_function_xxx2", args=[]):ValueError:('function xxx_non_existent_function_xxx2 does not exist',)
3434 vim.Function("xxx_non_existent_function_xxx3", self={}):ValueError:('function xxx_non_existent_function_xxx3 does not exist',)
3435 vim.Function("xxx_non_existent_function_xxx4", args=[], self={}):ValueError:('function xxx_non_existent_function_xxx4 does not exist',)
3436 >>> FunctionNew
3437 vim.Function("tr", self="abcFuncSelf"):TypeError:('unable to convert str to a Vim dictionary',)
3438 vim.Function("tr", args=427423):TypeError:('unable to convert int to a Vim list',)
3439 vim.Function("tr", self="abcFuncSelf2", args="abcFuncArgs2"):TypeError:('unable to convert str to a Vim dictionary',)
3440 vim.Function(self="abcFuncSelf2", args="abcFuncArgs2"):TypeError:('unable to convert str to a Vim dictionary',)
3441 vim.Function("tr", "", self="abcFuncSelf2", args="abcFuncArgs2"):TypeError:('unable to convert str to a Vim dictionary',)
3442 vim.Function("tr", ""):TypeError:('function takes exactly 1 argument (2 given)',)
3443 >> FunctionCall
3444 >>> Testing StringToChars using f({%s : 1})
3445 f({1 : 1}):TypeError:('expected str() or unicode() instance, but got int',)
3446 f({u"\0" : 1}):TypeError:('expected string without null bytes',)
3447 f({"\0" : 1}):TypeError:('expected string without null bytes',)
3448 <<< Finished
3449 >>> Testing StringToChars using f({"abcF" : {%s : 1}})
3450 f({"abcF" : {1 : 1}}):TypeError:('expected str() or unicode() instance, but got int',)
3451 f({"abcF" : {u"\0" : 1}}):TypeError:('expected string without null bytes',)
3452 f({"abcF" : {"\0" : 1}}):TypeError:('expected string without null bytes',)
3453 <<< Finished
3454 >>> Testing StringToChars using f({"abcF" : Mapping({%s : 1})})
3455 f({"abcF" : Mapping({1 : 1})}):TypeError:('expected str() or unicode() instance, but got int',)
3456 f({"abcF" : Mapping({u"\0" : 1})}):TypeError:('expected string without null bytes',)
3457 f({"abcF" : Mapping({"\0" : 1})}):TypeError:('expected string without null bytes',)
3458 <<< Finished
3459 >>> Testing *Iter* using f({"abcF" : %s})
3460 f({"abcF" : FailingIter()}):TypeError:('unable to convert FailingIter to a Vim structure',)
3461 f({"abcF" : FailingIterNext()}):NotImplementedError:('next',)
3462 <<< Finished
3463 >>> Testing ConvertFromPyObject using f({"abcF" : %s})
3464 f({"abcF" : None}):NOT FAILED
3465 f({"abcF" : {"": 1}}):ValueError:('empty keys are not allowed',)
3466 f({"abcF" : {u"": 1}}):ValueError:('empty keys are not allowed',)
3467 f({"abcF" : FailingMapping()}):NotImplementedError:('keys',)
3468 f({"abcF" : FailingMappingKey()}):NotImplementedError:('getitem:mappingkey',)
3469 f({"abcF" : FailingNumber()}):TypeError:('long() argument must be a string or a number',)
3470 <<< Finished
3471 >>> Testing StringToChars using f(Mapping({%s : 1}))
3472 f(Mapping({1 : 1})):TypeError:('expected str() or unicode() instance, but got int',)
3473 f(Mapping({u"\0" : 1})):TypeError:('expected string without null bytes',)
3474 f(Mapping({"\0" : 1})):TypeError:('expected string without null bytes',)
3475 <<< Finished
3476 >>> Testing StringToChars using f(Mapping({"abcG" : {%s : 1}}))
3477 f(Mapping({"abcG" : {1 : 1}})):TypeError:('expected str() or unicode() instance, but got int',)
3478 f(Mapping({"abcG" : {u"\0" : 1}})):TypeError:('expected string without null bytes',)
3479 f(Mapping({"abcG" : {"\0" : 1}})):TypeError:('expected string without null bytes',)
3480 <<< Finished
3481 >>> Testing StringToChars using f(Mapping({"abcG" : Mapping({%s : 1})}))
3482 f(Mapping({"abcG" : Mapping({1 : 1})})):TypeError:('expected str() or unicode() instance, but got int',)
3483 f(Mapping({"abcG" : Mapping({u"\0" : 1})})):TypeError:('expected string without null bytes',)
3484 f(Mapping({"abcG" : Mapping({"\0" : 1})})):TypeError:('expected string without null bytes',)
3485 <<< Finished
3486 >>> Testing *Iter* using f(Mapping({"abcG" : %s}))
3487 f(Mapping({"abcG" : FailingIter()})):TypeError:('unable to convert FailingIter to a Vim structure',)
3488 f(Mapping({"abcG" : FailingIterNext()})):NotImplementedError:('next',)
3489 <<< Finished
3490 >>> Testing ConvertFromPyObject using f(Mapping({"abcG" : %s}))
3491 f(Mapping({"abcG" : None})):NOT FAILED
3492 f(Mapping({"abcG" : {"": 1}})):ValueError:('empty keys are not allowed',)
3493 f(Mapping({"abcG" : {u"": 1}})):ValueError:('empty keys are not allowed',)
3494 f(Mapping({"abcG" : FailingMapping()})):NotImplementedError:('keys',)
3495 f(Mapping({"abcG" : FailingMappingKey()})):NotImplementedError:('getitem:mappingkey',)
3496 f(Mapping({"abcG" : FailingNumber()})):TypeError:('long() argument must be a string or a number',)
3497 <<< Finished
3498 >>> Testing *Iter* using f(%s)
3499 f(FailingIter()):TypeError:('unable to convert FailingIter to a Vim structure',)
3500 f(FailingIterNext()):NotImplementedError:('next',)
3501 <<< Finished
3502 >>> Testing ConvertFromPyObject using f(%s)
3503 f(None):NOT FAILED
3504 f({"": 1}):ValueError:('empty keys are not allowed',)
3505 f({u"": 1}):ValueError:('empty keys are not allowed',)
3506 f(FailingMapping()):NotImplementedError:('keys',)
3507 f(FailingMappingKey()):NotImplementedError:('getitem:mappingkey',)
3508 f(FailingNumber()):TypeError:('long() argument must be a string or a number',)
3509 <<< Finished
3510 >>> Testing StringToChars using fd(self={%s : 1})
3511 fd(self={1 : 1}):TypeError:('expected str() or unicode() instance, but got int',)
3512 fd(self={u"\0" : 1}):TypeError:('expected string without null bytes',)
3513 fd(self={"\0" : 1}):TypeError:('expected string without null bytes',)
3514 <<< Finished
3515 >>> Testing StringToChars using fd(self={"abcF" : {%s : 1}})
3516 fd(self={"abcF" : {1 : 1}}):TypeError:('expected str() or unicode() instance, but got int',)
3517 fd(self={"abcF" : {u"\0" : 1}}):TypeError:('expected string without null bytes',)
3518 fd(self={"abcF" : {"\0" : 1}}):TypeError:('expected string without null bytes',)
3519 <<< Finished
3520 >>> Testing StringToChars using fd(self={"abcF" : Mapping({%s : 1})})
3521 fd(self={"abcF" : Mapping({1 : 1})}):TypeError:('expected str() or unicode() instance, but got int',)
3522 fd(self={"abcF" : Mapping({u"\0" : 1})}):TypeError:('expected string without null bytes',)
3523 fd(self={"abcF" : Mapping({"\0" : 1})}):TypeError:('expected string without null bytes',)
3524 <<< Finished
3525 >>> Testing *Iter* using fd(self={"abcF" : %s})
3526 fd(self={"abcF" : FailingIter()}):TypeError:('unable to convert FailingIter to a Vim structure',)
3527 fd(self={"abcF" : FailingIterNext()}):NotImplementedError:('next',)
3528 <<< Finished
3529 >>> Testing ConvertFromPyObject using fd(self={"abcF" : %s})
3530 fd(self={"abcF" : None}):NOT FAILED
3531 fd(self={"abcF" : {"": 1}}):ValueError:('empty keys are not allowed',)
3532 fd(self={"abcF" : {u"": 1}}):ValueError:('empty keys are not allowed',)
3533 fd(self={"abcF" : FailingMapping()}):NotImplementedError:('keys',)
3534 fd(self={"abcF" : FailingMappingKey()}):NotImplementedError:('getitem:mappingkey',)
3535 fd(self={"abcF" : FailingNumber()}):TypeError:('long() argument must be a string or a number',)
3536 <<< Finished
3537 >>> Testing StringToChars using fd(self=Mapping({%s : 1}))
3538 fd(self=Mapping({1 : 1})):TypeError:('expected str() or unicode() instance, but got int',)
3539 fd(self=Mapping({u"\0" : 1})):TypeError:('expected string without null bytes',)
3540 fd(self=Mapping({"\0" : 1})):TypeError:('expected string without null bytes',)
3541 <<< Finished
3542 >>> Testing StringToChars using fd(self=Mapping({"abcG" : {%s : 1}}))
3543 fd(self=Mapping({"abcG" : {1 : 1}})):TypeError:('expected str() or unicode() instance, but got int',)
3544 fd(self=Mapping({"abcG" : {u"\0" : 1}})):TypeError:('expected string without null bytes',)
3545 fd(self=Mapping({"abcG" : {"\0" : 1}})):TypeError:('expected string without null bytes',)
3546 <<< Finished
3547 >>> Testing StringToChars using fd(self=Mapping({"abcG" : Mapping({%s : 1})}))
3548 fd(self=Mapping({"abcG" : Mapping({1 : 1})})):TypeError:('expected str() or unicode() instance, but got int',)
3549 fd(self=Mapping({"abcG" : Mapping({u"\0" : 1})})):TypeError:('expected string without null bytes',)
3550 fd(self=Mapping({"abcG" : Mapping({"\0" : 1})})):TypeError:('expected string without null bytes',)
3551 <<< Finished
3552 >>> Testing *Iter* using fd(self=Mapping({"abcG" : %s}))
3553 fd(self=Mapping({"abcG" : FailingIter()})):TypeError:('unable to convert FailingIter to a Vim structure',)
3554 fd(self=Mapping({"abcG" : FailingIterNext()})):NotImplementedError:('next',)
3555 <<< Finished
3556 >>> Testing ConvertFromPyObject using fd(self=Mapping({"abcG" : %s}))
3557 fd(self=Mapping({"abcG" : None})):NOT FAILED
3558 fd(self=Mapping({"abcG" : {"": 1}})):ValueError:('empty keys are not allowed',)
3559 fd(self=Mapping({"abcG" : {u"": 1}})):ValueError:('empty keys are not allowed',)
3560 fd(self=Mapping({"abcG" : FailingMapping()})):NotImplementedError:('keys',)
3561 fd(self=Mapping({"abcG" : FailingMappingKey()})):NotImplementedError:('getitem:mappingkey',)
3562 fd(self=Mapping({"abcG" : FailingNumber()})):TypeError:('long() argument must be a string or a number',)
3563 <<< Finished
3564 >>> Testing *Iter* using fd(self=%s)
3565 fd(self=FailingIter()):TypeError:('unable to convert FailingIter to a Vim dictionary',)
3566 fd(self=FailingIterNext()):TypeError:('unable to convert FailingIterNext to a Vim dictionary',)
3567 <<< Finished
3568 >>> Testing ConvertFromPyObject using fd(self=%s)
3569 fd(self=None):TypeError:('unable to convert NoneType to a Vim dictionary',)
3570 fd(self={"": 1}):ValueError:('empty keys are not allowed',)
3571 fd(self={u"": 1}):ValueError:('empty keys are not allowed',)
3572 fd(self=FailingMapping()):NotImplementedError:('keys',)
3573 fd(self=FailingMappingKey()):NotImplementedError:('getitem:mappingkey',)
3574 fd(self=FailingNumber()):TypeError:('unable to convert FailingNumber to a Vim dictionary',)
3575 <<< Finished
3576 >>> Testing ConvertFromPyMapping using fd(self=%s)
3577 fd(self=[]):TypeError:('unable to convert list to a Vim dictionary',)
3578 <<< Finished
3579 > TabPage
3580 >> TabPageAttr
3581 vim.current.tabpage.xxx:AttributeError:('xxx',)
3582 > TabList
3583 >> TabListItem
3584 vim.tabpages[1000]:IndexError:('no such tab page',)
3585 > Window
3586 >> WindowAttr
3587 vim.current.window.xxx:AttributeError:('xxx',)
3588 >> WindowSetattr
3589 vim.current.window.buffer = 0:TypeError:('readonly attribute: buffer',)
3590 vim.current.window.cursor = (100000000, 100000000):error:('cursor position outside buffer',)
3591 vim.current.window.cursor = True:TypeError:('argument must be 2-item sequence, not bool',)
3592 >>> Testing NumberToLong using vim.current.window.height = %s
3593 vim.current.window.height = []:TypeError:('expected int(), long() or something supporting coercing to long(), but got list',)
3594 vim.current.window.height = None:TypeError:('expected int(), long() or something supporting coercing to long(), but got NoneType',)
3595 vim.current.window.height = -1:ValueError:('number must be greater or equal to zero',)
3596 <<< Finished
3597 >>> Testing NumberToLong using vim.current.window.width = %s
3598 vim.current.window.width = []:TypeError:('expected int(), long() or something supporting coercing to long(), but got list',)
3599 vim.current.window.width = None:TypeError:('expected int(), long() or something supporting coercing to long(), but got NoneType',)
3600 vim.current.window.width = -1:ValueError:('number must be greater or equal to zero',)
3601 <<< Finished
3602 vim.current.window.xxxxxx = True:AttributeError:('xxxxxx',)
3603 > WinList
3604 >> WinListItem
3605 vim.windows[1000]:IndexError:('no such window',)
3606 > Buffer
3607 >> StringToLine (indirect)
Bram Moolenaar92fdd1e2020-07-03 18:00:05 +02003608 vim.current.buffer[0] = "\na":error:('string cannot contain newlines',)
Bram Moolenaarab589462020-07-06 21:03:06 +02003609 vim.current.buffer[0] = u"\na":error:('string cannot contain newlines',)
Bram Moolenaar92fdd1e2020-07-03 18:00:05 +02003610 >> SetBufferLine (indirect)
3611 vim.current.buffer[0] = True:TypeError:('bad argument type for built-in operation',)
3612 >> SetBufferLineList (indirect)
3613 vim.current.buffer[:] = True:TypeError:('bad argument type for built-in operation',)
3614 vim.current.buffer[:] = ["\na", "bc"]:error:('string cannot contain newlines',)
3615 >> InsertBufferLines (indirect)
3616 vim.current.buffer.append(None):TypeError:('bad argument type for built-in operation',)
3617 vim.current.buffer.append(["\na", "bc"]):error:('string cannot contain newlines',)
3618 vim.current.buffer.append("\nbc"):error:('string cannot contain newlines',)
3619 >> RBItem
3620 vim.current.buffer[100000000]:IndexError:('line number out of range',)
3621 >> RBAsItem
3622 vim.current.buffer[100000000] = "":IndexError:('line number out of range',)
3623 >> BufferAttr
3624 vim.current.buffer.xxx:AttributeError:('xxx',)
3625 >> BufferSetattr
3626 vim.current.buffer.name = True:TypeError:('expected str() or unicode() instance, but got bool',)
3627 vim.current.buffer.xxx = True:AttributeError:('xxx',)
3628 >> BufferMark
3629 vim.current.buffer.mark(0):TypeError:('expected str() or unicode() instance, but got int',)
3630 vim.current.buffer.mark("abcM"):ValueError:('mark name must be a single character',)
3631 vim.current.buffer.mark("!"):error:('invalid mark name',)
3632 >> BufferRange
3633 vim.current.buffer.range(1, 2, 3):TypeError:('function takes exactly 2 arguments (3 given)',)
3634 > BufMap
3635 >> BufMapItem
3636 vim.buffers[100000000]:KeyError:(100000000,)
3637 >>> Testing NumberToLong using vim.buffers[%s]
3638 vim.buffers[[]]:TypeError:('expected int(), long() or something supporting coercing to long(), but got list',)
3639 vim.buffers[None]:TypeError:('expected int(), long() or something supporting coercing to long(), but got NoneType',)
3640 vim.buffers[-1]:ValueError:('number must be greater than zero',)
3641 vim.buffers[0]:ValueError:('number must be greater than zero',)
3642 <<< Finished
3643 > Current
3644 >> CurrentGetattr
3645 vim.current.xxx:AttributeError:('xxx',)
3646 >> CurrentSetattr
3647 vim.current.line = True:TypeError:('bad argument type for built-in operation',)
3648 vim.current.buffer = True:TypeError:('expected vim.Buffer object, but got bool',)
3649 vim.current.window = True:TypeError:('expected vim.Window object, but got bool',)
3650 vim.current.tabpage = True:TypeError:('expected vim.TabPage object, but got bool',)
3651 vim.current.xxx = True:AttributeError:('xxx',)
3652 END
3653
3654 call assert_equal(expected, getline(2, '$'))
3655 close!
3656endfunc
3657
3658" Test import
3659func Test_python_import()
3660 new
3661 py cb = vim.current.buffer
3662
3663 py << trim EOF
3664 sys.path.insert(0, os.path.join(os.getcwd(), 'python_before'))
3665 sys.path.append(os.path.join(os.getcwd(), 'python_after'))
3666 vim.options['rtp'] = os.getcwd().replace(',', '\\,').replace('\\', '\\\\')
3667 l = []
3668 def callback(path):
3669 l.append(path[-len('/testdir'):].replace(os.path.sep, '/'))
3670 vim.foreach_rtp(callback)
3671 cb.append(repr(l))
3672 del l
3673 def callback(path):
3674 return path[-len('/testdir'):].replace(os.path.sep, '/')
3675 cb.append(repr(vim.foreach_rtp(callback)))
3676 del callback
3677 from module import dir as d
3678 from modulex import ddir
3679 cb.append(d + ',' + ddir)
3680 import before
3681 cb.append(before.dir)
3682 import after
3683 cb.append(after.dir)
3684 import topmodule as tm
3685 import topmodule.submodule as tms
3686 import topmodule.submodule.subsubmodule.subsubsubmodule as tmsss
3687 cb.append(tm.__file__.replace('.pyc', '.py').replace(os.path.sep, '/')[-len('modulex/topmodule/__init__.py'):])
3688 cb.append(tms.__file__.replace('.pyc', '.py').replace(os.path.sep, '/')[-len('modulex/topmodule/submodule/__init__.py'):])
3689 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 +02003690
Bram Moolenaar92fdd1e2020-07-03 18:00:05 +02003691 del before
3692 del after
3693 del d
3694 del ddir
3695 del tm
3696 del tms
3697 del tmsss
3698 EOF
3699
3700 let expected =<< trim END
3701 ['/testdir']
3702 '/testdir'
3703 2,xx
3704 before
3705 after
3706 pythonx/topmodule/__init__.py
3707 pythonx/topmodule/submodule/__init__.py
3708 pythonx/topmodule/submodule/subsubmodule/subsubsubmodule.py
3709 END
3710 call assert_equal(expected, getline(2, '$'))
3711 close!
Bram Moolenaarab589462020-07-06 21:03:06 +02003712
Bram Moolenaar8e7d6222020-12-18 19:49:56 +01003713 " Try to import a non-existing module with a dot (.)
Bram Moolenaarab589462020-07-06 21:03:06 +02003714 call AssertException(['py import a.b.c'], 'ImportError:')
Bram Moolenaar92fdd1e2020-07-03 18:00:05 +02003715endfunc
3716
3717" Test exceptions
3718func Test_python_exception()
Bram Moolenaarab589462020-07-06 21:03:06 +02003719 func Exe(e)
Bram Moolenaar92fdd1e2020-07-03 18:00:05 +02003720 execute a:e
Bram Moolenaarab589462020-07-06 21:03:06 +02003721 endfunc
Bram Moolenaar92fdd1e2020-07-03 18:00:05 +02003722
3723 new
3724 py cb = vim.current.buffer
3725
3726 py << trim EOF
3727 Exe = vim.bindeval('function("Exe")')
3728 ee('vim.command("throw \'abcN\'")')
3729 ee('Exe("throw \'def\'")')
3730 ee('vim.eval("Exe(\'throw \'\'ghi\'\'\')")')
3731 ee('vim.eval("Exe(\'echoerr \'\'jkl\'\'\')")')
3732 ee('vim.eval("Exe(\'xxx_non_existent_command_xxx\')")')
3733 ee('vim.eval("xxx_unknown_function_xxx()")')
3734 ee('vim.bindeval("Exe(\'xxx_non_existent_command_xxx\')")')
3735 del Exe
3736 EOF
3737 delfunction Exe
3738
3739 let expected =<< trim END
3740 vim.command("throw 'abcN'"):error:('abcN',)
3741 Exe("throw 'def'"):error:('def',)
3742 vim.eval("Exe('throw ''ghi''')"):error:('ghi',)
3743 vim.eval("Exe('echoerr ''jkl''')"):error:('Vim(echoerr):jkl',)
3744 vim.eval("Exe('xxx_non_existent_command_xxx')"):error:('Vim:E492: Not an editor command: xxx_non_existent_command_xxx',)
3745 vim.eval("xxx_unknown_function_xxx()"):error:('Vim:E117: Unknown function: xxx_unknown_function_xxx',)
3746 vim.bindeval("Exe('xxx_non_existent_command_xxx')"):error:('Vim:E492: Not an editor command: xxx_non_existent_command_xxx',)
3747 END
3748 call assert_equal(expected, getline(2, '$'))
3749 close!
3750endfunc
3751
3752" Regression: interrupting vim.command propagates to next vim.command
3753func Test_python_keyboard_interrupt()
3754 new
3755 py cb = vim.current.buffer
3756 py << trim EOF
3757 def test_keyboard_interrupt():
3758 try:
3759 vim.command('while 1 | endwhile')
3760 except KeyboardInterrupt:
3761 cb.append('Caught KeyboardInterrupt')
3762 except Exception:
3763 cb.append('!!!!!!!! Caught exception: ' + emsg(sys.exc_info()))
3764 else:
3765 cb.append('!!!!!!!! No exception')
3766 try:
3767 vim.command('$ put =\'Running :put\'')
3768 except KeyboardInterrupt:
3769 cb.append('!!!!!!!! Caught KeyboardInterrupt')
3770 except Exception:
3771 cb.append('!!!!!!!! Caught exception: ' + emsg(sys.exc_info()))
3772 else:
3773 cb.append('No exception')
3774 EOF
3775
3776 debuggreedy
3777 call inputsave()
3778 call feedkeys("s\ns\ns\ns\nq\n")
3779 redir => output
3780 debug silent! py test_keyboard_interrupt()
3781 redir END
3782 0 debuggreedy
3783 call inputrestore()
3784 py del test_keyboard_interrupt
3785
3786 let expected =<< trim END
3787 Caught KeyboardInterrupt
3788 Running :put
3789 No exception
3790 END
3791 call assert_equal(expected, getline(2, '$'))
3792 call assert_equal('', output)
3793 close!
3794endfunc
3795
Bram Moolenaar2e2f52a2020-12-21 16:03:02 +01003796func Test_python_non_utf8_string()
3797 smap <Esc>@ <A-@>
3798 python vim.command('redir => _tmp_smaps | smap | redir END')
3799 python vim.eval('_tmp_smaps').splitlines()
3800 sunmap <Esc>@
3801endfunc
3802
Bram Moolenaar6c2b7b82020-04-14 20:15:49 +02003803" vim: shiftwidth=2 sts=2 expandtab