test_png.py 1.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950
  1. from io import BytesIO
  2. from pathlib import Path
  3. import pytest
  4. from matplotlib.testing.decorators import image_comparison
  5. from matplotlib import cm, pyplot as plt
  6. @image_comparison(['pngsuite.png'], tol=0.03)
  7. def test_pngsuite():
  8. files = sorted(
  9. (Path(__file__).parent / "baseline_images/pngsuite").glob("basn*.png"))
  10. plt.figure(figsize=(len(files), 2))
  11. for i, fname in enumerate(files):
  12. data = plt.imread(fname)
  13. cmap = None # use default colormap
  14. if data.ndim == 2:
  15. # keep grayscale images gray
  16. cmap = cm.gray
  17. plt.imshow(data, extent=(i, i + 1, 0, 1), cmap=cmap)
  18. plt.gca().patch.set_facecolor("#ddffff")
  19. plt.gca().set_xlim(0, len(files))
  20. def test_truncated_file(tmp_path):
  21. path = tmp_path / 'test.png'
  22. path_t = tmp_path / 'test_truncated.png'
  23. plt.savefig(path)
  24. with open(path, 'rb') as fin:
  25. buf = fin.read()
  26. with open(path_t, 'wb') as fout:
  27. fout.write(buf[:20])
  28. with pytest.raises(Exception):
  29. plt.imread(path_t)
  30. def test_truncated_buffer():
  31. b = BytesIO()
  32. plt.savefig(b)
  33. b.seek(0)
  34. b2 = BytesIO(b.read(20))
  35. b2.seek(0)
  36. with pytest.raises(Exception):
  37. plt.imread(b2)