pctechguide.com

  • Home
  • Guides
  • Tutorials
  • Articles
  • Reviews
  • Glossary
  • Contact

Guidelines on Troubleshooting Python Code

Whenever we write a computer program we need to verify that it works as expected. Usually we execute the code, if necessary we provide some inputs, and finally we observe if the output obtained is what we want. If not, check the program, make the necessary corrections, and repeat the previous process. The action of testing and verifying that a program generates the expected results is usually done manually and not automatically. This can be tedious and time consuming when the software being written goes beyond a relatively small application.

Fortunately, there are automated unit tests, which are portions of code designed to check that the main code is working as expected.

Let’s look at an example. Suppose we want to write in Python a function that calculates the hypotenuse c of a right triangle given its a and b legs:

Pythagoras’ theorem states that the square of the hypotenuse is equal to the sum of the squares of the respective legs, that is:

In Python the hypotenuse function could be coded as follows:
from math import sqrt

def hypotenuse(a, b):
return sqrt(a ** 2 + b ** 2)
NOTE: All code presented here was tested with Python 3.7.

The following code could be considered a unit test to verify that the hypotenuse function returns the expected result from entries 3 and 4:
if hypotenuse(3.0, 4.0) == 5.0:
print(‘Passed the test’)
else
print(‘Test failed’)
However, writing tests similar to the previous example is not recommended because it requires a lot of code when we want to make multiple tests and it is not the conventional way to do it.

Source: searchengineland.com

The standard Python distribution provides two mechanisms that simplify the writing and automation of our unit tests: unittest and doctest. The first option is a module inspired by the unit testing frameworks developed by Erich Gamma and Kent Beck for the Java and Smalltalk languages. The second option, doctest, is generally considered simpler to use than unittest, although the latter may be more suitable for more complex tests.

Next I will make a brief introduction to the doctest module in order to elaborate unit tests when defining functions in Python.

The doctest goes inside the docstring
A docstring is a string of characters that is placed as the first statement of a module, class, method or function in order to explain its intent. I explained this a few years ago in more detail in this blog post titled Documenting Programs in Python.

The hypotenuse function, defined above, could have the docstring shown here:
from math import sqrt

def hypotenuse(a, b):
Calculate the hypotenuse of a right triangle.

Use the Pythagorean theorem to determine the
hypotenuse from the legs of a triangle.

Parameters:
a -- first leg
b -- second leg

'''
return sqrt(a ** 2 + b ** 2)

Here the docstring is a string of multi-line characters, which begins and ends with single (”’) or double (“””) double quotes.

The doctest module searches docstrings for text fragments that look like interactive Python sessions in order to execute them and verify that they work exactly as shown.

For example, the next Python interactive session shows how the hypotenuse function behaves with different arguments:

hypotenuse(3.0, 4.0)
5.0
hypotenuse(0.0, 0.0)
0.0
hypotenuse(8.0, 15.0)
17.0
hypotenuse(39.0, 80.0)
89.0
round(hypotenuse(1.0, 1.0), 4)
1.4142
NOTE: In the latter case the round function was used to round the result to 4 digits after the decimal point. It is recommended to do it in this way in order to avoid the precision problems that arise when real numbers appear with a fractional part composed of many digits.

The full text of this interactive session, including the prompts of the interpreter (>>>), is placed inside the doctring, typically at the end, although it can actually go anywhere:
from math import sqrt

def hypotenuse(a, b):
Calculate the hypotenuse of a right triangle.

Use the Pythagorean theorem to determine the
hypotenuse from the legs of a triangle.

Parameters:
a -- first leg
b -- second leg

Examples of use:

>>> hypotenuse(3.0, 4.0)
5.0
>>> hypotenuse(0.0, 0.0)
0.0
>>> hypotenuse(8.0, 15.0)
17.0
>>> hypotenuse(39.0, 80.0)
89.0
>>> round(hypotenuse(1.0, 1.0), 4)
1.4142

'''
return sqrt(a ** 2 + b ** 2)

Running the evidence
There are two options for running the tests. The first option is to use the system terminal and run a command similar to the next one (assuming that the file containing our code is called pitagoras.py):
python3 -m doctest pitagoras.py
The -m doctest option tells the Python interpreter to run the doctest module. The command does not produce any output if it passes all tests.

If any test fails, then you will see a message with the relevant information. For example, if we add to the doctring the following case, which has an incorrect result:

hypotenuse(2.0, 2.0)
2.0
when running the tests again we get a message similar to the following one:


File “pitagoras.py”, line 25, in
pitagoras.hypotenusa
Failed example:
hypotenuse(2.0, 2.0)
Expected:
2.0
Got:
2.8284271247461903


1 items had failures:
1 of 6 in pitagoras.hypotenusa
Test Failed 1 failures.
You can also add the -v option (enable verbose or detailed mode) on the command line when running our tests. In this case a complete report is produced with the information of all the tests, whether they were successful or not:
python3 -m doctest pitagoras.py -v
The way out in this case would be:
Trying:
hypotenuse(3.0, 4.0)
Expecting:
5.0
ok
Trying:
hypotenuse(0.0, 0.0)
Expecting:
0.0
ok
Trying:
hypotenuse(8.0, 15.0)
Expecting:
17.0
ok
Trying:
hypotenuse(39.0, 80.0)
Expecting:
89.0
ok
Trying:
round(hypotenuse(1.0, 1.0), 4)
Expecting:
1.4142
Okay.
Trying:
hypotenuse(2.0, 2.0)
Expecting:
2.0


