¿Qué es el Testing en Software?

2/20
Recursos
Transcripción

Las pruebas en el desarrollo de software son esenciales para garantizar la calidad y estabilidad del código antes de lanzarlo a producción. Tanto las pruebas manuales como las automatizadas juegan un rol fundamental para detectar errores. Usar Python para automatizar estas pruebas no solo ahorra tiempo, sino que también asegura que los errores críticos se detecten antes, evitando posibles pérdidas económicas y de confianza de los usuarios.

¿Qué son las pruebas manuales y cómo funcionan?

Las pruebas manuales consisten en validar el funcionamiento de un cambio en el código mediante la interacción directa con la aplicación. Esto se hace, por ejemplo, al modificar una línea de código, ejecutar la aplicación y verificar si el cambio funciona correctamente. Es similar al trabajo de un mecánico que ajusta un auto y luego lo prueba encendiéndolo cada vez.

¿Cómo funcionan las pruebas unitarias?

Las pruebas unitarias permiten validar que pequeñas piezas de código, como funciones individuales, trabajan correctamente. En el ejemplo de un mecánico, esto sería como revisar solo un neumático: inflarlo, verificar que no tenga fugas y confirmar que esté en buen estado. En Python, estas pruebas se automatizan utilizando la palabra clave assert, que compara los resultados esperados con los reales.

¿Qué son las pruebas de integración?

Las pruebas de integración verifican que diferentes componentes de la aplicación funcionen en conjunto sin problemas. En el caso del mecánico, sería comprobar que el neumático instalado en el coche funcione bien con el resto de las piezas del vehículo. En desarrollo de software, esto se traduce a verificar, por ejemplo, que el proceso de inicio de sesión funcione correctamente, desde la entrada del usuario hasta la confirmación del acceso.

¿Cómo Python nos ayuda a automatizar pruebas?

Python ofrece herramientas para automatizar las pruebas, permitiendo ejecutar muchas validaciones rápidamente sin intervención manual. A través de pruebas automatizadas, podemos detectar errores que de otro modo podrían pasar desapercibidos y llegar a producción, como un fallo en el cálculo de una orden de compra. Esto es crítico para evitar situaciones como la que enfrentó CrowdStrike, donde un error no detectado en una actualización paralizó aeropuertos.

Aportes 26

Preguntas 1

Ordenar por:

¿Quieres ver más aportes, preguntas y respuestas de la comunidad?

