test_context.py 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  1. # Copyright (c) Twisted Matrix Laboratories.
  2. # See LICENSE for details.
  3. """
  4. Tests for L{twisted.python.context}.
  5. """
  6. from __future__ import division, absolute_import
  7. from twisted.trial.unittest import SynchronousTestCase
  8. from twisted.python import context
  9. class ContextTests(SynchronousTestCase):
  10. """
  11. Tests for the module-scope APIs for L{twisted.python.context}.
  12. """
  13. def test_notPresentIfNotSet(self):
  14. """
  15. Arbitrary keys which have not been set in the context have an associated
  16. value of L{None}.
  17. """
  18. self.assertIsNone(context.get("x"))
  19. def test_setByCall(self):
  20. """
  21. Values may be associated with keys by passing them in a dictionary as
  22. the first argument to L{twisted.python.context.call}.
  23. """
  24. self.assertEqual(context.call({"x": "y"}, context.get, "x"), "y")
  25. def test_unsetAfterCall(self):
  26. """
  27. After a L{twisted.python.context.call} completes, keys specified in the
  28. call are no longer associated with the values from that call.
  29. """
  30. context.call({"x": "y"}, lambda: None)
  31. self.assertIsNone(context.get("x"))
  32. def test_setDefault(self):
  33. """
  34. A default value may be set for a key in the context using
  35. L{twisted.python.context.setDefault}.
  36. """
  37. key = object()
  38. self.addCleanup(context.defaultContextDict.pop, key, None)
  39. context.setDefault(key, "y")
  40. self.assertEqual("y", context.get(key))