【问题标题】:how to run a set of Python unit tests [duplicate]如何运行一组 Python 单元测试 [重复]
【发布时间】:2014-08-29 18:11:45
【问题描述】:

我正在使用 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()

【问题讨论】:

    标签: python unit-testing


    【解决方案1】:

    我最喜欢 Python 的事情是使用测试框架——nose、py.test 是最流行的(恕我直言)。 所以在你的 bash 脚本中,将控制变量传递给使用的框架,我猜你会更加 Pythonic。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-12-30
      • 2021-09-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多