test_doctest2.py 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126
  1. """A module to test whether doctest recognizes some 2.2 features,
  2. like static and class methods.
  3. >>> print('yup') # 1
  4. yup
  5. We include some (random) encoded (utf-8) text in the text surrounding
  6. the example. It should be ignored:
  7. ЉЊЈЁЂ
  8. """
  9. import sys
  10. import unittest
  11. if sys.flags.optimize >= 2:
  12. raise unittest.SkipTest("Cannot test docstrings with -O2")
  13. class C(object):
  14. """Class C.
  15. >>> print(C()) # 2
  16. 42
  17. We include some (random) encoded (utf-8) text in the text surrounding
  18. the example. It should be ignored:
  19. ЉЊЈЁЂ
  20. """
  21. def __init__(self):
  22. """C.__init__.
  23. >>> print(C()) # 3
  24. 42
  25. """
  26. def __str__(self):
  27. """
  28. >>> print(C()) # 4
  29. 42
  30. """
  31. return "42"
  32. class D(object):
  33. """A nested D class.
  34. >>> print("In D!") # 5
  35. In D!
  36. """
  37. def nested(self):
  38. """
  39. >>> print(3) # 6
  40. 3
  41. """
  42. def getx(self):
  43. """
  44. >>> c = C() # 7
  45. >>> c.x = 12 # 8
  46. >>> print(c.x) # 9
  47. -12
  48. """
  49. return -self._x
  50. def setx(self, value):
  51. """
  52. >>> c = C() # 10
  53. >>> c.x = 12 # 11
  54. >>> print(c.x) # 12
  55. -12
  56. """
  57. self._x = value
  58. x = property(getx, setx, doc="""\
  59. >>> c = C() # 13
  60. >>> c.x = 12 # 14
  61. >>> print(c.x) # 15
  62. -12
  63. """)
  64. @staticmethod
  65. def statm():
  66. """
  67. A static method.
  68. >>> print(C.statm()) # 16
  69. 666
  70. >>> print(C().statm()) # 17
  71. 666
  72. """
  73. return 666
  74. @classmethod
  75. def clsm(cls, val):
  76. """
  77. A class method.
  78. >>> print(C.clsm(22)) # 18
  79. 22
  80. >>> print(C().clsm(23)) # 19
  81. 23
  82. """
  83. return val
  84. class Test(unittest.TestCase):
  85. def test_testmod(self):
  86. import doctest, sys
  87. EXPECTED = 19
  88. f, t = doctest.testmod(sys.modules[__name__])
  89. if f:
  90. self.fail("%d of %d doctests failed" % (f, t))
  91. if t != EXPECTED:
  92. self.fail("expected %d tests to run, not %d" % (EXPECTED, t))
  93. # Pollute the namespace with a bunch of imported functions and classes,
  94. # to make sure they don't get tested.
  95. from doctest import *
  96. if __name__ == '__main__':
  97. unittest.main()