Reading-Notes


Project maintained by eslamakram Hosted on GitHub Pages — Theme by mattgraham

Unit Testing in Python

Unit testing is a software testing method by which individual units of source code are put under various tests to determine whether they are fit for use (Source). It determines and ascertains the quality of your code.

Generally, when the development process is complete, the developer codes criteria, or the results that are known to be potentially practical and useful, into the test script to verify a particular unit’s correctness. During test case execution, various frameworks log tests that fail any criterion and report them in a summary.

The unit test framework in Python is called unittest, which comes packaged with Python.

TDD cycle: 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)

module in python

If the python interpreter is running that module (the source file) as the main program, it sets the special name variable to have a value “main”. If this file is being imported from another module, name will be set to the module’s name. Module’s name is available as value to name global variable.

A module is a file containing Python definitions and statements. The file name is the module name with the suffix .py appended.

All of the code that is at indentation level 0 [Block 1] gets executed. Functions and classes that are defined are, well, defined, but none of their code runs. Here, as we executed script.py directly name variable will be main. So, code in this if block[Block 2] will only run if that module is the entry point to your program. Thus, you can test whether your script is being run directly or being imported by something else by testing name variable. If script is getting imported by some other module at that time name will be module name.

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.