Un buen conjunto de pruebas unitarias es fundamental para el éxito de cualquier project. Sin embargo, escribir estas pruebas puede llevar mucho tiempo y a menudo se ignoran. El chat de Copilot puede ayudar a generar estas pruebas de forma automática.
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. Puedes pedir al chat de Copilot que genere estas pruebas de forma automática.
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")
Ejemplos de indicaciones
/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 Copilot no son deterministas, por lo que puedes obtener una respuesta diferente a la aquí mostrada.
Si es la primera vez que solicita a chat de Copilot generar pruebas unitarias, es posible que le pregunte 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 pruebas en sí.
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()