Un buen conjunto de pruebas unitarias es fundamental para el éxito de cualquier proyecto. Sin embargo, escribir estas pruebas puede llevar mucho tiempo y a menudo se ignoran. Chat de Copiloto puede ayudarte a generar estas pruebas por ti.
Escenario de ejemplo
Imagina que tienes una función de Python que valida los datos antes de actualizar la base de datos. Debes crear pruebas unitarias para asegurarte de que la validación se realiza de la manera esperada. Puede pedir que Chat de Copiloto genere estas pruebas automáticamente.
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")
Mensaje de ejemplo
/tests Generate unit tests for this function. Validate both success and failure, and include edge cases.
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")
/tests Generate unit tests for this function. Validate both success and failure, and include edge cases.
/tests Generate unit tests for this function. Validate both success and failure, and include edge cases.
Respuesta de ejemplo
Nota:
La respuesta siguiente es un ejemplo. Las respuestas de Chat de Copiloto no son deterministas, por lo que puedes obtener una respuesta diferente a la aquí mostrada.
Si esta es la primera vez que solicita Chat de Copiloto generar pruebas unitarias, puede preguntarle si desea configurar pruebas unitarias para el proyecto. En este ejemplo, se supone que rechazas esta oferta.
Copilot proporcionará una estrategia para generar las pruebas y, a continuación, proporcionará las propias pruebas.
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()