Vim Tips Wiki
m (Corrected typo.)
(Change <tt> to <code>, perhaps also minor tweak.)
 
(14 intermediate revisions by 7 users not shown)
Line 2: Line 2:
 
|id=280
 
|id=280
 
|previous=279
 
|previous=279
|next=281
+
|next=282
|created=July 10, 2002
+
|created=2002
 
|complexity=intermediate
 
|complexity=intermediate
|author=Stefan Roemer, Max Ischenko, Pete Johns
+
|author=Stefan Roemer, Max Ischenko
 
|version=6.2
 
|version=6.2
 
|rating=86/23
 
|rating=86/23
Line 11: Line 11:
 
|category2=Integration
 
|category2=Integration
 
|category3=Python
 
|category3=Python
|category4=PyUnit
 
 
}}
 
}}
 
Vim has a wonderful ability to integrate with external tools, like compilers, make, ctags, etc. That's one of the reasons we love it. PyUnit can be seen as a "compiler" for Python code.
   
  +
Doing
Vim has a wonderful ability to integrate with external tools, like compilers, make, ctags, etc... That's one of the reasons we love it.
 
  +
<pre>
 
 
:compiler pyunit
PyUnit can be seen as a "compiler" for Python code. Setting the compiler to 'pyunit' will set the errorformat for PyUnit, enabling Vim to parse unittest.TextRunner's output and to enter quick-fix mode.
 
  +
</pre>
 
To run all your unit tests at once you'll need to set the 'makeprg' option and provide a runner.
 
   
  +
will set the <code>'errorformat'</code> option for PyUnit, enabling Vim to parse a <code>unittest</code> test runner's output and to enter quickfix mode.
This is often done using an ''alltests.py'' script.
 
   
 
To run all your unit tests at once, using Vim's <code>:make</code> command, you'll need to set the <code>'makeprg'</code> option and provide a test runner. This is often done using an <code>alltests.py</code> script.
 
<pre>
 
<pre>
setlocal makeprg=./alltests.py
+
:setlocal makeprg=./alltests.py
 
</pre>
 
</pre>
   
Contents of the alltests.py (for the sake of completeness):
+
Here is an example <code>alltests.py</code>:
 
<pre>
 
<pre>
 
#!/usr/bin/env python2
 
#!/usr/bin/env python2
Line 49: Line 49:
 
</pre>
 
</pre>
   
Here is an alternative ''alltests.py'':
+
Here is an alternative <code>alltests.py</code>:
 
<pre>
 
<pre>
 
#!/usr/bin/env python
 
#!/usr/bin/env python
#
+
#
 
# This script is based on the one found at http://vim.wikia.com/wiki/VimTip280
 
# This script is based on the one found at http://vim.wikia.com/wiki/VimTip280
 
# but has been generalised. It searches the current working directory for
 
# but has been generalised. It searches the current working directory for
# t_*.py or test_*.py files and runs each of the unit-tests found within.
+
# *_test.py (good) or test_*.py (bad) files and runs each of the unit-tests
  +
# found within.
 
#
 
#
# When run from within Vim as its 'makeprg' with the correct 'errorformat' set,
+
# When run from within Vim as its 'makeprg' with the correct 'errorformat' set
# any failure will deliver your cursor to the first line that breaks the unit
+
# (by setting ":compiler pyunit"), any failure will deliver your cursor to the
# tests.
+
# line that breaks the unit tests.
 
#
 
#
 
# Place this file somewhere where it can be run, such as ${HOME}/bin/alltests.py
 
# Place this file somewhere where it can be run, such as ${HOME}/bin/alltests.py
#
 
   
import unittest, sys, os, re
+
import unittest, sys, os, re, traceback
   
 
def find_all_test_files():
 
def find_all_test_files():
t_py_re = re.compile('^t(est)?_.*\.py$')
+
t_py_re = re.compile('^(test_.*|.*_test)\.py$')
is_test = lambda filename: t_py_re.match(filename)
+
is_test = lambda filename: t_py_re.match(filename)
drop_dot_py = lambda filename: filename[:-3]
+
drop_dot_py = lambda filename: filename[:-3]
return [drop_dot_py(module) for module in filter(is_test, os.listdir(os.curdir))]
+
return [drop_dot_py(module) for module in
  +
filter(is_test, os.listdir(os.getcwd()))]
 
   
 
