gpt4 book ai didi

python - 断言失败时继续 Python 的单元测试

转载 作者:IT老高 更新时间:2023-10-28 21:35:44 25 4
gpt4 key购买 nike

编辑:切换到一个更好的例子,并阐明了为什么这是一个真正的问题。

我想用 Python 编写单元测试,当断言失败时继续执行,这样我就可以在单个测试中看到多个失败。例如:

class Car(object):
def __init__(self, make, model):
self.make = make
self.model = make # Copy and paste error: should be model.
self.has_seats = True
self.wheel_count = 3 # Typo: should be 4.

class CarTest(unittest.TestCase):
def test_init(self):
make = "Ford"
model = "Model T"
car = Car(make=make, model=model)
self.assertEqual(car.make, make)
self.assertEqual(car.model, model) # Failure!
self.assertTrue(car.has_seats)
self.assertEqual(car.wheel_count, 4) # Failure!

这里,测试的目的是确保 Car 的 __init__ 正确设置其字段。我可以将它分解为四种方法(这通常是个好主意),但在这种情况下,我认为将其保留为测试单个概念的单个方法(“对象已正确初始化”)更具可读性。

如果我们假设最好不要分解该方法,那么我有一个新问题:我无法一次看到所有错误。当我修复 model 错误并重新运行测试时,会出现 wheel_count 错误。当我第一次运行测试时,这样可以节省我查看这两个错误的时间。

作为比较,Google 的 C++ 单元测试框架 distinguishes between在非致命 EXPECT_* 断言和致命 ASSERT_* 断言之间:

The assertions come in pairs that test the same thing but have different effects on the current function. ASSERT_* versions generate fatal failures when they fail, and abort the current function. EXPECT_* versions generate nonfatal failures, which don't abort the current function. Usually EXPECT_* are preferred, as they allow more than one failures to be reported in a test. However, you should use ASSERT_* if it doesn't make sense to continue when the assertion in question fails.

有没有办法在 Python 的 unittest 中获得类似 EXPECT_* 的行为?如果 unittest 中没有,那么是否有另一个 Python 单元测试框架支持这种行为?


顺便说一句,我很好奇有多少实际测试可以从非致命断言中受益,所以我查看了一些 code examples (于 2014 年 8 月 19 日编辑以使用搜索代码而不是 Google 代码搜索,RIP)。从第一页随机选择的 10 个结果中,所有测试都包含在同一测试方法中做出多个独立断言的测试。所有人都将从非致命断言中受益。

最佳答案

另一种获得非致命断言的方法是捕获断言异常并将异常存储在列表中。然后断言该列表是空的,作为拆解的一部分。

import unittest

class Car(object):
def __init__(self, make, model):
self.make = make
self.model = make # Copy and paste error: should be model.
self.has_seats = True
self.wheel_count = 3 # Typo: should be 4.

class CarTest(unittest.TestCase):
def setUp(self):
self.verificationErrors = []

def tearDown(self):
self.assertEqual([], self.verificationErrors)

def test_init(self):
make = "Ford"
model = "Model T"
car = Car(make=make, model=model)
try: self.assertEqual(car.make, make)
except AssertionError, e: self.verificationErrors.append(str(e))
try: self.assertEqual(car.model, model) # Failure!
except AssertionError, e: self.verificationErrors.append(str(e))
try: self.assertTrue(car.has_seats)
except AssertionError, e: self.verificationErrors.append(str(e))
try: self.assertEqual(car.wheel_count, 4) # Failure!
except AssertionError, e: self.verificationErrors.append(str(e))

if __name__ == "__main__":
unittest.main()

关于python - 断言失败时继续 Python 的单元测试,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4732827/

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