Gorka Gallardo Castany
Luis Martinez
ProfesorBuen trabajo! Agrega un test si por alguna razón el descuento es mayor que el precio.
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.
Gorka Gallardo Castany
Luis Martinez
ProfesorBuen trabajo! Agrega un test si por alguna razón el descuento es mayor que el precio.
John Eduard Meneses González
My solution!!
Yetzojhanan Varela Sierra
Faustino Vasquez
def caculate_total(products,discount=0): total = 0 for product in products: total += product["price"] - (product["price"] * discount / 100) return total def calculate_total_with_multiple_product_with_discount(): products = [ { "name": "Notebook", "price": 10, }, { "name": "Book", "price": 10, }, { "name": "Pen", "price": 10 } ] assert caculate_total(products, discount=10) == 27
Carlos Esteban Cabrera Reyes
Luis Martinez
ProfesorQué buen ejemplo! sigue así!
Germán García
Germán García
Espero ya no me borren mis comentarios
me faltó el resultado ya con el test de 10% de descuento del reto
l/Programs/Python/Python312/python.exe c:/Users/info/python-testing/PYTHON-TESTING/test.py
4.5
10.8
PS C:\Users\info\python-testing\PYTHON-TESTING>
Sara María Mejia Sánchez
Hola! Les comparto el código de la clase.
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()
Leonardo Damián Paillamilla
Mi codigo, faltaria agregar lanzamientos de errores para descuentos invalidos (negativos o mayor del 100%):
def calculate_total(products, discount=0): total = 0 for product in products: total += product["price"] total -= total * discount return total def test_calculate_total_with_discount(): print("Testeando calculate_total con descuento") products = [ {"name": "Producto A", "price": 10}, {"name": "Producto B", "price": 20} ] """Descuento del 10% sobre el total de 30, que es 3, entonces el total final es 27""" assert calculate_total(products, discount=0.1) == 27
Francisco Antonio Hernandez Sabatino
Hernán García Urrutia
Comparto mi solución
Rubén Téllez Gerardo
JOSUE MARTIN CHI PERERA
Daniel Felipe Ospina Guarnizo
mi solución:
Johan Moises Ariza Mahecha
César Ernesto Rivas Martínez
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
Victor Apolinares
Laura Bedoya
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()
Laura Bedoya
Laura Bedoya
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()
Emmanuel Ferreyra
Aqui mi codigo:
def calculate_total(products, discount=0): total = 0 for product in products: total += product['price'] return total def calculate_discount(total_price, discount): if discount < 0: raise ValueError("El descuento no puede ser negativo") elif discount > total_price: raise ValueError("El descuento no puede ser mayor que el precio") return total_price - discount def test_calculate_discount(): product = [ { 'name' : 'Notebook', 'price': 689 } ] assert calculate_discount(calculate_total(product), 89) == 600 def test_calculate_total_with_empty_list(): assert calculate_total([]) == 0 def test_calculate_total_with_single_product(): product = [ { 'name' : 'notebook', 'price' : 1822 } ] assert calculate_total(product) == 1822 def test_calculate_total_with_multiple_products(): product = [ { 'name' : 'notebook', 'price' : 1822 }, { 'name' : 'smartphone', 'price' : 829 }, { 'name' : 'Headsets', 'price' : 124 } ] assert calculate_total(product) == 2775 if __name__ == '__main__': test_calculate_total_with_single_product() test_calculate_total_with_multiple_products() test_calculate_discount()
Creo que pude:
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:
#----- 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
# 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”. """
from typing import List, Dict, Any, Set def calculate_price(items: list[dict[str, float, float]]): required_keys: Set[str] = {"name", "price"} total_price = 0.0 for item in items: if not required_keys.issubset(item.keys()): return ValueError(f"The items must have 'price' and 'name' properties, 'discount' is optional. Fault item: {item}.") price = item.get("price") if price < 0: return ValueError(f"'price' value cannot be less than zero (0).") total_price += price - (price * item.get("discount", 0)) return total_price
from calculate_price import calculate_price def test_calculate_price_with_one_item(): expected = 5.0 items: dict[str, float] = [ { "price": 5, "name": "product" } ] result = calculate_price(items) print(f"Result 'calculate_price' function: {result}\nExpected: {result}") assert result == expected def test_calculate_price_with_one_item_and_discount(): expected = 4.5 items: dict[str, float] = [ { "price": 5, "name": "product", "discount": 0.10 } ] result = calculate_price(items) print(f"Result 'test_calculate_price_with_one_item_and_discount' function: {result}\nExpected: {result}") assert result == expected def test_calculate_price_with_multiples_item(): expected = 24.5 items: dict[str, float] = [ { "price": 5, "name": "product1" }, { "price": 7.5, "name": "product2" }, { "price": 12, "name": "product2" } ] result = calculate_price(items) print(f"Result 'calculate_price' function: {result}\nExpected: {result}") assert result == expected def test_calculate_price_with_multiples_item_and_discount(): expected = 18.0 items: dict[str, float] = [ { "price": 5, "name": "product1", "discount": 0.10 }, { "price": 7.5, "name": "product2" }, { "price": 12, "name": "product2", "discount": 0.50 } ] result = calculate_price(items) print(f"Result 'test_calculate_price_with_multiples_item_and_discount' function: {result}\nExpected: {result}") assert result == expected def test_calculate_invalid_properties_in_item(): items: dict[str, float] = [ { "price": 5, } ] result = calculate_price(items) assert type(result) == ValueError print("Result: 'test_calculate_invalid_properties_in_item' return a 'ValueError' has expected when object does not have the 'price' or 'name' properties") def test_calculate_invalid_price(): items: dict[str, float] = [ { "price": -5, "name": "product" } ] result = calculate_price(items) assert type(result) == ValueError print("Result: 'test_calculate_invalid_properties_in_item' return a 'ValueError' has expected when value 'price' is less than zero(0).") if __name__ == "__main__": print("Init tests: ") test_calculate_price_with_one_item() test_calculate_price_with_multiples_item() test_calculate_invalid_properties_in_item() test_calculate_invalid_price() test_calculate_price_with_one_item_and_discount() test_calculate_price_with_multiples_item_and_discount()
#!/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:
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()
Comparto mi solución al reto propuesto:
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()
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()
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()
#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")