Introduction to the document test module in Python

Source: Internet
Author: User
This article mainly introduces the document test module in Python. the code is based on Python 2.x. For more information, see The Python official documentation. For example, the re module carries a lot of sample code:

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

You can input and execute the sample code in the Python interactive environment. The result is consistent with that shown in the sample code in the document.

These codes and other instructions can be written in comments, and some tools will automatically generate documents. Since these codes can be pasted and directly run, can they be automatically executed and written in comments?

The answer is yes.

When writing a comment, if you 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)

Clearly tell the caller of the function the expected input and output of the function.

In addition, the Python built-in doctest module can directly extract the code in the comments and perform the test.

Doctest strictly checks whether the test results are correct based on the input and output of the Python interactive command line. Only when a test exception occurs, you can use... to indicate an annoying output in the middle.

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

class Dict(dict):  '''  Simple dict but also support access as x.y style.  >>> d1 = Dict()  >>> d1['x'] = 100  >>> d1.x  100  >>> d1.y = 200  >>> d1['y']  200  >>> d2 = Dict(a=1, b=2, c='3')  >>> d2.c  '3'  >>> d2['empty']  Traceback (most recent call last):    ...  KeyError: 'empty'  >>> d2.empty  Traceback (most recent call last):    ...  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] = valueif __name__=='__main__':  import doctest  doctest.testmod()

Run python mydict. py:

$ python mydict.py

No output. This indicates that all the doctest operations we have written are correct. If the program has a problem, for example, comment out the _ getattr _ () method, and then run it again, an error is returned:

$ 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 13, in __main__.DictFailed example:  d2.cException raised:  Traceback (most recent call last):   ...   AttributeError: 'Dict' object has no attribute 'c'**********************************************************************

Note the last two lines of code. When the module is imported normally, doctest is not executed. Execute doctest only when the command line is running. Therefore, you do not have to worry that doctest will be executed in a non-test environment.
Summary

Doctest is very useful, not only for testing, but also for example code. Some document generation tools can automatically extract comments containing doctest. When you read the document, you also see doctest.

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.