test_context.py 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. # -*- coding: utf-8 -*-'
  2. from __future__ import absolute_import, unicode_literals
  3. from celery.app.task import Context
  4. # Retreive the values of all context attributes as a
  5. # dictionary in an implementation-agnostic manner.
  6. def get_context_as_dict(ctx, getter=getattr):
  7. defaults = {}
  8. for attr_name in dir(ctx):
  9. if attr_name.startswith('_'):
  10. continue # Ignore pseudo-private attributes
  11. attr = getter(ctx, attr_name)
  12. if callable(attr):
  13. continue # Ignore methods and other non-trivial types
  14. defaults[attr_name] = attr
  15. return defaults
  16. default_context = get_context_as_dict(Context())
  17. class test_Context:
  18. def test_default_context(self):
  19. # A bit of a tautological test, since it uses the same
  20. # initializer as the default_context constructor.
  21. defaults = dict(default_context, children=[])
  22. assert get_context_as_dict(Context()) == defaults
  23. def test_updated_context(self):
  24. expected = dict(default_context)
  25. changes = dict(id='unique id', args=['some', 1], wibble='wobble')
  26. ctx = Context()
  27. expected.update(changes)
  28. ctx.update(changes)
  29. assert get_context_as_dict(ctx) == expected
  30. assert get_context_as_dict(Context()) == default_context
  31. def test_modified_context(self):
  32. expected = dict(default_context)
  33. ctx = Context()
  34. expected['id'] = 'unique id'
  35. expected['args'] = ['some', 1]
  36. ctx.id = 'unique id'
  37. ctx.args = ['some', 1]
  38. assert get_context_as_dict(ctx) == expected
  39. assert get_context_as_dict(Context()) == default_context
  40. def test_cleared_context(self):
  41. changes = dict(id='unique id', args=['some', 1], wibble='wobble')
  42. ctx = Context()
  43. ctx.update(changes)
  44. ctx.clear()
  45. defaults = dict(default_context, children=[])
  46. assert get_context_as_dict(ctx) == defaults
  47. assert get_context_as_dict(Context()) == defaults
  48. def test_context_get(self):
  49. expected = dict(default_context)
  50. changes = dict(id='unique id', args=['some', 1], wibble='wobble')
  51. ctx = Context()
  52. expected.update(changes)
  53. ctx.update(changes)
  54. ctx_dict = get_context_as_dict(ctx, getter=Context.get)
  55. assert ctx_dict == expected
  56. assert get_context_as_dict(Context()) == default_context