READING-NOTE

View on GitHub

Testing & Modules

Unit tests and TDD?

Baby Steps

The API is pretty straightforward and your work was almost done. But with TDD we need to think about tests first. And to be ok with the possibility of the beginning to be hard sometimes — and it’s totally fine. Really. Coming back to the code and thinking with baby steps, what is the smaller test that we can do against a function (method/class) that will return the gender? Time for you to think Just recaping: we have a name as input and we need to return a gender as output. So, the smaller test is: given a name, return a gender.

Input: Ana [name]
Output: female [gender]

Important aspects about the unit test

def test_should_return_female_when_the_name_is_from_female_gender():
    detector = GenderDetector()
    expected_gender = detector.run(‘Ana’)
    assert expected_gender == ‘female’
mymodule/
 — module.py
 — another_folder/
 — — another_module.py
tests/
 — test_module.py
 — another_folder/
 — — test_another_module.py

Now you can execute the tests. I suggest the lib pytest to do it. But you are free to choose anything you like. Yay! We have our first test. It’s beautiful but it fails. And that is awesome!

The Cycle

1- 🆘 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)

2- ✅ Write the feature and make the test pass! (you can dance after that)

3- 🔵 Refactor the code — the first version doesn’t need to be the beautiful one (don’t be shy)

Using baby steps you can go through this cycle every time you add or modify a new feature in your code.

What does the if “name” == “”main“”: do?

When we execute file as command to the python interpreter

python script.py
# Python program to execute
# main directly
print ("Always executed")

if __name__ == "__main__":
	print ("Executed when invoked directly")
else:
	print ("Executed when imported")

Why Do we need it?

For example we are developing script which is designed to be used as module:

# Python program to execute
# function directly
def my_function():
	print ("I am inside function")

# We can test function by calling it.
my_function()

Now if we want to use that module by importing we have to comment out our call.

Rather than that approach best approach is to use following code:

# Python program to use
# main for function call.
if __name__ == "__main__":
	my_function()

import myscript

myscript.my_function()

Advantages :

  1. 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.
  2. If you import this script as a module in another script, the name is set to the name of the script/module.
  3. Python files can act as either reusable modules, or as standalone programs.
  4. if name == “main”: is used to execute some code only if the file was run directly, and not imported.