test_yaml_construct_str_as_unicode.py 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950
  1. # -*- coding: utf-8 -*-
  2. import pytest
  3. import ioex.datetimeex
  4. yaml = pytest.importorskip('yaml')
  5. @pytest.mark.parametrize(('loader'), [yaml.Loader, yaml.SafeLoader])
  6. @pytest.mark.parametrize(('yaml_string', 'expected_object'), [
  7. # ascii strings
  8. #
  9. # nota bene:
  10. # >>> yaml.dump('it\xc3\xa4m', allow_unicode = False) == '!!python/str "it\\xE4m"\n'
  11. # True
  12. # >>> yaml.dump('it\xc3\xa4m', allow_unicode = True) == "!!python/str 'it\xc3\xa4m'\n"
  13. # True
  14. ['item', u'item'],
  15. ['itäm', u'itäm'],
  16. [b'it\xc3\xa4m', u'itäm'],
  17. [b'"it\xc3\xa4m"', u'itäm'],
  18. [r'it\xE4m', u'it\\xE4m'],
  19. ['"itäm"', u'itäm'],
  20. [r'"it\xc3\xa4m"', u'it\xc3\xa4m'], # see comment above
  21. # unicode strings
  22. [r'"it\xE4m"', u'it\xE4m'],
  23. [r'"it\xE4m"', u'itäm'],
  24. [u'item', u'item'],
  25. [u'itäm', u'itäm'],
  26. ['{kĕyĭ: 可以}\n', {u'kĕyĭ': u'可以'}],
  27. ['{⚕: ☤}\n', {u'⚕': u'☤'}],
  28. # lists
  29. ['[item]', [u'item']],
  30. ['[itäm]', [u'itäm']],
  31. # dicts
  32. ['{key: value}', {u'key': u'value'}],
  33. ['{kï: valü}', {u'kï': u'valü'}],
  34. ])
  35. def test_to_yaml(yaml_string, expected_object, loader):
  36. # create subclass so call to class method does not interfere with other tests
  37. # see yaml.BaseConstructor.add_constructor()
  38. class TestLoader(loader):
  39. pass
  40. ioex.register_yaml_str_as_unicode_constructor(TestLoader)
  41. generated_object = yaml.load(yaml_string, Loader = TestLoader)
  42. assert type(expected_object) == type(generated_object)
  43. assert expected_object == generated_object
  44. if type(expected_object) is list:
  45. assert [type(i) for i in expected_object] == [type(i) for i in generated_object]
  46. elif type(expected_object) is dict:
  47. assert [type(k) for k in expected_object.keys()] == [type(k) for k in generated_object.keys()]
  48. assert [type(v) for v in expected_object.values()] == [type(v) for v in generated_object.values()]