如果你是Python和unittest的初学者,可以看一下单元测试介绍教程中的例子。其中使用with语句捕获ValueError。
被测试的脚本(invoice_calculator.py)是:
def divide_pay(amount, staff_hours):
"""
Divide an invoice evenly amongst staff depending on how many hours they
worked on a project
"""
total_hours = 0
for person in staff_hours:
total_hours += staff_hours[person]
if total_hours == 0:
raise ValueError("No hours entered")
per_hour = amount / total_hours
staff_pay = {}
for person in staff_hours:
pay = staff_hours[person] * per_hour
staff_pay[person] = pay
return staff_pay
单元测试包括此函数,以便捕获一个边缘情况,在该情况下 staff_hours = None
:
import unittest
from invoice_calculator import divide_pay
class InvoiceCalculatorTests(unittest.TestCase):
def test_equality(self):
pay = divide_pay(300.0, {"Alice": 3.0, "Bob": 6.0, "Carol": 0.0})
self.assertEqual(pay, {'Bob': 75.0, 'Alice': 75.0, 'Carol': 150.0})
def test_zero_hours_total(self):
with self.assertRaises(ValueError):
pay = divide_pay(360.0, {"Alice": 0.0, "Bob": 0.0, "Carol": 0.0})
if __name__ == "__main__":
unittest.main()
关于在
test_zero_hours_total(self)
中使用with
语句,实际上这里是如何工作/执行的?
test_zero_hours_total()
函数基本上是这样工作的(通俗易懂的描述):当将360.0, {"Alice": 0.0, "Bob": 0.0, "Carol": 0.0}
(这会在divide_pay()
中引发ValueError
)作为参数传递给divide_pay()
函数时,预期错误应该是ValueError
(我们通过将ValueError
传递给assertRaises()
函数来实现)。