test_png.py 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  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.04)
  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. # Using the old default data interpolation stage lets us
  18. # continue to use the existing reference image
  19. plt.imshow(data, extent=(i, i + 1, 0, 1), cmap=cmap,
  20. interpolation_stage='data')
  21. plt.gca().patch.set_facecolor("#ddffff")
  22. plt.gca().set_xlim(0, len(files))
  23. def test_truncated_file(tmp_path):
  24. path = tmp_path / 'test.png'
  25. path_t = tmp_path / 'test_truncated.png'
  26. plt.savefig(path)
  27. with open(path, 'rb') as fin:
  28. buf = fin.read()
  29. with open(path_t, 'wb') as fout:
  30. fout.write(buf[:20])
  31. with pytest.raises(Exception):
  32. plt.imread(path_t)
  33. def test_truncated_buffer():
  34. b = BytesIO()
  35. plt.savefig(b)
  36. b.seek(0)
  37. b2 = BytesIO(b.read(20))
  38. b2.seek(0)
  39. with pytest.raises(Exception):
  40. plt.imread(b2)