Ray's playground

 

Doctest: The Easiest Testing Tool(Chapter 2 of Python Testing Beginner's Guide)

test.txt
 1 This is a simple doctest that checks some of Python's arithmetic operations.
 2 >>> 2 + 2
 3 4
 4 >>> 3 * 3
 5 10
 6 
 7 Now we're going to take some more of doctest's syntax for a spin.
 8 >>> import sys
 9 >>> def test_write():
10 ...    sys.stdout.write("Hello\n")
11 ...    return True
12 >>> test_write()
13 Hello
14 True
15 
16 Here we use doctest's exception syntax to check that Python is correctly enforcing its grammer.
17 >>> def faulty():
18 ...    yield 5
19 ...    return 7
20 Traceback (most recent call last):
21 SyntaxError: 'return' with argument inside generator (<doctest test.txt[5]>, line 3)
22 
23 Next up, we're exploring the ellipsis.
24 >>> sys.modules # doctest: +ELLIPSIS
25 {...'sys'<module 'sys' (built-in)>...}
26 >>> 'This is an expression that evaluates to a string'
27 ... # doctest: +ELLIPSIS
28 'This is ... a string'
29 >>> 'This is also a string' # doctest: +ELLIPSIS
30 'This is ... a string'
31 >>> import datetime
32 >>> datetime.datetime.now().isoformat() # doctest: +ELLIPSIS
33 '...-...-...T...:...:...'
34 
35 Next, a demonstration of whitespace normalization.
36 >>> [123456789]
37 ... # doctest: +NORMALIZE_WHITESPACE
38 [123,
39  456,
40  789]
41 >>> sys.stdout.write("This text\n contains weird     spacing.")
42 ... # doctest: +NORMALIZE_WHITESPACE
43 This text contains weird spacing.
44 
45 Now we're telling doctest to skip a test
46 >>> 'This test would fail.' # doctest: +SKIP
47 If it were allowed to run.
48 

 

testable
 1 def testable(x):
 2     r"""
 3     The testable functin returns the square root of its parameter, or 3, whichever is larger.
 4     >>> testable(7)
 5     3.0
 6     >>> testable(16)
 7     4.0
 8     >>> testable(9)
 9     3.0
10     >>> testable(10) == 10 ** 0.5
11     True
12     """
13     if x < 9:
14         return 3.0
15     return x ** 0.5

posted on 2010-11-28 14:04  Ray Z  阅读(295)  评论(0编辑  收藏  举报

导航