我有一组鼻子测试用于测试一块硬件。例如,下面的测试涉及测试系统上每种模式的警报:
import target
modes = ("start","stop","restart","stage1","stage2")
max_alarm_time = 10
# generate tests for testing each mode
def test_generator():
for m in modes:
yield check_alarm, m, max_alarm_time
# test alarm for a mode
def check_alarm(m, max_alarm_time):
target.set_mode(m)
assert target.alarm() < max_alarm_time
我的大多数测试都有这样的外观,我正在测试系统上所有modes
的特定功能。
我现在希望使用同一组测试来测试一个新的硬件,它有两个额外的模式:
modes = ("start","stop","restart","stage1","stage2","stage3","stage4")
当然,我希望我的测试仍适用于旧硬件。运行自动化测试时,我需要为测试环境硬编码我连接的硬件。
我认为最好的方法是创建一个paramaters.py模块,如下所示:
def init(hardware):
global max_alarm_time
global modes
max_alarm_time = 10
if hardware == "old":
modes = ("start","stop","restart","stage1","stage2")
elif hardware == "new":
modes = ("start","stop","restart","stage1","stage2","stage3","stage4")
test_alarms.py现在看起来像这样:
import target
import parameters
# generate tests for testing each mode
def test_generator():
for m in parameters.modes:
yield check_alarm, m, parameters.max_alarm_time
# test alarm for a mode
def check_alarm(m, max_alarm_time):
target.set_mode(m)
assert target.alarm() < max_alarm_time
然后在我的主要内容中我有以下内容:
import nose
import parameters
parameters.init("new")
nose.main()
您认为这是一种有效的方法吗?
答案 0 :(得分:0)
解决类似问题的另一种方法是以下列方式滥用属性插件中的@attr
装饰器:
from nose.plugins.attrib import attr
max_alarm_time = 10
# generate tests for testing each mode
@attr(hardware='old')
@attr(modes = ("start","stop","restart","stage1","stage2"))
def test_generator_old():
for m in test_generator_old.__dict__['modes']:
yield check_alarm, m, max_alarm_time
@attr(hardware='new')
@attr(modes = ("start","stop","restart","stage1","stage2", "stage3","stage4"))
def test_generator_new():
for m in test_generator_new.__dict__['modes']:
yield check_alarm, m, max_alarm_time
# test alarm for a mode
def check_alarm(m, max_alarm_time):
print "mode=", m
您可以立即切换旧版&#39;和&#39; new&#39;,像这样:
$ nosetests modes_test.py -a hardware=new -v
modes_test.test_generator_new('start', 10) ... ok
modes_test.test_generator_new('stop', 10) ... ok
modes_test.test_generator_new('restart', 10) ... ok
modes_test.test_generator_new('stage1', 10) ... ok
modes_test.test_generator_new('stage2', 10) ... ok
modes_test.test_generator_new('stage3', 10) ... ok
modes_test.test_generator_new('stage4', 10) ... ok
----------------------------------------------------------------------
Ran 7 tests in 0.020s
OK
旧的: $ nosetests modes_test.py -a hardware = old -v
modes_test.test_generator_old('start', 10) ... ok
modes_test.test_generator_old('stop', 10) ... ok
modes_test.test_generator_old('restart', 10) ... ok
modes_test.test_generator_old('stage1', 10) ... ok
modes_test.test_generator_old('stage2', 10) ... ok
----------------------------------------------------------------------
Ran 5 tests in 0.015s
OK
此外,虽然我没有玩那么多,nose-testconfig可以帮助你做同样的伎俩。