ipunittest.py 6.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178
  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. from __future__ import absolute_import
  19. #-----------------------------------------------------------------------------
  20. # Copyright (C) 2009-2011 The IPython Development Team
  21. #
  22. # Distributed under the terms of the BSD License. The full license is in
  23. # the file COPYING, distributed as part of this software.
  24. #-----------------------------------------------------------------------------
  25. #-----------------------------------------------------------------------------
  26. # Imports
  27. #-----------------------------------------------------------------------------
  28. # Stdlib
  29. import re
  30. import unittest
  31. from doctest import DocTestFinder, DocTestRunner, TestResults
  32. #-----------------------------------------------------------------------------
  33. # Classes and functions
  34. #-----------------------------------------------------------------------------
  35. def count_failures(runner):
  36. """Count number of failures in a doctest runner.
  37. Code modeled after the summarize() method in doctest.
  38. """
  39. return [TestResults(f, t) for f, t in runner._name2ft.values() if f > 0 ]
  40. class IPython2PythonConverter(object):
  41. """Convert IPython 'syntax' to valid Python.
  42. Eventually this code may grow to be the full IPython syntax conversion
  43. implementation, but for now it only does prompt convertion."""
  44. def __init__(self):
  45. self.rps1 = re.compile(r'In\ \[\d+\]: ')
  46. self.rps2 = re.compile(r'\ \ \ \.\.\.+: ')
  47. self.rout = re.compile(r'Out\[\d+\]: \s*?\n?')
  48. self.pyps1 = '>>> '
  49. self.pyps2 = '... '
  50. self.rpyps1 = re.compile ('(\s*%s)(.*)$' % self.pyps1)
  51. self.rpyps2 = re.compile ('(\s*%s)(.*)$' % self.pyps2)
  52. def __call__(self, ds):
  53. """Convert IPython prompts to python ones in a string."""
  54. from . import globalipapp
  55. pyps1 = '>>> '
  56. pyps2 = '... '
  57. pyout = ''
  58. dnew = ds
  59. dnew = self.rps1.sub(pyps1, dnew)
  60. dnew = self.rps2.sub(pyps2, dnew)
  61. dnew = self.rout.sub(pyout, dnew)
  62. ip = globalipapp.get_ipython()
  63. # Convert input IPython source into valid Python.
  64. out = []
  65. newline = out.append
  66. for line in dnew.splitlines():
  67. mps1 = self.rpyps1.match(line)
  68. if mps1 is not None:
  69. prompt, text = mps1.groups()
  70. newline(prompt+ip.prefilter(text, False))
  71. continue
  72. mps2 = self.rpyps2.match(line)
  73. if mps2 is not None:
  74. prompt, text = mps2.groups()
  75. newline(prompt+ip.prefilter(text, True))
  76. continue
  77. newline(line)
  78. newline('') # ensure a closing newline, needed by doctest
  79. #print "PYSRC:", '\n'.join(out) # dbg
  80. return '\n'.join(out)
  81. #return dnew
  82. class Doc2UnitTester(object):
  83. """Class whose instances act as a decorator for docstring testing.
  84. In practice we're only likely to need one instance ever, made below (though
  85. no attempt is made at turning it into a singleton, there is no need for
  86. that).
  87. """
  88. def __init__(self, verbose=False):
  89. """New decorator.
  90. Parameters
  91. ----------
  92. verbose : boolean, optional (False)
  93. Passed to the doctest finder and runner to control verbosity.
  94. """
  95. self.verbose = verbose
  96. # We can reuse the same finder for all instances
  97. self.finder = DocTestFinder(verbose=verbose, recurse=False)
  98. def __call__(self, func):
  99. """Use as a decorator: doctest a function's docstring as a unittest.
  100. This version runs normal doctests, but the idea is to make it later run
  101. ipython syntax instead."""
  102. # Capture the enclosing instance with a different name, so the new
  103. # class below can see it without confusion regarding its own 'self'
  104. # that will point to the test instance at runtime
  105. d2u = self
  106. # Rewrite the function's docstring to have python syntax
  107. if func.__doc__ is not None:
  108. func.__doc__ = ip2py(func.__doc__)
  109. # Now, create a tester object that is a real unittest instance, so
  110. # normal unittest machinery (or Nose, or Trial) can find it.
  111. class Tester(unittest.TestCase):
  112. def test(self):
  113. # Make a new runner per function to be tested
  114. runner = DocTestRunner(verbose=d2u.verbose)
  115. for the_test in d2u.finder.find(func, func.__name__):
  116. runner.run(the_test)
  117. failed = count_failures(runner)
  118. if failed:
  119. # Since we only looked at a single function's docstring,
  120. # failed should contain at most one item. More than that
  121. # is a case we can't handle and should error out on
  122. if len(failed) > 1:
  123. err = "Invalid number of test results:" % failed
  124. raise ValueError(err)
  125. # Report a normal failure.
  126. self.fail('failed doctests: %s' % str(failed[0]))
  127. # Rename it so test reports have the original signature.
  128. Tester.__name__ = func.__name__
  129. return Tester
  130. def ipdocstring(func):
  131. """Change the function docstring via ip2py.
  132. """
  133. if func.__doc__ is not None:
  134. func.__doc__ = ip2py(func.__doc__)
  135. return func
  136. # Make an instance of the classes for public use
  137. ipdoctest = Doc2UnitTester()
  138. ip2py = IPython2PythonConverter()