2

I am attempting to run some unit tests in python from what I believe 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)

Which looks to kick off the testing okay but it doesn't pick up any of the test in TestConvertNumberToString.py. In that class I have a set of functions which start with 'test'.

What should I be doing such that running python TestSuite.py actually kicks off all of my tests in UnitTests?

2 Answers 2

4

Here is some code which will run all the unit tests in a 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 testsuite.py, then you would run it like this:

testsuite.py UnitTests
Sign up to request clarification or add additional context in comments.

1 Comment

Beautiful, thanks. It was the import function I was missing
0

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

$ trial UnitTests.TestConvertStringToNumber

on the command line; or, better yet, just

$ trial UnitTests

to discover and run all tests in the package.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.