-
Notifications
You must be signed in to change notification settings - Fork 15
Expand file tree
/
Copy pathdoctest_cheat.py
More file actions
executable file
·151 lines (104 loc) · 2.2 KB
/
doctest_cheat.py
File metadata and controls
executable file
·151 lines (104 loc) · 2.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
#!/usr/bin/env python
"""
Embed tests into docstrings.
Serves mainly as good example for documentation.
Cannot replace unittest, specially for more complex functions.
The test format is exactly the same as seen in an interactive Python session.
This is a docstring for the module, so tests inside it will be run.
Pass:
>>> print 'abc'
abc
Fail:
>>> 1
2
Define names:
>>> a = 1
>>> print a
1
This is only works for stuff defined in current docstring:
>>> mod_doc = 1
Search for `mod_doc` elsewhere and see the fail.
Indent:
>>> if True:
... print 'a'
a
Multiline output:
>>> for a in [1,2]:
... print a
1
2
Unpredictable output:
>>> f # doctest: +ELLIPSIS
<function f at 0x...>
The comment `# doctest: +ELLIPSIS` is obligatory and is called a *directive*.
Exceptions:
>>> raise ZeroDivisionError
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ZeroDivisionError
Fails:
>>> raise ZeroDivisionError
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AnotherError
"""
def f():
"""
Fail:
>>> 1
2
Call itself:
>>> print f()
1
Call other functions:
>>> print f2()
2
>>> mod_doc
Traceback (most recent call last):
File "/usr/lib/python2.7/doctest.py", line 1289, in __run
compileflags, 1) in test.globs
File "<doctest __main__.f[4]>", line 1, in <module>
mod_doc
NameError: name 'mod_doc' is not defined
"""
return 1
"""
Not a docstring becaues there is stuff before it.
Not tested:
>>> 1+1
4
"""
def f2():
return 2
def func_with_very_long_name():
"""
To avoid typing large names several times, you could to as follows:
>>> a = func_with_very_long_name
>>> a()
1
>>> a() + 1
2
>>> a() + 3
4
"""
return 1
class C():
"""
>>> C().f()
'C.f'
"""
def f(self):
"""
>>> C().f()
'C.f'
"""
return 'C.f'
if __name__ == '__main__':
if '##testmod':
# Test current module:
import doctest
doctest.testmod()
# Test given module:
#doctest.testmod(doctest)
# From the command line:
#python -m doctest file.py