原 文: http://www.vim.org/tips/tip.php?tip_id=280 翻 译: huangyi yi.codeplayer@gmail.com 修 订: 更新日期: 2006-5-18 VimTip 280: 整合PyUnit测试框架 -------------------------------- Vim拥有优秀的整合外部工具的能力,比如编译器、make、ctags等等。 这也是我们喜欢它的原因之一。 PyUnit可以被看做是一个Python测试代码的“编译器”。 要让vim理解它,我们应该先告诉Vim PyUnit所使用的语言。我们可以通过设置“errorformat”选项来做到这一点: setlocal efm=%C\ %.%#,%A\ \ File\ \"%f\"\\,\ line\ %l%.%#,%Z%[%^\ ]%\\@=%m 这段魔术一般的字母使Vim得以解析unittest.TextRunner的输出并进入 quick-fix 模式。 要想一次性运行所有单元测试的话,你需要设置“makeprg”选项并提供一个runner。 我目前使用的设置是这样的: setlocal makeprg=./alltests.py alltests.py (for the sake of completeness) 的内容是: #!/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') ============== end of the alltests.py file ======================== 谈到这个的时候,我想再推荐一些映射。 我的 vim/files/ftplugin/python.vim 文件的结尾部分是这样写的: setlocal makeprg=./alltests.py\ -q setlocal efm=%C\ %.%#,%A\ \ File\ \"%f\"\\,\ line\ %l%.%#,%Z%[%^\ ]%\\@=%m iabbr sae self.assertEquals iabbr sar self.assertRaises 更多细节请参看 :help quick-fix, :help 'efm' 和 :help 'makeprg'。 See also: http://c2.com/cgi/wiki?PythonUnit Many thanks to Stefan Roemer who patiently spent quite some time to build 'efm' for me.