test_yaml_represent_unicode_as_str.py 1.5 KB

123456789101112131415161718192021222324252627282930313233
  1. # -*- coding: utf-8 -*-
  2. import pytest
  3. import ioex.datetimeex
  4. yaml = pytest.importorskip('yaml')
  5. @pytest.mark.parametrize(('dumper'), [yaml.Dumper, yaml.SafeDumper])
  6. @pytest.mark.parametrize(('unicode_string', 'expected_yaml_string', 'dump_params'), [
  7. [[u'item'], '[item]\n', {}],
  8. [[u'itäm'], '["it\\xE4m"]\n', {'allow_unicode': False}],
  9. [[u'itäm'], '[itäm]\n', {'allow_unicode': True}],
  10. [[u'itäm'], u'[itäm]\n'.encode('utf-8'), {'allow_unicode': True}],
  11. [{u'key': u'value'}, '{key: value}\n', {}],
  12. [{u'kï': u'valü'}, '{"k\\xEF": "val\\xFC"}\n', {'allow_unicode': False}],
  13. [{u'kï': u'valü'}, '{kï: valü}\n', {'allow_unicode': True}],
  14. [{u'kï': u'valü'}, u'{kï: valü}\n'.encode('utf-8'), {'allow_unicode': True}],
  15. [{u'kĕyĭ': u'可以'}, '{kĕyĭ: 可以}\n', {'allow_unicode': True}],
  16. [{u'⚕': u'☤'}, '{⚕: ☤}\n', {'allow_unicode': True}],
  17. ])
  18. def test_to_yaml(unicode_string, expected_yaml_string, dump_params, dumper):
  19. # create subclass so call to class method does not interfere with other tests
  20. # see yaml.BaseRepresenter.add_representer()
  21. class TestDumper(dumper):
  22. pass
  23. ioex.register_yaml_unicode_as_str_representer(TestDumper)
  24. generated_yaml_string = yaml.dump(
  25. unicode_string,
  26. Dumper = TestDumper,
  27. default_flow_style = True,
  28. **dump_params
  29. )
  30. assert type(expected_yaml_string) == type(generated_yaml_string)
  31. assert expected_yaml_string == generated_yaml_string