Doctest: Make your testing simpler and more efficient

Introduction: Doctest is part of the Python standard library, which allows developers to test by writing examples in documentation strings (docstrings). Not only does this allow for documentation while ensuring the correctness of the code, it also makes it easier for readers to understand the usage of the code and the expected output.

Advantages of comparing unittest and pytest:

1. Simplicity: Compared with unittest and pytest, Doctest has a more concise syntax. It writes test examples in documentation strings, making the test look clearer and easier to read.

2. Intuitiveness: By reading the examples in Doctest, developers and users can quickly understand the usage of functions or methods.

3. Ease of use: Doctest does not require additional installation and configuration. It is part of the Python standard library and can be used directly.

Installation: Doctest is a built-in library of Python and does not require additional installation.

Parameter description: Common parameters:

-v:启用详细模式,显示所有测试用例的输出结果。

doctest.testmod():运行当前模块中的所有 Doctest。

verbose 参数,如果设置为True则在执行测试的时候会输出详细信息。
默认是False,表示运行测试时,只有失败的用例会输出详细信息,成功的测试用例不会输出任何信息。

Case:   test addition function , test string reversal function, use of class object methods. ​​​​​​​

# -*- coding: utf-8 -*-
# time: 2023/9/26 0:47
# file: doctest_demo.py
# 公众号: 伤心的辣条
import doctest


def add(a, b):
    """
    # case1 加法函数
    This function adds two numbers and returns the sum.

    >>> add(2, 3)
    5

    >>> add(-1, 1)
    0
    """
    return a + b


def reverse_string(s):
    """
    # case2 翻转字符串函数
    This function returns the reversed string.

    >>> reverse_string('hello')
    'olleh'

    >>> reverse_string('Python')
    'nohtyP'
    """
    return s[::-1]


class Cat:
    def __init__(self, name, age):
        self.name = name
        self.age = age

    def fishing(self):
        """
        >>> c = Cat('tom', 5)
        >>> c.fishing()
        tom is a cat, 5 years old, and now he is fishing.
        True

        >>> c = Cat('Lucy', 22)
        >>> c.fishing()
        Lucy is too old to fish.
        False

        >>> c = Cat('Lily', 1)
        >>> c.fishing()
        Lily is too young to fish yet.
        False
        """
        if 2 <= self.age <= 20:
            print(f"{self.name} is a cat, {self.age} years old, and now he is fishing.")
            return True
        elif self.age < 2:
            print(f"{self.name} is too young to fish yet.")
            return False
        else:
            print(f"{self.name} is too old to fish.")
            return False


if __name__ == '__main__':
    doctest.testmod(verbose=True)

operation result:

When it doesn’t meet expectations:

Note: Make sure the test case output exactly matches the example, including spaces and newlines. Doctest is more suitable for simple test scenarios that don't require much setup and cleanup.

Summary: Doctest is a simple, intuitive, and easy-to-use testing framework that allows you to quickly write and understand tests through examples in documentation strings. Compared to other testing frameworks, Doctest provides a clear and efficient solution for simple testing scenarios. In daily Python development, rational use of Doctest can help you better ensure the correctness and quality of your code.

Finally: The complete software testing video tutorial below has been compiled and uploaded. Friends who need it can get it by themselves [guaranteed 100% free]

Software Testing Interview Document

We must study to find a high-paying job. The following interview questions are the latest interview materials from first-tier Internet companies such as Alibaba, Tencent, Byte, etc., and some Byte bosses have given authoritative answers. After finishing this set I believe everyone can find a satisfactory job based on the interview information.

Guess you like

Origin blog.csdn.net/AI_Green/article/details/133306533