comparison src/testdir/test_python2.vim @ 21190:10eb6c38938c v8.2.1146

patch 8.2.1146: not enough testing for Python Commit: https://github.com/vim/vim/commit/ab5894638413748fcedfe28691e6c27893924520 Author: Bram Moolenaar <Bram@vim.org> Date: Mon Jul 6 21:03:06 2020 +0200 patch 8.2.1146: not enough testing for Python Problem: Not enough testing for Python. Solution: Add more tests. Fix uncovered problems. (Yegappan Lakshmanan, closes #6392)
author Bram Moolenaar <Bram@vim.org>
date Mon, 06 Jul 2020 21:15:05 +0200
parents adae19565eea
children 8531ddd7dd63
comparison
equal deleted inserted replaced
21189:86a6df062aea 21190:10eb6c38938c
1 " Test for python 2 commands. 1 " Test for python 2 commands.
2 2
3 source check.vim 3 source check.vim
4 CheckFeature python 4 CheckFeature python
5 CheckFeature quickfix 5 CheckFeature quickfix
6 source shared.vim
6 7
7 " NOTE: This will cause errors when run under valgrind. 8 " NOTE: This will cause errors when run under valgrind.
8 " This would require recompiling Python with: 9 " This would require recompiling Python with:
9 " ./configure --without-pymalloc 10 " ./configure --without-pymalloc
10 " See http://svn.python.org/view/python/trunk/Misc/README.valgrind?view=markup 11 " See http://svn.python.org/view/python/trunk/Misc/README.valgrind?view=markup
53 vim.current.buffer.append(expr + ':NOT FAILED') 54 vim.current.buffer.append(expr + ':NOT FAILED')
54 EOF 55 EOF
55 endfunc 56 endfunc
56 57
57 func Test_pydo() 58 func Test_pydo()
58 " Check deleting lines does not trigger ml_get error. 59 " Check deleting lines does not trigger an ml_get error.
59 new 60 new
60 call setline(1, ['one', 'two', 'three']) 61 call setline(1, ['one', 'two', 'three'])
61 pydo vim.command("%d_") 62 pydo vim.command("%d_")
62 bwipe! 63 bwipe!
63 64
64 " Check switching to another buffer does not trigger ml_get error. 65 " Check switching to another buffer does not trigger an ml_get error.
65 new 66 new
66 let wincount = winnr('$') 67 let wincount = winnr('$')
67 call setline(1, ['one', 'two', 'three']) 68 call setline(1, ['one', 'two', 'three'])
68 pydo vim.command("new") 69 pydo vim.command("new")
69 call assert_equal(wincount + 1, winnr('$')) 70 call assert_equal(wincount + 1, winnr('$'))
70 bwipe! 71 bwipe!
71 bwipe! 72 bwipe!
73
74 " Try modifying a buffer with 'nomodifiable' set
75 set nomodifiable
76 call assert_fails('pydo toupper(line)', 'cannot save undo information')
77 set modifiable
78
79 " Invalid command
80 call AssertException(['pydo non_existing_cmd'],
81 \ "Vim(pydo):NameError: global name 'non_existing_cmd' is not defined")
82 call AssertException(["pydo raise Exception('test')"],
83 \ 'Vim(pydo):Exception: test')
84 call AssertException(["pydo {lambda}"],
85 \ 'Vim(pydo):SyntaxError: invalid syntax')
72 endfunc 86 endfunc
73 87
74 func Test_set_cursor() 88 func Test_set_cursor()
75 " Check that setting the cursor position works. 89 " Check that setting the cursor position works.
76 new 90 new
104 call assert_equal(name, 'f.name'->pyeval()) 118 call assert_equal(name, 'f.name'->pyeval())
105 catch 119 catch
106 call assert_false(v:exception) 120 call assert_false(v:exception)
107 endtry 121 endtry
108 122
109 let caught_vim_err = v:false 123 " Non-existing function attribute
110 try 124 call AssertException(["let x = pyeval('f.abc')"],
111 let x = pyeval('f.abc') 125 \ 'Vim(let):AttributeError: abc')
112 catch
113 call assert_match('AttributeError: abc', v:exception)
114 let caught_vim_err = v:true
115 endtry
116 call assert_equal(v:true, caught_vim_err)
117 126
118 py del f 127 py del f
119 delfunc s:foo 128 delfunc s:foo
120 endfunc 129 endfunc
121 130
248 call setline(1, ['one', 'two', 'three']) 257 call setline(1, ['one', 'two', 'three'])
249 py b = vim.current.buffer 258 py b = vim.current.buffer
250 py r = b.range(1, 3) 259 py r = b.range(1, 3)
251 call assert_equal(0, pyeval('r.start')) 260 call assert_equal(0, pyeval('r.start'))
252 call assert_equal(2, pyeval('r.end')) 261 call assert_equal(2, pyeval('r.end'))
262 call assert_equal('one', pyeval('r[0]'))
263 call assert_equal('one', pyeval('r[-3]'))
264 call assert_equal('three', pyeval('r[-4]'))
253 call assert_equal(['two', 'three'], pyeval('r[1:]')) 265 call assert_equal(['two', 'three'], pyeval('r[1:]'))
254 py r[0] = 'green' 266 py r[0] = 'green'
255 call assert_equal(['green', 'two', 'three'], getline(1, '$')) 267 call assert_equal(['green', 'two', 'three'], getline(1, '$'))
256 py r[0:2] = ['red', 'blue'] 268 py r[0:2] = ['red', 'blue']
257 call assert_equal(['red', 'blue', 'three'], getline(1, '$')) 269 call assert_equal(['red', 'blue', 'three'], getline(1, '$'))
258 call assert_equal(['start', 'end', '__members__'], pyeval('r.__members__')) 270 call assert_equal(['start', 'end', '__members__'], pyeval('r.__members__'))
259 271
260 let caught_vim_err = v:false 272 " try different invalid start/end index for the range slice
261 try 273 %d
262 let x = pyeval('r.abc') 274 call setline(1, ['one', 'two', 'three'])
263 catch 275 py r[-10:1] = ["a"]
264 call assert_match('AttributeError: abc', v:exception) 276 py r[10:12] = ["b"]
265 let caught_vim_err = v:true 277 py r[-10:-9] = ["c"]
266 endtry 278 py r[1:0] = ["d"]
267 call assert_equal(v:true, caught_vim_err) 279 call assert_equal(['c', 'd', 'a', 'two', 'three', 'b'], getline(1, '$'))
280
281 " FIXME: The following code triggers ml_get errors
282 " %d
283 " let x = pyeval('r[:]')
284
285 " Non-existing range attribute
286 call AssertException(["let x = pyeval('r.abc')"],
287 \ 'Vim(let):AttributeError: abc')
268 288
269 close! 289 close!
270 endfunc 290 endfunc
271 291
272 " Test for the python tabpage object 292 " Test for the python tabpage object
273 func Test_python_tabpage() 293 func Test_python_tabpage()
274 tabnew 294 tabnew
275 py t = vim.tabpages[1] 295 py t = vim.tabpages[1]
296 py wl = t.windows
276 tabclose 297 tabclose
277 let caught_vim_err = v:false 298 " Accessing a closed tabpage
278 try 299 call AssertException(["let n = pyeval('t.number')"],
279 let n = pyeval('t.number') 300 \ 'Vim(let):vim.error: attempt to refer to deleted tab page')
280 catch 301 call AssertException(["let n = pyeval('len(wl)')"],
281 call assert_match('vim.error: attempt to refer to deleted tab page', 302 \ 'Vim(let):vim.error: attempt to refer to deleted tab page')
282 \ v:exception) 303 call AssertException(["py w = wl[0]"],
283 let caught_vim_err = v:true 304 \ 'Vim(python):vim.error: attempt to refer to deleted tab page')
284 endtry 305 call AssertException(["py vim.current.tabpage = t"],
285 call assert_equal(v:true, caught_vim_err) 306 \ 'Vim(python):vim.error: attempt to refer to deleted tab page')
307 call assert_match('<tabpage object (deleted)', pyeval('repr(t)'))
286 %bw! 308 %bw!
287 endfunc 309 endfunc
288 310
289 " Test for the python window object 311 " Test for the python window object
290 func Test_python_window() 312 func Test_python_window()
291 new 313 " Test for setting the window height
314 10new
315 py vim.current.window.height = 5
316 call assert_equal(5, winheight(0))
317
318 " Test for setting the window width
319 10vnew
320 py vim.current.window.width = 6
321 call assert_equal(6, winwidth(0))
322
323 " Try accessing a closed window
292 py w = vim.current.window 324 py w = vim.current.window
325 py wopts = w.options
293 close 326 close
294 let caught_vim_err = v:false 327 " Access the attributes of a closed window
295 try 328 call AssertException(["let n = pyeval('w.number')"],
296 let n = pyeval('w.number') 329 \ 'Vim(let):vim.error: attempt to refer to deleted window')
297 catch 330 call AssertException(["py w.height = 5"],
298 call assert_match('vim.error: attempt to refer to deleted window', 331 \ 'Vim(python):vim.error: attempt to refer to deleted window')
299 \ v:exception) 332 call AssertException(["py vim.current.window = w"],
300 let caught_vim_err = v:true 333 \ 'Vim(python):vim.error: attempt to refer to deleted window')
301 endtry 334 " Try to set one of the options of the closed window
302 call assert_equal(v:true, caught_vim_err) 335 " FIXME: The following causes ASAN failure
336 "call AssertException(["py wopts['list'] = False"],
337 " \ 'vim.error: problem while switching windows')
338 call assert_match('<window object (deleted)', pyeval("repr(w)"))
339 %bw!
303 endfunc 340 endfunc
304 341
305 " Test for the python List object 342 " Test for the python List object
306 func Test_python_list() 343 func Test_python_list()
307 let l = [1, 2] 344 let l = [1, 2]
308 py pl = vim.bindeval('l') 345 py pl = vim.bindeval('l')
309 call assert_equal(['locked', '__members__'], pyeval('pl.__members__')) 346 call assert_equal(['locked', '__members__'], pyeval('pl.__members__'))
347
348 " Try to convert a null List
349 call AssertException(["py t = vim.eval('test_null_list()')"],
350 \ 'Vim(python):SystemError: error return without exception set')
351
352 " Try to convert a List with a null List item
353 call AssertException(["py t = vim.eval('[test_null_list()]')"],
354 \ 'Vim(python):SystemError: error return without exception set')
355
356 " Try to bind a null List variable
357 let cmds =<< trim END
358 let l = test_null_list()
359 py ll = vim.bindeval('l')
360 END
361 call AssertException(cmds, 'Vim(python):SystemError: error return without exception set')
310 362
311 let l = [] 363 let l = []
312 py l = vim.bindeval('l') 364 py l = vim.bindeval('l')
313 py f = vim.bindeval('function("strlen")') 365 py f = vim.bindeval('function("strlen")')
314 " Extending List directly with different types 366 " Extending List directly with different types
320 " List assignment 372 " List assignment
321 py l[0] = 0 373 py l[0] = 0
322 call assert_equal([0, "as'd", [1, 2, function("strlen"), {'a': 1}]], l) 374 call assert_equal([0, "as'd", [1, 2, function("strlen"), {'a': 1}]], l)
323 py l[-2] = f 375 py l[-2] = f
324 call assert_equal([0, function("strlen"), [1, 2, function("strlen"), {'a': 1}]], l) 376 call assert_equal([0, function("strlen"), [1, 2, function("strlen"), {'a': 1}]], l)
377
378 " appending to a list
379 let l = [1, 2]
380 py ll = vim.bindeval('l')
381 py ll[2] = 8
382 call assert_equal([1, 2, 8], l)
383
384 " Using dict as an index
385 call AssertException(['py ll[{}] = 10'],
386 \ 'Vim(python):TypeError: index must be int or slice, not dict')
325 endfunc 387 endfunc
326 388
327 " Test for the python Dict object 389 " Test for the python Dict object
328 func Test_python_dict() 390 func Test_python_dict()
329 let d = {} 391 let d = {}
330 py pd = vim.bindeval('d') 392 py pd = vim.bindeval('d')
331 call assert_equal(['locked', 'scope', '__members__'], 393 call assert_equal(['locked', 'scope', '__members__'],
332 \ pyeval('pd.__members__')) 394 \ pyeval('pd.__members__'))
395
396 " Try to convert a null Dict
397 call AssertException(["py t = vim.eval('test_null_dict()')"],
398 \ 'Vim(python):SystemError: error return without exception set')
399
400 " Try to convert a Dict with a null List value
401 call AssertException(["py t = vim.eval(\"{'a' : test_null_list()}\")"],
402 \ 'Vim(python):SystemError: error return without exception set')
403
404 " Try to convert a Dict with a null string key
405 py t = vim.eval("{test_null_string() : 10}")
406 call assert_fails("let d = pyeval('t')", 'E859:')
407
408 " Dict length
409 let d = {'a' : 10, 'b' : 20}
410 py d = vim.bindeval('d')
411 call assert_equal(2, pyeval('len(d)'))
412
413 " Deleting an non-existing key
414 call AssertException(["py del d['c']"], "Vim(python):KeyError: 'c'")
333 endfunc 415 endfunc
334 416
335 " Extending Dictionary directly with different types 417 " Extending Dictionary directly with different types
336 func Test_python_dict_extend() 418 func Test_python_dict_extend()
337 let d = {} 419 let d = {}
353 cmpfun = lambda a, b: cmp(repr(a), repr(b)) 435 cmpfun = lambda a, b: cmp(repr(a), repr(b))
354 dk.sort(cmpfun) 436 dk.sort(cmpfun)
355 dv.sort(cmpfun) 437 dv.sort(cmpfun)
356 di.sort(cmpfun) 438 di.sort(cmpfun)
357 EOF 439 EOF
440
441 " Try extending a locked dictionary
442 lockvar d
443 call AssertException(["py d.update({'b' : 20})"],
444 \ 'Vim(python):vim.error: dictionary is locked')
445 unlockvar d
358 446
359 call assert_equal(1, pyeval("d['f'](self={})")) 447 call assert_equal(1, pyeval("d['f'](self={})"))
360 call assert_equal("['-1', '0', '1', 'b', 'f']", pyeval('repr(dk)')) 448 call assert_equal("['-1', '0', '1', 'b', 'f']", pyeval('repr(dk)'))
361 call assert_equal("['asd', -1L, <vim.Function '1'>, <vim.dictionary object at >, <vim.list object at >]", substitute(pyeval('repr(dv)'),'0x\x\+','','g')) 449 call assert_equal("['asd', -1L, <vim.Function '1'>, <vim.dictionary object at >, <vim.list object at >]", substitute(pyeval('repr(dv)'),'0x\x\+','','g'))
362 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')) 450 call assert_equal("[('-1', <vim.dictionary object at >), ('0', -1L), ('1', 'asd'), ('b', <vim.list object at >), ('f', <vim.Function '1'>)]", substitute(pyeval('repr(di)'),'0x\x\+','','g'))
550 except vim.error: 638 except vim.error:
551 cb.append('l[2] threw vim.error: ' + emsg(sys.exc_info())) 639 cb.append('l[2] threw vim.error: ' + emsg(sys.exc_info()))
552 EOF 640 EOF
553 call assert_equal(['', "l[2] threw vim.error: error:('list is locked',)"], 641 call assert_equal(['', "l[2] threw vim.error: error:('list is locked',)"],
554 \ getline(1, '$')) 642 \ getline(1, '$'))
643
644 " Try to concatenate a locked list
645 call AssertException(['py l += [4, 5]'],
646 \ 'Vim(python):vim.error: list is locked')
647
555 call assert_equal([0, 1, 2, 3], l) 648 call assert_equal([0, 1, 2, 3], l)
556 unlockvar! l 649 unlockvar! l
557 close! 650 close!
558 endfunc 651 endfunc
559 652
663 silent! call extend(l, [1]) 756 silent! call extend(l, [1])
664 silent! call extend(ll, [1]) 757 silent! call extend(ll, [1])
665 call assert_equal([0], l) 758 call assert_equal([0], l)
666 call assert_equal([1], ll) 759 call assert_equal([1], ll)
667 unlet l ll 760 unlet l ll
761
762 " Try changing an attribute of a fixed list
763 py a = vim.bindeval('v:argv')
764 call AssertException(['py a.locked = 0'],
765 \ 'Vim(python):TypeError: cannot modify fixed list')
668 endfunc 766 endfunc
669 767
670 " Test for pyeval() 768 " Test for pyeval()
671 func Test_python_pyeval() 769 func Test_python_pyeval()
672 let l = pyeval('range(3)') 770 let l = pyeval('range(3)')
677 775
678 let v:errmsg = '' 776 let v:errmsg = ''
679 call assert_equal(v:none, pyeval('None')) 777 call assert_equal(v:none, pyeval('None'))
680 call assert_equal('', v:errmsg) 778 call assert_equal('', v:errmsg)
681 779
780 py v = vim.eval('test_null_function()')
781 call assert_equal(v:none, pyeval('v'))
782
682 if has('float') 783 if has('float')
683 call assert_equal(0.0, pyeval('0.0')) 784 call assert_equal(0.0, pyeval('0.0'))
684 endif 785 endif
685 786
686 " Invalid values: 787 " Evaluate an invalid values
687 let caught_859 = 0 788 call AssertException(['let v = pyeval(''"\0"'')'], 'E859:')
688 try 789 call AssertException(['let v = pyeval(''{"\0" : 1}'')'], 'E859:')
689 let v = pyeval('"\0"') 790 call AssertException(['let v = pyeval("undefined_name")'],
690 catch /E859:/ 791 \ "Vim(let):NameError: name 'undefined_name' is not defined")
691 let caught_859 = 1 792 call AssertException(['let v = pyeval("vim")'], 'E859:')
692 endtry 793 endfunc
693 call assert_equal(1, caught_859) 794
694 795 " Test for vim.bindeval()
695 let caught_859 = 0 796 func Test_python_vim_bindeval()
696 try 797 " Float
697 let v = pyeval('{"\0" : 1}') 798 let f = 3.14
698 catch /E859:/ 799 py f = vim.bindeval('f')
699 let caught_859 = 1 800 call assert_equal(3.14, pyeval('f'))
700 endtry 801
701 call assert_equal(1, caught_859) 802 " Blob
702 803 let b = 0z12
703 let caught_nameerr = 0 804 py b = vim.bindeval('b')
704 try 805 call assert_equal("\x12", pyeval('b'))
705 let v = pyeval("undefined_name") 806
706 catch /NameError: name 'undefined_name'/ 807 " Bool
707 let caught_nameerr = 1 808 call assert_equal(1, pyeval("vim.bindeval('v:true')"))
708 endtry 809 call assert_equal(0, pyeval("vim.bindeval('v:false')"))
709 call assert_equal(1, caught_nameerr) 810 call assert_equal(v:none, pyeval("vim.bindeval('v:null')"))
710 811 call assert_equal(v:none, pyeval("vim.bindeval('v:none')"))
711 let caught_859 = 0
712 try
713 let v = pyeval("vim")
714 catch /E859:/
715 let caught_859 = 1
716 endtry
717 call assert_equal(1, caught_859)
718 endfunc 812 endfunc
719 813
720 " threading 814 " threading
721 " Running pydo command (Test_pydo) before this test, stops the python thread 815 " Running pydo command (Test_pydo) before this test, stops the python thread
722 " from running. So this test should be run before the pydo test 816 " from running. So this test should be run before the pydo test
810 call assert_equal([4, 3], pyeval('l')) 904 call assert_equal([4, 3], pyeval('l'))
811 py l = ll[::2] 905 py l = ll[::2]
812 call assert_equal([0, 2, 4], pyeval('l')) 906 call assert_equal([0, 2, 4], pyeval('l'))
813 py l = ll[4:2:1] 907 py l = ll[4:2:1]
814 call assert_equal([], pyeval('l')) 908 call assert_equal([], pyeval('l'))
909
910 " Error case: Use an invalid index
911 call AssertException(['py ll[-10] = 5'], 'Vim(python):vim.error: internal error:')
912
913 " Use a step value of 0
914 call AssertException(['py ll[0:3:0] = [1, 2, 3]'],
915 \ 'Vim(python):ValueError: slice step cannot be zero')
916
917 " Error case: Invalid slice type
918 call AssertException(["py x = ll['abc']"],
919 \ 'Vim(python):TypeError: index must be int or slice, not str')
815 py del l 920 py del l
921
922 " Error case: List with a null list item
923 let l = [test_null_list()]
924 py ll = vim.bindeval('l')
925 call AssertException(["py x = ll[:]"],
926 \ 'Vim(python):SystemError: error return without exception set')
816 endfunc 927 endfunc
817 928
818 " Vars 929 " Vars
819 func Test_python_vars() 930 func Test_python_vars()
820 let g:foo = 'bac' 931 let g:foo = 'bac'
1247 B: 1:'.,,' 2:',,' 3:'.,,' 4:'.,,' 1358 B: 1:'.,,' 2:',,' 3:'.,,' 4:'.,,'
1248 END 1359 END
1249 1360
1250 call assert_equal(expected, g:res) 1361 call assert_equal(expected, g:res)
1251 unlet g:res 1362 unlet g:res
1363
1364 call assert_equal(0, pyeval("'' in vim.options"))
1365
1366 " use an empty key to index vim.options
1367 call AssertException(["let v = pyeval(\"vim.options['']\")"],
1368 \ 'Vim(let):ValueError: empty keys are not allowed')
1369 call AssertException(["py vim.current.window.options[''] = 0"],
1370 \ 'Vim(python):ValueError: empty keys are not allowed')
1371 call AssertException(["py vim.current.window.options[{}] = 0"],
1372 \ 'Vim(python):TypeError: expected str() or unicode() instance, but got dict')
1373
1374 " set one of the number options to a very large number
1375 let cmd = ["py vim.options['previewheight'] = 9999999999999999"]
1376 call AssertException(cmd, 'OverflowError:')
1377
1378 " unset a global-local string option
1379 call AssertException(["py del vim.options['errorformat']"],
1380 \ 'Vim(python):ValueError: unable to unset global option errorformat')
1252 endfunc 1381 endfunc
1253 1382
1254 " Test for vim.buffer object 1383 " Test for vim.buffer object
1255 func Test_python_buffer() 1384 func Test_python_buffer()
1256 new 1385 new
1265 let bnr2 = bufnr() 1394 let bnr2 = bufnr()
1266 call setline(1, ['First line', 'Second line', 'Third line']) 1395 call setline(1, ['First line', 'Second line', 'Third line'])
1267 py b = vim.current.buffer 1396 py b = vim.current.buffer
1268 wincmd w 1397 wincmd w
1269 1398
1399 " Test for getting lines from the buffer using a slice
1400 call assert_equal(['First line'], pyeval('b[-10:1]'))
1401 call assert_equal(['Third line'], pyeval('b[2:10]'))
1402 call assert_equal([], pyeval('b[2:0]'))
1403 call assert_equal([], pyeval('b[10:12]'))
1404 call assert_equal([], pyeval('b[-10:-8]'))
1405
1270 " Tests BufferAppend and BufferItem 1406 " Tests BufferAppend and BufferItem
1271 py cb.append(b[0]) 1407 py cb.append(b[0])
1272 call assert_equal(['First line'], getbufline(bnr1, 2)) 1408 call assert_equal(['First line'], getbufline(bnr1, 2))
1273 %d 1409 %d
1410
1411 " Try to append using out-of-range line number
1412 call AssertException(["py b.append('abc', 10)"],
1413 \ 'Vim(python):IndexError: line number out of range')
1414
1415 " Append a non-string item
1416 call AssertException(["py b.append([22])"],
1417 \ 'Vim(python):TypeError: expected str() or unicode() instance, but got int')
1274 1418
1275 " Tests BufferSlice and BufferAssSlice 1419 " Tests BufferSlice and BufferAssSlice
1276 py cb.append('abc5') # Will be overwritten 1420 py cb.append('abc5') # Will be overwritten
1277 py cb[-1:] = b[:-2] 1421 py cb[-1:] = b[:-2]
1278 call assert_equal(['First line'], getbufline(bnr1, 2)) 1422 call assert_equal(['First line'], getbufline(bnr1, 2))
1361 vim.command('cd .') 1505 vim.command('cd .')
1362 del b 1506 del b
1363 EOF 1507 EOF
1364 call assert_equal([''], getline(1, '$')) 1508 call assert_equal([''], getline(1, '$'))
1365 1509
1510 " Delete all the lines in a buffer
1511 call setline(1, ['a', 'b', 'c'])
1512 py vim.current.buffer[:] = []
1513 call assert_equal([''], getline(1, '$'))
1514
1515 " Test for modifying a 'nomodifiable' buffer
1516 setlocal nomodifiable
1517 call AssertException(["py vim.current.buffer[0] = 'abc'"],
1518 \ "Vim(python):vim.error: Vim:E21: Cannot make changes, 'modifiable' is off")
1519 call AssertException(["py vim.current.buffer[0] = None"],
1520 \ "Vim(python):vim.error: Vim:E21: Cannot make changes, 'modifiable' is off")
1521 call AssertException(["py vim.current.buffer[:] = None"],
1522 \ "Vim(python):vim.error: Vim:E21: Cannot make changes, 'modifiable' is off")
1523 call AssertException(["py vim.current.buffer[:] = []"],
1524 \ "Vim(python):vim.error: Vim:E21: Cannot make changes, 'modifiable' is off")
1525 call AssertException(["py vim.current.buffer.append('abc')"],
1526 \ "Vim(python):vim.error: Vim:E21: Cannot make changes, 'modifiable' is off")
1527 call AssertException(["py vim.current.buffer.append([])"],
1528 \ "Vim(python):vim.error: Vim:E21: Cannot make changes, 'modifiable' is off")
1529 setlocal modifiable
1530
1366 augroup BUFS 1531 augroup BUFS
1367 autocmd! 1532 autocmd!
1368 augroup END 1533 augroup END
1369 augroup! BUFS 1534 augroup! BUFS
1370 %bw! 1535 %bw!
1536
1537 " Range object for a deleted buffer
1538 new Xfile
1539 call setline(1, ['one', 'two', 'three'])
1540 py b = vim.current.buffer
1541 py r = vim.current.buffer.range(0, 2)
1542 call assert_equal('<range Xfile (0:2)>', pyeval('repr(r)'))
1543 %bw!
1544 call AssertException(['py r[:] = []'],
1545 \ 'Vim(python):vim.error: attempt to refer to deleted buffer')
1546 call assert_match('<buffer object (deleted)', pyeval('repr(b)'))
1547 call assert_match('<range object (for deleted buffer)', pyeval('repr(r)'))
1548 call AssertException(["let n = pyeval('len(r)')"],
1549 \ 'Vim(let):vim.error: attempt to refer to deleted buffer')
1550 call AssertException(["py r.append('abc')"],
1551 \ 'Vim(python):vim.error: attempt to refer to deleted buffer')
1552
1553 " object for a deleted buffer
1554 call AssertException(["py b[0] = 'one'"],
1555 \ 'Vim(python):vim.error: attempt to refer to deleted buffer')
1556 call AssertException(["py b.append('one')"],
1557 \ 'Vim(python):vim.error: attempt to refer to deleted buffer')
1558 call AssertException(["let n = pyeval('len(b)')"],
1559 \ 'Vim(let):vim.error: attempt to refer to deleted buffer')
1560 call AssertException(["py pos = b.mark('a')"],
1561 \ 'Vim(python):vim.error: attempt to refer to deleted buffer')
1562 call AssertException(["py vim.current.buffer = b"],
1563 \ 'Vim(python):vim.error: attempt to refer to deleted buffer')
1564 call AssertException(["py rn = b.range(0, 2)"],
1565 \ 'Vim(python):vim.error: attempt to refer to deleted buffer')
1371 endfunc 1566 endfunc
1372 1567
1373 " Test vim.buffers object 1568 " Test vim.buffers object
1374 func Test_python_buffers() 1569 func Test_python_buffers()
1375 %bw! 1570 %bw!
1466 tabnew 2 1661 tabnew 2
1467 vnew a.2 1662 vnew a.2
1468 vnew b.2 1663 vnew b.2
1469 vnew c.2 1664 vnew c.2
1470 1665
1666 call assert_equal(4, pyeval('vim.current.window.tabpage.number'))
1667
1471 py << trim EOF 1668 py << trim EOF
1472 cb.append('Number of tabs: ' + str(len(vim.tabpages))) 1669 cb.append('Number of tabs: ' + str(len(vim.tabpages)))
1473 cb.append('Current tab pages:') 1670 cb.append('Current tab pages:')
1474 def W(w): 1671 def W(w):
1475 if repr(w).find('(unknown)') != -1: 1672 if repr(w).find('(unknown)') != -1:
1615 Current window: <window 0> 1812 Current window: <window 0>
1616 Current buffer: <buffer Xfile> 1813 Current buffer: <buffer Xfile>
1617 Current line: 'python interface' 1814 Current line: 'python interface'
1618 END 1815 END
1619 call assert_equal(expected, getbufline(bufnr('Xfile'), 2, '$')) 1816 call assert_equal(expected, getbufline(bufnr('Xfile'), 2, '$'))
1817 py vim.current.line = 'one line'
1818 call assert_equal('one line', getline('.'))
1620 call deletebufline(bufnr('Xfile'), 1, '$') 1819 call deletebufline(bufnr('Xfile'), 1, '$')
1621 1820
1622 py << trim EOF 1821 py << trim EOF
1623 ws = list(vim.windows) 1822 ws = list(vim.windows)
1624 ts = list(vim.tabpages) 1823 ts = list(vim.tabpages)
1737 \ pyeval('vim.Function(''tr'', args=[123, 3, 4], self={}, auto_rebind=False)')) 1936 \ pyeval('vim.Function(''tr'', args=[123, 3, 4], self={}, auto_rebind=False)'))
1738 endfunc 1937 endfunc
1739 1938
1740 " Test vim.Function 1939 " Test vim.Function
1741 func Test_python_vim_func() 1940 func Test_python_vim_func()
1742 function Args(...) 1941 func Args(...)
1743 return a:000 1942 return a:000
1744 endfunction 1943 endfunc
1745 1944
1746 function SelfArgs(...) dict 1945 func SelfArgs(...) dict
1747 return [a:000, self] 1946 return [a:000, self]
1748 endfunction 1947 endfunc
1749 1948
1750 " The following four lines should not crash 1949 " The following four lines should not crash
1751 let Pt = function('tr', [[]], {'l': []}) 1950 let Pt = function('tr', [[]], {'l': []})
1752 py Pt = vim.bindeval('Pt') 1951 py Pt = vim.bindeval('Pt')
1753 unlet Pt 1952 unlet Pt
1754 py del Pt 1953 py del Pt
1954
1955 call assert_equal(3, pyeval('vim.strwidth("a\tb")'))
1755 1956
1756 %bw! 1957 %bw!
1757 py cb = vim.current.buffer 1958 py cb = vim.current.buffer
1758 py << trim EOF 1959 py << trim EOF
1759 def ecall(out_prefix, func, *args, **kwargs): 1960 def ecall(out_prefix, func, *args, **kwargs):
2127 endfunc 2328 endfunc
2128 2329
2129 " Test subclassing 2330 " Test subclassing
2130 func Test_python_subclass() 2331 func Test_python_subclass()
2131 new 2332 new
2132 fun Put(...) 2333 func Put(...)
2133 return a:000 2334 return a:000
2134 endfun 2335 endfunc
2135 2336
2136 py << trim EOF 2337 py << trim EOF
2137 class DupDict(vim.Dictionary): 2338 class DupDict(vim.Dictionary):
2138 def __setitem__(self, key, value): 2339 def __setitem__(self, key, value):
2139 super(DupDict, self).__setitem__(key, value) 2340 super(DupDict, self).__setitem__(key, value)
2209 close! 2410 close!
2210 endfunc 2411 endfunc
2211 2412
2212 " Test errors 2413 " Test errors
2213 func Test_python_errors() 2414 func Test_python_errors()
2214 fun F() dict 2415 func F() dict
2215 endfun 2416 endfunc
2216 2417
2217 fun D() 2418 func D()
2218 endfun 2419 endfunc
2219 2420
2220 new 2421 new
2221 py cb = vim.current.buffer 2422 py cb = vim.current.buffer
2222 2423
2223 py << trim EOF 2424 py << trim EOF
2535 cb.append("> WinList") 2736 cb.append("> WinList")
2536 cb.append(">> WinListItem") 2737 cb.append(">> WinListItem")
2537 ee('vim.windows[1000]') 2738 ee('vim.windows[1000]')
2538 cb.append("> Buffer") 2739 cb.append("> Buffer")
2539 cb.append(">> StringToLine (indirect)") 2740 cb.append(">> StringToLine (indirect)")
2741 ee('vim.current.buffer[0] = "\\na"')
2540 ee('vim.current.buffer[0] = u"\\na"') 2742 ee('vim.current.buffer[0] = u"\\na"')
2541 ee('vim.current.buffer[0] = "\\na"')
2542 cb.append(">> SetBufferLine (indirect)") 2743 cb.append(">> SetBufferLine (indirect)")
2543 ee('vim.current.buffer[0] = True') 2744 ee('vim.current.buffer[0] = True')
2544 cb.append(">> SetBufferLineList (indirect)") 2745 cb.append(">> SetBufferLineList (indirect)")
2545 ee('vim.current.buffer[:] = True') 2746 ee('vim.current.buffer[:] = True')
2546 ee('vim.current.buffer[:] = ["\\na", "bc"]') 2747 ee('vim.current.buffer[:] = ["\\na", "bc"]')
3358 > WinList 3559 > WinList
3359 >> WinListItem 3560 >> WinListItem
3360 vim.windows[1000]:IndexError:('no such window',) 3561 vim.windows[1000]:IndexError:('no such window',)
3361 > Buffer 3562 > Buffer
3362 >> StringToLine (indirect) 3563 >> StringToLine (indirect)
3564 vim.current.buffer[0] = "\na":error:('string cannot contain newlines',)
3363 vim.current.buffer[0] = u"\na":error:('string cannot contain newlines',) 3565 vim.current.buffer[0] = u"\na":error:('string cannot contain newlines',)
3364 vim.current.buffer[0] = "\na":error:('string cannot contain newlines',)
3365 >> SetBufferLine (indirect) 3566 >> SetBufferLine (indirect)
3366 vim.current.buffer[0] = True:TypeError:('bad argument type for built-in operation',) 3567 vim.current.buffer[0] = True:TypeError:('bad argument type for built-in operation',)
3367 >> SetBufferLineList (indirect) 3568 >> SetBufferLineList (indirect)
3368 vim.current.buffer[:] = True:TypeError:('bad argument type for built-in operation',) 3569 vim.current.buffer[:] = True:TypeError:('bad argument type for built-in operation',)
3369 vim.current.buffer[:] = ["\na", "bc"]:error:('string cannot contain newlines',) 3570 vim.current.buffer[:] = ["\na", "bc"]:error:('string cannot contain newlines',)
3440 import topmodule.submodule as tms 3641 import topmodule.submodule as tms
3441 import topmodule.submodule.subsubmodule.subsubsubmodule as tmsss 3642 import topmodule.submodule.subsubmodule.subsubsubmodule as tmsss
3442 cb.append(tm.__file__.replace('.pyc', '.py').replace(os.path.sep, '/')[-len('modulex/topmodule/__init__.py'):]) 3643 cb.append(tm.__file__.replace('.pyc', '.py').replace(os.path.sep, '/')[-len('modulex/topmodule/__init__.py'):])
3443 cb.append(tms.__file__.replace('.pyc', '.py').replace(os.path.sep, '/')[-len('modulex/topmodule/submodule/__init__.py'):]) 3644 cb.append(tms.__file__.replace('.pyc', '.py').replace(os.path.sep, '/')[-len('modulex/topmodule/submodule/__init__.py'):])
3444 cb.append(tmsss.__file__.replace('.pyc', '.py').replace(os.path.sep, '/')[-len('modulex/topmodule/submodule/subsubmodule/subsubsubmodule.py'):]) 3645 cb.append(tmsss.__file__.replace('.pyc', '.py').replace(os.path.sep, '/')[-len('modulex/topmodule/submodule/subsubmodule/subsubsubmodule.py'):])
3646
3445 del before 3647 del before
3446 del after 3648 del after
3447 del d 3649 del d
3448 del ddir 3650 del ddir
3449 del tm 3651 del tm
3461 pythonx/topmodule/submodule/__init__.py 3663 pythonx/topmodule/submodule/__init__.py
3462 pythonx/topmodule/submodule/subsubmodule/subsubsubmodule.py 3664 pythonx/topmodule/submodule/subsubmodule/subsubsubmodule.py
3463 END 3665 END
3464 call assert_equal(expected, getline(2, '$')) 3666 call assert_equal(expected, getline(2, '$'))
3465 close! 3667 close!
3668
3669 " Try to import a non-existing moudle with a dot (.)
3670 call AssertException(['py import a.b.c'], 'ImportError:')
3466 endfunc 3671 endfunc
3467 3672
3468 " Test exceptions 3673 " Test exceptions
3469 func Test_python_exception() 3674 func Test_python_exception()
3470 fun Exe(e) 3675 func Exe(e)
3471 execute a:e 3676 execute a:e
3472 endfun 3677 endfunc
3473 3678
3474 new 3679 new
3475 py cb = vim.current.buffer 3680 py cb = vim.current.buffer
3476 3681
3477 py << trim EOF 3682 py << trim EOF