File “pitagoras.py”, line 25, in
pitagoras.hypotenusa
Failed example:
hypotenuse(2.0, 2.0)
Expected:
2.0
Got:
2.8284271247461903
1 items had no tests:
pitagoras


1 items had failures:
1 of 6 in pitagoras.hypotenusa
6 tests in 2 items.
5 passed and 1 failed.
Test Failed 1 failures.
The second option to run the tests is to add the following three lines of code at the end of the pitagoras.py file:
if name == ‘main‘:
import doctest
doctest.testmod()
The previous if statement checks whether the current file is being executed as a program (when the name variable is equal to the string ‘main‘) or if it was imported as a module (when the name variable is equal to the module name, in this case the string ‘pitagoras’). We only want to carry out the tests when the file is run as a program and, when so, we import the doctest module followed by the invocation of its testmod function.

After this we can run our file as we see fit (for example, from the terminal or using our favorite development environment). If it is from the terminal, just type the following command:
python3 pitagoras.py
As we saw before, if no output is produced it means that all the tests were passed.

If we want to see the whole report of successful and failed tests we can add again the -v option in the terminal command:
python3 pitagoras.py -v
Alternatively, the same effect can be achieved by modifying the code to add the optional True verbose parameter when invoking the testmod function:
doctest.testmod(verbose=True)
Now, every time the file is run as a program, regardless of whether or not the -v option was used from the terminal, you will get the full report with the result of all tests.

With all the mentioned adjustments, the file pitagoras.py remains in its final version like this:
from math import sqrt

def hypotenuse(a, b):
Calculate the hypotenuse of a right triangle.

Use the Pythagorean theorem to determine the
hypotenuse from the legs of a triangle.

Parameters:
a -- first leg
b -- second leg

Examples of use:

>>> hypotenuse(3.0, 4.0)
5.0
>>> hypotenuse(0.0, 0.0)
0.0
>>> hypotenuse(8.0, 15.0)
17.0
>>> hypotenuse(39.0, 80.0)
89.0
>>> round(hypotenuse(1.0, 1.0), 4)
1.4142
>>> hypotenuse(2.0, 2.0)
2.0

'''
return sqrt(a ** 2 + b ** 2)

if name == ‘main‘:
import doctest
doctest.testmod(verbose=True)
This version of the program can be run from the terminal, as already explained, or from any editor or development environment for Python (IDLE, Spyder, Visual Studio Code, etc.) using the respective mechanisms available to execute code.

Best Practices
These are some recommended practices when writing unit tests using doctest:
They should logically be as simple as possible.

Filed Under: Articles

Latest Articles

Voice Modems

Voice modems are part of the current communications convergence trend - the merging of voice, data, fax, and even video - which is affecting all aspects of data communications. Consider the Internet, originally a file transfer system, which is … [Read More...]

Micro ATX motherboard form factor

Introduced in the late 1990s, the MicroATX is basically a smaller version of Intel's ATX specification, intended for compact, low-cost consumer systems with limited expansion potential. The maximum size of the board is 9.6in square, and its designed to fit into either a standard ATX … [Read More...]

FireWire 800 Interfaces

In early 2001 the battle between IEEE 1394 and USB advanced another step with the 1394 Trade Association's approval of specifications for a faster version of IEEE 1394, called IEEE 1394b. The new standard is backwards compatible - special … [Read More...]

What is the Best VPN for Gamers?

Of the 44% of UK Internet users who have used a virtual private network (VPN) at some point in their lives, approximately 39% of this demographic are … [Read More...]

Think About Headless Commerce as of a Modular System

In recent years, eCommerce has transformed to where consumers no longer handle purchases on conventional websites. Shopping is currently carried out … [Read More...]

Service That Succeeds: How To Build an Effective IT Service Desk

In today’s tech-forward world, building a capable IT service team is essential for businesses hoping to scale tech-related hurdles and soar past the … [Read More...]

A simple PC guide on keeping safe while using public Wi-Fi

Did you know that there is a cyberattack every 39 seconds? You are more likely to be a victim if you are lax about your digital security. This … [Read More...]

Motivating Students to Learn Computer Science

Computer science has been an important part of the educational curriculum for decades. Professor Seymour Papert, a mathematician from South Africa … [Read More...]

AI is Driving Changes in the Field of Urban Planning

Artificial intelligence is changing many aspects of our lives. It is being used in more fields than ever before. One of the fields affected by AI … [Read More...]

Guides

  • Computer Communications
  • Mobile Computing
  • PC Components
  • PC Data Storage
  • PC Input-Output
  • PC Multimedia
  • Processors (CPUs)

Recent Posts

Apple Quicktime

Recognizing the drawback of requiring a costly playback adapter, Apple developed a video format that can be played without … [Read More...]

Remote Utilities for Computer Remote Access

Staying connected to your PC while you are travelling or away from it is an extremely useful feature in today’s computer landscape. Remote access … [Read More...]

How to Get Music From Ipod to Computer

When it comes to getting music from your ipod onto your computer, Itunes does not let you. The music industry is very concerned over piracy and … [Read More...]

[footer_backtotop]

Copyright © 2022 About | Privacy | Contact Information | Wrtie For Us | Disclaimer | Copyright License | Authors