title | shortTitle | intro | redirect_from | versions | category | complexity | octicon | topics | ||||||
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
Generate unit tests | Generate unit tests | {% data variables.product.prodname_copilot_chat_short %} can help with generating unit tests for a function. |
|
|
|
| beaker |
|
A good suite of unit tests is critical to the success of any project. However, writing these tests can be time-consuming and are often neglected. {% data variables.product.prodname_copilot_chat_short %} can help generate these tests for you.
Imagine you have a Python function which validates data before updating the database. You need to create unit tests to ensure the validation performs the way you expect. You can ask {% data variables.product.prodname_copilot_chat_short %} to generate these tests for you.
defvalidate_price(price: float): ifprice<=0: raiseValueError("Price must be greater than 0") ifprice>1000: raiseValueError("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.
{% data reusables.copilot.example-prompts.response-is-an-example %}
If this is your first time asking {% data variables.product.prodname_copilot_chat_short %} to generate unit tests, it may ask you if you wish to configure unit tests for your project. For this example, we are assuming you decline this offer.
{% data variables.product.prodname_copilot_short %} will provide a strategy for generating the tests, and then provide the tests themselves.
importunittestfromgenerate_unit_testsimportvalidate_priceclassTestValidateProduct(unittest.TestCase): deftest_price_zero(self): withself.assertRaises(ValueError) ascontext: validate_price(0) self.assertEqual(str(context.exception), "Price must be greater than 0") deftest_price_negative(self): withself.assertRaises(ValueError) ascontext: validate_price(-10) self.assertEqual(str(context.exception), "Price must be greater than 0") deftest_price_above_limit(self): withself.assertRaises(ValueError) ascontext: validate_price(1500) self.assertEqual(str(context.exception), "Price must be less than or equal to 1000") deftest_price_edge_case_zero(self): withself.assertRaises(ValueError) ascontext: validate_price(0) self.assertEqual(str(context.exception), "Price must be greater than 0") deftest_price_edge_case_max(self): try: validate_price(1000) exceptValueError: self.fail("validate_price() raised ValueError unexpectedly!") if__name__=='__main__': unittest.main()
{% data reusables.copilot.example-prompts.further-reading-items %}