Testing and Modules
TDD with Python
The tests can be considered as your alive documentation. We need to be descriptive about it and to say what is expected and what we are testing.
The test file name should follow the same name of module name. For instance, if our module is gender.py, our test name should be test_gender.py.
AAA: Arrange, Act and Assert.
- Arrange: you need to organize the data needed to execute that piece of code (input);
- Act: here you will execute the code being tested (exercise the behaviour);
- Assert: after executing the code, you will check if the result (output) is the same as you were expecting.
The cycle is made by three steps:
- 🆘 Write a unit test and make it fail (it needs to fail because the feature isn’t there, right? If this test passes, call the Ghostbusters, really)
- ✅ Write the feature and make the test pass! (you can dance after that)
- 🔵 Refactor the code — the first version doesn’t need to be the beautiful one (don’t be shy)
Takeaways
- The greatest advantage about TDD is to craft the software design first
- Your code will be more reliable: after a change you can run your tests and be in peace
- Beginning may be hard — and that’s fine. You just need to practice!
if name == main
allows you to test whether your script is being run directly or being imported by something else by testing name variable
Advantages :
- Every Python module has it’s name defined and if this is ‘main’, it implies that the module is being run standalone by the user and we can do corresponding appropriate actions.
- If you import this script as a module in another script, the name is set to the name of the script/module.
- Python files can act as either reusable modules, or as standalone programs.
if name == “main”: is used to execute some code only if the file was run directly, and not imported.
Recursion
def fib(n):
if n <=1:
return n
else:
return ( fib(n - 1) + fib(n - 2) )
References