How do you do unittest?

Tom Plunket tomas at fancy.org
Fri Aug 1 13:56:59 EDT 2003


Will Stuyvesant wrote:

> ----------------------- test.bat ------------------------
> cd test
> test_mod.py
> cd ..
> ---------------------------------------------------------

Could you do simply "test/test_mod.py" ?  Then the current
directory would still be the "main" directory.  Not sure how
Python handles the paths in a case like this though.

> I guess the author of PiaN does not use a 'test' subdirectory 
> himself, as it is now the example 17-2 does only work in the 
> source directory.

I just have all of my test_*.py files and my main test.py in the
main source folder.  My test.py automatically runs all of the
tests that exist, I have to thank this group for getting me down
the right path.

(The 'Directory' stuff is because my unittests create lots of
files.  It's a work-in-progress.  RunTests() is the function most
relevant to this discussion.)

---- test.py ----

import unittest
import os, sys

def SetupDirectory(name):
    testDir = os.environ['TESTING_DIRECTORY']
    testDir = os.path.join(testDir, name)

    if not os.path.exists(testDir):
        os.mkdir(testDir)

    os.chdir(testDir)                
    
def PruneDirectory(dir):
    files = os.listdir(dir)

    for f in files:
        fullpath = os.path.join(dir, f)

        if os.path.isfile(fullpath):
            os.remove(fullpath)
        elif os.path.isdir(fullpath):
            PruneDirectory(fullpath)

    os.rmdir(dir)

def CreateTempDirectory():
#    testDir = os.environ['TEMP']
#    testDir = os.path.join(testDir, 'filefiend_test')
    testDir = os.path.join(os.getcwd(), 'testdata')

    if os.path.exists(testDir):
        PruneDirectory(testDir)

    os.mkdir(testDir)
    os.environ['TESTING_DIRECTORY'] = testDir

def RemoveTempDirectory():
    testDir = os.environ['TESTING_DIRECTORY']
    os.chdir(os.path.join(testDir, os.pardir))
    PruneDirectory(testDir)

def RunTests():
    files = os.listdir(os.curdir)
    names = []
    for file in files:
        if file[:5] == "test_" and file[-3:] == os.extsep+"py":
            names.append(file[:-3])

    CreateTempDirectory()

    suite = unittest.defaultTestLoader.loadTestsFromNames(names)
    runner = unittest.TextTestRunner(verbosity=1)
    result = runner.run(suite)

    RemoveTempDirectory()

#    raw_input("\n<Enter> to continue.\n")
    sys.exit(not result.wasSuccessful())


if __name__ == "__main__":
    RunTests()

-tom!

-- 
There's really no reason to send a copy of your
followup to my email address, so please don't.




More information about the Python-list mailing list