javleds / python_basic_first_challenge Goto Github PK
View Code? Open in Web Editor NEWFirst challenge for python basic, calculate triangle area, triangle type and rock paper scissors
First challenge for python basic, calculate triangle area, triangle type and rock paper scissors
Bajé el código y solo le tuve que hacer un cambio en src/input_utils.py
:
from .number_utils import is_float
en lugar de
from number_utils import is_float
Esto porque me marcaba este error:
======================================================================
ERROR: test_input_utils (unittest.loader._FailedTest)
----------------------------------------------------------------------
ImportError: Failed to import test module: test_input_utils
Traceback (most recent call last):
File "/usr/lib/python3.7/unittest/loader.py", line 154, in loadTestsFromName
module = __import__(module_name)
File "/home/david/Projects/jelid/python_basic_first_challenge/tests/test_input_utils.py", line 3, in <module>
from src.input_utils import ask_for_number
File "/home/david/Projects/jelid/python_basic_first_challenge/src/input_utils.py", line 1, in <module>
from number_utils import is_float
ModuleNotFoundError: No module named 'number_utils'
----------------------------------------------------------------------
Ran 1 test in 0.000s
FAILED (errors=1)
Luego, ejecutando el siguiente comando python3 -m unittest tests/test_input_utils.py
me responde lo siguiente:
...
----------------------------------------------------------------------
Ran 3 tests in 0.001s
OK
Yo veo que funciona bien tu test input, solo quité la anotación y lo hice directo. Pero cuando le pongo una letra en lugar de un número, se queda en un ciclo infinito. Yo siempre recomiendo usar try ... except ...
para tener un mejor control de excepciones, en lugar del while True
que estas usando, porque aunque la experiencia del usuario puede ser mejor dado que el programa no avanza a menos de el usuario ingrese un valor correcto, ya no es tan amigable con las pruebas. Yo lo programaría así:
def ask_for_number(message: str) -> float:
value = None
try:
while value is None:
value = input(message)
value = float(value)
except Exception as err:
print(str(err))
print('Invalid character, please type a number. Or press `q` to exit')
return value
De esa forma, cuando ejecuto la prueba no se queda en un ciclo infinito cuando meten una letra en lugar de un número y puedes hacer más robusta tu prueba al considerar casos de errores controlados:
$ python3 -m unittest tests/test_input_utils.py
..could not convert string to float:
Invalid character, please type a number. Or press `q` to exit
F
======================================================================
FAIL: test_multiple_cases (tests.test_input_utils.TestInputUtils)
----------------------------------------------------------------------
Traceback (most recent call last):
File "/home/david/Projects/jelid/python_basic_first_challenge/tests/test_input_utils.py", line 19, in test_multiple_cases
self.assertEqual(ask_for_number(''), 10.0)
AssertionError: '' != 10.0
----------------------------------------------------------------------
Ran 3 tests in 0.001s
FAILED (failures=1)
Aunque ya para concluir, lo más importante es primero preguntar ¿qué quieres probar? es conveniente hacer pruebas separadas, lógica e interacción con el usuario. Me refiero a que si deseas probar tu lógica, separa esa parte dentro de tu código y luego si quieres hacer pruebas de la interacción con el usuario, solo te enfoques a eso. Por último, te recomiendo estos enlaces:
El primer enlace te dice como "organizar" mejor tu código, por lo que preguntabas de incluir el if __name__ == '__main__':
es precisamente cuando ejecutas la prueba directa python3 test/test_input_utils.py
en lugar de python3 -m unittest tests/test_input_utils.py
, pero lo puedes organizar en un solo archivo como una "suite" de pruebas, y mandas a llamar desde ahí todas las pruebas que quieres hacer, y solo ejecutar algo como python3 tests/suite.py
y eso te permite hacerlo más "sencillo".
A ver si luego comparto en phpmx algunos tips con GitHub Actions: https://github.com/marketplace/actions/python-unit-test
A declarative, efficient, and flexible JavaScript library for building user interfaces.
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google ❤️ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.