ipunittest.py 6.6 KB

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