File:  [CENS] / python / pyGiNaC / test / runtests
Revision 1.3: download - view: text, annotated - select for diffs - revision graph
Thu Mar 15 13:48:35 2001 UTC (16 years, 8 months ago) by pearu
Branches: MAIN
CVS tags: HEAD
Major revision, now more explicit wrapping

#!/usr/bin/env python
# -*- Python -*-
'''
UnitTest runner

Usage:
    > python runtests.py               # run tests for all *.tst files
    > python runtests.py <*.tst files>

<filename>.tst is read line by line. The following line patterns are
used for testing:

    <varname> = <Python expression>
    
    <Python expression> :: <Expected result of str(Python expression)>

    `<Python expression> :: <Expected result of repr(Python expression)>

Features:
    All other lines are ignored. "#" is a comment
    character. White-spaces are ignored (actually they are **removed**.
    Therefore testing string outputs is not exact).  All errorness
    lines are ignored. When defining the same <varname> multiple
    times, only the last instance is used in **all** tests.
    If <Python expression> starts with "!" then what follows is treated
    as Python statement (but "::" is still needed, result is then "").

Special <varnames>: module,result,string,check*,setUp,test.
Avoid these in *.tst files, except module which is mandatory.

To specify your module, use

    module = __import__('<module name to be tested>')

It is used as "from <module name to be tested> import *" for all test
lines. If import fails, the testing will be terminated.

Examples:
    module = __import__('symbolic')
    a = 5
    a+5 :: 10               # passed
    a+5 :: 11               # reported as failure
    "ab" + "c" :: abc       # passed
    s = "a c"
    s :: a c                # passed
    s :: ac                 # passed (read above about whitespaces)
    l = [1,2]
    ! l[0] = 3 ::
    l :: [3,2]
    ! del l[0] ::
    l :: [2]

Credits to
    Steve Purcell, the author of PyUnit (see http://pyunit.sourceforge.net/)

Copyright 2000 Pearu Peterson all rights reserved,
Pearu Peterson <pearu@cens.ioc.ee>          
Permission to use, modify, and distribute this software is given under the
terms of the LGPL.  See http://www.fsf.org

NO WARRANTY IS EXPRESSED OR IMPLIED.  USE AT YOUR OWN RISK.
$Revision: 1.3 $
$Date: 2001-03-15 13:48:35 $
Pearu Peterson
'''

__version__ = "$Id: runtests,v 1.3 2001-03-15 13:48:35 pearu Exp $"

import sys,os,string,re,traceback
import unittest            # get it from http://pyunit.sourceforge.net/

verbose = 0

class TestCase(unittest.TestCase):
    global verbose
    def setUp(self):
        self.sys = sys
        for n in dir(TestCase):
            if n[0]=='_': continue
            if n[:5]=='check': continue
            if n[:5]=='setUp': continue
            exec 'self.%s = TestCase.%s'%(n,n)
        self.string = string
        tb = ''
        if verbose: tb = 'traceback.print_exc()'
        self.test = 'exec "import traceback\\ntry: result = str(%s)\\nexcept: result=sys.exc_type.__name__+\',\'+str(sys.exc_value);'+tb+'" in self.module.__dict__,self.__dict__;r = self.result.replace(\' \',\'\')'
        self.exetest = 'exec "import traceback\\nresult=\\"\\"\\ntry: %s\\nexcept: result=sys.exc_type.__name__+\',\'+str(sys.exc_value);'+tb+'" in self.module.__dict__,self.__dict__;r = self.result.replace(\' \',\'\')'

def suite(fn):
    print
    print string.center('--> Running unittest on file %s <--'%`fn`,70)
    print
    assert type(fn)==type('')
    suite = unittest.TestSuite()
    i = 0
    f = open(fn,'r')
    l = f.readline()
    while l:
        i+=1
        ol = l
        if '#' in l: l = l[:string.find(l,'#')]
        l = string.strip(l)
        if not l:
            l = f.readline()
            continue

        if not l.count('::'):
            if l.count('=')==1 and l[0]!='!':
                try:
                    if hasattr(TestCase,'module'):
                        exec l in TestCase.module.__dict__,TestCase.__dict__
                    else:
                        exec l in TestCase.__dict__
                except ImportError:
                    print 'E: Break L#%s: %s'%(i,ol[:-1])
                    print '   %s: %3s'%(sys.exc_type.__name__,sys.exc_value)
                    break
                except:
                    print 'E: Break L#%s: %s'%(i,ol[:-1])
                    print '   %s: %3s'%(sys.exc_type.__name__,sys.exc_value)
                    break
            else:
                print 'W: Skip L#%3s: %s'%(i,ol[:-1])
            l = f.readline()
            continue
        e,x = map(string.strip,string.split(l,'::',1))
        x = string.replace(x,' ','')
        for (o,r) in [(r'"',r'\"'),(r"'",r'\"')]:
            e = string.replace(e,o,r)
        if e[0]=='`' and e[-1]!='`':
            e = e + '`'
        if e[0]=='!':
            e = e[1:].lstrip()
            exec 'def check_line_no_%s(self):\n\texec self.exetest%%(%s)\n\tassert r==%s,"""expected %s but got %%s from %s"""%%(`r`)\n'%(i,`e`,`x`,`x`,`e`)
        else:
            exec 'def check_line_no_%s(self):\n\texec self.test%%(%s)\n\tassert r==%s,"""expected %s but got %%s from %s"""%%(`r`)\n'%(i,`e`,`x`,`x`,`e`)
        exec 'TestCase.check%s = check_line_no_%s'%(i,i)
        suite.addTest(TestCase("check%s"%i))
        l = f.readline()
    f.close()
    return suite


if __name__ == "__main__":
    args = sys.argv[1:]
    if '-v' in args:
        verbose = 1
        del args[args.index('-v')]
    for fn in args:
        if os.path.isfile(fn):
            unittest.TextTestRunner().run(suite(fn))
    if not args:
        import glob
        for fn in glob.glob('*.tst'):
            unittest.TextTestRunner().run(suite(fn))

FreeBSD-CVSweb <freebsd-cvsweb@FreeBSD.org>