Last Updated: February 25, 2016
·
7.354K
· wandhydrant

Running a specific test in python with nose

This tip comes in handy when doing TDD or fixing a failing test in a fairly large project where running the complete test suite can take some time.

Let's pretend we want to test some methods of datetime.date and datetime.time.

Our project has this directory structure:

root-dir/
  test/
    __init__.py
    test_date.py
    test_time.py

The content of the two test modules is as follows:

# test/test_date.py
import unittest
from datetime import date

class DateTestCase(unittest.TestCase):
    def test_isoformat(self):
        d = date(2014, 5, 2)

        self.assertEqual(d.isoformat(), "2014-05-02")

    def test_isoweekday(self):
        d = date(2014, 5, 2)

        self.assertEqual(d.isoweekday(), 5)
# test/test_time.py
import unittest
from datetime import time

class TimeTestCase(unittest.TestCase):
    def test_isoformat(self):
        t = time(12, 30, 30, 0)

        self.assertEqual(t.isoformat(), "12:30:30")

You can now do this from your command line:

# execute all tests (test_date and test_time)
$ nosetests
# execute all test cases in module test_date (DateTestCase.test_isoformat and DateTestCase.test_isoweekday)
$ nosetests test.test_date
# execute all test methods of DateTestCase (test_isoformat and test_isoweekday)
$ nosetests test.test_date:DateTestCase
# execute only one test method of DateTestCase (test_isoformat)
$ nosetests test.test_date:DateTestCase.test_isoformat