test_png.py 1.3 KB

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