blob: 128055b32e23503b85875ad29752693ff1225606 [file] [log] [blame]
Bram Moolenaardb913952012-06-29 12:54:53 +02001Tests for various python features. vim: set ft=vim :
2
Bram Moolenaar995a8cd2013-02-20 16:54:27 +01003NOTE: This will cause errors when run under valgrind.
4This would require recompiling Python with:
5 ./configure --without-pymalloc
6See http://svn.python.org/view/python/trunk/Misc/README.valgrind?view=markup
7
Bram Moolenaardb913952012-06-29 12:54:53 +02008STARTTEST
9:so small.vim
Bram Moolenaar8600e402013-05-30 13:28:41 +020010:set encoding=latin1
Bram Moolenaar9f3685a2013-06-12 14:20:36 +020011:set noswapfile
Bram Moolenaardb913952012-06-29 12:54:53 +020012:if !has('python') | e! test.ok | wq! test.out | endif
Bram Moolenaarc24c1ac2013-05-16 20:47:56 +020013:lang C
Bram Moolenaardb913952012-06-29 12:54:53 +020014:fun Test()
Bram Moolenaar841fbd22013-06-23 14:37:07 +020015:py import vim
Bram Moolenaardb913952012-06-29 12:54:53 +020016:let l = []
17:py l=vim.bindeval('l')
18:py f=vim.bindeval('function("strlen")')
19:" Extending List directly with different types
20:py l.extend([1, "as'd", [1, 2, f, {'a': 1}]])
21:$put =string(l)
22:$put =string(l[-1])
23:try
24: $put =string(l[-4])
25:catch
26: $put =v:exception[:13]
27:endtry
28:" List assignment
29:py l[0]=0
30:$put =string(l)
31:py l[-2]=f
32:$put =string(l)
33:"
34:" Extending Dictionary directly with different types
35:let d = {}
Bram Moolenaar355fd9b2013-05-30 13:14:13 +020036:fun d.f()
37: return 1
38:endfun
Bram Moolenaara9922d62013-05-30 13:01:18 +020039py << EOF
40d=vim.bindeval('d')
41d['1']='asd'
42d.update(b=[1, 2, f])
43d.update((('-1', {'a': 1}),))
44d.update({'0': -1})
45dk = d.keys()
46dv = d.values()
47di = d.items()
Bram Moolenaar27610ed2013-06-12 14:26:26 +020048cmpfun = lambda a, b: cmp(repr(a), repr(b))
49dk.sort(cmpfun)
50dv.sort(cmpfun)
51di.sort(cmpfun)
Bram Moolenaara9922d62013-05-30 13:01:18 +020052EOF
Bram Moolenaar355fd9b2013-05-30 13:14:13 +020053:$put =pyeval('d[''f''](self={})')
Bram Moolenaara9922d62013-05-30 13:01:18 +020054:$put =pyeval('repr(dk)')
55:$put =substitute(pyeval('repr(dv)'),'0x\x\+','','g')
56:$put =substitute(pyeval('repr(di)'),'0x\x\+','','g')
Bram Moolenaar355fd9b2013-05-30 13:14:13 +020057:for [key, Val] in sort(items(d))
58: $put =string(key) . ' : ' . string(Val)
59: unlet key Val
Bram Moolenaardb913952012-06-29 12:54:53 +020060:endfor
Bram Moolenaar841fbd22013-06-23 14:37:07 +020061:py del dk
62:py del di
63:py del dv
Bram Moolenaardb913952012-06-29 12:54:53 +020064:"
65:" removing items with del
66:py del l[2]
67:$put =string(l)
68:let l = range(8)
69:py l=vim.bindeval('l')
70:try
71: py del l[:3]
72: py del l[1:]
73:catch
74: $put =v:exception
75:endtry
76:$put =string(l)
77:"
78:py del d['-1']
Bram Moolenaar355fd9b2013-05-30 13:14:13 +020079:py del d['f']
Bram Moolenaara9922d62013-05-30 13:01:18 +020080:$put =string(pyeval('d.get(''b'', 1)'))
81:$put =string(pyeval('d.pop(''b'')'))
82:$put =string(pyeval('d.get(''b'', 1)'))
83:$put =string(pyeval('d.pop(''1'', 2)'))
84:$put =string(pyeval('d.pop(''1'', 2)'))
85:$put =pyeval('repr(d.has_key(''0''))')
86:$put =pyeval('repr(d.has_key(''1''))')
87:$put =pyeval('repr(''0'' in d)')
88:$put =pyeval('repr(''1'' in d)')
89:$put =pyeval('repr(list(iter(d)))')
Bram Moolenaardb913952012-06-29 12:54:53 +020090:$put =string(d)
Bram Moolenaarde71b562013-06-02 17:41:54 +020091:$put =pyeval('repr(d.popitem())')
Bram Moolenaara9922d62013-05-30 13:01:18 +020092:$put =pyeval('repr(d.get(''0''))')
93:$put =pyeval('repr(list(iter(d)))')
Bram Moolenaardb913952012-06-29 12:54:53 +020094:"
95:" removing items out of range: silently skip items that don't exist
96:let l = [0, 1, 2, 3]
97:py l=vim.bindeval('l')
98:" The following two ranges delete nothing as they match empty list:
99:py del l[2:1]
100:$put =string(l)
101:py del l[2:2]
102:$put =string(l)
103:py del l[2:3]
104:$put =string(l)
105:let l = [0, 1, 2, 3]
106:py l=vim.bindeval('l')
107:py del l[2:4]
108:$put =string(l)
109:let l = [0, 1, 2, 3]
110:py l=vim.bindeval('l')
111:py del l[2:5]
112:$put =string(l)
113:let l = [0, 1, 2, 3]
114:py l=vim.bindeval('l')
115:py del l[2:6]
116:$put =string(l)
117:let l = [0, 1, 2, 3]
118:py l=vim.bindeval('l')
119:" The following two ranges delete nothing as they match empty list:
120:py del l[-1:2]
121:$put =string(l)
122:py del l[-2:2]
123:$put =string(l)
124:py del l[-3:2]
125:$put =string(l)
126:let l = [0, 1, 2, 3]
127:py l=vim.bindeval('l')
128:py del l[-4:2]
129:$put =string(l)
130:let l = [0, 1, 2, 3]
131:py l=vim.bindeval('l')
132:py del l[-5:2]
133:$put =string(l)
134:let l = [0, 1, 2, 3]
135:py l=vim.bindeval('l')
136:py del l[-6:2]
137:$put =string(l)
138:"
139:" Slice assignment to a list
140:let l = [0, 1, 2, 3]
141:py l=vim.bindeval('l')
142:py l[0:0]=['a']
143:$put =string(l)
144:let l = [0, 1, 2, 3]
145:py l=vim.bindeval('l')
146:py l[1:2]=['b']
147:$put =string(l)
148:let l = [0, 1, 2, 3]
149:py l=vim.bindeval('l')
150:py l[2:4]=['c']
151:$put =string(l)
152:let l = [0, 1, 2, 3]
153:py l=vim.bindeval('l')
154:py l[4:4]=['d']
155:$put =string(l)
156:let l = [0, 1, 2, 3]
157:py l=vim.bindeval('l')
158:py l[-1:2]=['e']
159:$put =string(l)
160:let l = [0, 1, 2, 3]
161:py l=vim.bindeval('l')
162:py l[-10:2]=['f']
163:$put =string(l)
164:let l = [0, 1, 2, 3]
165:py l=vim.bindeval('l')
166:py l[2:-10]=['g']
167:$put =string(l)
168:let l = []
169:py l=vim.bindeval('l')
170:py l[0:0]=['h']
171:$put =string(l)
172:"
173:" Locked variables
174:let l = [0, 1, 2, 3]
175:py l=vim.bindeval('l')
176:lockvar! l
177:py l[2]='i'
178:$put =string(l)
179:unlockvar! l
180:"
181:" Function calls
Bram Moolenaar9fee7d42013-11-28 17:04:43 +0100182py << EOF
183import sys
184def ee(expr, g=globals(), l=locals()):
185 try:
186 exec(expr, g, l)
187 except:
188 ei = sys.exc_info()
189 msg = sys.exc_info()[0].__name__ + ':' + repr(sys.exc_info()[1].args)
190 msg = msg.replace('TypeError:(\'argument 1 ', 'TypeError:(\'')
191 if expr.find('None') > -1:
192 msg = msg.replace('TypeError:(\'iteration over non-sequence\',)',
193 'TypeError:("\'NoneType\' object is not iterable",)')
194 if expr.find('FailingNumber') > -1:
195 msg = msg.replace(', not \'FailingNumber\'', '').replace('"', '\'')
196 msg = msg.replace('TypeError:(\'iteration over non-sequence\',)',
197 'TypeError:("\'FailingNumber\' object is not iterable",)')
198 if msg.find('(\'\'') > -1 or msg.find('(\'can\'t') > -1:
199 msg = msg.replace('(\'', '("').replace('\',)', '",)')
200 if expr == 'fd(self=[])':
201 # HACK: PyMapping_Check changed meaning
202 msg = msg.replace('AttributeError:(\'keys\',)',
203 'TypeError:(\'unable to convert list to vim dictionary\',)')
204 vim.current.buffer.append(expr + ':' + msg)
205 else:
206 vim.current.buffer.append(expr + ':NOT FAILED')
207EOF
Bram Moolenaar841fbd22013-06-23 14:37:07 +0200208:fun New(...)
209: return ['NewStart']+a:000+['NewEnd']
210:endfun
211:fun DictNew(...) dict
212: return ['DictNewStart']+a:000+['DictNewEnd', self]
213:endfun
Bram Moolenaardb913952012-06-29 12:54:53 +0200214:let l=[function('New'), function('DictNew')]
215:py l=vim.bindeval('l')
216:py l.extend(list(l[0](1, 2, 3)))
217:$put =string(l)
218:py l.extend(list(l[1](1, 2, 3, self={'a': 'b'})))
219:$put =string(l)
220:py l.extend([l[0].name])
221:$put =string(l)
Bram Moolenaar9fee7d42013-11-28 17:04:43 +0100222:py ee('l[1](1, 2, 3)')
Bram Moolenaar355fd9b2013-05-30 13:14:13 +0200223:py f=l[0]
Bram Moolenaardb913952012-06-29 12:54:53 +0200224:delfunction New
Bram Moolenaar9fee7d42013-11-28 17:04:43 +0100225:py ee('f(1, 2, 3)')
Bram Moolenaardb913952012-06-29 12:54:53 +0200226:if has('float')
227: let l=[0.0]
228: py l=vim.bindeval('l')
229: py l.extend([0.0])
230: $put =string(l)
231:else
232: $put ='[0.0, 0.0]'
233:endif
Bram Moolenaarc11073c2012-09-05 19:17:42 +0200234:let messages=[]
Bram Moolenaar841fbd22013-06-23 14:37:07 +0200235:delfunction DictNew
Bram Moolenaar03db85b2013-05-15 14:51:35 +0200236py <<EOF
Bram Moolenaarc11073c2012-09-05 19:17:42 +0200237d=vim.bindeval('{}')
238m=vim.bindeval('messages')
Bram Moolenaar03db85b2013-05-15 14:51:35 +0200239def em(expr, g=globals(), l=locals()):
240 try:
241 exec(expr, g, l)
242 except:
243 m.extend([sys.exc_type.__name__])
Bram Moolenaarc11073c2012-09-05 19:17:42 +0200244
Bram Moolenaar841fbd22013-06-23 14:37:07 +0200245em('d["abc1"]')
246em('d["abc1"]="\\0"')
247em('d["abc1"]=vim')
Bram Moolenaar03db85b2013-05-15 14:51:35 +0200248em('d[""]=1')
249em('d["a\\0b"]=1')
250em('d[u"a\\0b"]=1')
Bram Moolenaara9922d62013-05-30 13:01:18 +0200251
Bram Moolenaar841fbd22013-06-23 14:37:07 +0200252em('d.pop("abc1")')
Bram Moolenaarde71b562013-06-02 17:41:54 +0200253em('d.popitem()')
Bram Moolenaar841fbd22013-06-23 14:37:07 +0200254del em
255del m
Bram Moolenaarc11073c2012-09-05 19:17:42 +0200256EOF
257:$put =messages
Bram Moolenaar66b79852012-09-21 14:00:35 +0200258:unlet messages
259:" locked and scope attributes
260:let d={} | let dl={} | lockvar dl
261:for s in split("d dl v: g:")
262: let name=tr(s, ':', 's')
263: execute 'py '.name.'=vim.bindeval("'.s.'")'
264: let toput=s.' : '.join(map(['locked', 'scope'], 'v:val.":".pyeval(name.".".v:val)'), ';')
265: $put =toput
266:endfor
Bram Moolenaar841fbd22013-06-23 14:37:07 +0200267:silent! let d.abc2=1
268:silent! let dl.abc3=1
Bram Moolenaar66b79852012-09-21 14:00:35 +0200269:py d.locked=True
270:py dl.locked=False
271:silent! let d.def=1
272:silent! let dl.def=1
273:put ='d:'.string(d)
274:put ='dl:'.string(dl)
275:unlet d dl
276:
277:let l=[] | let ll=[] | lockvar ll
278:for s in split("l ll")
279: let name=tr(s, ':', 's')
280: execute 'py '.name.'=vim.bindeval("'.s.'")'
281: let toput=s.' : locked:'.pyeval(name.'.locked')
282: $put =toput
283:endfor
284:silent! call extend(l, [0])
285:silent! call extend(ll, [0])
286:py l.locked=True
287:py ll.locked=False
288:silent! call extend(l, [1])
289:silent! call extend(ll, [1])
290:put ='l:'.string(l)
291:put ='ll:'.string(ll)
292:unlet l ll
Bram Moolenaardb913952012-06-29 12:54:53 +0200293:"
294:" pyeval()
295:let l=pyeval('range(3)')
296:$put =string(l)
297:let d=pyeval('{"a": "b", "c": 1, "d": ["e"]}')
298:$put =sort(items(d))
Bram Moolenaardb913952012-06-29 12:54:53 +0200299:if has('float')
300: let f=pyeval('0.0')
301: $put =string(f)
302:else
303: $put ='0.0'
304:endif
Bram Moolenaarc11073c2012-09-05 19:17:42 +0200305:" Invalid values:
306:for e in ['"\0"', '{"\0": 1}', 'undefined_name', 'vim']
307: try
308: let v=pyeval(e)
309: catch
310: let toput=e.":\t".v:exception[:13]
311: $put =toput
312: endtry
313:endfor
Bram Moolenaar76d711c2013-02-13 14:17:08 +0100314:"
315:" threading
316:let l = [0]
317:py l=vim.bindeval('l')
Bram Moolenaardee2e312013-06-23 16:35:47 +0200318py <<EOF
Bram Moolenaar76d711c2013-02-13 14:17:08 +0100319import threading
320import time
321
322class T(threading.Thread):
323 def __init__(self):
324 threading.Thread.__init__(self)
325 self.t = 0
326 self.running = True
327
328 def run(self):
329 while self.running:
330 self.t += 1
331 time.sleep(0.1)
332
333t = T()
Bram Moolenaar841fbd22013-06-23 14:37:07 +0200334del T
Bram Moolenaar76d711c2013-02-13 14:17:08 +0100335t.start()
336EOF
337:sleep 1
338:py t.running = False
339:py t.join()
340:py l[0] = t.t > 8 # check if the background thread is working
Bram Moolenaar841fbd22013-06-23 14:37:07 +0200341:py del time
342:py del threading
Bram Moolenaar9fee7d42013-11-28 17:04:43 +0100343:py del t
Bram Moolenaar76d711c2013-02-13 14:17:08 +0100344:$put =string(l)
345:"
346:" settrace
347:let l = []
348:py l=vim.bindeval('l')
Bram Moolenaardee2e312013-06-23 16:35:47 +0200349py <<EOF
Bram Moolenaar76d711c2013-02-13 14:17:08 +0100350import sys
351
352def traceit(frame, event, arg):
353 global l
354 if event == "line":
355 l.extend([frame.f_lineno])
356 return traceit
357
358def trace_main():
359 for i in range(5):
360 pass
361EOF
362:py sys.settrace(traceit)
363:py trace_main()
Bram Moolenaardee2e312013-06-23 16:35:47 +0200364:py sys.settrace(None)
Bram Moolenaar841fbd22013-06-23 14:37:07 +0200365:py del traceit
366:py del trace_main
Bram Moolenaar76d711c2013-02-13 14:17:08 +0100367:$put =string(l)
Bram Moolenaar24b11fb2013-04-05 19:32:36 +0200368:"
369:" Slice
370:py ll = vim.bindeval('[0, 1, 2, 3, 4, 5]')
371:py l = ll[:4]
372:$put =string(pyeval('l'))
373:py l = ll[2:]
374:$put =string(pyeval('l'))
375:py l = ll[:-4]
376:$put =string(pyeval('l'))
377:py l = ll[-2:]
378:$put =string(pyeval('l'))
379:py l = ll[2:4]
380:$put =string(pyeval('l'))
381:py l = ll[4:2]
382:$put =string(pyeval('l'))
383:py l = ll[-4:-2]
384:$put =string(pyeval('l'))
385:py l = ll[-2:-4]
386:$put =string(pyeval('l'))
387:py l = ll[:]
388:$put =string(pyeval('l'))
389:py l = ll[0:6]
390:$put =string(pyeval('l'))
391:py l = ll[-10:10]
392:$put =string(pyeval('l'))
Bram Moolenaar230bb3f2013-04-24 14:07:45 +0200393:"
394:" Vars
395:let g:foo = 'bac'
Bram Moolenaar841fbd22013-06-23 14:37:07 +0200396:let w:abc3 = 'def'
Bram Moolenaar230bb3f2013-04-24 14:07:45 +0200397:let b:baz = 'bar'
Bram Moolenaara4720012013-05-15 16:27:37 +0200398:let t:bar = 'jkl'
Bram Moolenaar230bb3f2013-04-24 14:07:45 +0200399:try
400: throw "Abc"
401:catch
402: put =pyeval('vim.vvars[''exception'']')
403:endtry
404:put =pyeval('vim.vars[''foo'']')
Bram Moolenaar841fbd22013-06-23 14:37:07 +0200405:put =pyeval('vim.current.window.vars[''abc3'']')
Bram Moolenaar230bb3f2013-04-24 14:07:45 +0200406:put =pyeval('vim.current.buffer.vars[''baz'']')
Bram Moolenaara4720012013-05-15 16:27:37 +0200407:put =pyeval('vim.current.tabpage.vars[''bar'']')
Bram Moolenaar84e0f6c2013-05-06 03:52:55 +0200408:"
409:" Options
410:" paste: boolean, global
411:" previewheight number, global
412:" operatorfunc: string, global
413:" number: boolean, window-local
414:" numberwidth: number, window-local
415:" colorcolumn: string, window-local
416:" statusline: string, window-local/global
417:" autoindent: boolean, buffer-local
Bram Moolenaar55b8ad32013-05-17 13:38:04 +0200418:" shiftwidth: number, buffer-local
Bram Moolenaar84e0f6c2013-05-06 03:52:55 +0200419:" omnifunc: string, buffer-local
420:" preserveindent: boolean, buffer-local/global
421:" path: string, buffer-local/global
422:let g:bufs=[bufnr('%')]
423:new
424:let g:bufs+=[bufnr('%')]
425:vnew
426:let g:bufs+=[bufnr('%')]
427:wincmd j
428:vnew
429:let g:bufs+=[bufnr('%')]
430:wincmd l
431:fun RecVars(opt)
432: let gval =string(eval('&g:'.a:opt))
433: let wvals=join(map(range(1, 4), 'v:val.":".string(getwinvar(v:val, "&".a:opt))'))
434: let bvals=join(map(copy(g:bufs), 'v:val.":".string(getbufvar(v:val, "&".a:opt))'))
435: put =' G: '.gval
436: put =' W: '.wvals
437: put =' B: '.wvals
438:endfun
439py << EOF
440def e(s, g=globals(), l=locals()):
441 try:
442 exec(s, g, l)
Bram Moolenaar03db85b2013-05-15 14:51:35 +0200443 except:
Bram Moolenaara7b64ce2013-05-21 20:40:40 +0200444 vim.command('return ' + repr(sys.exc_type.__name__))
Bram Moolenaar84e0f6c2013-05-06 03:52:55 +0200445
446def ev(s, g=globals(), l=locals()):
447 try:
448 return eval(s, g, l)
Bram Moolenaar03db85b2013-05-15 14:51:35 +0200449 except:
Bram Moolenaara7b64ce2013-05-21 20:40:40 +0200450 vim.command('let exc=' + repr(sys.exc_type.__name__))
Bram Moolenaar84e0f6c2013-05-06 03:52:55 +0200451 return 0
452EOF
Bram Moolenaar841fbd22013-06-23 14:37:07 +0200453:fun E(s)
Bram Moolenaar84e0f6c2013-05-06 03:52:55 +0200454: python e(vim.eval('a:s'))
Bram Moolenaar841fbd22013-06-23 14:37:07 +0200455:endfun
456:fun Ev(s)
Bram Moolenaara7b64ce2013-05-21 20:40:40 +0200457: let r=pyeval('ev(vim.eval("a:s"))')
458: if exists('exc')
459: throw exc
460: endif
461: return r
Bram Moolenaar841fbd22013-06-23 14:37:07 +0200462:endfun
Bram Moolenaar84e0f6c2013-05-06 03:52:55 +0200463:py gopts1=vim.options
464:py wopts1=vim.windows[2].options
465:py wopts2=vim.windows[0].options
466:py wopts3=vim.windows[1].options
467:py bopts1=vim.buffers[vim.bindeval("g:bufs")[2]].options
468:py bopts2=vim.buffers[vim.bindeval("g:bufs")[1]].options
469:py bopts3=vim.buffers[vim.bindeval("g:bufs")[0]].options
Bram Moolenaar04188112013-06-01 20:32:12 +0200470:set path=.,..,,
Bram Moolenaar84e0f6c2013-05-06 03:52:55 +0200471:let lst=[]
472:let lst+=[['paste', 1, 0, 1, 2, 1, 1, 0 ]]
473:let lst+=[['previewheight', 5, 1, 6, 'a', 0, 1, 0 ]]
474:let lst+=[['operatorfunc', 'A', 'B', 'C', 2, 0, 1, 0 ]]
475:let lst+=[['number', 0, 1, 1, 0, 1, 0, 1 ]]
476:let lst+=[['numberwidth', 2, 3, 5, -100, 0, 0, 1 ]]
Bram Moolenaar841fbd22013-06-23 14:37:07 +0200477:let lst+=[['colorcolumn', '+1', '+2', '+3', 'abc4', 0, 0, 1 ]]
Bram Moolenaar84e0f6c2013-05-06 03:52:55 +0200478:let lst+=[['statusline', '1', '2', '4', 0, 0, 1, 1 ]]
479:let lst+=[['autoindent', 0, 1, 1, 2, 1, 0, 2 ]]
Bram Moolenaar55b8ad32013-05-17 13:38:04 +0200480:let lst+=[['shiftwidth', 0, 2, 1, 3, 0, 0, 2 ]]
Bram Moolenaar84e0f6c2013-05-06 03:52:55 +0200481:let lst+=[['omnifunc', 'A', 'B', 'C', 1, 0, 0, 2 ]]
482:let lst+=[['preserveindent', 0, 1, 1, 2, 1, 1, 2 ]]
483:let lst+=[['path', '.,,', ',,', '.', 0, 0, 1, 2 ]]
484:for [oname, oval1, oval2, oval3, invval, bool, global, local] in lst
485: py oname=vim.eval('oname')
486: py oval1=vim.bindeval('oval1')
487: py oval2=vim.bindeval('oval2')
488: py oval3=vim.bindeval('oval3')
489: if invval is 0 || invval is 1
490: py invval=bool(vim.bindeval('invval'))
491: else
492: py invval=vim.bindeval('invval')
493: endif
494: if bool
495: py oval1=bool(oval1)
496: py oval2=bool(oval2)
497: py oval3=bool(oval3)
498: endif
499: put ='>>> '.oname
500: for v in ['gopts1', 'wopts1', 'bopts1']
501: try
502: put =' p/'.v.': '.Ev('repr('.v.'['''.oname.'''])')
503: catch
504: put =' p/'.v.'! '.v:exception
505: endtry
Bram Moolenaara7b64ce2013-05-21 20:40:40 +0200506: let r=E(v.'['''.oname.''']=invval')
507: if r isnot 0
508: put =' inv: '.string(invval).'! '.r
509: endif
Bram Moolenaar84e0f6c2013-05-06 03:52:55 +0200510: for vv in (v is# 'gopts1' ? [v] : [v, v[:-2].'2', v[:-2].'3'])
511: let val=substitute(vv, '^.opts', 'oval', '')
Bram Moolenaara7b64ce2013-05-21 20:40:40 +0200512: let r=E(vv.'['''.oname.''']='.val)
513: if r isnot 0
514: put =' '.vv.'! '.r
515: endif
Bram Moolenaar84e0f6c2013-05-06 03:52:55 +0200516: endfor
517: endfor
518: call RecVars(oname)
519: for v in ['wopts3', 'bopts3']
Bram Moolenaara7b64ce2013-05-21 20:40:40 +0200520: let r=E('del '.v.'["'.oname.'"]')
521: if r isnot 0
522: put =' del '.v.'! '.r
523: endif
Bram Moolenaar84e0f6c2013-05-06 03:52:55 +0200524: endfor
525: call RecVars(oname)
Bram Moolenaar84e0f6c2013-05-06 03:52:55 +0200526:endfor
Bram Moolenaar841fbd22013-06-23 14:37:07 +0200527:delfunction RecVars
528:delfunction E
529:delfunction Ev
530:py del ev
531:py del e
Bram Moolenaar84e0f6c2013-05-06 03:52:55 +0200532:only
Bram Moolenaarb6c589a2013-05-15 14:39:52 +0200533:for buf in g:bufs[1:]
534: execute 'bwipeout!' buf
535:endfor
Bram Moolenaar841fbd22013-06-23 14:37:07 +0200536:py del gopts1
537:py del wopts1
538:py del wopts2
539:py del wopts3
540:py del bopts1
541:py del bopts2
542:py del bopts3
543:py del oval1
544:py del oval2
545:py del oval3
546:py del oname
547:py del invval
Bram Moolenaarbd80f352013-05-12 21:16:23 +0200548:"
549:" Test buffer object
550:vnew
551:put ='First line'
552:put ='Second line'
553:put ='Third line'
554:1 delete _
555:py b=vim.current.buffer
556:wincmd w
557:mark a
Bram Moolenaare9ba5162013-05-29 22:02:22 +0200558:augroup BUFS
559: autocmd BufFilePost * python cb.append(vim.eval('expand("<abuf>")') + ':BufFilePost:' + vim.eval('bufnr("%")'))
560: autocmd BufFilePre * python cb.append(vim.eval('expand("<abuf>")') + ':BufFilePre:' + vim.eval('bufnr("%")'))
561:augroup END
Bram Moolenaarbd80f352013-05-12 21:16:23 +0200562py << EOF
563cb = vim.current.buffer
564# Tests BufferAppend and BufferItem
565cb.append(b[0])
566# Tests BufferSlice and BufferAssSlice
Bram Moolenaar841fbd22013-06-23 14:37:07 +0200567cb.append('abc5') # Will be overwritten
Bram Moolenaarbd80f352013-05-12 21:16:23 +0200568cb[-1:] = b[:-2]
569# Test BufferLength and BufferAssSlice
570cb.append('def') # Will not be overwritten
571cb[len(cb):] = b[:]
572# Test BufferAssItem and BufferMark
573cb.append('ghi') # Will be overwritten
574cb[-1] = repr((len(cb) - cb.mark('a')[0], cb.mark('a')[1]))
575# Test BufferRepr
576cb.append(repr(cb) + repr(b))
577# Modify foreign buffer
578b.append('foo')
579b[0]='bar'
580b[0:0]=['baz']
581vim.command('call append("$", getbufline(%i, 1, "$"))' % b.number)
Bram Moolenaare9ba5162013-05-29 22:02:22 +0200582# Test assigning to name property
Bram Moolenaar04188112013-06-01 20:32:12 +0200583import os
Bram Moolenaare9ba5162013-05-29 22:02:22 +0200584old_name = cb.name
585cb.name = 'foo'
Bram Moolenaar04188112013-06-01 20:32:12 +0200586cb.append(cb.name[-11:].replace(os.path.sep, '/'))
Bram Moolenaare9ba5162013-05-29 22:02:22 +0200587b.name = 'bar'
Bram Moolenaar04188112013-06-01 20:32:12 +0200588cb.append(b.name[-11:].replace(os.path.sep, '/'))
Bram Moolenaare9ba5162013-05-29 22:02:22 +0200589cb.name = old_name
Bram Moolenaar04188112013-06-01 20:32:12 +0200590cb.append(cb.name[-17:].replace(os.path.sep, '/'))
Bram Moolenaar841fbd22013-06-23 14:37:07 +0200591del old_name
Bram Moolenaarbd80f352013-05-12 21:16:23 +0200592# Test CheckBuffer
Bram Moolenaare9ba5162013-05-29 22:02:22 +0200593for _b in vim.buffers:
594 if _b is not cb:
595 vim.command('bwipeout! ' + str(_b.number))
596del _b
Bram Moolenaar9e822c02013-05-29 22:15:30 +0200597cb.append('valid: b:%s, cb:%s' % (repr(b.valid), repr(cb.valid)))
Bram Moolenaar841fbd22013-06-23 14:37:07 +0200598for expr in ('b[1]','b[:] = ["A", "B"]','b[:]','b.append("abc6")', 'b.name = "!"'):
Bram Moolenaarbd80f352013-05-12 21:16:23 +0200599 try:
600 exec(expr)
601 except vim.error:
602 pass
603 else:
604 # Usually a SEGV here
605 # Should not happen in any case
606 cb.append('No exception for ' + expr)
Bram Moolenaare9ba5162013-05-29 22:02:22 +0200607vim.command('cd .')
Bram Moolenaar841fbd22013-06-23 14:37:07 +0200608del b
Bram Moolenaarbd80f352013-05-12 21:16:23 +0200609EOF
Bram Moolenaare9ba5162013-05-29 22:02:22 +0200610:augroup BUFS
611: autocmd!
612:augroup END
613:augroup! BUFS
Bram Moolenaarb6c589a2013-05-15 14:39:52 +0200614:"
615:" Test vim.buffers object
616:set hidden
617:edit a
618:buffer #
619:edit b
620:buffer #
621:edit c
622:buffer #
623py << EOF
Bram Moolenaar2a0f3d32013-05-21 22:23:56 +0200624try:
625 from __builtin__ import next
626except ImportError:
627 next = lambda o: o.next()
Bram Moolenaarb6c589a2013-05-15 14:39:52 +0200628# Check GCing iterator that was not fully exhausted
629i = iter(vim.buffers)
630cb.append('i:' + str(next(i)))
631# and also check creating more then one iterator at a time
632i2 = iter(vim.buffers)
633cb.append('i2:' + str(next(i2)))
634cb.append('i:' + str(next(i)))
635# The following should trigger GC and not cause any problems
636del i
637del i2
638i3 = iter(vim.buffers)
639cb.append('i3:' + str(next(i3)))
640del i3
641
642prevnum = 0
643for b in vim.buffers:
644 # Check buffer order
645 if prevnum >= b.number:
646 cb.append('!!! Buffer numbers not in strictly ascending order')
647 # Check indexing: vim.buffers[number].number == number
648 cb.append(str(b.number) + ':' + repr(vim.buffers[b.number]) + '=' + repr(b))
649 prevnum = b.number
Bram Moolenaar841fbd22013-06-23 14:37:07 +0200650del prevnum
Bram Moolenaarb6c589a2013-05-15 14:39:52 +0200651
652cb.append(str(len(vim.buffers)))
653
654bnums = list(map(lambda b: b.number, vim.buffers))[1:]
655
656# Test wiping out buffer with existing iterator
657i4 = iter(vim.buffers)
658cb.append('i4:' + str(next(i4)))
659vim.command('bwipeout! ' + str(bnums.pop(0)))
660try:
661 next(i4)
662except vim.error:
663 pass
664else:
665 cb.append('!!!! No vim.error')
666i4 = iter(vim.buffers)
667vim.command('bwipeout! ' + str(bnums.pop(-1)))
668vim.command('bwipeout! ' + str(bnums.pop(-1)))
669cb.append('i4:' + str(next(i4)))
670try:
671 next(i4)
672except StopIteration:
673 cb.append('StopIteration')
Bram Moolenaar841fbd22013-06-23 14:37:07 +0200674del i4
675del bnums
Bram Moolenaarb6c589a2013-05-15 14:39:52 +0200676EOF
Bram Moolenaara4720012013-05-15 16:27:37 +0200677:"
678:" Test vim.{tabpage,window}list and vim.{tabpage,window} objects
679:tabnew 0
680:tabnew 1
681:vnew a.1
682:tabnew 2
683:vnew a.2
684:vnew b.2
685:vnew c.2
686py << EOF
687cb.append('Number of tabs: ' + str(len(vim.tabpages)))
688cb.append('Current tab pages:')
689def W(w):
Bram Moolenaar2a0f3d32013-05-21 22:23:56 +0200690 if repr(w).find('(unknown)') != -1:
Bram Moolenaara4720012013-05-15 16:27:37 +0200691 return '<window object (unknown)>'
692 else:
693 return repr(w)
Bram Moolenaar2a0f3d32013-05-21 22:23:56 +0200694
Bram Moolenaare9ba5162013-05-29 22:02:22 +0200695start = len(cb)
696
697def Cursor(w):
Bram Moolenaar2a0f3d32013-05-21 22:23:56 +0200698 if w.buffer is cb:
699 return repr((start - w.cursor[0], w.cursor[1]))
700 else:
701 return repr(w.cursor)
702
Bram Moolenaara4720012013-05-15 16:27:37 +0200703for t in vim.tabpages:
704 cb.append(' ' + repr(t) + '(' + str(t.number) + ')' + ': ' + str(len(t.windows)) + ' windows, current is ' + W(t.window))
705 cb.append(' Windows:')
706 for w in t.windows:
Bram Moolenaar2a0f3d32013-05-21 22:23:56 +0200707 cb.append(' ' + W(w) + '(' + str(w.number) + ')' + ': displays buffer ' + repr(w.buffer) + '; cursor is at ' + Cursor(w))
Bram Moolenaara4720012013-05-15 16:27:37 +0200708 # Other values depend on the size of the terminal, so they are checked partly:
709 for attr in ('height', 'row', 'width', 'col'):
710 try:
711 aval = getattr(w, attr)
712 if type(aval) is not long:
713 raise TypeError
714 if aval < 0:
715 raise ValueError
716 except Exception:
717 cb.append('!!!!!! Error while getting attribute ' + attr + ': ' + sys.exc_type.__name__)
Bram Moolenaar841fbd22013-06-23 14:37:07 +0200718 del aval
719 del attr
Bram Moolenaara4720012013-05-15 16:27:37 +0200720 w.cursor = (len(w.buffer), 0)
Bram Moolenaar841fbd22013-06-23 14:37:07 +0200721del W
722del Cursor
Bram Moolenaara4720012013-05-15 16:27:37 +0200723cb.append('Number of windows in current tab page: ' + str(len(vim.windows)))
724if list(vim.windows) != list(vim.current.tabpage.windows):
725 cb.append('!!!!!! Windows differ')
726EOF
727:"
728:" Test vim.current
729py << EOF
730def H(o):
731 return repr(o)
732cb.append('Current tab page: ' + repr(vim.current.tabpage))
733cb.append('Current window: ' + repr(vim.current.window) + ': ' + H(vim.current.window) + ' is ' + H(vim.current.tabpage.window))
734cb.append('Current buffer: ' + repr(vim.current.buffer) + ': ' + H(vim.current.buffer) + ' is ' + H(vim.current.window.buffer)+ ' is ' + H(vim.current.tabpage.window.buffer))
Bram Moolenaar841fbd22013-06-23 14:37:07 +0200735del H
Bram Moolenaara4720012013-05-15 16:27:37 +0200736# Assigning: fails
737try:
738 vim.current.window = vim.tabpages[0].window
739except ValueError:
740 cb.append('ValueError at assigning foreign tab window')
741
742for attr in ('window', 'tabpage', 'buffer'):
743 try:
744 setattr(vim.current, attr, None)
745 except TypeError:
746 cb.append('Type error at assigning None to vim.current.' + attr)
Bram Moolenaar841fbd22013-06-23 14:37:07 +0200747del attr
Bram Moolenaara4720012013-05-15 16:27:37 +0200748
749# Assigning: success
750vim.current.tabpage = vim.tabpages[-2]
751vim.current.buffer = cb
752vim.current.window = vim.windows[0]
753vim.current.window.cursor = (len(vim.current.buffer), 0)
754cb.append('Current tab page: ' + repr(vim.current.tabpage))
755cb.append('Current window: ' + repr(vim.current.window))
756cb.append('Current buffer: ' + repr(vim.current.buffer))
757cb.append('Current line: ' + repr(vim.current.line))
Bram Moolenaar9e822c02013-05-29 22:15:30 +0200758ws = list(vim.windows)
759ts = list(vim.tabpages)
Bram Moolenaara4720012013-05-15 16:27:37 +0200760for b in vim.buffers:
761 if b is not cb:
Bram Moolenaarcac867a2013-05-21 19:50:34 +0200762 vim.command('bwipeout! ' + str(b.number))
Bram Moolenaar841fbd22013-06-23 14:37:07 +0200763del b
Bram Moolenaar9e822c02013-05-29 22:15:30 +0200764cb.append('w.valid: ' + repr([w.valid for w in ws]))
765cb.append('t.valid: ' + repr([t.valid for t in ts]))
Bram Moolenaar841fbd22013-06-23 14:37:07 +0200766del w
767del t
768del ts
769del ws
Bram Moolenaara4720012013-05-15 16:27:37 +0200770EOF
771:tabonly!
772:only!
Bram Moolenaarcac867a2013-05-21 19:50:34 +0200773:"
774:" Test types
775py << EOF
776for expr, attr in (
777 ('vim.vars', 'Dictionary'),
778 ('vim.options', 'Options'),
779 ('vim.bindeval("{}")', 'Dictionary'),
780 ('vim.bindeval("[]")', 'List'),
781 ('vim.bindeval("function(\'tr\')")', 'Function'),
782 ('vim.current.buffer', 'Buffer'),
783 ('vim.current.range', 'Range'),
784 ('vim.current.window', 'Window'),
785 ('vim.current.tabpage', 'TabPage'),
786):
787 cb.append(expr + ':' + attr + ':' + repr(type(eval(expr)) is getattr(vim, attr)))
Bram Moolenaar841fbd22013-06-23 14:37:07 +0200788del expr
789del attr
Bram Moolenaarcac867a2013-05-21 19:50:34 +0200790EOF
Bram Moolenaara7b64ce2013-05-21 20:40:40 +0200791:"
Bram Moolenaardd8aca62013-05-29 22:36:10 +0200792:" Test __dir__() method
793py << EOF
794for name, o in (
795 ('current', vim.current),
796 ('buffer', vim.current.buffer),
797 ('window', vim.current.window),
798 ('tabpage', vim.current.tabpage),
799 ('range', vim.current.range),
800 ('dictionary', vim.bindeval('{}')),
801 ('list', vim.bindeval('[]')),
802 ('function', vim.bindeval('function("tr")')),
803 ('output', sys.stdout),
804 ):
805 cb.append(name + ':' + ','.join(dir(o)))
806del name
807del o
808EOF
809:"
Bram Moolenaara9922d62013-05-30 13:01:18 +0200810:" Test vim.*.__new__
811:$put =string(pyeval('vim.Dictionary({})'))
812:$put =string(pyeval('vim.Dictionary(a=1)'))
813:$put =string(pyeval('vim.Dictionary(((''a'', 1),))'))
Bram Moolenaar78cddbe2013-05-30 13:05:58 +0200814:$put =string(pyeval('vim.List()'))
Bram Moolenaar841fbd22013-06-23 14:37:07 +0200815:$put =string(pyeval('vim.List(iter(''abc7''))'))
Bram Moolenaar355fd9b2013-05-30 13:14:13 +0200816:$put =string(pyeval('vim.Function(''tr'')'))
Bram Moolenaar01a7a722013-05-30 12:26:58 +0200817:"
818:" Test stdout/stderr
819:redir => messages
Bram Moolenaar841fbd22013-06-23 14:37:07 +0200820:py sys.stdout.write('abc8') ; sys.stdout.write('def')
821:py sys.stderr.write('abc9') ; sys.stderr.write('def')
822:py sys.stdout.writelines(iter('abcA'))
823:py sys.stderr.writelines(iter('abcB'))
Bram Moolenaar01a7a722013-05-30 12:26:58 +0200824:redir END
825:$put =string(substitute(messages, '\d\+', '', 'g'))
Bram Moolenaara9922d62013-05-30 13:01:18 +0200826:" Test subclassing
Bram Moolenaar355fd9b2013-05-30 13:14:13 +0200827:fun Put(...)
828: $put =string(a:000)
829: return a:000
830:endfun
Bram Moolenaara9922d62013-05-30 13:01:18 +0200831py << EOF
832class DupDict(vim.Dictionary):
833 def __setitem__(self, key, value):
834 super(DupDict, self).__setitem__(key, value)
835 super(DupDict, self).__setitem__('dup_' + key, value)
836dd = DupDict()
837dd['a'] = 'b'
Bram Moolenaar78cddbe2013-05-30 13:05:58 +0200838
839class DupList(vim.List):
840 def __getitem__(self, idx):
841 return [super(DupList, self).__getitem__(idx)] * 2
842
843dl = DupList()
Bram Moolenaar841fbd22013-06-23 14:37:07 +0200844dl2 = DupList(iter('abcC'))
Bram Moolenaar78cddbe2013-05-30 13:05:58 +0200845dl.extend(dl2[0])
Bram Moolenaar355fd9b2013-05-30 13:14:13 +0200846
847class DupFun(vim.Function):
848 def __call__(self, arg):
849 return super(DupFun, self).__call__(arg, arg)
850
851df = DupFun('Put')
Bram Moolenaara9922d62013-05-30 13:01:18 +0200852EOF
853:$put =string(sort(keys(pyeval('dd'))))
Bram Moolenaar78cddbe2013-05-30 13:05:58 +0200854:$put =string(pyeval('dl'))
855:$put =string(pyeval('dl2'))
Bram Moolenaar355fd9b2013-05-30 13:14:13 +0200856:$put =string(pyeval('df(2)'))
Bram Moolenaar841fbd22013-06-23 14:37:07 +0200857:$put =string(pyeval('dl') is# pyeval('dl'))
858:$put =string(pyeval('dd') is# pyeval('dd'))
859:$put =string(pyeval('df'))
860:delfunction Put
861py << EOF
862del DupDict
863del DupList
864del DupFun
865del dd
866del dl
867del dl2
868del df
869EOF
Bram Moolenaar01a7a722013-05-30 12:26:58 +0200870:"
Bram Moolenaarf4258302013-06-02 18:20:17 +0200871:" Test chdir
872py << EOF
873import os
874fnamemodify = vim.Function('fnamemodify')
875cb.append(fnamemodify('.', ':p:h:t'))
876cb.append(vim.eval('@%'))
877os.chdir('..')
Bram Moolenaar8e46f722013-07-13 14:08:16 +0200878path = fnamemodify('.', ':p:h:t')
879if path != 'src':
880 # Running tests from a shadow directory, so move up another level
881 # This will result in @% looking like shadow/testdir/test86.in, hence the
882 # extra fnamemodify
883 os.chdir('..')
884 cb.append(fnamemodify('.', ':p:h:t'))
885 cb.append(fnamemodify(vim.eval('@%'), ':s?^%s.??' % path).replace(os.path.sep, '/'))
886 os.chdir(path)
887 del path
888else:
889 cb.append(fnamemodify('.', ':p:h:t'))
890 cb.append(vim.eval('@%').replace(os.path.sep, '/'))
Bram Moolenaarf4258302013-06-02 18:20:17 +0200891os.chdir('testdir')
892cb.append(fnamemodify('.', ':p:h:t'))
893cb.append(vim.eval('@%'))
Bram Moolenaar841fbd22013-06-23 14:37:07 +0200894del fnamemodify
Bram Moolenaarf4258302013-06-02 18:20:17 +0200895EOF
896:"
Bram Moolenaar8600e402013-05-30 13:28:41 +0200897:" Test errors
898:fun F() dict
899:endfun
900:fun D()
Bram Moolenaara7b64ce2013-05-21 20:40:40 +0200901:endfun
902py << EOF
Bram Moolenaar8600e402013-05-30 13:28:41 +0200903d = vim.Dictionary()
Bram Moolenaar841fbd22013-06-23 14:37:07 +0200904ned = vim.Dictionary(foo='bar', baz='abcD')
Bram Moolenaar8600e402013-05-30 13:28:41 +0200905dl = vim.Dictionary(a=1)
906dl.locked = True
907l = vim.List()
Bram Moolenaar841fbd22013-06-23 14:37:07 +0200908ll = vim.List('abcE')
Bram Moolenaar8600e402013-05-30 13:28:41 +0200909ll.locked = True
910f = vim.Function('string')
911fd = vim.Function('F')
912fdel = vim.Function('D')
913vim.command('delfunction D')
914
915def subexpr_test(expr, name, subexprs):
916 cb.append('>>> Testing %s using %s' % (name, expr))
917 for subexpr in subexprs:
918 ee(expr % subexpr)
919 cb.append('<<< Finished')
920
921def stringtochars_test(expr):
922 return subexpr_test(expr, 'StringToChars', (
923 '1', # Fail type checks
924 'u"\\0"', # Fail PyString_AsStringAndSize(bytes, , NULL) check
925 '"\\0"', # Fail PyString_AsStringAndSize(object, , NULL) check
926 ))
927
928class Mapping(object):
929 def __init__(self, d):
930 self.d = d
931
932 def __getitem__(self, key):
933 return self.d[key]
934
935 def keys(self):
936 return self.d.keys()
937
938 def items(self):
939 return self.d.items()
940
941def convertfrompyobject_test(expr, recurse=True):
942 # pydict_to_tv
943 stringtochars_test(expr % '{%s : 1}')
944 if recurse:
Bram Moolenaar841fbd22013-06-23 14:37:07 +0200945 convertfrompyobject_test(expr % '{"abcF" : %s}', False)
Bram Moolenaar8600e402013-05-30 13:28:41 +0200946 # pymap_to_tv
947 stringtochars_test(expr % 'Mapping({%s : 1})')
948 if recurse:
Bram Moolenaar841fbd22013-06-23 14:37:07 +0200949 convertfrompyobject_test(expr % 'Mapping({"abcG" : %s})', False)
Bram Moolenaar8600e402013-05-30 13:28:41 +0200950 # pyseq_to_tv
951 iter_test(expr)
952 return subexpr_test(expr, 'ConvertFromPyObject', (
953 'None', # Not conversible
954 '{"": 1}', # Empty key not allowed
Bram Moolenaar78b59572013-06-02 18:54:21 +0200955 '{u"": 1}', # Same, but with unicode object
Bram Moolenaar8600e402013-05-30 13:28:41 +0200956 'FailingMapping()', #
957 'FailingMappingKey()', #
Bram Moolenaardee2e312013-06-23 16:35:47 +0200958 'FailingNumber()', #
Bram Moolenaar8600e402013-05-30 13:28:41 +0200959 ))
960
961def convertfrompymapping_test(expr):
962 convertfrompyobject_test(expr)
963 return subexpr_test(expr, 'ConvertFromPyMapping', (
964 '[]',
965 ))
966
967def iter_test(expr):
968 return subexpr_test(expr, '*Iter*', (
969 'FailingIter()',
970 'FailingIterNext()',
971 ))
972
Bram Moolenaardee2e312013-06-23 16:35:47 +0200973def number_test(expr, natural=False, unsigned=False):
974 if natural:
975 unsigned = True
976 return subexpr_test(expr, 'NumberToLong', (
977 '[]',
978 'None',
979 ) + (unsigned and ('-1',) or ())
980 + (natural and ('0',) or ()))
981
Bram Moolenaar8600e402013-05-30 13:28:41 +0200982class FailingTrue(object):
983 def __nonzero__(self):
Bram Moolenaardee2e312013-06-23 16:35:47 +0200984 raise NotImplementedError('bool')
Bram Moolenaar8600e402013-05-30 13:28:41 +0200985
986class FailingIter(object):
987 def __iter__(self):
Bram Moolenaardee2e312013-06-23 16:35:47 +0200988 raise NotImplementedError('iter')
Bram Moolenaar8600e402013-05-30 13:28:41 +0200989
990class FailingIterNext(object):
991 def __iter__(self):
992 return self
993
994 def next(self):
Bram Moolenaardee2e312013-06-23 16:35:47 +0200995 raise NotImplementedError('next')
Bram Moolenaar8600e402013-05-30 13:28:41 +0200996
997class FailingMappingKey(object):
998 def __getitem__(self, item):
Bram Moolenaardee2e312013-06-23 16:35:47 +0200999 raise NotImplementedError('getitem:mappingkey')
Bram Moolenaar8600e402013-05-30 13:28:41 +02001000
1001 def keys(self):
Bram Moolenaar841fbd22013-06-23 14:37:07 +02001002 return list("abcH")
Bram Moolenaar8600e402013-05-30 13:28:41 +02001003
1004class FailingMapping(object):
1005 def __getitem__(self):
Bram Moolenaardee2e312013-06-23 16:35:47 +02001006 raise NotImplementedError('getitem:mapping')
Bram Moolenaar8600e402013-05-30 13:28:41 +02001007
1008 def keys(self):
Bram Moolenaardee2e312013-06-23 16:35:47 +02001009 raise NotImplementedError('keys')
Bram Moolenaar8600e402013-05-30 13:28:41 +02001010
1011class FailingList(list):
1012 def __getitem__(self, idx):
1013 if i == 2:
Bram Moolenaardee2e312013-06-23 16:35:47 +02001014 raise NotImplementedError('getitem:list')
Bram Moolenaar8600e402013-05-30 13:28:41 +02001015 else:
1016 return super(FailingList, self).__getitem__(idx)
1017
Bram Moolenaardee2e312013-06-23 16:35:47 +02001018class NoArgsCall(object):
1019 def __call__(self):
1020 pass
1021
1022class FailingCall(object):
1023 def __call__(self, path):
1024 raise NotImplementedError('call')
1025
1026class FailingNumber(object):
1027 def __int__(self):
1028 raise NotImplementedError('int')
1029
Bram Moolenaar8600e402013-05-30 13:28:41 +02001030cb.append("> Output")
1031cb.append(">> OutputSetattr")
1032ee('del sys.stdout.softspace')
Bram Moolenaardee2e312013-06-23 16:35:47 +02001033number_test('sys.stdout.softspace = %s', unsigned=True)
1034number_test('sys.stderr.softspace = %s', unsigned=True)
Bram Moolenaar8600e402013-05-30 13:28:41 +02001035ee('sys.stdout.attr = None')
1036cb.append(">> OutputWrite")
1037ee('sys.stdout.write(None)')
1038cb.append(">> OutputWriteLines")
1039ee('sys.stdout.writelines(None)')
1040ee('sys.stdout.writelines([1])')
Bram Moolenaardee2e312013-06-23 16:35:47 +02001041iter_test('sys.stdout.writelines(%s)')
Bram Moolenaar8600e402013-05-30 13:28:41 +02001042cb.append("> VimCommand")
Bram Moolenaardee2e312013-06-23 16:35:47 +02001043stringtochars_test('vim.command(%s)')
1044ee('vim.command("", 2)')
Bram Moolenaar8600e402013-05-30 13:28:41 +02001045#! Not checked: vim->python exceptions translating: checked later
1046cb.append("> VimToPython")
1047#! Not checked: everything: needs errors in internal python functions
1048cb.append("> VimEval")
Bram Moolenaardee2e312013-06-23 16:35:47 +02001049stringtochars_test('vim.eval(%s)')
1050ee('vim.eval("", FailingTrue())')
Bram Moolenaar8600e402013-05-30 13:28:41 +02001051#! Not checked: everything: needs errors in internal python functions
1052cb.append("> VimEvalPy")
Bram Moolenaardee2e312013-06-23 16:35:47 +02001053stringtochars_test('vim.bindeval(%s)')
1054ee('vim.eval("", 2)')
Bram Moolenaar8600e402013-05-30 13:28:41 +02001055#! Not checked: vim->python exceptions translating: checked later
1056cb.append("> VimStrwidth")
Bram Moolenaardee2e312013-06-23 16:35:47 +02001057stringtochars_test('vim.strwidth(%s)')
1058cb.append("> VimForeachRTP")
1059ee('vim.foreach_rtp(None)')
1060ee('vim.foreach_rtp(NoArgsCall())')
1061ee('vim.foreach_rtp(FailingCall())')
1062ee('vim.foreach_rtp(int, 2)')
1063cb.append('> import')
1064old_rtp = vim.options['rtp']
1065vim.options['rtp'] = os.getcwd().replace(',', '\\,').replace('\\', '\\\\')
1066ee('import xxx_no_such_module_xxx')
1067ee('import failing_import')
1068ee('import failing')
1069vim.options['rtp'] = old_rtp
1070del old_rtp
Bram Moolenaar8600e402013-05-30 13:28:41 +02001071cb.append("> Dictionary")
1072cb.append(">> DictionaryConstructor")
Bram Moolenaar841fbd22013-06-23 14:37:07 +02001073ee('vim.Dictionary("abcI")')
Bram Moolenaar8600e402013-05-30 13:28:41 +02001074##! Not checked: py_dict_alloc failure
1075cb.append(">> DictionarySetattr")
1076ee('del d.locked')
1077ee('d.locked = FailingTrue()')
1078ee('vim.vvars.locked = False')
1079ee('d.scope = True')
1080ee('d.xxx = True')
1081cb.append(">> _DictionaryItem")
1082ee('d.get("a", 2, 3)')
1083stringtochars_test('d.get(%s)')
1084ee('d.pop("a")')
1085ee('dl.pop("a")')
Bram Moolenaarba2d7ff2013-11-04 00:34:53 +01001086cb.append(">> DictionaryContains")
1087ee('"" in d')
1088ee('0 in d')
Bram Moolenaar8600e402013-05-30 13:28:41 +02001089cb.append(">> DictionaryIterNext")
1090ee('for i in ned: ned["a"] = 1')
Bram Moolenaar841fbd22013-06-23 14:37:07 +02001091del i
Bram Moolenaar8600e402013-05-30 13:28:41 +02001092cb.append(">> DictionaryAssItem")
1093ee('dl["b"] = 1')
1094stringtochars_test('d[%s] = 1')
1095convertfrompyobject_test('d["a"] = %s')
1096cb.append(">> DictionaryUpdate")
1097cb.append(">>> kwargs")
1098cb.append(">>> iter")
1099ee('d.update(FailingMapping())')
1100ee('d.update([FailingIterNext()])')
Bram Moolenaardee2e312013-06-23 16:35:47 +02001101iter_test('d.update(%s)')
Bram Moolenaar8600e402013-05-30 13:28:41 +02001102convertfrompyobject_test('d.update(%s)')
1103stringtochars_test('d.update(((%s, 0),))')
1104convertfrompyobject_test('d.update((("a", %s),))')
1105cb.append(">> DictionaryPopItem")
1106ee('d.popitem(1, 2)')
1107cb.append(">> DictionaryHasKey")
1108ee('d.has_key()')
1109cb.append("> List")
1110cb.append(">> ListConstructor")
1111ee('vim.List(1, 2)')
1112ee('vim.List(a=1)')
Bram Moolenaardee2e312013-06-23 16:35:47 +02001113iter_test('vim.List(%s)')
Bram Moolenaar8600e402013-05-30 13:28:41 +02001114convertfrompyobject_test('vim.List([%s])')
1115cb.append(">> ListItem")
1116ee('l[1000]')
1117cb.append(">> ListAssItem")
1118ee('ll[1] = 2')
1119ee('l[1000] = 3')
1120cb.append(">> ListAssSlice")
Bram Moolenaar841fbd22013-06-23 14:37:07 +02001121ee('ll[1:100] = "abcJ"')
Bram Moolenaardee2e312013-06-23 16:35:47 +02001122iter_test('l[:] = %s')
Bram Moolenaar8600e402013-05-30 13:28:41 +02001123convertfrompyobject_test('l[:] = [%s]')
1124cb.append(">> ListConcatInPlace")
Bram Moolenaardee2e312013-06-23 16:35:47 +02001125iter_test('l.extend(%s)')
Bram Moolenaar8600e402013-05-30 13:28:41 +02001126convertfrompyobject_test('l.extend([%s])')
1127cb.append(">> ListSetattr")
1128ee('del l.locked')
1129ee('l.locked = FailingTrue()')
1130ee('l.xxx = True')
1131cb.append("> Function")
1132cb.append(">> FunctionConstructor")
1133ee('vim.Function("123")')
1134ee('vim.Function("xxx_non_existent_function_xxx")')
1135ee('vim.Function("xxx#non#existent#function#xxx")')
1136cb.append(">> FunctionCall")
1137convertfrompyobject_test('f(%s)')
1138convertfrompymapping_test('fd(self=%s)')
1139cb.append("> TabPage")
1140cb.append(">> TabPageAttr")
1141ee('vim.current.tabpage.xxx')
1142cb.append("> TabList")
1143cb.append(">> TabListItem")
1144ee('vim.tabpages[1000]')
1145cb.append("> Window")
1146cb.append(">> WindowAttr")
1147ee('vim.current.window.xxx')
1148cb.append(">> WindowSetattr")
1149ee('vim.current.window.buffer = 0')
Bram Moolenaarca982c82013-05-31 19:01:16 +02001150ee('vim.current.window.cursor = (100000000, 100000000)')
Bram Moolenaar8600e402013-05-30 13:28:41 +02001151ee('vim.current.window.cursor = True')
Bram Moolenaardee2e312013-06-23 16:35:47 +02001152number_test('vim.current.window.height = %s', unsigned=True)
1153number_test('vim.current.window.width = %s', unsigned=True)
Bram Moolenaar8600e402013-05-30 13:28:41 +02001154ee('vim.current.window.xxxxxx = True')
1155cb.append("> WinList")
1156cb.append(">> WinListItem")
1157ee('vim.windows[1000]')
1158cb.append("> Buffer")
1159cb.append(">> StringToLine (indirect)")
Bram Moolenaardee2e312013-06-23 16:35:47 +02001160ee('vim.current.buffer[0] = u"\\na"')
Bram Moolenaar8600e402013-05-30 13:28:41 +02001161ee('vim.current.buffer[0] = "\\na"')
1162cb.append(">> SetBufferLine (indirect)")
1163ee('vim.current.buffer[0] = True')
Bram Moolenaar841fbd22013-06-23 14:37:07 +02001164cb.append(">> SetBufferLineList (indirect)")
Bram Moolenaar8600e402013-05-30 13:28:41 +02001165ee('vim.current.buffer[:] = True')
1166ee('vim.current.buffer[:] = ["\\na", "bc"]')
1167cb.append(">> InsertBufferLines (indirect)")
1168ee('vim.current.buffer.append(None)')
1169ee('vim.current.buffer.append(["\\na", "bc"])')
1170ee('vim.current.buffer.append("\\nbc")')
1171cb.append(">> RBItem")
Bram Moolenaarca982c82013-05-31 19:01:16 +02001172ee('vim.current.buffer[100000000]')
Bram Moolenaar8600e402013-05-30 13:28:41 +02001173cb.append(">> RBAsItem")
Bram Moolenaarca982c82013-05-31 19:01:16 +02001174ee('vim.current.buffer[100000000] = ""')
Bram Moolenaar8600e402013-05-30 13:28:41 +02001175cb.append(">> BufferAttr")
1176ee('vim.current.buffer.xxx')
1177cb.append(">> BufferSetattr")
1178ee('vim.current.buffer.name = True')
1179ee('vim.current.buffer.xxx = True')
1180cb.append(">> BufferMark")
1181ee('vim.current.buffer.mark(0)')
Bram Moolenaar841fbd22013-06-23 14:37:07 +02001182ee('vim.current.buffer.mark("abcM")')
Bram Moolenaar8600e402013-05-30 13:28:41 +02001183ee('vim.current.buffer.mark("!")')
1184cb.append(">> BufferRange")
1185ee('vim.current.buffer.range(1, 2, 3)')
1186cb.append("> BufMap")
1187cb.append(">> BufMapItem")
Bram Moolenaar8600e402013-05-30 13:28:41 +02001188ee('vim.buffers[100000000]')
Bram Moolenaardee2e312013-06-23 16:35:47 +02001189number_test('vim.buffers[%s]', natural=True)
Bram Moolenaar8600e402013-05-30 13:28:41 +02001190cb.append("> Current")
1191cb.append(">> CurrentGetattr")
1192ee('vim.current.xxx')
1193cb.append(">> CurrentSetattr")
1194ee('vim.current.line = True')
1195ee('vim.current.buffer = True')
1196ee('vim.current.window = True')
1197ee('vim.current.tabpage = True')
1198ee('vim.current.xxx = True')
Bram Moolenaar841fbd22013-06-23 14:37:07 +02001199del d
1200del ned
1201del dl
1202del l
1203del ll
1204del f
1205del fd
1206del fdel
1207del subexpr_test
1208del stringtochars_test
1209del Mapping
1210del convertfrompyobject_test
1211del convertfrompymapping_test
1212del iter_test
Bram Moolenaardee2e312013-06-23 16:35:47 +02001213del number_test
Bram Moolenaar841fbd22013-06-23 14:37:07 +02001214del FailingTrue
1215del FailingIter
1216del FailingIterNext
1217del FailingMapping
1218del FailingMappingKey
1219del FailingList
Bram Moolenaardee2e312013-06-23 16:35:47 +02001220del NoArgsCall
1221del FailingCall
1222del FailingNumber
Bram Moolenaar8600e402013-05-30 13:28:41 +02001223EOF
Bram Moolenaar841fbd22013-06-23 14:37:07 +02001224:delfunction F
Bram Moolenaar8600e402013-05-30 13:28:41 +02001225:"
Bram Moolenaara9f22202013-06-11 18:48:21 +02001226:" Test import
1227py << EOF
Bram Moolenaar9f3685a2013-06-12 14:20:36 +02001228sys.path.insert(0, os.path.join(os.getcwd(), 'python_before'))
1229sys.path.append(os.path.join(os.getcwd(), 'python_after'))
Bram Moolenaara9f22202013-06-11 18:48:21 +02001230vim.options['rtp'] = os.getcwd().replace(',', '\\,').replace('\\', '\\\\')
Bram Moolenaardee2e312013-06-23 16:35:47 +02001231l = []
1232def callback(path):
Bram Moolenaar877aa002013-06-26 21:49:51 +02001233 l.append(path[-len('/testdir'):].replace(os.path.sep, '/'))
Bram Moolenaardee2e312013-06-23 16:35:47 +02001234vim.foreach_rtp(callback)
1235cb.append(repr(l))
1236del l
1237def callback(path):
Bram Moolenaar877aa002013-06-26 21:49:51 +02001238 return path[-len('/testdir'):].replace(os.path.sep, '/')
Bram Moolenaardee2e312013-06-23 16:35:47 +02001239cb.append(repr(vim.foreach_rtp(callback)))
1240del callback
Bram Moolenaara9f22202013-06-11 18:48:21 +02001241from module import dir as d
1242from modulex import ddir
1243cb.append(d + ',' + ddir)
Bram Moolenaar9f3685a2013-06-12 14:20:36 +02001244import before
1245cb.append(before.dir)
1246import after
1247cb.append(after.dir)
Bram Moolenaardee2e312013-06-23 16:35:47 +02001248import topmodule as tm
1249import topmodule.submodule as tms
1250import topmodule.submodule.subsubmodule.subsubsubmodule as tmsss
Bram Moolenaar877aa002013-06-26 21:49:51 +02001251cb.append(tm.__file__.replace('.pyc', '.py').replace(os.path.sep, '/')[-len('modulex/topmodule/__init__.py'):])
1252cb.append(tms.__file__.replace('.pyc', '.py').replace(os.path.sep, '/')[-len('modulex/topmodule/submodule/__init__.py'):])
1253cb.append(tmsss.__file__.replace('.pyc', '.py').replace(os.path.sep, '/')[-len('modulex/topmodule/submodule/subsubmodule/subsubsubmodule.py'):])
Bram Moolenaar841fbd22013-06-23 14:37:07 +02001254del before
1255del after
1256del d
1257del ddir
Bram Moolenaardee2e312013-06-23 16:35:47 +02001258del tm
1259del tms
1260del tmsss
Bram Moolenaara9f22202013-06-11 18:48:21 +02001261EOF
Bram Moolenaarc09a6d62013-06-10 21:27:29 +02001262:"
Bram Moolenaar8600e402013-05-30 13:28:41 +02001263:" Test exceptions
1264:fun Exe(e)
1265: execute a:e
1266:endfun
1267py << EOF
Bram Moolenaara7b64ce2013-05-21 20:40:40 +02001268Exe = vim.bindeval('function("Exe")')
Bram Moolenaar841fbd22013-06-23 14:37:07 +02001269ee('vim.command("throw \'abcN\'")')
Bram Moolenaara7b64ce2013-05-21 20:40:40 +02001270ee('Exe("throw \'def\'")')
1271ee('vim.eval("Exe(\'throw \'\'ghi\'\'\')")')
1272ee('vim.eval("Exe(\'echoerr \'\'jkl\'\'\')")')
1273ee('vim.eval("Exe(\'xxx_non_existent_command_xxx\')")')
Bram Moolenaar9fee7d42013-11-28 17:04:43 +01001274ee('vim.eval("xxx_unknown_function_xxx()")')
Bram Moolenaara7b64ce2013-05-21 20:40:40 +02001275ee('vim.bindeval("Exe(\'xxx_non_existent_command_xxx\')")')
Bram Moolenaar841fbd22013-06-23 14:37:07 +02001276del Exe
1277EOF
1278:delfunction Exe
1279:"
Bram Moolenaard6b8a522013-11-11 01:05:48 +01001280:" Regression: interrupting vim.command propagates to next vim.command
1281py << EOF
1282def test_keyboard_interrupt():
1283 try:
1284 vim.command('while 1 | endwhile')
1285 except KeyboardInterrupt:
1286 cb.append('Caught KeyboardInterrupt')
1287 except Exception:
1288 cb.append('!!!!!!!! Caught exception: ' + repr(sys.exc_info))
1289 else:
1290 cb.append('!!!!!!!! No exception')
1291 try:
1292 vim.command('$ put =\'Running :put\'')
1293 except KeyboardInterrupt:
1294 cb.append('!!!!!!!! Caught KeyboardInterrupt')
1295 except Exception:
1296 cb.append('!!!!!!!! Caught exception: ' + repr(sys.exc_info))
1297 else:
1298 cb.append('No exception')
1299EOF
1300:debuggreedy
1301:call inputsave()
1302:call feedkeys("s\ns\ns\ns\nq\n")
1303:redir => output
1304:debug silent! py test_keyboard_interrupt()
1305:redir END
1306:0 debuggreedy
1307:silent $put =output
1308:unlet output
1309:py del test_keyboard_interrupt
1310:"
Bram Moolenaar841fbd22013-06-23 14:37:07 +02001311:" Cleanup
1312py << EOF
1313del cb
1314del ee
1315del sys
1316del os
1317del vim
Bram Moolenaara7b64ce2013-05-21 20:40:40 +02001318EOF
Bram Moolenaardb913952012-06-29 12:54:53 +02001319:endfun
1320:"
Bram Moolenaar841fbd22013-06-23 14:37:07 +02001321:fun RunTest()
1322:let checkrefs = !empty($PYTHONDUMPREFS)
1323:let start = getline(1, '$')
1324:for i in range(checkrefs ? 10 : 1)
1325: if i != 0
1326: %d _
1327: call setline(1, start)
1328: endif
1329: call Test()
1330: if i == 0
1331: let result = getline(1, '$')
1332: endif
1333:endfor
1334:if checkrefs
1335: %d _
1336: call setline(1, result)
1337:endif
1338:endfun
Bram Moolenaardb913952012-06-29 12:54:53 +02001339:"
Bram Moolenaar841fbd22013-06-23 14:37:07 +02001340:call RunTest()
1341:delfunction RunTest
1342:delfunction Test
Bram Moolenaardb913952012-06-29 12:54:53 +02001343:call garbagecollect(1)
1344:"
1345:/^start:/,$wq! test.out
Bram Moolenaardee2e312013-06-23 16:35:47 +02001346:" vim: et ts=4 isk-=\:
Bram Moolenaar66b79852012-09-21 14:00:35 +02001347:call getchar()
Bram Moolenaardb913952012-06-29 12:54:53 +02001348ENDTEST
1349
1350start: