How to write Doctest in Python



Writing documents and testing code play a key role in the software development process. In fact, testing the code ensures that the program will work properly. It also provides compatibility between programming and user needs.

In fact, writing a document and testing it before encoding helps the programmer a lot. This is because the programmer makes sure that the coded function (for example) is well thought out and considers only possible cases.

The Python programming language is one of the programming languages ​​that is very easy to teach and learn. Therefore, many developers choose this language as their first programming language. In fact, Python was developed as a universal language and can be used for anything.

The Python programming language has many possibilities. One of these features is a framework module called Doctest. This module programmatically searches the Python code for sections of text in comments that look like interactive Python sessions. The module then runs these sessions to verify that the reference code provided by Doctest is running as expected.

But how to write Doctest in Python? In the continuation of this article from Pars Pack we will teach you step by step how to write Doctest. So join us.

Note: To use the Doctest function, you must first install Python 3 and create a programming environment.

Structure of Doctest in Python

Writing Doctest in Python is similar to writing a comment, except that there are three quotes (“” “at the beginning and end. Doctests are sometimes written with an example of the expected function and output. But sometimes there may be explanations of what the function intends to do.

Inserting a comment shows that you, as a programmer, have stated your goals more clearly and that the person reading the code understands it well. More generally, one of the conditions for clean and orderly coding is the timely use of comments to provide explanations!

The structure of the doctest python

Training in doctest python and its structure

Note: To be with you during the application of the example in this tutorial, install an interactive Python shell on your local system; By running the Python3 command; Open up. Now, by adding examples after <<<, you can copy, paste or edit them.

The following is a mathematical example from Doctest for a function like add (a, b) that puts two numbers together:

"""
Given two integers, return the sum.

>>> add (2, 3)
۵
"""

This example includes an explanatory line, an example of an add () function with two integers as input values. If you plan to add more than 2 integers in the future with this function, you need to change the Doctest to match the inputs of your function.

This doctoral degree has so far been read by everyone. However, this document string can be repeated with machine-readable parameters and a return description – to illuminate the input / output variables to this function.

Then we add docstrings for both arguments sent to the function and the return value. The documentation records data types for each of the values ​​- parameter a, parameter b and the return value. In this case, all parameters are integers.

"""
Given two integers, return the sum.

:param a: int
:param b: int
:return: int

>>> add(2, 3)
۵
"""

Well, now Doctest is ready for commissioning and testing.

Turn Doctest into function

Doctests are usually placed in a function after the def command and before the function code. After the initial definition of a function, it will have indents according to Python conventions. This short function shows how to insert a channel into it.

def add(a, b):
"""
Given two integers, return the sum.

:param a: int
:param b: int
:return: int

>> add(2, 3)
۵
"""
return a + b

You already have a function, so you need to enter the Doctest module and have a command to run it.

To do this, you need to add the following description to before and after your function:

import Doctest
...
Doctest .testmod()

In this step, instead of saving it to a program file, test it in the Python shell. To do this, you can use the python3 command:

$ python3

If you use this execution path, you will get the following output after pressing the Enter key on your keyboard:

Output
Type "help", "copyright", "credits" or "license" for more information.
>>>

After the <<< sign, you can start entering the code you want.

The full code used in this example includes the function () with the channel, the channel and the call to call the channel. Now put it in your Python translator to test it on the plant:

import Doctest

def add(a, b):
"""
Given two integers, return the sum.

:param a: int
:param b: int
:return: int

>>> add(2, 3)
۵
"""
return a + b

Doctest .testmod()

After starting, you will receive the following source code:

Output
TestResults(failed=0, attempted=1)

This means that the code is executed according to your expectations!

Note that if in the above program the sum of two integers a + b is changed by multiplying two numbers a * b, you will be notified that it is not successful:

**********************************************************************
File "__main__", line 9, in __main__.add
Failed example:
    add(2, 3)
Expected:
    ۵
Got:
    ۶
**********************************************************************
۱ items had failures:
   ۱ of   1 in __main__.add
***Test Failed*** 1 failures.
TestResults(failed=1, attempted=1)

Using the example above, you can understand the importance of the Doctest module. Because the whole thing will show you what happened. You may want to look at more examples. For example, take the values ​​of a and b for zero and then take their sum with the + operator:

import Doctest

def add(a, b):
"""
Given two integers, return the sum.

:param a: int
:param b: int
:return: int

>>> add(2, 3)
۵
>>> add(0, 0)
۰
"""
return a + b

Doctest .testmod()

After implementation you will receive the following feedback from Python Translator:

TestResults(failed=0, attempted=2)

This result indicates that Doctest has performed two tests. One is related to the sum of value added (2,3) and the other is related to the sum (0,0). Both results are correct.

If you change the program again to use the multiplier * instead of the + operator, you can see the meaning of the endpoints in the Doctest module. Because in the second example add (0,0) will return the same value (whether multiplied or added).

import Doctest

def add(a, b):
"""
Given two integers, return the sum.

:param a: int
:param b: int
:return: int

>>> add(2, 3)
۵
>>> add(0, 0)
۰
"""
return a * b

Doctest .testmod()

The following output now returns:

**********************************************************************
File "__main__", line 9, in __main__.add
Failed example:
add(2, 3)
Expected:
۵
Got:
۶
**********************************************************************
۱ items had failures:
۱ of 2 in __main__.add
***Test Failed*** 1 failures.
TestResults(failed=1, attempted=2)

When you make changes to the program, you may get an error for one of the examples, but in general the steps will be performed as before. So keep in mind that making small changes to the program will create opportunities for it to fail or not run.

Doctest in programming files

So far, you have used the Python interactive terminal as your example. Now use a program file to count the number of vowels in a word.

Doctest python testing module

Doctest python module for easier testing

In a program you can import and call the Doctest module in the if __name__ == “__main__” clause: at the bottom of the program file. First, create a new file – counting_vowels.py – in your text editor. You can use the nano editor on the command line:

$ nano counting_vowels.py

You can start by defining the count_vowels function and passing the word parameter to the function:

def count_vowels(word):

Before writing the puff function, it is best to explain what you want from the function in Doctest:

def count_vowels(word):
    """
    Given a single word, return the total number of vowels in that single word.

We consider the data type with the word parameter and the returned data type first as a string and in the second case as an integer. In fact, in the first case, a string is displayed, and in the second case, an integer is displayed.

def count_vowels(word):
    """
    Given a single word, return the total number of vowels in that single word.

    :param word: str
    :return: int

You can try an example to better understand the topic. Think of a vowel word and enter it in the string of the document string.

For example, choose the word “Cusco”. How many vowels are there in this word? In English, vowels include a, e, i, o and u. So in this example you have two vowels o and u.

Now we add the test for the word Cuso and its return, which is 2 as integers in our program:

def count_vowels(word):
    """
    Given a single word, return the total number of vowels in that single word.

    :param word: str
    :return: int

    >>> count_vowels('Cusco')
    ۲

To better understand the topic, try another example with more vowels like Manila:

def count_vowels(word):
    """
    Given a single word, return the total number of vowels in that single word.

    :param word: str
    :return: int

    >>> count_vowels('Cusco')
    ۲

    >>> count_vowels('Manila')
    ۳
    """

Doctest is currently running. So you can start coding your program.

Let’s start with initializing a variable: Use total_vowels to keep vowels in the word. Now in the next step create a for loop to repeat between the letters in the string. Then use a conditional statement to check that the letters are vowels. The number of vowels will increase during the cycle and finally the last number obtained from the word vowel count will be returned to total_values. The program is therefore similar to the structure presented without a channel, as follows:

def count_vowels(word):
    total_vowels = 0
    for letter in word:
        if letter in 'aeiou':
            total_vowels += 1
    return total_vowels

Now enter your master key at the bottom of the code and run the Ductest module:

if __name__ == "__main__":
    import doctest
    doctest.testmod()

Finally, the program is as follows:

def count_vowels(word):
    """
    Given a single word, return the total number of vowels in that single word.

    :param word: str
    :return: int

    >>> count_vowels('Cusco')
    ۲

    >>> count_vowels('Manila')
    ۳
    """
    total_vowels = 0
    for letter in word:
        if letter in 'aeiou':
            total_vowels += 1
    return total_vowels

if __name__ == "__main__":
    import doctest
    doctest.testmod()

You can run this program using the python or python3 command (depending on your virtual resources):

python counting_vowels.py

If your entire program is written as above, all tests must be passed and you will not get any results. This means that you have passed the tests. This feature is useful for starting the program for other purposes. If you run the test specifically to see the result, you can use the v-flag as follows:

python counting_vowels.py -v

Finally, when you start the program, you will get the following output:

Trying:
    count_vowels('Cusco')
Expecting:
    ۲
ok
Trying:
    count_vowels('Manila')
Expecting:
    ۳
ok
۱ items had no tests:
    __main__
۱ items passed all tests:
   ۲ tests in __main__.count_vowels
۲ tests in 2 items.
۲ passed and 0 failed.
Test passed.

So far, you have successfully passed the test. However, the program code may not be optimized for specific situations. Below we will learn how to use Doctests to improve our code.

Use Doctest to improve and strengthen code

So far we have a program that works. But perhaps the best program is not available. So at this stage we will try to correct its minor shortcomings. For example, have you ever wondered what would happen if we introduced a vowel in the main form?

Use doctests in Python

Example of using doctests in Python

As a result, you will enter another example in Doctest. Think of the word “Istanbul” this time. Like Manila, Istanbul has three vowels.
Here you can see the updated program with a new example:

def count_vowels(word):
    """
    Given a single word, return the total number of vowels in that single word.

    :param word: str
    :return: int

    >>> count_vowels('Cusco')
    ۲

    >>> count_vowels('Manila')
    ۳

    >>> count_vowels('Istanbul')
    ۳
    """
    total_vowels = 0
    for letter in word:
        if letter in 'aeiou':
            total_vowels += 1
    return total_vowels

if __name__ == "__main__":
    import doctest
    doctest.testmod()

Run the program again now:

$ python counting_vowels.py

At that moment, we discovered the mistake we were looking for! Simply put, you will get the following output after execution:

**********************************************************************
File "counting_vowels.py", line 14, in __main__.count_vowels
Failed example:
    count_vowels('Istanbul')
Expected:
    ۳
Got:
    ۲
**********************************************************************
۱ items had failures:
   ۱ of   3 in __main__.count_vowels
***Test Failed*** 1 failures.

The above output indicates that your application has encountered an error. You expected it to show 3 vowels while recognizing only 2 vowels. But what is the reason for this error?

The reason for the error is that in the conditional phrase if the letter in ‘aeiou’: you have defined lowercase vowels and the program cannot recognize uppercase letters.

To solve this problem, you can define vowels as AEIOUaeiou ‘or you can change the word to word.lower () to convert each uppercase letter to lowercase and thus calculate it except for counting. Slow.

def count_vowels(word):
    """
    Given a single word, return the total number of vowels in that single word.

    :param word: str
    :return: int

    >>> count_vowels('Cusco')
    ۲

    >>> count_vowels('Manila')
    ۳

    >>> count_vowels('Istanbul')
    ۳
    """
    total_vowels = 0
    for letter in word.lower():
        if letter in 'aeiou':
            total_vowels += 1
    return total_vowels

if __name__ == "__main__":
    import doctest
    doctest.testmod()

Finally, run the program using python counting_vowels.py -v and a wordy flag. This program may not be the best possible program and errors will occur after starting it.

For example, if you consider the word “Sydney”. In English, the letter Y is sometimes considered a vowel. Or, for example, if you consider the word “Würzburg”, what is the letter “ü” in English? How should these words be treated? What code or commands will you use for these words?

As a programmer, you sometimes have to make complex decisions. In many cases, you will not consider the full range of options. That’s why the Doctest module is a good tool to start thinking about specific cases and recording basic documentation. But in the end, you have to use human custom tests to create strong applications.

Conclusion

The Doctest module is not only a way to test and document software, but also a way to think about coding, how to get started, document, test and write code. In fact, the lack of code testing will lead not only to errors but also to software malfunctions.

Frequently Asked Questions

1. How do I use Doctest in Python?

The easiest way to start using doctest is to use the following code in each M module:

  • if __name__ == “__main__”: import doctest doctest. test mode ()
  • python M. py.
  • python M. py -v.
  • python -m doctest -in example. py.

2. What is the correct way to write Doctest in Python?

  1. The Python test using the Doctest module is as follows:
  2. Enter the Doctest module.
  3. Write the function with docstring. Inside Docstring, write the following two lines to test the same feature. >>>…
  4. Write the function code.
  5. Now call Doctest. Testmod function (name = function name, verbose = True) for testing.

{“@context”: “https://schema.org”, “@type”: “FAQPage”, “mainEntity”: [{
“@type”: “Question”,
“name”: “چگونه از Doctest در پایتون استفاده کنیم؟”,
“acceptedAnswer”: {
“@type”: “Answer”,
“text”: “ساده ترین راه برای شروع استفاده از doctest این است که در هر ماژول M از کد زیر استفاده کنید:

if __name__ == “__main__”: import doctest doctest. testmod()
python M. py.
python M. py -v.
python -m doctest -v example. py.”
}
},{
“@type”: “Question”,
“name”: “روش صحیح نوشتن Doctest در پایتون چیست؟”,
“acceptedAnswer”: {
“@type”: “Answer”,
“text”: “تست در پایتون با استفاده از ماژول Doctest به صورت زیر است:
ماژول Doctest را وارد کنید.
تابع را با docstring بنویسید. در داخل Docstring دو خط زیر را برای آزمایش همان تابع بنویسید. >>>…
کد تابع را بنویسید.
حالا با Doctest را فراخوانی کنید. تابع testmod(name=function_name، verbose=True) برای آزمایش.”
}
}]
}

How to write Doctest in Python for the first time in Parsupak. appear.

Leave Your Comment

Your email address will not be published.

Supportscreen tag