当您对代码进行更改时,及时更新所有测试以验证新的行为并捕获新代码可能引入的错误非常重要。Copilot Chat 可以帮助您快速更新测试以匹配代码更改,确保您的测试套件与实现保持同步。
示例情景
假设您有一个 Python 函数 calculate_discount,用于计算给定购买金额的折扣。原始代码中,金额超过 $100 时可获得 10% 的折扣。您正对函数的逻辑进行更改,使得只有金额超过 $150 时才获得 10% 的折扣,并且现在对超过 $200 的金额提供 20% 的折扣。
原始代码
在原始代码中,购买金额超过 $100 可获得 10% 的折扣。
def calculate_discount(amount: float) -> float:
if amount > 100:
return amount * 0.1 # 10% discount
return 0.0
更新后的代码
在更改后的代码中,只有金额超过 $150 时才获得 10% 的折扣,而金额超过 $200 时则获得 20% 的折扣。
def calculate_discount(amount: float) -> float:
if amount > 200:
return amount * 0.2
elif amount > 150:
return amount * 0.1
return 0.0
现有测试
此示例展示了为原始代码编写的现有测试。
import unittest
from discount import calculate_discount
class TestCalculateDiscount(unittest.TestCase):
def test_discount_above_100(self):
# $140 should get a $14 discount (10%)
self.assertAlmostEqual(calculate_discount(140), 14.0)
def test_discount_below_100(self):
# $80 should get no discount
self.assertEqual(calculate_discount(80), 0.0)
def test_discount_exactly_100(self):
# $100 is not above 100, so no discount
self.assertEqual(calculate_discount(100), 0.0)
if __name__ == '__main__':
unittest.main()
示例提示
您可以请求 Copilot Chat 识别并更新受逻辑更改影响的任何测试。
Given the update to the `calculate_discount` function, update the unit tests that may fail or become outdated as a result.
示例回复
注意
以下响应为示例。Copilot Chat 的回复具有不确定性,您可能会得到与此处显示的不同的响应。
Copilot Chat 会分析您的代码和现有测试,并识别在代码更改后哪些测试会失败或变得误导。
例如,Copilot Chat 解释说
test_discount_above_100将会 失败test_discount_below_100和test_discount_exactly_100将通过,但它们现在 具有误导性,因为 10% 折扣的阈值已变为 $150,而不是 $100。
此外,Copilot Chat 会识别任何 缺失的测试覆盖,例如针对金额超过 $200 的新 20% 折扣层级。
Copilot Chat 提出了一套更新后的测试。
更新后的测试
import unittest
from discount import calculate_discount
class TestCalculateDiscount(unittest.TestCase):
def test_discount_above_200(self):
# $250 should get a $50 discount (20%)
self.assertAlmostEqual(calculate_discount(250), 50.0)
def test_discount_above_150(self):
# $175 should get a $17.50 discount (10%)
self.assertAlmostEqual(calculate_discount(175), 17.5)
def test_discount_at_or_below_150(self):
# $150 is not above 150, so no discount
self.assertEqual(calculate_discount(150), 0.0)
# $80 should get no discount
self.assertEqual(calculate_discount(80), 0.0)
if __name__ == '__main__':
unittest.main()