Introducing the documentation test module in Python

Source: Internet
Author: User
If you often read the official Python documentation, you can see that many documents have sample code. For example, the RE module takes a lot of sample code:

>>> import re>>> m = Re.search (' (? <=abc) def ', ' abcdef ') >>> m.group (0) ' Def '

These sample code can be entered and executed in Python's interactive environment, and the results are consistent with the sample code shown in the documentation.

These codes and other instructions can be written in comments, and then, by some tools, the document is automatically generated. Since the code itself can be pasted and run directly, could it be possible to automate the code written in the comments?

The answer is yes.

When we write a comment, write a comment like this:

def ABS (n):  "Function to  get absolute value of number.  Example:  >>> ABS (1)  1  >>> abs ( -1)  1  >>> abs (0)  0  "  return n if n >= 0 else (-N)

It is undoubtedly more explicit to tell the caller of the function the expected input and output of the function.

Also, Python's built-in "Document Test" (doctest) module can extract the code directly from the comments and perform the test.

Doctest strictly follows the input and output of the Python interactive command line to determine whether the test results are correct. Only when testing an exception, you can use ... Represents a large piece of annoying output in the middle.

Let's use Doctest to test the last written Dict class:

Class Dict (Dict):  "Simple  Dict and also support access as x.y style.  >>> D1 = Dict ()  >>> d1[' x '] = +  >>> d1.x  >>> d1.y =  gt;>> d1[' y ']  >>> d2 = Dict (A=1, b=2, c= ' 3 ')  >>> d2.c  ' 3 '  >> > d2[' empty '  Traceback (most recent):    ...  Keyerror: ' Empty '  >>> d2.empty  Traceback (most recent):    ...  Attributeerror: ' Dict ' object has no attribute ' empty '  def __init__ (self, **kw):    super (Dict, self). _ _init__ (**kw)  def __getattr__ (self, key):    try:      return Self[key]    except Keyerror:      raise Attributeerror (r "' Dict ' object has no attribute '%s '"% key)  def __setattr__ (self, Key, value):    Self[key] = Valu EIF __name__== ' __main__ ':  import doctest  doctest.testmod ()

Run Python mydict.py:

$ python mydict.py

There's nothing out there. This shows that the doctest we have written is correct. If there is a problem with the program, such as commenting out the __getattr__ () method, then the operation will be error:

$ python mydict.py**********************************************************************file "mydict.py", line 7, in __main__. dictfailed Example:  d1.xexception raised:  Traceback (most recent call last):   ...  Attributeerror: ' Dict ' object has no attribute ' x ' ****************************************************************** File "mydict.py", line +, in __main__. dictfailed Example:  d2.cexception raised:  Traceback (most recent call last):   ...   Attributeerror: ' Dict ' object has no attribute ' C ' ****************************************************************** ****

Notice the last two lines of code. When the module is imported normally, the doctest will not be executed. The doctest is executed only when the command line is running. So don't worry that doctest will execute in a non-test environment.
Summary

Doctest is very useful, not only for testing, but also for direct example code. With some document generation tools, you can automatically extract comments that contain doctest. When users look at the document, they also see the doctest.

  • 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: info-contact@alibabacloud.com 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.