Skip to main content

単体テストの生成

Copilot Chat は、関数の単体テストの生成に役立ちます。

あらゆるプロジェクトの成功には、適切な単体テスト スイートが不可欠です。 ただし、このようなテストの記述には時間がかかるため、行われないこともよくあります。 Copilot Chat は、このようなテストの自動生成に役立ちます。

シナリオ例

データベースを更新する前にデータを検証する Python 関数があるとします。 検証が期待どおりに実行されることを確認するために、単体テストを作成する必要があります。 このようなテストの自動生成を Copilot Chat に依頼できます。

def validate_price(price: float): if price <= 0: raise ValueError("Price must be greater than 0") if price > 1000: raise ValueError("Price must be less than or equal to 1000") 

プロンプトの例

Copilot Chat prompt 1000: raise ValueError("Price must be less than or equal to 1000")/tests Generate unit tests for this function. Validate both success and failure, and include edge cases." target="_blank" class="btn btn-sm mr-1 tooltipped tooltipped-nw no-underline" aria-label="Run this prompt with context in Copilot Chat">
/tests Generate unit tests for this function. Validate both success and failure, and include edge cases. 

応答の例

メモ

次の応答は例です。 Copilot Chat の応答は非決定的であるため、ここで示したものとは異なる応答が返される可能性があります。

Copilot Chat に単体テストの生成を初めて依頼する場合は、プロジェクトの単体テストを構成するかどうかを尋ねられることがあります。 この例では、この提案を拒否すると想定しています。

Copilot からは、テストを生成するための戦略が提供され、次にテスト自体が提供されます。

import unittest from generate_unit_tests import validate_price class TestValidateProduct(unittest.TestCase): def test_price_zero(self): with self.assertRaises(ValueError) as context: validate_price(0) self.assertEqual(str(context.exception), "Price must be greater than 0") def test_price_negative(self): with self.assertRaises(ValueError) as context: validate_price(-10) self.assertEqual(str(context.exception), "Price must be greater than 0") def test_price_above_limit(self): with self.assertRaises(ValueError) as context: validate_price(1500) self.assertEqual(str(context.exception), "Price must be less than or equal to 1000") def test_price_edge_case_zero(self): with self.assertRaises(ValueError) as context: validate_price(0) self.assertEqual(str(context.exception), "Price must be greater than 0") def test_price_edge_case_max(self): try: validate_price(1000) except ValueError: self.fail("validate_price() raised ValueError unexpectedly!") if __name__ == '__main__': unittest.main() 

参考資料