test_py_reader_writer.py 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. # -*- coding: utf-8 -*-
  2. from __future__ import print_function, absolute_import, division
  3. import pytest
  4. import six
  5. from cyson import PyWriter, PyReader, dumps, loads, dumps_into
  6. if six.PY3:
  7. unicode = str
  8. def switch_string_type(string):
  9. if isinstance(string, unicode):
  10. return string.encode('utf8')
  11. elif isinstance(string, bytes):
  12. return string.decode('utf8')
  13. raise TypeError('expected bytes or unicode, got {!r}'.format(string))
  14. CASES = [
  15. None,
  16. # int
  17. 0, 1, -1, 2**63, -2**63, 2**64 - 1,
  18. # float
  19. 0.0, 100.0, -100.0,
  20. # long
  21. 10**100, 2**300, -7**100,
  22. # bytes
  23. b'', b'hello', u'Привет'.encode('utf8'),
  24. # unicode
  25. u'', u'hello', u'Привет',
  26. # tuple
  27. (), (0,), (1, 'hello'), (17, 'q') * 100,
  28. # list
  29. [], [0], ['hello', set([1, 2, 3])], [17, 'q'] * 100,
  30. # dict
  31. {}, {'a': 'b'}, {'a': 17}, {'a': frozenset([1, 2, 3])}, {b'a': 1, u'b': 2},
  32. {1: 2, 3: 4, 5: None}, {(1, 2, 3): (1, 4, 9), None: 0},
  33. # set
  34. set(), {1, 2, 3}, {'hello', 'world'},
  35. # frozenset
  36. frozenset(), frozenset([1, 2, 3]), frozenset(['hello', 'world']),
  37. ]
  38. @pytest.mark.parametrize('format', ['binary', 'text', 'pretty'])
  39. @pytest.mark.parametrize('value', CASES)
  40. def test_roundtrip(value, format):
  41. encoded = dumps(value, format=format, Writer=PyWriter)
  42. decoded = loads(encoded, Reader=PyReader)
  43. assert encoded == dumps(value, format=switch_string_type(format), Writer=PyWriter)
  44. assert type(decoded) is type(value)
  45. assert decoded == value
  46. @pytest.mark.parametrize('format', ['binary', 'text', 'pretty'])
  47. @pytest.mark.parametrize('value', CASES)
  48. def test_roundtrip_bytearray(value, format):
  49. encoded1 = bytearray()
  50. encoded2 = bytearray()
  51. dumps_into(encoded1, value, format=format, Writer=PyWriter)
  52. dumps_into(encoded2, value, format=switch_string_type(format), Writer=PyWriter)
  53. decoded = loads(encoded1, Reader=PyReader)
  54. assert decoded == loads(encoded2, Reader=PyReader)
  55. assert type(decoded) is type(value)
  56. assert decoded == value