**Tipos de Testing:** 1. **Testing Unitario**: Verifica el correcto funcionamiento de unidades individuales de código, como funciones o métodos. 2. **Testing de Integración**: Asegura que los diferentes módulos o componentes funcionen bien en conjunto. 3. **Testing de Sistema**: Evalúa el sistema completo para asegurarse de que cumple con los requisitos especificados. 4. **Testing de Aceptación**: Verifica que el software satisface las necesidades del usuario final. 5. **Testing de Regresión**: Asegura que los cambios o actualizaciones no hayan introducido nuevos errores en funcionalidades ya existentes.
Creo que pude: ```js def calculate_total(products, discount_coupon): total = 0 for product in products: total += (product["price"] - (discount_coupon * product["price"])) return total def test_calculate_total_with_empty_list(): print("Test passed 1") assert calculate_total([],0) == 0 def test_calculate_total_with_single_product(): products = [{"name": "Product 1", "price": 10}] print("Test passed 2") assert calculate_total(products,0.10) == 9 def test_calculate_total_with_multiple_products(): products = [{"name": "Product 1", "price": 10}, {"name": "Product 2", "price": 20}] print("Test passed 3") assert calculate_total(products,0.10) == 27 if __name__ == "__main__": test_calculate_total_with_empty_list() test_calculate_total_with_single_product() test_calculate_total_with_multiple_products() ```def calculate\_total(products, discount\_coupon):    total = 0    for product in products:        total += (product\["price"] - (discount\_coupon \* product\["price"]))    return total def test\_calculate\_total\_with\_empty\_list():    print("Test passed 1")    assert calculate\_total(\[],0) == 0 def test\_calculate\_total\_with\_single\_product():    products = \[{"name": "Product 1", "price": 10}]    print("Test passed 2")    assert calculate\_total(products,0.10) == 9 def test\_calculate\_total\_with\_multiple\_products():    products = \[{"name": "Product 1", "price": 10}, {"name": "Product 2", "price": 20}]    print("Test passed 3")    assert calculate\_total(products,0.10) == 27 if \_\_name\_\_ == "\_\_main\_\_":    test\_calculate\_total\_with\_empty\_list()    test\_calculate\_total\_with\_single\_product()    test\_calculate\_total\_with\_multiple\_products()
Le agregué un descuento diferente a cada producto y agregué una función que realiza el descuento: ```python #----- Funciones de aplicación ----- def calculate_total(products): total = 0 for product in products: total += product["price"] return total def calculate_discount(products): total = 0 for product in products: total += product["price"] - (product["price"] * (product["discount"]/100)) return total #----- Funciones de prueba (precios)----- def test_calculate_total_with_empty_list(): assert calculate_total([]) == 0 def test_calculate_total_with_single_product(): products = [ { "name": "notebook", "price": 5 } ] assert calculate_total(products) == 5 def test_calculate_total_with_multiple_product(): products = [ { "name": "notebook", "price": 10 }, { "name": "pen", "price": 2 } ] assert calculate_total(products) == 12 # ----- Funciones de prueba (descuento) ----- def test_calculate_discount_with_empty_list(): assert calculate_discount([]) == 0 def test_calculate_discount_with_single_product(): products = [ { "name": "notebook", "price": 50, "discount": 50 } ] assert calculate_discount(products) == 25 def test_calculate_discount_with_multiple_product(): products = [ { "name": "notebook", "price": 10, "discount": 10 }, { "name": "pen", "price": 10, "discount": 10 } ] assert calculate_discount(products) == 18 if __name__ == "__main__": test_calculate_total_with_empty_list() test_calculate_total_with_single_product() test_calculate_total_with_multiple_product() test_calculate_discount_with_empty_list() test_calculate_discount_with_single_product() test_calculate_discount_with_multiple_product() ```
RETO: Le agregué un 10% de descuento a todos los productos ```js # Curso de Unit Testing en Python # Clase 2 - ¿Qué es el Testing en Software? # Código que va a ir a producción: def calculate_total(products): total = 0 for product in products: total += product["price"] *product["discount"] return total # Pruebas def test_calculate_total_with_empty_list(): # print("prueba") assert calculate_total([]) == 0 def test_calculate_total_with_single_product(): products = [ { "name": "Notebook", "price": 5, "discount": 0.9 } ] print(calculate_total(products)) assert calculate_total(products) == 4.5 def test_calculate_total_with_multiple_products(): products = [ { "name": "Book", "price": 10, "discount": 0.9 }, { "name": "Pen", "price": 2, "discount": 0.9 } ] print(calculate_total(products)) assert calculate_total(products) == 10.8 if __name__ == "__main__": # test_calculate_total_with_empty_list() test_calculate_total_with_single_product() test_calculate_total_with_multiple_products() # https://ellibrodepython.com/assert-python """ assert() en testing La función assert() puede ser también muy útil para realizar testing de nuestro código, especialmente para test unitarios o unit tests. Imagínate que tenemos una función calcula_media() que como su nombre indica calcula la media de un conjunto de números. def calcula_media(lista): return sum(lista)/len(lista) En el mundo de la programación es muy importante probar o testear el software, para asegurarse de que está libre de errores. Gracias al uso de assert() podemos realizar estas comprobaciones de manera automática. assert(calcula_media([5, 10, 7.5]) == 7.5) assert(calcula_media([4, 8]) == 6) Por lo que si hacemos que estas comprobaciones sean parte de nuestro código, podríamos proteger nuestra función, asegurándonos de que nadie la “rompa”. """ ```
Hola! Les comparto el código de la clase. ```python def calculate_total(products): total = 0 for product in products: total += product["price"] return total def test_calculate_total_with_empty_list(): assert calculate_total([]) == 0 def test_calculate_total_with_single_product(): products = [ { "name": "Notebook", "price": 100 } ] assert calculate_total(products) == 100 def test_calculate_total_with_multiple_products(): products = [ { "name": "Book", "price": 20 }, { "name": "Pen", "price": 5 } ] assert calculate_total(products) == 25 if __name__ == '__main__': test_calculate_total_with_empty_list() test_calculate_total_with_single_product() test_calculate_total_with_multiple_products() ```
```python #!/home/changery/Platzi/024-UnitTestingPy/env/bin/python ### Código que iría a producción def calculate_total(products): total = 0 for product in products: total += product["price"] return total def calculate_total_with_discount(products, discount_prc): total = calculate_total(products) return total * (1 - discount_prc/100) ## Código de las pruebas ### Objetos productos_1_objeto = [{ "name": "Libreta", "price": 5 }] productos_varios_objetos = [ { "name": "Libreta", "price": 5 }, { "name": "Lapiz", "price":1 } ] ### Pruebas def test_calculate_total_with_empty_list(): assert calculate_total([]) == 0 def test_calculate_total_with_single_product(): assert calculate_total(productos_1_objeto) == 5 assert calculate_total(productos_1_objeto) != 10 def test_calculate_total_with_multiple_products(): assert calculate_total(productos_varios_objetos) == 6 def test_calculate_total_with_global_discount(): assert calculate_total_with_discount(productos_varios_objetos, 50) == 3 if __name__ == "__main__": test_calculate_total_with_empty_list() test_calculate_total_with_single_product() test_calculate_total_with_multiple_products() test_calculate_total_with_global_discount() ```
Testing de diferentes productos con diferentes descuentos: ```js def caculate_total(products): total = 0 for product in products: total += product["price"] - (product["price"] * product["discount"] / 100) return total def test_calculate_total_with_empty_product(): products = [] assert caculate_total(products) == 0 def test_calculate_total_with_empty_product(): products = [{ "name": "Notebook", "price": 15, "discount": 10 }] assert caculate_total(products) == 0 def test_calculate_total_with_multiple_discount_product(): products = [ { "name": "Notebook", "price": 15, "discount": 10 }, { "name": "Book", "price": 10, "discount": 30 }, { "name": "Pen", "price": 5, "discount": 20 } ] assert caculate_total(products) == 24.5 if __name__ == "__main__": test_calculate_total_with_multiple_discount_product() ```def caculate\_total(products):    total = 0    for product in products:        total += product\["price"] - (product\["price"] \* product\["discount"] / 100)    return total def test\_calculate\_total\_with\_empty\_product():    products = \[]    assert caculate\_total(products) == 0 def test\_calculate\_total\_with\_empty\_product():    products = \[{        "name": "Notebook",        "price": 15,        "discount": 10        }]    assert caculate\_total(products) == 0 def test\_calculate\_total\_with\_multiple\_discount\_product():    products = \[        {        "name": "Notebook",        "price": 15,        "discount": 10        },        {        "name": "Book",        "price": 10,        "discount": 30        },        {        "name": "Pen",        "price": 5,        "discount": 20        }    ]    assert caculate\_total(products) == 24.5 if \_\_name\_\_ == "\_\_main\_\_":    test\_calculate\_total\_with\_multiple\_discount\_product()
mi solución: ![](https://static.platzi.com/media/user_upload/image-0d26abd2-f042-4462-8670-842218d7c9a1.jpg) ![](https://static.platzi.com/media/user_upload/image-cc9b44bf-299c-4c53-be9d-fb6cb423eb9f.jpg) ![](https://static.platzi.com/media/user_upload/image-3b6f760e-258e-4210-85dc-925647d79766.jpg)
Comparto mi solución al reto propuesto: ```js def calculate_discount(total_price, discount_percentage): discount_total = (discount_percentage * total_price) / 100 return discount_total def calculate_total(products, discount=0): total = 0 for product in products: total += product["price"] if discount > 0: discount_value = calculate_discount(total, discount) total -= discount_value return total def test_calculate_total_with_empty_list(): assert calculate_total([]) == 0 print("Passed Test 1 😁") def test_calculate_total_with_single_product(): products = [ { "name": "Notebook", "price": 5 } ] assert calculate_total(products) == 5 print("Passed Test 2 😁") def test_calculate_total_with_multiple_product(): products = [ { "name": "Book", "price": 10 }, { "name": "Pen", "price": 2 } ] assert calculate_total(products) == 12 print("Passed Test 3 😁") def test_calculate_total_with_discount(): products = [ { "name": "Book", "price": 5 }, { "name": "Pen", "price": 5 } ] discount = 50 assert calculate_total(products, discount) == 5 print("Passed Test 4 😁") def test_calculate_total_without_discount(): products = [ { "name": "Book", "price": 5 }, { "name": "Pen", "price": 5 } ] assert calculate_total(products) == 10 print("Passed Test 5 😁") def test_calculate_discount_total(): total_product = 20 discount_total = 50 assert calculate_discount(total_product, discount_total) == 10 print("Passed Test 6 😁") if __name__ == "__main__": test_calculate_total_with_empty_list() test_calculate_total_with_single_product() test_calculate_total_with_multiple_product() test_calculate_total_with_discount() test_calculate_total_without_discount() test_calculate_discount_total() ```
```python def calculate_total(products, discount=0): total = 0 for product in products: total += product['price'] total = total - (total * discount/100) return total def test_calculate_total_with_10_percent_discount(): products = [ {'name': 'Product 1', 'price': 100}, {'name': 'Product 2', 'price': 200}, ] assert calculate_total(products, 10) == 270 ```
```js def calculate_total(products, discount_percent=0): total = 0 for product in products: total += product['price'] * (1 + discount_percent/100) return round(total,2) def test_calculate_total_with_empty_list(): assert calculate_total([]) == 0 def test_calculate_total_with_single_product(): products = [ {"name": "Notebook", "price": 5} ] assert calculate_total(products) == 5 def test_calculate_total_with_multiple_product(): products = [ {"name": "Notebook", "price": 5}, {"name": "Book", "price": 1}, {"name": "Pen", "price": 1}, ] assert calculate_total(products) == 7 def test_calculate_total_with_single_product_with_discount(): products = [ {"name": "Notebook", "price": 5} ] assert calculate_total(products, 10) == 5.5 def test_calculate_total_with_multiple_product_with_discount(): products = [ {"name": "Notebook", "price": 5}, {"name": "Book", "price": 1}, {"name": "Pen", "price": 1}, ] assert calculate_total(products, 10) == 7.7 if __name__ == "__main__": test_calculate_total_with_empty_list() test_calculate_total_with_single_product() test_calculate_total_with_multiple_product() test_calculate_total_with_single_product_with_discount() test_calculate_total_with_multiple_product_with_discount() ```def calculate\_total(products, discount\_percent=0):    total = 0    for product in products:        total += product\['price'] \*  (1 + discount\_percent/100)    return round(total,2) def test\_calculate\_total\_with\_empty\_list():    assert calculate\_total(\[]) == 0 def test\_calculate\_total\_with\_single\_product():    products = \[        {"name": "Notebook", "price": 5}    ]    assert calculate\_total(products) ==  5 def test\_calculate\_total\_with\_multiple\_product():    products = \[        {"name": "Notebook", "price": 5},        {"name": "Book", "price": 1},        {"name": "Pen", "price": 1},    ]        assert calculate\_total(products) ==  7 def test\_calculate\_total\_with\_single\_product\_with\_discount():    products = \[        {"name": "Notebook", "price": 5}    ]    assert calculate\_total(products, 10) ==  5.5 def test\_calculate\_total\_with\_multiple\_product\_with\_discount():    products = \[        {"name": "Notebook", "price": 5},        {"name": "Book", "price": 1},        {"name": "Pen", "price": 1},    ]        assert calculate\_total(products, 10) ==  7.7 if \_\_name\_\_ == "\_\_main\_\_":    test\_calculate\_total\_with\_empty\_list()    test\_calculate\_total\_with\_single\_product()    test\_calculate\_total\_with\_multiple\_product()    test\_calculate\_total\_with\_single\_product\_with\_discount()    test\_calculate\_total\_with\_multiple\_product\_with\_discount()
```js def calculate_total(products): total = sum(product["price"] for product in products) return total *0.95 if total >= 50 else total def test_calculate_total_with_empty(): assert calculate_total([]) == 0 def test_calculate_total_with_single_product(): products = [ {"name": "book", "price": 5} ] assert calculate_total(products) == 5 def test_calculate_total_with_multiple_products(): products = [ {"name": "book", "price": 15}, {"name": "pencil", "price": 10}, {"name": "bag", "price": 50} ] assert calculate_total(products) == 71.25 if __name__ == "__main__": test_calculate_total_with_empty() test_calculate_total_with_single_product() test_calculate_total_with_multiple_products() ```
```js def calculate_total(products): total = sum(product["price"] for product in products) return total *0.95 if total >= 50 else total def test_calculate_total_with_empty(): assert calculate_total([]) == 0 def test_calculate_total_with_single_product(): products = [ {"name": "book", "price": 5} ] assert calculate_total(products) == 5 def test_calculate_total_with_multiple_products(): products = [ {"name": "book", "price": 15}, {"name": "pencil", "price": 10}, {"name": "bag", "price": 50} ] assert calculate_total(products) == 71.25 if __name__ == "__main__": test_calculate_total_with_empty() test_calculate_total_with_single_product() test_calculate_total_with_multiple_products() ```def calculate\_total(products):    total = sum(product\["price"] for product in products)    return total \*0.95 if total >= 50 else total def test\_calculate\_total\_with\_empty():    assert calculate\_total(\[]) == 0    def test\_calculate\_total\_with\_single\_product():    products = \[        {"name": "book", "price": 5}    ]    assert calculate\_total(products) == 5    def test\_calculate\_total\_with\_multiple\_products():    products = \[        {"name": "book", "price": 15},        {"name": "pencil", "price": 10},        {"name": "bag", "price": 50}    ]    assert calculate\_total(products) == 71.25    if \_\_name\_\_ == "\_\_main\_\_":    test\_calculate\_total\_with\_empty()    test\_calculate\_total\_with\_single\_product()    test\_calculate\_total\_with\_multiple\_products()
def calculate\_total(products):    total = sum(product\["price"] for product in products)    return total \*0.95 if total >= 50 else total def test\_calculate\_total\_with\_empty():    assert calculate\_total(\[]) == 0    def test\_calculate\_total\_with\_single\_product():    products = \[        {"name": "book", "price": 5}    ]    assert calculate\_total(products) == 5    def test\_calculate\_total\_with\_multiple\_products():    products = \[        {"name": "book", "price": 15},        {"name": "pencil", "price": 10},        {"name": "bag", "price": 50}    ]    assert calculate\_total(products) == 71.25    if \_\_name\_\_ == "\_\_main\_\_":    test\_calculate\_total\_with\_empty()    test\_calculate\_total\_with\_single\_product()    test\_calculate\_total\_with\_multiple\_products()
```python #Aqui va mi solución !! :) def calculate_total(products, discount=0): total = 0 for product in products: total += product["price"] if discount > 0: total -= total * (discount / 100) return total def test_calculate_total_with_empty_list(): assert calculate_total([]) == 0 def test_calculate_total_with_single_product(): products = [ { "name": "Notebook", "price": 5 } ] assert calculate_total(products) == 5 assert calculate_total(products, discount=10) == 4.5 def test_calculate_total_with_multiple_product(): products = [ { "name": "Book", "price": 10 }, { "name": "Pen", "price": 2 } ] assert calculate_total(products) == 12 assert calculate_total(products, discount=50) == 6 if __name__ == "__main__": test_calculate_total_with_empty_list() test_calculate_total_with_single_product() test_calculate_total_with_multiple_product() print("Todos los test OK") ```def calculate\_total(products, discount=0):    total = 0    for product in products:        total += product\["price"]     if discount > 0:        total -= total \* (discount / 100)     return total def test\_calculate\_total\_with\_empty\_list():        assert calculate\_total(\[]) == 0 def test\_calculate\_total\_with\_single\_product():    products = \[        {            "name": "Notebook", "price": 5        }    ]       assert calculate\_total(products) == 5    assert calculate\_total(products, discount=10) == 4.5 def test\_calculate\_total\_with\_multiple\_product():    products = \[        {            "name": "Book", "price": 10        },        {            "name": "Pen", "price": 2        }    ]       assert calculate\_total(products) == 12    assert calculate\_total(products, discount=50) == 6 if \_\_name\_\_ == "\_\_main\_\_":    test\_calculate\_total\_with\_empty\_list()    test\_calculate\_total\_with\_single\_product()    test\_calculate\_total\_with\_multiple\_product()    print("Todos los test OK")
```python def calculate_total(products): #This code will go to production 1. total = 0 for product in products: total += product["price"] - ((product["price"] * product["discount"])/100) #print(total) return total def test_calculate_total_with_single_product(): products = [ { "name":"book", "price":10, "discount": 20 } ] assert calculate_total(products) == 8 def test_calculate_total_with_multiply_product(): products = [ { "name":"bbook", "price":10, "discount": 20 }, { "name":"Pen", "price":20, "discount": 10 }, { "name":"Glasses", "price":30, "discount": 0 } ] assert calculate_total(products) == 56 def test_calculate_total_with_empty_list(): print("prueba") assert calculate_total([]) == 0 #ASSERT ESA CONDICION DEBE DAR VRD if __name__ == "__main__": test_calculate_total_with_empty_list() test_calculate_total_with_single_product() test_calculate_total_with_multiply_product() ```def calculate\_total(products):      #This code will go to production 1.    total = 0    for product in products:        total += product\["price"] - ((product\["price"] \* product\["discount"])/100)        #print(total)    return total def test\_calculate\_total\_with\_single\_product():    products = \[        {            "name":"book", "price":10, "discount": 20        }    ]    assert calculate\_total(products) == 8 def test\_calculate\_total\_with\_multiply\_product():    products = \[        {            "name":"bbook", "price":10, "discount": 20        },        {            "name":"Pen", "price":20, "discount": 10        },        {            "name":"Glasses", "price":30, "discount": 0        }    ]    assert calculate\_total(products) == 56 def test\_calculate\_total\_with\_empty\_list():    print("prueba")    assert calculate\_total(\[]) == 0  #ASSERT ESA CONDICION DEBE DAR VRD if \_\_name\_\_ == "\_\_main\_\_":    test\_calculate\_total\_with\_empty\_list()    test\_calculate\_total\_with\_single\_product()    test\_calculate\_total\_with\_multiply\_product()
```js def calculate_total(products, discount): total = 0 for product in products: total += product["price"] - discount / 100 * product["price"] return total.__int__() def test_calculate_total_with_empty_list(): assert calculate_total([], 0) == 0 def test_calculate_total_with_single_product(): products = [{"name": "iPhone", "price": 1000}] print(calculate_total(products, 30)) assert calculate_total(products, 30) == 700 def test_calculate_total_with_multiple_products(): products = [ {"name": "iPhone", "price": 1000}, {"name": "MacBook", "price": 2000}, {"name": "iPad", "price": 500}, ] print(calculate_total(products, 20)) assert calculate_total(products, 20) == 2800 if __name__ == "__main__": test_calculate_total_with_empty_list() test_calculate_total_with_single_product() test_calculate_total_with_multiple_products() ```def calculate\_total(products, discount):    total = 0    for product in products:        total += product\["price"] - discount / 100 \* product\["price"]    return total.\_\_int\_\_() def test\_calculate\_total\_with\_empty\_list():    assert calculate\_total(\[], 0) == 0 def test\_calculate\_total\_with\_single\_product():    products = \[{"name": "iPhone", "price": 1000}]    print(calculate\_total(products, 30))    assert calculate\_total(products, 30) == 700 def test\_calculate\_total\_with\_multiple\_products():    products = \[        {"name": "iPhone", "price": 1000},        {"name": "MacBook", "price": 2000},        {"name": "iPad", "price": 500},    ]    print(calculate\_total(products, 20))    assert calculate\_total(products, 20) == 2800 if \_\_name\_\_ == "\_\_main\_\_":    test\_calculate\_total\_with\_multiple\_products()
```python def calculate_total(products: list, discount: float) -> tuple[float, float, float]: """ Calcula el total de una lista de productos aplicando un descuento. Args: products (list): Lista de diccionarios con productos. Cada producto debe tener una clave 'price'. discount (float): Valor del descuento entre 0 y 1 (ej: 0.1 para 10%). Returns: tuple: (total original, total con descuento, valor del descuento) Raises: ValueError: Si el descuento está fuera del rango 0-1 """ if not 0 <= discount <= 1: raise ValueError("El descuento debe estar entre 0 y 1") total = sum(product["price"] for product in products) discount_value = round(total * discount, 2) new_total = round(total * (1 - discount), 2) return total, new_total, discount_value def test_calculate_total_with_empty_list(): """Prueba el cálculo con una lista vacía de productos.""" total, new_total, discount = calculate_total([], 0) assert (total, new_total, discount) == (0, 0, 0), \ f"Expected (0, 0, 0), but got ({total}, {new_total}, {discount})" def test_calculate_total_with_single_product(): """Prueba el cálculo con un solo producto y 10% de descuento.""" products = [ { "name": "Notebook", "price": 5 } ] discount = 0.1 total, new_total, discount_value = calculate_total(products, discount) assert (total, new_total, discount_value) == (5, 4.5, 0.5), \ f"Expected (5, 4.5, 0.5), but got ({total}, {new_total}, {discount_value})" def test_calculate_total_with_multiple_products(): """Prueba el cálculo con múltiples productos y 10% de descuento.""" products = [ { "name": "Book", "price": 10 }, { "name": "Pen", "price": 2 } ] discount = 0.1 total, new_total, discount_value = calculate_total(products, discount) assert (total, new_total, discount_value) == (12, 10.8, 1.2), \ f"Expected (12, 10.8, 1.2), but got ({total}, {new_total}, {discount_value})" def test_invalid_discount(): """Prueba que se lance una excepción con descuentos inválidos.""" try: calculate_total([], 1.5) assert False, "Se esperaba una ValueError para descuento > 1" except ValueError: pass try: calculate_total([], -0.5) assert False, "Se esperaba una ValueError para descuento < 0" except ValueError: pass if __name__ == "__main__": try: test_calculate_total_with_empty_list() test_calculate_total_with_single_product() test_calculate_total_with_multiple_products() test_invalid_discount() print("✅ Todas las pruebas pasaron exitosamente!") except AssertionError as e: print(f"❌ Error en las pruebas: {str(e)}") ```def calculate\_total(products: list, discount: float) -> tuple\[float, float, float]: *""" Calcula el total de una lista de productos aplicando un descuento.* *Args: products (list): Lista de diccionarios con productos. Cada producto debe tener una clave 'price'. discount (float): Valor del descuento entre 0 y 1 (ej: 0.1 para 10%).* *Returns: tuple: (total original, total con descuento, valor del descuento)* *Raises: ValueError: Si el descuento está fuera del rango 0-1 """* if not 0 <= discount <= 1: raise ValueError("El descuento debe estar entre 0 y 1") total = sum(product\["price"] for product in products) discount\_value = round(total \* discount, 2) new\_total = round(total \* (1 - discount), 2) return total, new\_total, discount\_value def test\_calculate\_total\_with\_empty\_list(): *"""Prueba el cálculo con una lista vacía de productos."""* total, new\_total, discount = calculate\_total(\[], 0) assert (total, new\_total, discount) == (0, 0, 0), \ f"Expected (0, 0, 0), but got ({total}, {new\_total}, {discount})" def test\_calculate\_total\_with\_single\_product(): *"""Prueba el cálculo con un solo producto y 10% de descuento."""* products = \[ { "name": "Notebook", "price": 5 } ] discount = 0.1 total, new\_total, discount\_value = calculate\_total(products, discount) assert (total, new\_total, discount\_value) == (5, 4.5, 0.5), \ f"Expected (5, 4.5, 0.5), but got ({total}, {new\_total}, {discount\_value})" def test\_calculate\_total\_with\_multiple\_products(): *"""Prueba el cálculo con múltiples productos y 10% de descuento."""* products = \[ { "name": "Book", "price": 10 }, { "name": "Pen", "price": 2 } ] discount = 0.1 total, new\_total, discount\_value = calculate\_total(products, discount) assert (total, new\_total, discount\_value) == (12, 10.8, 1.2), \ f"Expected (12, 10.8, 1.2), but got ({total}, {new\_total}, {discount\_value})" def test\_invalid\_discount(): *"""Prueba que se lance una excepción con descuentos inválidos."""* try: calculate\_total(\[], 1.5) assert False, "Se esperaba una ValueError para descuento > 1" except ValueError: pass try: calculate\_total(\[], -0.5) assert False, "Se esperaba una ValueError para descuento < 0" except ValueError: pass if \_\_name\_\_ == "\_\_main\_\_": try: test\_calculate\_total\_with\_empty\_list() test\_calculate\_total\_with\_single\_product() test\_calculate\_total\_with\_multiple\_products() test\_invalid\_discount() print("✅ Todas las pruebas pasaron exitosamente!") except AssertionError as e: print(f"❌ Error en las pruebas: {str(e)}")
Test con descuento:def calculate\_total(products): total = 0 for product in products: *# Discount calculation for each product* product\_with\_discount = product\['price'] - product\["price"]\*product\['discount']/100 total += product\_with\_discount return total def test\_calculate\_total\_with\_empty\_list(): assert calculate\_total(\[]) == 0 def test\_calculate\_total\_with\_single\_product(): products = \[ { "name": "Notebook", "price": 5, "discount": 10 } ] assert calculate\_total(products) == 4.5 def test\_calculate\_total\_with\_multiple\_product(): *# add discount value for each product* products = \[ { "name": "Book", "price": 10, "discount": 0 }, { "name": "Pen", "price": 2, "discount": 10 } ] assert calculate\_total(products) == 11.8 if \_\_name\_\_ == "\_\_main\_\_": test\_calculate\_total\_with\_empty\_list() test\_calculate\_total\_with\_single\_product() test\_calculate\_total\_with\_multiple\_product() ```js def calculate_total(products): total = 0 for product in products: # Discount calculation for each product product_with_discount = product['price'] - product["price"]*product['discount']/100 total += product_with_discount return total def test_calculate_total_with_empty_list(): assert calculate_total([]) == 0 def test_calculate_total_with_single_product(): products = [ { "name": "Notebook", "price": 5, "discount": 10 } ] assert calculate_total(products) == 4.5 def test_calculate_total_with_multiple_product(): # add discount value for each product products = [ { "name": "Book", "price": 10, "discount": 0 }, { "name": "Pen", "price": 2, "discount": 10 } ] assert calculate_total(products) == 11.8 if __name__ == "__main__": test_calculate_total_with_empty_list() test_calculate_total_with_single_product() test_calculate_total_with_multiple_product() ```
```js def calculate_total(products): total = 0 for product in products: total += product["price"] return total def test_calculate_total_with_empty_list(): assert calculate_total([]) == 0 def test_calculate_total_with_single_product(): products = [ { "name": "Notebook", "price": 5 } ] assert calculate_total(products) == 5 def test_calculate_total_with_multiple_product(): products = [ { "name": "Book", "price": 10 }, { "name": "Pen", "price": 2 } ] assert calculate_total(products) == 12 # ---------------------------- def calculate_total_with_discount(products): total = 0 for product in products: total += product["price"] - (product["discount"]/100 * product["price"]) return total def test_calculate_total_discount_with_empty_list(): assert calculate_total_with_discount([]) == 0 def test_calculate_total_discount_with_single_product(): products = [ { "name": "Notebook", "price": 5, "discount": 10 } ] assert calculate_total_with_discount(products) == 4.5 def test_calculate_total_discount_with_multiple_product(): products = [ { "name": "Book", "price": 10, "discount": 10 }, { "name": "Pen", "price": 2, "discount": 10 } ] assert calculate_total_with_discount(products) == 10.8 if __name__ == "__main__": print("*"*3+" Running tests without discount "+"*"*3) test_calculate_total_with_empty_list() test_calculate_total_with_single_product() test_calculate_total_with_multiple_product() print("*"*3+" All tests passed "+"*"*3) # ---------------------------- print("*"*3+" Running tests with discount "+"*"*3) test_calculate_total_discount_with_empty_list() test_calculate_total_discount_with_single_product() test_calculate_total_discount_with_multiple_product() print("*"*3+" All tests passed "+"*"*3) ```
````python def calculate_total(products, discount=0): total = 0 for product in products: total += product["price"] # Aplicar descuento total -= total * (discount/100) return total def test_calculate_total_with_empty_list(): assert calculate_total([]) == 0 # Lista vacía, sin productos, total 0 def test_calculate_total_single_product(): products = [ { "name": "Notebook", "price": 5 } ] assert calculate_total(products) == 5 # Sin descuento def test_calculate_total_single_product_with_discount(): products = [ { "name": "Notebook", "price": 100 } ] # Aplicamos un descuento del 10%, por lo que el total debe ser 90 assert calculate_total(products, discount=10) == 90 # Descuento del 10% def test_calculate_total_multiple_product_with_discount(): products = [ { "name": "Notebook", "price": 5 } ] assert calculate_total(products, discount=50) == 2.5 # Descuento al 50% def test_calculate_total_multiple_product(): products = [ { "name": "Book", "price": 10 }, { "name": "Pen", "price": 2 } ] assert calculate_total(products, discount=50) == 6 # Descuento al 50% if __name__ == "__main__": test_calculate_total_with_empty_list() test_calculate_total_single_product() test_calculate_total_single_product_with_discount() test_calculate_total_multiple_product() test_calculate_total_multiple_product_with_discount() # Corregido el nombre de la función ```*def* calculate\_total(*products*, *discount*=0):    total = 0    for product in products:        total += product\["price"]    # Aplicar descuento    total -= total \* (discount/100)    return total *def* test\_calculate\_total\_with\_empty\_list():    assert calculate\_total(\[]) == 0  # Lista vacía, sin productos, total 0 *def* test\_calculate\_total\_single\_product():    products = \[        {            "name": "Notebook", "price": 5        }    ]    assert calculate\_total(products) == 5  # Sin descuento *def* test\_calculate\_total\_single\_product\_with\_discount():    products = \[        {            "name": "Notebook",             "price": 100        }    ]    # Aplicamos un descuento del 10%, por lo que el total debe ser 90    assert calculate\_total(products, *discount*=10) == 90  # Descuento del 10% *def* test\_calculate\_total\_multiple\_product\_with\_discount():    products = \[        {            "name": "Notebook", "price": 5        }    ]    assert calculate\_total(products, *discount*=50) == 2.5  # Descuento al 50% *def* test\_calculate\_total\_multiple\_product():    products = \[        {            "name": "Book", "price": 10        },        {            "name": "Pen", "price": 2        }    ]    assert calculate\_total(products, *discount*=50) == 6  # Descuento al 50% if \_\_name\_\_ == "\_\_main\_\_":    test\_calculate\_total\_with\_empty\_list()    test\_calculate\_total\_single\_product()    test\_calculate\_total\_single\_product\_with\_discount()    test\_calculate\_total\_multiple\_product()    test\_calculate\_total\_multiple\_product\_with\_discount()  # Corregido el nombre de la función ````
Mi aporte al reto de la clase. Agregue un parámetro descuento para poder ser usado en las siguientes funciones añadí más productos y le añadí el descuento y una validación ```python def calculate_total(products, discount = 0): total = 0 for product in products: total += product['price'] if discount > 0: total -= total * (discount/100) return total def test_calculate_total_with_empty_list(): assert calculate_total([]) == 0 def test_calculate_total_with_single_product(): products = [ { "Name": "Notebook", "price": 5 } ] assert calculate_total(products) == 5 def test_calculate_total_with_multiple_product(): products = [ { "Name": "Book", "price": 10 }, { "Name": "Pen", "price": 2 }, { "Name": "Pencil", "price": 4 }, { "Name": "Erased", "price": 5 } ] assert calculate_total(products) == 21 def test_calculate_total_with_discount(): products = [ { "Name": "Book", "price": 10 }, { "Name": "Pen", "price": 2 }, { "Name": "Pencil", "price": 4 }, { "Name": "Eraser", "price": 5 } ] assert calculate_total(products, discount=10) == 18.9 # 10% discount on 21 if __name__ == "__main__": test_calculate_total_with_empty_list() test_calculate_total_with_single_product() test_calculate_total_with_multiple_product() test_calculate_total_with_discount() ```
Muy bueno
Aquí les dejo 5 ventajas de usar testing de software que me ha tirado la IA: 1. Detección temprana de errores: Identificar y corregir errores en las primeras etapas del desarrollo reduce el costo y el esfuerzo necesarios para solucionarlos más adelante. 2. Mejora de la calidad del software: Las pruebas aseguran que el software cumpla con los requisitos y funcione correctamente, lo que mejora la satisfacción del cliente y la reputación del producto. 3. Facilita el mantenimiento: Un buen conjunto de pruebas puede servir como documentación y ejemplos, lo que facilita la comprensión y el mantenimiento del código a largo plazo. 4. Aumenta la eficiencia del desarrollo: Las pruebas automatizadas permiten realizar cambios y actualizaciones de manera más ágil, favoreciendo la integración continua y el desarrollo ágil. 5. Prevención de regresiones: Las pruebas continuas ayudan a asegurar que nuevas modificaciones no introduzcan errores en partes del software que ya funcionaban correctamente.
```js import unittest def calculate_total(products): total = 0 for product in products: total += product["price"] return total class TestCalculateTotal(unittest.TestCase): def test_calculate_total_with_empty_list(self): self.assertEqual(calculate_total([]), 0) def test_calculate_total_with_single_product(self): products = [ { "name": "Notebook", "price": 5 } ] self.assertEqual(calculate_total(products), 5) def test_calculate_total_with_multiple_product(self): products = [ { "name": "Book", "price": 10 }, { "name": "Pen", "price": 2 } ] self.assertEqual(calculate_total(products), 12) if __name__ == "__main__": unittest.main() ``` COnfirmación Correcta por consola.
Mi solución: ```js def calculate_total(products, discount=0): total=0 for product in products: total+= product["price"] * (1-(discount/100)) return total def test_calculate_total_with_empty_list(): assert calculate_total([]) == 0 def test_calculate_total_with_single_product(): products = [ { "name" : "noteBook", "price" : 10 } ] assert calculate_total(products,10) == 9 def test_calculate_total_with_multi_products(): products = [ { "name" : "noteBook", "price" : 10 }, { "name" : "cellphone", "price" : 20 }, { "name" : "mouse", "price" : 15 } ] assert calculate_total(products,20) == 36 if __name__ == "__main__": test_calculate_total_with_empty_list() test_calculate_total_with_single_product() test_calculate_total_with_multi_products() ```def calculate\_total(products, discount=0): total=0 for product in products: total+= product\["price"] \* (1-(discount/100)) return total def test\_calculate\_total\_with\_empty\_list(): assert calculate\_total(\[]) == 0 def test\_calculate\_total\_with\_single\_product(): products = \[ { "name" : "noteBook", "price" : 10 } ] assert calculate\_total(products,10) == 9 def test\_calculate\_total\_with\_multi\_products(): products = \[ { "name" : "noteBook", "price" : 10 }, { "name" : "cellphone", "price" : 20 }, { "name" : "mouse", "price" : 15 } ] assert calculate\_total(products,20) == 36 if \_\_name\_\_ == "\_\_main\_\_": test\_calculate\_total\_with\_empty\_list() test\_calculate\_total\_with\_single\_product() test\_calculate\_total\_with\_multi\_products()