Debian Codegraph @

IPython/testing/ipunittest.py

raw
1 """Experimental code for cleaner support of IPython syntax with unittest.
2
3 In IPython up until 0.10, we've used very hacked up nose machinery for running
4 tests with IPython special syntax, and this has proved to be extremely slow.
5 This module provides decorators to try a different approach, stemming from a
6 conversation Brian and I (FP) had about this problem Sept/09.
7
8 The goal is to be able to easily write simple functions that can be seen by
9 unittest as tests, and ultimately for these to support doctests with full
10 IPython syntax. Nose already offers this based on naming conventions and our
11 hackish plugins, but we are seeking to move away from nose dependencies if
12 possible.
13
14 This module follows a different approach, based on decorators.
15
16 - A decorator called @ipdoctest can mark any function as having a docstring
17 that should be viewed as a doctest, but after syntax conversion.
18
19 Authors
20 -------
21
22 - Fernando Perez <[email protected]>
23 """
24
25
26 #-----------------------------------------------------------------------------
27 # Copyright (C) 2009-2011 The IPython Development Team
28 #
29 # Distributed under the terms of the BSD License. The full license is in
30 # the file COPYING, distributed as part of this software.
31 #-----------------------------------------------------------------------------
32
33 #-----------------------------------------------------------------------------
34 # Imports
35 #-----------------------------------------------------------------------------
36
37 # Stdlib
38 import re
39 import sys
40 import unittest
41 import builtins
42 from doctest import DocTestFinder, DocTestRunner, TestResults
43 from IPython.terminal.interactiveshell import InteractiveShell
44
45 #-----------------------------------------------------------------------------
46 # Classes and functions
47 #-----------------------------------------------------------------------------
48
49 def count_failures(runner):
50 """Count number of failures in a doctest runner.
51
52 Code modeled after the summarize() method in doctest.
53 """
54 if sys.version_info < (3, 13):
55 return [TestResults(f, t) for f, t in runner._name2ft.values() if f > 0]
56 else:
57 return [
58 TestResults(failure, try_)
59 for failure, try_, skip in runner._stats.values()
60 if failure > 0
61 ]
62
63
64 class IPython2PythonConverter:
65 """Convert IPython 'syntax' to valid Python.
66
67 Eventually this code may grow to be the full IPython syntax conversion
68 implementation, but for now it only does prompt conversion."""
69
70 def __init__(self):
71 self.rps1 = re.compile(r'In\ \[\d+\]: ')
72 self.rps2 = re.compile(r'\ \ \ \.\.\.+: ')
73 self.rout = re.compile(r'Out\[\d+\]: \s*?\n?')
74 self.pyps1 = '>>> '
75 self.pyps2 = '... '
76 self.rpyps1 = re.compile (r'(\s*%s)(.*)$' % self.pyps1)
77 self.rpyps2 = re.compile (r'(\s*%s)(.*)$' % self.pyps2)
78
79 def __call__(self, ds):
80 """Convert IPython prompts to python ones in a string."""
81 from . import globalipapp
82
83 pyps1 = '>>> '
84 pyps2 = '... '
85 pyout = ''
86
87 dnew = ds
88 dnew = self.rps1.sub(pyps1, dnew)
89 dnew = self.rps2.sub(pyps2, dnew)
90 dnew = self.rout.sub(pyout, dnew)
91 ip = InteractiveShell.instance()
92
93 # Convert input IPython source into valid Python.
94 out = []
95 newline = out.append
96 for line in dnew.splitlines():
97
98 mps1 = self.rpyps1.match(line)
99 if mps1 is not None:
100 prompt, text = mps1.groups()
101 newline(prompt+ip.prefilter(text, False))
102 continue
103
104 mps2 = self.rpyps2.match(line)
105 if mps2 is not None:
106 prompt, text = mps2.groups()
107 newline(prompt+ip.prefilter(text, True))
108 continue
109
110 newline(line)
111 newline('') # ensure a closing newline, needed by doctest
112 # print("PYSRC:", '\n'.join(out)) # dbg
113 return '\n'.join(out)
114
115 #return dnew
116
117
118 class Doc2UnitTester:
119 """Class whose instances act as a decorator for docstring testing.
120
121 In practice we're only likely to need one instance ever, made below (though
122 no attempt is made at turning it into a singleton, there is no need for
123 that).
124 """
125 def __init__(self, verbose=False):
126 """New decorator.
127
128 Parameters
129 ----------
130
131 verbose : boolean, optional (False)
132 Passed to the doctest finder and runner to control verbosity.
133 """
134 self.verbose = verbose
135 # We can reuse the same finder for all instances
136 self.finder = DocTestFinder(verbose=verbose, recurse=False)
137
138 def __call__(self, func):
139 """Use as a decorator: doctest a function's docstring as a unittest.
140
141 This version runs normal doctests, but the idea is to make it later run
142 ipython syntax instead."""
143
144 # Capture the enclosing instance with a different name, so the new
145 # class below can see it without confusion regarding its own 'self'
146 # that will point to the test instance at runtime
147 d2u = self
148
149 # Rewrite the function's docstring to have python syntax
150 if func.__doc__ is not None:
151 func.__doc__ = ip2py(func.__doc__)
152
153 # Now, create a tester object that is a real unittest instance, so
154 # normal unittest machinery (or Nose, or Trial) can find it.
155 class Tester(unittest.TestCase):
156 def test(self):
157 # Make a new runner per function to be tested
158 runner = DocTestRunner(verbose=d2u.verbose)
159 for the_test in d2u.finder.find(func, func.__name__):
160 runner.run(the_test)
161 failed = count_failures(runner)
162 if failed:
163 # Since we only looked at a single function's docstring,
164 # failed should contain at most one item. More than that
165 # is a case we can't handle and should error out on
166 if len(failed) > 1:
167 err = "Invalid number of test results: %s" % failed
168 raise ValueError(err)
169 # Report a normal failure.
170 self.fail('failed doctests: %s' % str(failed[0]))
171
172 # Rename it so test reports have the original signature.
173 Tester.__name__ = func.__name__
174 return Tester
175
176
177 def ipdocstring(func):
178 """Change the function docstring via ip2py.
179 """
180 if func.__doc__ is not None:
181 func.__doc__ = ip2py(func.__doc__)
182 return func
183
184
185 # Make an instance of the classes for public use
186 ipdoctest = Doc2UnitTester()
187 ip2py = IPython2PythonConverter()