test_serialization.py 2.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495
  1. from __future__ import absolute_import, unicode_literals
  2. import json
  3. import pickle
  4. import sys
  5. from datetime import date, datetime, time, timedelta
  6. import pytest
  7. import pytz
  8. from case import Mock, mock, skip
  9. from kombu import Queue
  10. from celery.utils.serialization import (UnpickleableExceptionWrapper,
  11. ensure_serializable,
  12. get_pickleable_etype, jsonify)
  13. class test_AAPickle:
  14. def test_no_cpickle(self):
  15. prev = sys.modules.pop('celery.utils.serialization', None)
  16. try:
  17. with mock.mask_modules('cPickle'):
  18. from celery.utils.serialization import pickle
  19. import pickle as orig_pickle
  20. assert pickle.dumps is orig_pickle.dumps
  21. finally:
  22. sys.modules['celery.utils.serialization'] = prev
  23. class test_ensure_serializable:
  24. @skip.unless_python3()
  25. def test_json_py3(self):
  26. assert (1, "<class 'object'>") == \
  27. ensure_serializable([1, object], encoder=json.dumps)
  28. @skip.if_python3()
  29. def test_json_py2(self):
  30. assert (1, "<type 'object'>") == \
  31. ensure_serializable([1, object], encoder=json.dumps)
  32. def test_pickle(self):
  33. assert (1, object) == \
  34. ensure_serializable((1, object), encoder=pickle.dumps)
  35. class test_UnpickleExceptionWrapper:
  36. def test_init(self):
  37. x = UnpickleableExceptionWrapper('foo', 'Bar', [10, lambda x: x])
  38. assert x.exc_args
  39. assert len(x.exc_args) == 2
  40. class test_get_pickleable_etype:
  41. def test_get_pickleable_etype(self):
  42. class Unpickleable(Exception):
  43. def __reduce__(self):
  44. raise ValueError('foo')
  45. assert get_pickleable_etype(Unpickleable) is Exception
  46. class test_jsonify:
  47. @pytest.mark.parametrize('obj', [
  48. Queue('foo'),
  49. ['foo', 'bar', 'baz'],
  50. {'foo': 'bar'},
  51. datetime.utcnow(),
  52. datetime.utcnow().replace(tzinfo=pytz.utc),
  53. datetime.utcnow().replace(microsecond=0),
  54. date(2012, 1, 1),
  55. time(hour=1, minute=30),
  56. time(hour=1, minute=30, microsecond=3),
  57. timedelta(seconds=30),
  58. 10,
  59. 10.3,
  60. 'hello',
  61. ])
  62. def test_simple(self, obj):
  63. assert jsonify(obj)
  64. def test_unknown_type_filter(self):
  65. unknown_type_filter = Mock()
  66. obj = object()
  67. assert (jsonify(obj, unknown_type_filter=unknown_type_filter) is
  68. unknown_type_filter.return_value)
  69. unknown_type_filter.assert_called_with(obj)
  70. with pytest.raises(ValueError):
  71. jsonify(obj)