Python Learning note __8.4 document testing

Source: Internet
Author: User

# This is a learning note for the Liaoche teacher Python tutorial

1 , overview

Write the specification's comment code in the document. Python's built-in document Test (doctest) module can extract the code directly from the comments and perform the test.

1.1 , to ABS () function as an example:

# abs.py

def ABS (n):

    ''' # Two for a pair, newline input

Function to get absolute value of number. # a simple introduction

Example:

>>> ABS (1) # test

1

>>> ABS (-1)

1

>>> ABS (0)

0

    '''   #

return n if n >= 0 else (-N) # function Body

$ python ABS. py # command-line executor, no return value, the code is correct

1.2 , doctest to test the last written Dict class

# mydict2.py

Class Dict (Dict):

 '''

Simple Dict-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):

        ... # of these three . represents a large segment of output

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] = value

If __name__== ' __main__ ':

Import Doctest

Doctest.testmod ()

Summarize:

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.


Python Learning note __8.4 document testing

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.