1
0

test_msgpack.py 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  1. import pytest
  2. import salt.utils.msgpack
  3. from tests.support.mock import MagicMock, patch
  4. def test_load_encoding(tmpdir):
  5. """
  6. test when using msgpack version >= 1.0.0 we
  7. can still load/dump when using unsupported
  8. encoding kwarg. This kwarg has been removed
  9. in this version.
  10. https://github.com/msgpack/msgpack-python/blob/master/ChangeLog.rst
  11. """
  12. fname = tmpdir.join("test_load_encoding.txt")
  13. kwargs = {"encoding": "utf-8"}
  14. data = [1, 2, 3]
  15. with patch.object(salt.utils.msgpack, "version", (1, 0, 0)):
  16. with salt.utils.files.fopen(fname.strpath, "wb") as wfh:
  17. salt.utils.msgpack.dump(data, wfh)
  18. with salt.utils.files.fopen(fname.strpath, "rb") as rfh:
  19. ret = salt.utils.msgpack.load(rfh, **kwargs)
  20. assert ret == data
  21. @pytest.mark.parametrize(
  22. "version,encoding", [((2, 1, 3), False), ((1, 0, 0), False), ((0, 6, 2), True)]
  23. )
  24. def test_load_multiple_versions(version, encoding, tmpdir):
  25. """
  26. test when using msgpack on multiple versions that
  27. we only remove encoding on >= 1.0.0
  28. """
  29. fname = tmpdir.join("test_load_multipl_versions.txt")
  30. with patch.object(salt.utils.msgpack, "version", version):
  31. data = [1, 2, 3]
  32. mock_dump = MagicMock(return_value=data)
  33. patch_dump = patch("msgpack.pack", mock_dump)
  34. mock_load = MagicMock(return_value=data)
  35. patch_load = patch("msgpack.unpack", mock_load)
  36. kwargs = {"encoding": "utf-8"}
  37. with patch_dump, patch_load:
  38. with salt.utils.files.fopen(fname.strpath, "wb") as wfh:
  39. salt.utils.msgpack.dump(data, wfh, encoding="utf-8")
  40. if encoding:
  41. assert "encoding" in mock_dump.call_args.kwargs
  42. else:
  43. assert "encoding" not in mock_dump.call_args.kwargs
  44. with salt.utils.files.fopen(fname.strpath, "rb") as rfh:
  45. salt.utils.msgpack.load(rfh, **kwargs)
  46. if encoding:
  47. assert "encoding" in mock_load.call_args.kwargs
  48. else:
  49. assert "encoding" not in mock_load.call_args.kwargs