def suite():
 
def suite():
sys.path.append(os.curdir)
+
sys.path.append(os.curdir)
  +
modules_to_test = find_all_test_files()
 
modules_to_test = find_all_test_files()
+
print 'Testing', ', '.join(modules_to_test)
  +
alltests = unittest.TestSuite()
print 'Testing', ', '.join(modules_to_test)
 
 
for module in map(__import__, modules_to_test):
 
alltests = unittest.TestSuite()
+
alltests.addTest(unittest.findTestCases(module))
 
return alltests
for module in map(__import__, modules_to_test):
 
alltests.addTest(unittest.findTestCases(module))
 
 
return alltests
 
   
 
if __name__ == '__main__':
 
if __name__ == '__main__':
  +
try:
 
unittest.main(defaultTest='suite')
 
unittest.main(defaultTest='suite')
  +
except SystemExit:
  +
pass
  +
except:
  +
# we reverse the Exception/Traceback printout order so vim's
  +
# quickfix works properly
  +
exceptionType, exceptionValue, exceptionTraceback = sys.exc_info()
  +
  +
sys.stderr.write("Exception:\n")
  +
ex = traceback.format_exception_only(exceptionType, exceptionValue)
  +
for line in ex:
  +
sys.stderr.write(line)
  +
  +
sys.stderr.write("\nTraceback (most recent call first):\n")
  +
tb = traceback.format_tb(exceptionTraceback)
  +
for line in reversed(tb):
  +
sys.stderr.write(line)
   
 
</pre>
 
</pre>
   
  +
To have Vim automatically use these settings for all Python files, add the following to <code>~/.vim/after/ftplugin/python.vim</code> (<code>$HOME\vimfiles\after\ftplugin\python.vim</code> on Windows)
A sample ''~/.vim/ftplugin/python.vim'' looks like this:
 
   
 
<pre>
 
<pre>
" A Vim filetype plugin to set up PyUnit as the 'compiler' for python files.
+
" Additions to Vim's filetype plugin for Python, to set up PyUnit as
  +
" the 'compiler' for Python files.
   
" This sets up the errorformat...
+
" Set the errorformat.
 
compiler pyunit
 
compiler pyunit
   
" Set the 'makeprg', this allows you to call :make on any .py file and run all
+
" Set 'makeprg': this allows you to call :make on any .py file and
" of the unit tests in the current working directory
+
" run all of the unit tests in the current working directory.
" Ensure you have this file...
+
" Ensure you have this file.
 
setlocal makeprg=${HOME}/bin/alltests.py
 
setlocal makeprg=${HOME}/bin/alltests.py
  +
</pre>
   
 
==References==
" Some useful abbreviations when writing unit tests in Python...
 
 
*{{help|'efm'}}
 
*{{help|'makeprg'}}
  +
*{{help|compiler-pyunit}}
 
*{{help|quickfix}}
 
*http://c2.com/cgi/wiki?PythonUnit
  +
  +
==Comments==
 
The following abbreviations are useful when writing unit tests in Python.
  +
<pre>
 
iabbr <buffer> sa_ self.assert_
 
iabbr <buffer> sa_ self.assert_
 
iabbr <buffer> sae self.assertEquals
 
iabbr <buffer> sae self.assertEquals
Line 112: Line 137:
 
</pre>
 
</pre>
   
  +
----
==References==
 
  +
I don't think the abbreviations belong in this tip. They are not ''on topic'' and may be distracting. ([[User:Spiiph|Spiiph]] 10:48, 3 August 2009 (UTC))
 
*{{help|'efm'}}
 
*{{help|'makeprg'}}
 
*{{help|compiler-pyunit}}
 
*{{help|quickfix}}
 
*http://c2.com/cgi/wiki?PythonUnit
 
   
  +
There are no tips really suitable for holding the iabbr info; following are slightly plausible candidates. Meanwhile, I have moved the abbreviations to the comments section where they are less intrusive. [[User:JohnBeckett|JohnBeckett]] 03:20, 4 August 2009 (UTC)
[[User:PeteJohns|PeteJohns]] 04:33, 1 January 2009 (UTC)
 
  +
*[[VimTip610|610 Use abbreviations for frequently-used words]]
  +
*[[VimTip709|709 Simple creation of scripts]]
  +
*[[VimTip778|778 Speed up Python coding]]
  +
