1
0

test_json.py 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  1. """
  2. Test our two JSON serializers (orjson, and Python's built-in json module).
  3. Need to ensure that we get the same output regardless of the serializer used.
  4. """
  5. import sys
  6. from datetime import date, datetime
  7. import numpy as np
  8. import pytest
  9. try:
  10. # try to import module, only run test if succeeded
  11. import orjson # noqa: F401
  12. except ImportError:
  13. pass
  14. @pytest.mark.skipif('orjson' not in sys.modules, reason='requires the orjson library.')
  15. def test_json():
  16. # only run test if orjson is available to not break it on 32 bit systems
  17. # or architectures where orjson is not supported.
  18. # pylint: disable=import-outside-toplevel
  19. from nicegui.json.builtin_wrapper import dumps as builtin_dumps
  20. from nicegui.json.orjson_wrapper import dumps as orjson_dumps
  21. # test different scalar and array types
  22. tests = [
  23. None,
  24. 'text',
  25. True,
  26. 1.0,
  27. 1,
  28. [],
  29. dict(),
  30. dict(key1='value1', key2=1),
  31. date(2020, 1, 31),
  32. datetime(2020, 1, 31, 12, 59, 59, 123456),
  33. [1.0, -3, 0],
  34. ['test', '€'],
  35. [0, None, False, np.pi, 'text', date(2020, 1, 31), datetime(2020, 1, 31, 12, 59, 59, 123456), np.array([1.0])],
  36. np.array([1.0, 0]),
  37. np.array([0, False, np.pi]),
  38. np.array(['2010-10-17 07:15:30', '2011-05-13 08:20:35', '2013-01-15 09:09:09'], dtype=np.datetime64),
  39. np.array([1.0, None, 'test'], dtype=np.object_)
  40. ]
  41. for test in tests:
  42. orjson_str = orjson_dumps(test)
  43. builtin_str = builtin_dumps(test)
  44. assert orjson_str == builtin_str, f'json serializer implementations do not match: orjson={orjson_str}, built-in={builtin_str}'