test_glibbase.py 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. # Copyright (c) Twisted Matrix Laboratories.
  2. # See LICENSE for details.
  3. """
  4. Tests for twisted.internet.glibbase.
  5. """
  6. from __future__ import division, absolute_import
  7. import sys
  8. from twisted.trial.unittest import TestCase
  9. from twisted.internet._glibbase import ensureNotImported
  10. class EnsureNotImportedTests(TestCase):
  11. """
  12. L{ensureNotImported} protects against unwanted past and future imports.
  13. """
  14. def test_ensureWhenNotImported(self):
  15. """
  16. If the specified modules have never been imported, and import
  17. prevention is requested, L{ensureNotImported} makes sure they will not
  18. be imported in the future.
  19. """
  20. modules = {}
  21. self.patch(sys, "modules", modules)
  22. ensureNotImported(["m1", "m2"], "A message.",
  23. preventImports=["m1", "m2", "m3"])
  24. self.assertEqual(modules, {"m1": None, "m2": None, "m3": None})
  25. def test_ensureWhenNotImportedDontPrevent(self):
  26. """
  27. If the specified modules have never been imported, and import
  28. prevention is not requested, L{ensureNotImported} has no effect.
  29. """
  30. modules = {}
  31. self.patch(sys, "modules", modules)
  32. ensureNotImported(["m1", "m2"], "A message.")
  33. self.assertEqual(modules, {})
  34. def test_ensureWhenFailedToImport(self):
  35. """
  36. If the specified modules have been set to L{None} in C{sys.modules},
  37. L{ensureNotImported} does not complain.
  38. """
  39. modules = {"m2": None}
  40. self.patch(sys, "modules", modules)
  41. ensureNotImported(["m1", "m2"], "A message.", preventImports=["m1", "m2"])
  42. self.assertEqual(modules, {"m1": None, "m2": None})
  43. def test_ensureFailsWhenImported(self):
  44. """
  45. If one of the specified modules has been previously imported,
  46. L{ensureNotImported} raises an exception.
  47. """
  48. module = object()
  49. modules = {"m2": module}
  50. self.patch(sys, "modules", modules)
  51. e = self.assertRaises(ImportError, ensureNotImported,
  52. ["m1", "m2"], "A message.",
  53. preventImports=["m1", "m2"])
  54. self.assertEqual(modules, {"m2": module})
  55. self.assertEqual(e.args, ("A message.",))