11from __future__ import annotations
22
3+ from io import BytesIO
4+
35import pytest
46
57from PIL .GimpPaletteFile import GimpPaletteFile
@@ -14,22 +16,57 @@ def test_sanity() -> None:
1416 GimpPaletteFile (fp )
1517
1618 with open ("Tests/images/bad_palette_file.gpl" , "rb" ) as fp :
17- with pytest .raises (SyntaxError ):
19+ with pytest .raises (SyntaxError , match = "bad palette file" ):
1820 GimpPaletteFile (fp )
1921
2022 with open ("Tests/images/bad_palette_entry.gpl" , "rb" ) as fp :
21- with pytest .raises (ValueError ):
23+ with pytest .raises (ValueError , match = "bad palette entry" ):
2224 GimpPaletteFile (fp )
2325
2426
25- def test_get_palette () -> None :
27+ @pytest .mark .parametrize (
28+ "filename, size" , (("custom_gimp_palette.gpl" , 8 ), ("full_gimp_palette.gpl" , 256 ))
29+ )
30+ def test_get_palette (filename : str , size : int ) -> None :
2631 # Arrange
27- with open ("Tests/images/custom_gimp_palette.gpl" , "rb" ) as fp :
32+ with open ("Tests/images/" + filename , "rb" ) as fp :
2833 palette_file = GimpPaletteFile (fp )
2934
3035 # Act
3136 palette , mode = palette_file .getpalette ()
3237
3338 # Assert
3439 assert mode == "RGB"
35- assert len (palette ) / 3 == 8
40+ assert len (palette ) / 3 == size
41+
42+
43+ def test_frombytes () -> None :
44+ # Test that __init__ stops reading after 260 lines
45+ with open ("Tests/images/custom_gimp_palette.gpl" , "rb" ) as fp :
46+ custom_data = fp .read ()
47+ custom_data += b"#\n " * 300 + b" 0 0 0 Index 12"
48+ b = BytesIO (custom_data )
49+ palette = GimpPaletteFile (b )
50+ assert len (palette .palette ) / 3 == 8
51+
52+ # Test that __init__ only reads 256 entries
53+ with open ("Tests/images/full_gimp_palette.gpl" , "rb" ) as fp :
54+ full_data = fp .read ()
55+ data = full_data .replace (b"#\n " , b"" ) + b" 0 0 0 Index 256"
56+ b = BytesIO (data )
57+ palette = GimpPaletteFile (b )
58+ assert len (palette .palette ) / 3 == 256
59+
60+ # Test that frombytes() can read beyond that
61+ palette = GimpPaletteFile .frombytes (data )
62+ assert len (palette .palette ) / 3 == 257
63+
64+ # Test that __init__ raises an error if a comment is too long
65+ data = full_data [:- 1 ] + b"a" * 100
66+ b = BytesIO (data )
67+ with pytest .raises (SyntaxError , match = "bad palette file" ):
68+ palette = GimpPaletteFile (b )
69+
70+ # Test that frombytes() can read the data regardless
71+ palette = GimpPaletteFile .frombytes (data )
72+ assert len (palette .palette ) / 3 == 256
0 commit comments