Code Monkey home page Code Monkey logo

python_basic_first_challenge's People

Contributors

javleds avatar

Watchers

 avatar  avatar

python_basic_first_challenge's Issues

Comentarios/Mejoras

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

Screenshot from 2021-05-19 08-11-54

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

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.