test_input_stream.py 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  1. # -*- coding: utf-8 -*-
  2. from __future__ import print_function, absolute_import, division
  3. import atexit
  4. import io
  5. import os
  6. import tempfile
  7. import pytest
  8. import six
  9. from cyson import Reader, InputStream, dumps
  10. def prepare_file(string):
  11. filepath = tempfile.mktemp()
  12. with open(filepath, 'wb') as sink:
  13. sink.write(string)
  14. atexit.register(os.remove, filepath)
  15. return filepath
  16. def prepare_bytesio(string, klass):
  17. obj = klass()
  18. obj.write(b'?:!;*')
  19. obj.write(string)
  20. obj.seek(5)
  21. return obj
  22. def slice_string(string):
  23. index = 0
  24. length = len(string)
  25. while index < length:
  26. yield string[index:index + 2]
  27. index += 2
  28. # <method name>, <input constructor>
  29. CASES = (
  30. ('from_string', lambda x: x),
  31. ('from_iter', slice_string),
  32. ('from_file', lambda x: prepare_bytesio(x, io.BytesIO)),
  33. ('from_file', lambda x: open(prepare_file(x), 'rb')),
  34. ('from_fd', lambda x: os.open(prepare_file(x), os.O_RDONLY)),
  35. )
  36. if six.PY2:
  37. import StringIO
  38. import cStringIO
  39. CASES += (
  40. ('from_file', lambda x: prepare_bytesio(x, StringIO.StringIO)),
  41. ('from_file', lambda x: prepare_bytesio(x, cStringIO.StringIO)),
  42. )
  43. DATA = {u'a': [1, u'word', 3], b'b': b'xyz', u'c': None}
  44. ETALON = {b'a': [1, b'word', 3], b'b': b'xyz', b'c': None}
  45. @pytest.fixture(scope='module')
  46. def serialized_data():
  47. return dumps(DATA, format='binary')
  48. def test_serizlized_data(serialized_data):
  49. assert type(serialized_data) is bytes
  50. @pytest.mark.parametrize('method_name,make_input', CASES)
  51. def test_input_streams(method_name, make_input, serialized_data):
  52. method = getattr(InputStream, method_name)
  53. input_stream = method(make_input(serialized_data))
  54. assert Reader(input_stream).node() == ETALON