mockdoctest.py 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102
  1. # Copyright (c) Twisted Matrix Laboratories.
  2. # See LICENSE for details.
  3. # this module is a trivial class with doctests to test trial's doctest
  4. # support.
  5. from __future__ import division, absolute_import
  6. class Counter(object):
  7. """a simple counter object for testing trial's doctest support
  8. >>> c = Counter()
  9. >>> c.value()
  10. 0
  11. >>> c += 3
  12. >>> c.value()
  13. 3
  14. >>> c.incr()
  15. >>> c.value() == 4
  16. True
  17. >>> c == 4
  18. True
  19. >>> c != 9
  20. True
  21. """
  22. _count = 0
  23. def __init__(self, initialValue=0, maxval=None):
  24. self._count = initialValue
  25. self.maxval = maxval
  26. def __iadd__(self, other):
  27. """add other to my value and return self
  28. >>> c = Counter(100)
  29. >>> c += 333
  30. >>> c == 433
  31. True
  32. """
  33. if self.maxval is not None and ((self._count + other) > self.maxval):
  34. raise ValueError("sorry, counter got too big")
  35. else:
  36. self._count += other
  37. return self
  38. def __eq__(self, other):
  39. """equality operator, compare other to my value()
  40. >>> c = Counter()
  41. >>> c == 0
  42. True
  43. >>> c += 10
  44. >>> c.incr()
  45. >>> c == 10 # fail this test on purpose
  46. True
  47. """
  48. return self._count == other
  49. def __ne__(self, other):
  50. """inequality operator
  51. >>> c = Counter()
  52. >>> c != 10
  53. True
  54. """
  55. return not self.__eq__(other)
  56. def incr(self):
  57. """increment my value by 1
  58. >>> from twisted.trial.test.mockdoctest import Counter
  59. >>> c = Counter(10, 11)
  60. >>> c.incr()
  61. >>> c.value() == 11
  62. True
  63. >>> c.incr()
  64. Traceback (most recent call last):
  65. File "<stdin>", line 1, in ?
  66. File "twisted/trial/test/mockdoctest.py", line 51, in incr
  67. self.__iadd__(1)
  68. File "twisted/trial/test/mockdoctest.py", line 39, in __iadd__
  69. raise ValueError, "sorry, counter got too big"
  70. ValueError: sorry, counter got too big
  71. """
  72. self.__iadd__(1)
  73. def value(self):
  74. """return this counter's value
  75. >>> c = Counter(555)
  76. >>> c.value() == 555
  77. True
  78. """
  79. return self._count
  80. def unexpectedException(self):
  81. """i will raise an unexpected exception...
  82. ... *CAUSE THAT'S THE KINDA GUY I AM*
  83. >>> 1/0
  84. """