The last post we’ve shared included setting up & using Vim for Python/Django-related development. I’ll assume throughout the guide that you’ve been using Vim ever since (Vim is amazing :)).
Well, let me add up another helpful tutorial on how to use vim, this time for your unit tests. We’ll also tackle a very helpful plugin for vim that will make testing easier for you and me. So, let’s begin, shall we?
First of all, we should get ready and prepare all the necessary stuff to get us going. We would need to install Nose, a unit testing framework for Python. It will supply us with the helpful nosetests command that will detect all the tests in the current directory and run them.
To install Nose:
$ sudo apt-get install python-nose
or if you are in Mac OS X:
$ sudo easy_install nose
If you don’t want to use Nose, you can still make your own python script that can do the job for you.
After Nose is installed, we would need a compiler which will tell vim what program to run and parse the output to detect errors. You can download that here.
Next, we’ll put a little color in vim by installing a plugin called vim-makegreen made by ReinH. This plugin will highlight the code with red or green that will tell if the code passed or failed, which is extremely helpful when you’re out trying to test big chunks of code. Download vim-makegreen at git.
The next thing we do, after we’ve installed nose and downloaded the files, is to have vim use them. I’ll detail the instructions below on how to do that.
- Extract the compiler and put the compiler folder in your .vim folder (Create it if it does not exist yet)
- Make sure nose.vim is in the compiler folder
- Put makegreen.vim in the plugin folder of .vim
Once that is done, we’re all set!
Using the Tools
Go to your work environment, and open up the folder that contains your test codes (tests.py). Activate vim, and type in the code below:
$ :compiler nose$ :make
The first line tells vim which program to run, and the second one will run nosetests that will detect all the tests and show us if there are any errors in any of the code.
If you’ve done everything right, you’ll see the lines of code from your unit tests and tells you the errors if there are any. Now, to make use of our makegreen plugin, type in:
That will give you a nice highlight bar of green or reds depending if the code passed or not.
There are a lot of tools available for unit testing with vim on Django development, and this is just one of them. Hopefully, you’ll find this useful and apply it to your daily Vimming needs.