コードを変更するときは、新しい動作を検証し、新しいコードによって導入されたバグをキャッチするようにテストを更新することが重要です。 Copilot チャット を使用すると、コードの変更に合わせてテストをすばやく更新し、テスト スイートが実装と同期し続けることができます。
サンプル シナリオ
特定の購入金額の割引を決定する 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 チャット に問い合わせれば、ロジックの変更によって影響を受けるテストを特定し、更新することができます。
Given the update to the `calculate_discount` function, update the unit tests that may fail or become outdated as a result.
応答の例
レスポンスが例であることを示すための例。
Copilot チャット は、コードと既存のテストを分析し、コードの変更後に失敗するか、誤解を招くようになったテストを特定します。
たとえば、Copilot チャット では、次のことが説明されています。
*
test_discount_above_100はこれから失敗します
*
test_discount_below_100とtest_discount_exactly_100は合格しますが、10%割引のしきい値が$100ではなく$150になったため、誤解を招くようになりました。
さらに、Copilot チャット は、200 ドルを超える金額の新しい 20% 割引レベルなど、 テスト 対象範囲が不足しているかどうかを識別します。
Copilot チャット は、更新された一連のテストを提案します。
更新されたテスト
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()