Testing your code is nearly a requirement (even more so in Ruby). Unittests are now the most vital elements for evaluating the quality/viability of a project.
I was a little jealous of Ruby where you don’t have so much to write to implement unittests. Here is a simple example:
require "mymodule" require "test/unit" class TestMyModule < Test::Unit::TestCase def test_simple assert_equal(1, 1 ) end end
Now, using Nose, you can get even shorter code. If you do standard Python projects, you’ll use a setup.py file. To use nose, you do not even need to specify the path where to find the tests, just add two lines (tests_require and test_suite) to call nosetest:
from setuptools import setup, find_packages import sys, os import mymodule version = mymodule.__version__ setup(name='myproject', version=version, description="Module to display blah blah blah.", long_description=""" """, classifiers=, # Get strings from http://pypi.python.org/pypi?%3Aaction=list_classifiers keywords='mymodule foobar', author='Toto tester', email@example.com', url='', license='GPL', packages=find_packages(exclude=['ez_setup', 'examples', 'tests']), include_package_data=True, tests_require='nose', test_suite='nose.collector', zip_safe=False, install_requires=[ # -*- Extra requirements: -*- 'simplejson', ], entry_points=""" # -*- Entry points: -*- [console_scripts] mymodule = mymodule.mainmodule:main """, )
Now, to add tests, you just have to create a directory named tests (in the root of your project, where your setup.py resides, and then add a python file()s. No need to add a __init__.py to set the directory as a module. Now just add simple python files, like my-tests.py :
import mymodule class TestAstInfoCli(object): def setup(self): pass def teardown(self): pass def test_annuaire_inverse(self): assert 1 == 1
As you can see, no need to import anything for doing unittests, not even the standard python unittest module! That’s better than ruby! The downside of this is that nose is an ‘external’ package, so you’ll have to install it first (or set it as a dependency in your setup.py file, as shown above).
If you don’t use a setup.py, you can call nose directly from the command line, with ‘nosetest’.
Now, let’s find an equivalent to the really cool rspec ruby module!