Running tests from a module

I am trying to run some unit tests in python from what I think is a module. I have a directory structure like

TestSuite.py
UnitTests
  |__init__.py
  |TestConvertStringToNumber.py

      

In testsuite.py I have

import unittest

import UnitTests

class TestSuite:
    def __init__(self):
        pass

print "Starting testting"
suite = unittest.TestLoader().loadTestsFromModule(UnitTests)
unittest.TextTestRunner(verbosity=1).run(suite)

      

Who wants to start testing but it doesn't pick up any test cases in TestConvertNumberToString.py. In this class, I have a set of functions that start with 'test'.

What should I do to get python TestSuite.py to actually start all my tests in UnitTests?

+2


source to share


2 answers


Here's some code that will run all the unit tests in the directory:

#!/usr/bin/env python
import unittest
import sys
import os

unit_dir = sys.argv[1] if len(sys.argv) > 1 else '.'
os.chdir(unit_dir)
suite = unittest.TestSuite()
for filename in os.listdir('.'):
    if filename.endswith('.py') and filename.startswith('test_'):
        modname = filename[:-2]
        module = __import__(modname)
        suite.addTest(unittest.TestLoader().loadTestsFromModule(module))

unittest.TextTestRunner(verbosity=2).run(suite)

      



If you call it testuite.py, you run it like this:

testsuite.py UnitTests

      

+4


source


Using Twisted "trial" test runner, you can get rid of TestSuite.py and simply do:

$ trial UnitTests.TestConvertStringToNumber

      

on the command line; or better yet, just



$ trial UnitTests

      

to discover and run all tests in the package.

0


source







All Articles