如何运行一组Python单元测试

时间:2014-07-08 20:56:23

标签: python unit-testing

我正在使用Bash脚本运行一组单元测试。什么是更普遍的Pythonic方式呢?

假设我无法改变单元测试,那么最好的Pythonic方式是什么?

运行所有测试的Bash脚本如下:

#!/bin/bash

function PJTUnitTests () {
    exitCode=0
    for test in $(ls PACKAGE_DIRECTORY/test/test_transform.py PACKAGE_DIRECTORY/test/test_trf*.py); do
        name=$(basename $test)
        echo "running ${name}"
        ${test} &> ${name}.test
        if [ $? != "0" ]; then 
           echo "$(date) "${test}" failed" | tee -a test.fail
           exitCode=1
        else
        echo "$(date) ${test} ok" | tee -a test.ok
        fi
    done
    if [ $exitCode != "0" ]; then
        echo "At least one test failed -- see summary file test.fail for details."
    else
        echo "All tests passed."
    fi
}

PJTUnitTests

代表性的单元测试如下:

import json
import subprocess
import os
import os.path
import sys
import unittest

from PACKAGE.MODULE1 import msg

class Echotest(unittest.TestCase):

    def test_runEcho(self):
        cmd = ['Echo_1.py']
        cmd.extend(['--testInt', '1234'])
        cmd.extend(['--testFloat', '-1.212'])
        cmd.extend(['--testIntList', '1,2,3,4,5,6'])
        cmd.extend(['--testSubstepList', 'all:juice', 'jane:apple', 'bob:orange', 'alice:pear'])
        cmd.extend(['--testSubstepInt', 'all:34', 'jane:1', 'bob:2', 'alice:-3'])
        cmd.extend(['--testSubstepBool', 'all:True', 'jane:false', 'bob:tRuE', 'alice:FaLse'])
        msg.info('Will run this transform: {0}'.format(cmd))
        p = subprocess.Popen(cmd, shell = False, stdout = subprocess.PIPE, stderr = subprocess.STDOUT, bufsize = 1)
        while p.poll() is None:
            line = p.stdout.readline()
            sys.stdout.write(line)
        # Hoover up remaining buffered output lines.
        for line in p.stdout:
            sys.stdout.write(line)
        self.assertEqual(p.returncode, 0)

        # Now load metadata and test a few important values.
        with open('jobReport.json') as jr:
            md = json.load(jr)
            self.assertEqual(isinstance(md, dict), True)

if __name__ == '__main__':
    unittest.main()

1 个答案:

答案 0 :(得分:1)

我认为最pythonic将是使用测试框架 - 鼻子,py.test是最受欢迎的(恕我直言)。 所以在你的bash脚本中将控制变量传递给所使用的框架,我想你会更加pythonic。