将python脚本参数传递给测试模块

zch*_*odd 6 python unit-testing

我有几个测试模块都通过驱动程序脚本一起调用,可以采用各种参数.测试本身是使用python unittest模块编写的.

import optparse
import unittest
import sys
import os

from tests import testvalidator
from tests import testmodifier
from tests import testimporter

#modify the path so that the test modules under /tests have access to the project root
sys.path.insert(0, os.path.dirname(__file__))

def run(verbosity):
    if verbosity == "0":
            sys.stdout = open(os.devnull, 'w')

    test_suite = unittest.TestSuite()
    test_suite.addTest(unittest.TestLoader().loadTestsFromTestCase(testvalidator.TestValidator))
    test_suite.addTest(unittest.TestLoader().loadTestsFromTestCase(testmodifier.TestModifier))
    test_suite.addTest(unittest.TestLoader().loadTestsFromTestCase(testimporter.TestDataImporter))

    unittest.TextTestRunner(verbosity=int(verbosity)).run(test_suite)

if __name__ == "__main__":

    #a simple way to control output verbosity
    parser = optparse.OptionParser()
    parser.add_option("--verbosity", "--verbosity", dest="verbosity", default="0")
    (options, args) = parser.parse_args()

    run(options.verbosity)
Run Code Online (Sandbox Code Playgroud)

我的问题是,在这些测试模块中,我有一些我想根据传递给驱动程序的不同参数跳过的测试.我知道unittest提供了一系列装饰器,但我不知道将这些信息传递给各个模块的最佳方法.--skip-slow例如,如果我有一个参数,那么我怎么能将测试注释为缓慢,并将它们跳过?

感谢您的时间.

Joh*_*Doe 2

其实我自己也一直在想这个问题,最后找到了解决方案。

主文件...

...
if __name__ == '__main__':
    args = argparser()

    from tests import *

    ...
Run Code Online (Sandbox Code Playgroud)

在您的测试模块中,只需执行以下操作:

from __main__ import args

print args
Run Code Online (Sandbox Code Playgroud)

我对此进行了测试,效果相当不错。好处是它非常简单,而且根本没有太多的技巧。