Doctest first experience and doctest experience

Source: Internet
Author: User

Doctest first experience and doctest experience

The test code is effective only when it is placed in two places. One is the beginning of the module, and the other is the next line of the function declaration statement.

Doctest Conceptual Model

In the official python documentation, doctest is described as follows:


The doctest module searches for code snippets that look like python interactive sessions and then tries to execute and verify the results.

Does the name remind you of docstring?

The process of writing doctest is like importing a tested module in an interactive shell, and then executing the functions in the tested module one by one. In fact, doctest is also written in this way. After writing a module, test the function in this module in shell and copy and paste the content in the shell session into a doctest case.

Test code verification:

This example shows how to embed doctest cases in the source code.
The line starting with '>>>' is the doctest test case.
A line without '>' is the output of the test case.
If the actual running result is inconsistent with the expected result, it is marked as a test failure.
def multiply(a, b):
    >>> multiply(4, 3)
    >>> multiply('a', 3)
    return a * b
if __name__=='__main__':
    import doctest

Then locate the file directory in the command line and run python-m doctest-v

The parameter-v indicates Printing Details. If no error is found after removal, nothing is displayed.

The test results are as follows:

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.