我正在编写一个测试脚本,其中包含用于不同测试的不同函数。我希望能够随机选择一个测试来运行。我已经通过以下功能实现了这一点......
test_options = ("AOI", "RMODE")
def random_test(test_options, control_obj):
ran_test_opt = choice(test_options)
if ran_test_opt.upper() == "AOI":
logging.debug("Random AOI Test selected")
random_aoi()
elif ran_test_opt.upper() == "RMODE":
logging.debug("Random Read Mode Test selected")
random_read_mode(control_obj)
但是,我想在不修改随机测试选择功能的情况下添加更多测试功能。我想做的就是将测试函数添加到脚本中。此外,我还想要一种方法来选择将包含在随机选择中的测试。这就是变量 test_options 所做的。我将如何改变我的随机生成函数来实现这一点?
编辑:我通过将所有测试都包含在测试类中来解决所有测试可能需要不同参数的事实。所有参数都将传递到 init 中,测试函数将使用“self”引用它们。当他们需要特定变量时...
class Test(object):
"""A class that contains and keeps track of the tests and the different modes"""
def __init__(self, parser, control_obj):
self.parser = parser
self.control_obj = control_obj
def random_test(self):
test_options = []
for name in self.parser.options('Test_Selection'):
if self.parser.getboolean('Test_Selection', name):
test_options.append(name.lower())
ran_test_opt = choice(test_options)
ran_test_func = getattr(self, ran_test_opt)
ran_test_func()
#### TESTS ####
def random_aoi(self):
logging.info("Random AOI Test")
self.control_obj.random_readout_size()
def random_read_mode(self):
logging.info("Random Readout Mode Test")
self.control_obj.random_read_mode()
最佳答案
您可以在 python 中创建一个您可以调用的函数列表:
test_options = (random_aoi, random_read_mode)
def random_test(test_options, control_obj):
ran_test_opt = choice(test_options)
ran_test_opt(control_obj) # call the randomly selected function
你必须让每个函数以这种方式接受相同的参数,这样你才能以相同的方式调用它们。
关于python - 随机选择功能,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22016917/