test_jsonutil.py 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. # coding: utf-8
  2. """Test suite for our JSON utilities."""
  3. # Copyright (c) Jupyter Development Team.
  4. # Distributed under the terms of the Modified BSD License.
  5. import datetime
  6. from datetime import timedelta
  7. import json
  8. try:
  9. from unittest import mock
  10. except ImportError:
  11. # py2
  12. import mock
  13. from dateutil.tz import tzlocal, tzoffset
  14. from jupyter_client import jsonutil
  15. from jupyter_client.session import utcnow
  16. def test_extract_dates():
  17. timestamps = [
  18. '2013-07-03T16:34:52.249482',
  19. '2013-07-03T16:34:52.249482Z',
  20. '2013-07-03T16:34:52.249482-0800',
  21. '2013-07-03T16:34:52.249482+0800',
  22. '2013-07-03T16:34:52.249482-08:00',
  23. '2013-07-03T16:34:52.249482+08:00',
  24. ]
  25. extracted = jsonutil.extract_dates(timestamps)
  26. ref = extracted[0]
  27. for dt in extracted:
  28. assert isinstance(dt, datetime.datetime)
  29. assert dt.tzinfo != None
  30. assert extracted[0].tzinfo.utcoffset(ref) == tzlocal().utcoffset(ref)
  31. assert extracted[1].tzinfo.utcoffset(ref) == timedelta(0)
  32. assert extracted[2].tzinfo.utcoffset(ref) == timedelta(hours=-8)
  33. assert extracted[3].tzinfo.utcoffset(ref) == timedelta(hours=8)
  34. assert extracted[4].tzinfo.utcoffset(ref) == timedelta(hours=-8)
  35. assert extracted[5].tzinfo.utcoffset(ref) == timedelta(hours=8)
  36. def test_parse_ms_precision():
  37. base = '2013-07-03T16:34:52'
  38. digits = '1234567890'
  39. parsed = jsonutil.parse_date(base)
  40. assert isinstance(parsed, datetime.datetime)
  41. for i in range(len(digits)):
  42. ts = base + '.' + digits[:i]
  43. parsed = jsonutil.parse_date(ts)
  44. if i >= 1 and i <= 6:
  45. assert isinstance(parsed, datetime.datetime)
  46. else:
  47. assert isinstance(parsed, str)
  48. def test_date_default():
  49. naive = datetime.datetime.now()
  50. local = tzoffset('Local', -8 * 3600)
  51. other = tzoffset('Other', 2 * 3600)
  52. data = dict(naive=naive, utc=utcnow(), withtz=naive.replace(tzinfo=other))
  53. with mock.patch.object(jsonutil, 'tzlocal', lambda : local):
  54. jsondata = json.dumps(data, default=jsonutil.date_default)
  55. assert "Z" in jsondata
  56. assert jsondata.count("Z") == 1
  57. extracted = jsonutil.extract_dates(json.loads(jsondata))
  58. for dt in extracted.values():
  59. assert isinstance(dt, datetime.datetime)
  60. assert dt.tzinfo != None