test_yaml.py 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. # -*- coding: utf-8 -*-
  2. # Import Python Libs
  3. from __future__ import absolute_import, print_function, unicode_literals
  4. import collections
  5. import textwrap
  6. # Import Salt libs
  7. import salt.renderers.yaml as yaml
  8. from salt.ext import six
  9. # Import Salt Testing libs
  10. from tests.support.mixins import LoaderModuleMockMixin
  11. from tests.support.mock import patch
  12. from tests.support.unit import TestCase
  13. class YAMLRendererTestCase(TestCase, LoaderModuleMockMixin):
  14. def setup_loader_modules(self):
  15. return {yaml: {}}
  16. def assert_unicode(self, value):
  17. """
  18. Make sure the entire data structure is unicode
  19. """
  20. if six.PY3:
  21. return
  22. if isinstance(value, six.string_types):
  23. if not isinstance(value, six.text_type):
  24. self.raise_error(value)
  25. elif isinstance(value, collections.Mapping):
  26. for k, v in six.iteritems(value):
  27. self.assert_unicode(k)
  28. self.assert_unicode(v)
  29. elif isinstance(value, collections.Iterable):
  30. for item in value:
  31. self.assert_unicode(item)
  32. def assert_matches(self, ret, expected):
  33. self.assertEqual(ret, expected)
  34. self.assert_unicode(ret)
  35. def test_yaml_render_string(self):
  36. data = "string"
  37. result = yaml.render(data)
  38. self.assertEqual(result, data)
  39. def test_yaml_render_unicode(self):
  40. data = "!!python/unicode python unicode string"
  41. result = yaml.render(data)
  42. self.assertEqual(result, "python unicode string")
  43. def test_yaml_render_old_unicode(self):
  44. config = {"use_yamlloader_old": True}
  45. with patch.dict(yaml.__opts__, config): # pylint: disable=no-member
  46. self.assert_matches(
  47. yaml.render(
  48. textwrap.dedent(
  49. """\
  50. foo:
  51. a: Д
  52. b: {'a': u'\\u0414'}"""
  53. )
  54. ),
  55. {"foo": {"a": "\u0414", "b": {"a": "\u0414"}}},
  56. )