gpt4 book ai didi

python - Python unittest 可以自动重新尝试失败的测试用例/套件吗?

转载 作者:太空狗 更新时间:2023-10-30 00:37:12 27 4
gpt4 key购买 nike

小问题
是否可以根据预定义函数在失败/错误 N 次时重新尝试单元测试。 (像用户的提示)

背景
为避免重新输入整页系统信息,请参阅关于 passing data to unittests 的 SO 问题和 auto test discovery有关我的物理设置的更多详细信息。

关于手头的问题,我知道我可以通过重新编写我的测试用例来循环直到它获得所需的结果(参见下面的伪代码)然后基于此进行断言。但是我宁愿不去重写 100 个测试用例。

我会有人指出,如果单元测试失败,它应该失败并完成。我 100% 同意如果人为错误可以消除。这是我连接的物理系统,数字万用表的导线多次连接不当,可能会因连接松动而失败。

伪解决方法

class Suite_VoltageRegulator(unittest.TestCase):
def test_voltage_5v_regulator(self):
keep_running = 'y'
error_detected = False

print '\n'
# Display User Test Configuration
msg = \
'1) Connect Front DMM GND(black) to the TP_COM\n' +\
'2) Connect Front DMM POS(red) to the TP-A\n' +\
'3) Ensure the DMM terminal button indicates FRONT'

continue_test = prompt.Prompt_Ok_Cancel('User Action Required!', msg)

if not continue_test:
self.assertTrue(False, 'User Canceled Test!')

while(keep_running == 'y'):
try:
# Run the test
results = measure_voltage_from_system()

# Analyze Results
test_status = pf.value_within_range(results, REGULATOR_5V_LOW, REGULATOR_5V_HIGH)

catch:
error_detected = True

# Retest Failed Cards
if(test_status == False):
keep_running = rawinput('Test FAILED: Retry Test? (y/n):')
elif(error_detected == True):
keep_running = rawinput('Test ERROR: Retry Test? (y/n):')
else:
keep_running = 'n'

# Inform the user on the test results
self.assertTrue(test_status, 'FAIL: 5V Regulator (' +str(results)+ ') Out of Range!')

编辑 8/22/11 下午 3:30 CST
我知道我在这个用例中违反了单元测试的定义。这些问题/评论也在我的其他一些 SO 问题中得到解决。我们选择的设计目标之一是利用现有框架以避免必须“重新发明轮子”。我们选择 python 的 unittest 并不是基于它的定义,而是基于它执行和显示一系列测试的灵 active 和健壮性。

进入这个项目,我知道有些事情需要解决方法,因为这个模块不是为这个用途而设计的。在这个时候,我仍然相信这些变通办法比重写我自己的测试运行器更容易/更便宜。

编辑 8/22/11 下午 5:22 CST
我并没有死心塌地地以这种方式将 unittest 用于 future 的项目,但是我相当倾向于使用现有的框架工作来避免重复别人的工作。下面的评论是此 pycopia-QA 的示例似乎很适合这个项目。我当前项目的唯一缺点是我已经编写了数百个单元测试测试用例,如果我要重写它们,那将是一项非常艰巨的任务(请注意,这也是一项没有资金支持的工作)

编辑 8/24/11 11:00 AM CST
future 的项目可能很明显会切换到针对此类测试的更加量身定制的框架。但是,我仍然有使用 unittest 运行的项目,因此仍然需要仅使用 unittest(或 nose + 3rd 插件)的解决方案。

最佳答案

原始问题 4 年后 - 我希望有人会关心 :)这是我在单元测试之上执行此操作的解决方案。它有点丑陋并且依赖于 TestCase 基类的实现,但它有效。

class MyTest(unittest.TestCase):
###
### Insert test methods here
###

# Wrapping each test method so that a retry would take place.
def run(self, result=None):
self.origTestMethodName = self._testMethodName
self._testMethodName = "_testRetryWrapper"
super(MyTest, self).run(result)
self._testMethodName = self.origTestMethodName

def _testRetryWrapper(self):
testMethod = getattr(self, self.origTestMethodName)
retryAttemptsLeft = settings.testRetryCount

while True:
try:
testMethod()
break
except:
if retryAttemptsLeft == 0:
raise
else:
retryAttemptsLeft = retryAttemptsLeft - 1

关于python - Python unittest 可以自动重新尝试失败的测试用例/套件吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7152428/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com