test_autodict_yaml.py 1.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  1. # -*- coding: utf-8 -*-
  2. import pytest
  3. from ioex import AutoDict
  4. yaml = pytest.importorskip('yaml')
  5. def test_to_yaml():
  6. d = AutoDict()
  7. d['A'] = 1.1
  8. d['B'][2] = 'b'
  9. d['C'][3]['c'] = [u'Γ', u'γ']
  10. class TestDumper(yaml.SafeDumper):
  11. pass
  12. TestDumper.add_representer(type(d), lambda d, c: type(c).to_yaml(d, c))
  13. generated_yaml = yaml.dump(
  14. d,
  15. Dumper=TestDumper,
  16. default_flow_style=False)
  17. loaded_dict = yaml.load(generated_yaml)
  18. assert isinstance(loaded_dict, dict)
  19. expected_dict = {
  20. 'A': 1.1,
  21. 'B': {2: 'b'},
  22. 'C': {3: {'c': [u'Γ', u'γ']}},
  23. }
  24. assert expected_dict == loaded_dict
  25. def test_register_yaml_representer():
  26. d = AutoDict()
  27. d['A'] = 1.1
  28. d['B'][2] = 'b'
  29. d['C'][3]['c'] = [u'Γ', u'γ']
  30. class TestDumper(yaml.SafeDumper):
  31. pass
  32. AutoDict.register_yaml_representer(TestDumper)
  33. generated_yaml = yaml.dump(
  34. d,
  35. Dumper=TestDumper,
  36. default_flow_style=False)
  37. loaded_dict = yaml.load(generated_yaml)
  38. assert isinstance(loaded_dict, dict)
  39. expected_dict = {
  40. 'A': 1.1,
  41. 'B': {2: 'b'},
  42. 'C': {3: {'c': [u'Γ', u'γ']}},
  43. }
  44. assert expected_dict == loaded_dict