created February 18, 2004 · complexity basic · author Max Ischenko · version 6.0
Doing a lot of programming in Python, I need to switch quickly between Python module and corresponding unit-test module. Often there is one unit-testing module for multiple python modules.
This function allows you to switch to correct unit testing module quickly, using the filename hardcoded at the end of the file. Idea is stolen from Twisted sources.
Put this to your ftplugin/python.vim:
nmap <buffer> <F5> :call JumpToTestFile()<CR> fun! JumpToTestFile() let line = getline("$") if line =~ "^### testfile: " let filename = strpart(line, 14) execute ":e " . filename else echo "TEST PATTERN ### testfile: NOT FOUND!" endif endfun
Fix indents in following, and combine/clean.
I created this general purpose script (some may disagree since I dropped down to python scripting; sorry, just don't have time to hunt through docs for vim script info!) ... but if you have python compiled in with your vim, and happen to use a test framework, this with very little tweaking may help.
I generally have a 1:1 correspondence between modules and test scripts, so this approach saves me having to put test file names in my source.
inoremap <M-t> <ESC>:call UTestToggle()<CR> nnoremap <M-t> :call UTestToggle()<CR> function! UTestToggle() python << EOF # toggles between a path like: /myproject/person.py and /myproject/test/utest_person.py # could mkdir the 'test' directory if not exists, but chances are the user will # be doing that outside of vim anyway. import vim from os import path UTEST_PREFIX='test/utest_' curfile = vim.current.buffer.name if curfile: if UTEST_PREFIX in curfile: # switch to the matching source vim.command('e %s' % curfile.replace(UTEST_PREFIX, '')) else: # switch to the matching utest_filename.py|qpy filepath, filename = path.split(curfile) vim.command('e %s' % path.join(filepath, UTEST_PREFIX+filename)) EOF endfunction
Minor change, my fault for not testing it a bit. This rev switches to a buffer if the file is already in vim's buffer list, rather than calling the edit command. Was seeing instances where unsaved changes were lost. Note: vim complains about free() when I run this; gvim doesn't appear to, although that may just be surpressed output.
# first try to load from buffer for buf in vim.buffers: if target == buf.name: vim.command('b!%s' % buf.number) return # must not be in buffers, open file vim.command('e! %s' % target) return
curfile = vim.current.buffer.name if curfile:
if UTEST_PREFIX in curfile: # switch to the matching source edit(curfile.replace(UTEST_PREFIX, )) else: # switch to the matching utest_filename.py|qpy filepath, filename = path.split(curfile) edit(path.join(filepath, UTEST_PREFIX+filename))