*[[VimTip1041|1041 Snippets for JavaScript, HTML and Python]]

Latest revision as of 05:22, 13 July 2012

Tip 280 Printable Monobook Previous Next

created 2002 · complexity intermediate · author Stefan Roemer, Max Ischenko · version 6.2


Vim has a wonderful ability to integrate with external tools, like compilers, make, ctags, etc. That's one of the reasons we love it. PyUnit can be seen as a "compiler" for Python code.

Doing

:compiler pyunit

will set the 'errorformat' option for PyUnit, enabling Vim to parse a unittest test runner's output and to enter quickfix mode.

To run all your unit tests at once, using Vim's :make command, you'll need to set the 'makeprg' option and provide a test runner. This is often done using an alltests.py script.

:setlocal makeprg=./alltests.py

Here is an example alltests.py:

#!/usr/bin/env python2
import unittest
import sys
sys.path.append('unittests')

modules_to_test = (
'fooTest',
'barTest',
'bazTest',
)

def suite():
  alltests = unittest.TestSuite()
  for module in map(__import__, modules_to_test):
    alltests.addTest(unittest.findTestCases(module))
  return alltests

if __name__ == '__main__':
  unittest.main(defaultTest='suite')

Here is an alternative alltests.py:

#!/usr/bin/env python
#
# This script is based on the one found at http://vim.wikia.com/wiki/VimTip280
# but has been generalised. It searches the current working directory for
# *_test.py (good) or test_*.py (bad) files and runs each of the unit-tests
# found within.
#
# When run from within Vim as its 'makeprg' with the correct 'errorformat' set
# (by setting ":compiler pyunit"), any failure will deliver your cursor to the
# line that breaks the unit tests.
#
# Place this file somewhere where it can be run, such as ${HOME}/bin/alltests.py

import unittest, sys, os, re, traceback

def find_all_test_files():
    t_py_re = re.compile('^(test_.*|.*_test)\.py$')
    is_test = lambda filename: t_py_re.match(filename)
    drop_dot_py = lambda filename: filename[:-3]
    return [drop_dot_py(module) for module in
            filter(is_test, os.listdir(os.getcwd()))]

def suite():
    sys.path.append(os.curdir)
    modules_to_test = find_all_test_files()
    print 'Testing', ', '.join(modules_to_test)
    alltests = unittest.TestSuite()
    for module in map(__import__, modules_to_test):
	alltests.addTest(unittest.findTestCases(module))
    return alltests

if __name__ == '__main__':
    try:
        unittest.main(defaultTest='suite')
    except SystemExit:
        pass
    except:
        # we reverse the Exception/Traceback printout order so vim's
        # quickfix works properly
        exceptionType, exceptionValue, exceptionTraceback = sys.exc_info()

        sys.stderr.write("Exception:\n")
        ex = traceback.format_exception_only(exceptionType, exceptionValue)
        for line in ex:
            sys.stderr.write(line)

        sys.stderr.write("\nTraceback (most recent call first):\n")
        tb = traceback.format_tb(exceptionTraceback)
        for line in reversed(tb):
            sys.stderr.write(line)

To have Vim automatically use these settings for all Python files, add the following to ~/.vim/after/ftplugin/python.vim ($HOME\vimfiles\after\ftplugin\python.vim on Windows)

" Additions to Vim's filetype plugin for Python, to set up PyUnit as
" the 'compiler' for Python files.

" Set the errorformat.
compiler pyunit

" Set 'makeprg': this allows you to call :make on any .py file and
" run all of the unit tests in the current working directory.
" Ensure you have this file.
setlocal makeprg=${HOME}/bin/alltests.py

References[]

Comments[]

The following abbreviations are useful when writing unit tests in Python.

iabbr <buffer> sa_ self.assert_
iabbr <buffer> sae self.assertEquals
iabbr <buffer> saf self.assertFalse
iabbr <buffer> san self.assertNotEquals
iabbr <buffer> sar self.assertRaises
iabbr <buffer> sat self.assertTrue

I don't think the abbreviations belong in this tip. They are not on topic and may be distracting. (Spiiph 10:48, 3 August 2009 (UTC))

There are no tips really suitable for holding the iabbr info; following are slightly plausible candidates. Meanwhile, I have moved the abbreviations to the comments section where they are less intrusive. JohnBeckett 03:20, 4 August 2009 (UTC)