modulehelpers.py 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. # Copyright (c) Twisted Matrix Laboratories.
  2. # See LICENSE for details.
  3. """
  4. Testing helpers related to the module system.
  5. """
  6. from __future__ import division, absolute_import
  7. __all__ = ['NoReactor', 'AlternateReactor']
  8. import sys
  9. import twisted.internet
  10. from twisted.test.test_twisted import SetAsideModule
  11. class NoReactor(SetAsideModule):
  12. """
  13. Context manager that uninstalls the reactor, if any, and then restores it
  14. afterwards.
  15. """
  16. def __init__(self):
  17. SetAsideModule.__init__(self, "twisted.internet.reactor")
  18. def __enter__(self):
  19. SetAsideModule.__enter__(self)
  20. if "twisted.internet.reactor" in self.modules:
  21. del twisted.internet.reactor
  22. def __exit__(self, excType, excValue, traceback):
  23. SetAsideModule.__exit__(self, excType, excValue, traceback)
  24. # Clean up 'reactor' attribute that may have been set on
  25. # twisted.internet:
  26. reactor = self.modules.get("twisted.internet.reactor", None)
  27. if reactor is not None:
  28. twisted.internet.reactor = reactor
  29. else:
  30. try:
  31. del twisted.internet.reactor
  32. except AttributeError:
  33. pass
  34. class AlternateReactor(NoReactor):
  35. """
  36. A context manager which temporarily installs a different object as the
  37. global reactor.
  38. """
  39. def __init__(self, reactor):
  40. """
  41. @param reactor: Any object to install as the global reactor.
  42. """
  43. NoReactor.__init__(self)
  44. self.alternate = reactor
  45. def __enter__(self):
  46. NoReactor.__enter__(self)
  47. twisted.internet.reactor = self.alternate
  48. sys.modules['twisted.internet.reactor'] = self.alternate