Pillow

Форк
0
/
test_file_ppm.py 
387 строк · 10.6 Кб
1
from __future__ import annotations
2

3
import sys
4
from io import BytesIO
5
from pathlib import Path
6

7
import pytest
8

9
from PIL import Image, PpmImagePlugin
10

11
from .helper import (
12
    assert_image_equal,
13
    assert_image_equal_tofile,
14
    assert_image_similar,
15
    hopper,
16
)
17

18
# sample ppm stream
19
TEST_FILE = "Tests/images/hopper.ppm"
20

21

22
def test_sanity() -> None:
23
    with Image.open(TEST_FILE) as im:
24
        assert im.mode == "RGB"
25
        assert im.size == (128, 128)
26
        assert im.format == "PPM"
27
        assert im.get_format_mimetype() == "image/x-portable-pixmap"
28

29

30
@pytest.mark.parametrize(
31
    "data, mode, pixels",
32
    (
33
        (b"P2 3 1 4 0 2 4", "L", (0, 128, 255)),
34
        (b"P2 3 1 257 0 128 257", "I", (0, 32640, 65535)),
35
        # P3 with maxval < 255
36
        (
37
            b"P3 3 1 17 0 1 2 8 9 10 15 16 17",
38
            "RGB",
39
            ((0, 15, 30), (120, 135, 150), (225, 240, 255)),
40
        ),
41
        # P3 with maxval > 255
42
        # Scale down to 255, since there is no RGB mode with more than 8-bit
43
        (
44
            b"P3 3 1 257 0 1 2 128 129 130 256 257 257",
45
            "RGB",
46
            ((0, 1, 2), (127, 128, 129), (254, 255, 255)),
47
        ),
48
        (b"P5 3 1 4 \x00\x02\x04", "L", (0, 128, 255)),
49
        (b"P5 3 1 257 \x00\x00\x00\x80\x01\x01", "I", (0, 32640, 65535)),
50
        # P6 with maxval < 255
51
        (
52
            b"P6 3 1 17 \x00\x01\x02\x08\x09\x0A\x0F\x10\x11",
53
            "RGB",
54
            (
55
                (0, 15, 30),
56
                (120, 135, 150),
57
                (225, 240, 255),
58
            ),
59
        ),
60
        # P6 with maxval > 255
61
        (
62
            b"P6 3 1 257 \x00\x00\x00\x01\x00\x02"
63
            b"\x00\x80\x00\x81\x00\x82\x01\x00\x01\x01\xFF\xFF",
64
            "RGB",
65
            (
66
                (0, 1, 2),
67
                (127, 128, 129),
68
                (254, 255, 255),
69
            ),
70
        ),
71
    ),
72
)
73
def test_arbitrary_maxval(
74
    data: bytes, mode: str, pixels: tuple[int | tuple[int, int, int], ...]
75
) -> None:
76
    fp = BytesIO(data)
77
    with Image.open(fp) as im:
78
        assert im.size == (3, 1)
79
        assert im.mode == mode
80

81
        px = im.load()
82
        assert tuple(px[x, 0] for x in range(3)) == pixels
83

84

85
def test_16bit_pgm() -> None:
86
    with Image.open("Tests/images/16_bit_binary.pgm") as im:
87
        assert im.mode == "I"
88
        assert im.size == (20, 100)
89
        assert im.get_format_mimetype() == "image/x-portable-graymap"
90

91
        assert_image_equal_tofile(im, "Tests/images/16_bit_binary_pgm.tiff")
92

93

94
def test_16bit_pgm_write(tmp_path: Path) -> None:
95
    with Image.open("Tests/images/16_bit_binary.pgm") as im:
96
        filename = str(tmp_path / "temp.pgm")
97
        im.save(filename, "PPM")
98

99
        assert_image_equal_tofile(im, filename)
100

101

102
def test_pnm(tmp_path: Path) -> None:
103
    with Image.open("Tests/images/hopper.pnm") as im:
104
        assert_image_similar(im, hopper(), 0.0001)
105

106
        filename = str(tmp_path / "temp.pnm")
107
        im.save(filename)
108

109
        assert_image_equal_tofile(im, filename)
110

111

112
def test_pfm(tmp_path: Path) -> None:
113
    with Image.open("Tests/images/hopper.pfm") as im:
114
        assert im.info["scale"] == 1.0
115
        assert_image_equal(im, hopper("F"))
116

117
        filename = str(tmp_path / "tmp.pfm")
118
        im.save(filename)
119

120
        assert_image_equal_tofile(im, filename)
121

122

123
def test_pfm_big_endian(tmp_path: Path) -> None:
124
    with Image.open("Tests/images/hopper_be.pfm") as im:
125
        assert im.info["scale"] == 2.5
126
        assert_image_equal(im, hopper("F"))
127

128
        filename = str(tmp_path / "tmp.pfm")
129
        im.save(filename)
130

131
        assert_image_equal_tofile(im, filename)
132

133

134
@pytest.mark.parametrize(
135
    "data",
136
    [
137
        b"Pf 1 1 NaN \0\0\0\0",
138
        b"Pf 1 1 inf \0\0\0\0",
139
        b"Pf 1 1 -inf \0\0\0\0",
140
        b"Pf 1 1 0.0 \0\0\0\0",
141
        b"Pf 1 1 -0.0 \0\0\0\0",
142
    ],
143
)
144
def test_pfm_invalid(data: bytes) -> None:
145
    with pytest.raises(ValueError):
146
        with Image.open(BytesIO(data)):
147
            pass
148

149

150
@pytest.mark.parametrize(
151
    "plain_path, raw_path",
152
    (
153
        (
154
            "Tests/images/hopper_1bit_plain.pbm",  # P1
155
            "Tests/images/hopper_1bit.pbm",  # P4
156
        ),
157
        (
158
            "Tests/images/hopper_8bit_plain.pgm",  # P2
159
            "Tests/images/hopper_8bit.pgm",  # P5
160
        ),
161
        (
162
            "Tests/images/hopper_8bit_plain.ppm",  # P3
163
            "Tests/images/hopper_8bit.ppm",  # P6
164
        ),
165
    ),
166
)
167
def test_plain(plain_path: str, raw_path: str) -> None:
168
    with Image.open(plain_path) as im:
169
        assert_image_equal_tofile(im, raw_path)
170

171

172
def test_16bit_plain_pgm() -> None:
173
    # P2 with maxval 2 ** 16 - 1
174
    with Image.open("Tests/images/hopper_16bit_plain.pgm") as im:
175
        assert im.mode == "I"
176
        assert im.size == (128, 128)
177
        assert im.get_format_mimetype() == "image/x-portable-graymap"
178

179
        # P5 with maxval 2 ** 16 - 1
180
        assert_image_equal_tofile(im, "Tests/images/hopper_16bit.pgm")
181

182

183
@pytest.mark.parametrize(
184
    "header, data, comment_count",
185
    (
186
        (b"P1\n2 2", b"1010", 10**6),
187
        (b"P2\n3 1\n4", b"0 2 4", 1),
188
        (b"P3\n2 2\n255", b"0 0 0 001 1 1 2 2 2 255 255 255", 10**6),
189
    ),
190
)
191
def test_plain_data_with_comment(
192
    tmp_path: Path, header: bytes, data: bytes, comment_count: int
193
) -> None:
194
    path1 = str(tmp_path / "temp1.ppm")
195
    path2 = str(tmp_path / "temp2.ppm")
196
    comment = b"# comment" * comment_count
197
    with open(path1, "wb") as f1, open(path2, "wb") as f2:
198
        f1.write(header + b"\n\n" + data)
199
        f2.write(header + b"\n" + comment + b"\n" + data + comment)
200

201
    with Image.open(path1) as im:
202
        assert_image_equal_tofile(im, path2)
203

204

205
@pytest.mark.parametrize("data", (b"P1\n128 128\n", b"P3\n128 128\n255\n"))
206
def test_plain_truncated_data(tmp_path: Path, data: bytes) -> None:
207
    path = str(tmp_path / "temp.ppm")
208
    with open(path, "wb") as f:
209
        f.write(data)
210

211
    with Image.open(path) as im:
212
        with pytest.raises(ValueError):
213
            im.load()
214

215

216
@pytest.mark.parametrize("data", (b"P1\n128 128\n1009", b"P3\n128 128\n255\n100A"))
217
def test_plain_invalid_data(tmp_path: Path, data: bytes) -> None:
218
    path = str(tmp_path / "temp.ppm")
219
    with open(path, "wb") as f:
220
        f.write(data)
221

222
    with Image.open(path) as im:
223
        with pytest.raises(ValueError):
224
            im.load()
225

226

227
@pytest.mark.parametrize(
228
    "data",
229
    (
230
        b"P3\n128 128\n255\n012345678910",  # half token too long
231
        b"P3\n128 128\n255\n012345678910 0",  # token too long
232
    ),
233
)
234
def test_plain_ppm_token_too_long(tmp_path: Path, data: bytes) -> None:
235
    path = str(tmp_path / "temp.ppm")
236
    with open(path, "wb") as f:
237
        f.write(data)
238

239
    with Image.open(path) as im:
240
        with pytest.raises(ValueError):
241
            im.load()
242

243

244
def test_plain_ppm_value_negative(tmp_path: Path) -> None:
245
    path = str(tmp_path / "temp.ppm")
246
    with open(path, "wb") as f:
247
        f.write(b"P3\n128 128\n255\n-1")
248

249
    with Image.open(path) as im:
250
        with pytest.raises(ValueError, match="Channel value is negative"):
251
            im.load()
252

253

254
def test_plain_ppm_value_too_large(tmp_path: Path) -> None:
255
    path = str(tmp_path / "temp.ppm")
256
    with open(path, "wb") as f:
257
        f.write(b"P3\n128 128\n255\n256")
258

259
    with Image.open(path) as im:
260
        with pytest.raises(ValueError, match="Channel value too large"):
261
            im.load()
262

263

264
def test_magic() -> None:
265
    with pytest.raises(SyntaxError):
266
        PpmImagePlugin.PpmImageFile(fp=BytesIO(b"PyInvalid"))
267

268

269
def test_header_with_comments(tmp_path: Path) -> None:
270
    path = str(tmp_path / "temp.ppm")
271
    with open(path, "wb") as f:
272
        f.write(b"P6 #comment\n#comment\r12#comment\r8\n128 #comment\n255\n")
273

274
    with Image.open(path) as im:
275
        assert im.size == (128, 128)
276

277

278
def test_non_integer_token(tmp_path: Path) -> None:
279
    path = str(tmp_path / "temp.ppm")
280
    with open(path, "wb") as f:
281
        f.write(b"P6\nTEST")
282

283
    with pytest.raises(ValueError):
284
        with Image.open(path):
285
            pass
286

287

288
def test_header_token_too_long(tmp_path: Path) -> None:
289
    path = str(tmp_path / "temp.ppm")
290
    with open(path, "wb") as f:
291
        f.write(b"P6\n 01234567890")
292

293
    with pytest.raises(ValueError) as e:
294
        with Image.open(path):
295
            pass
296

297
    assert str(e.value) == "Token too long in file header: 01234567890"
298

299

300
def test_truncated_file(tmp_path: Path) -> None:
301
    # Test EOF in header
302
    path = str(tmp_path / "temp.pgm")
303
    with open(path, "wb") as f:
304
        f.write(b"P6")
305

306
    with pytest.raises(ValueError) as e:
307
        with Image.open(path):
308
            pass
309

310
    assert str(e.value) == "Reached EOF while reading header"
311

312
    # Test EOF for PyDecoder
313
    fp = BytesIO(b"P5 3 1 4")
314
    with Image.open(fp) as im:
315
        with pytest.raises(ValueError):
316
            im.load()
317

318

319
def test_not_enough_image_data(tmp_path: Path) -> None:
320
    path = str(tmp_path / "temp.ppm")
321
    with open(path, "wb") as f:
322
        f.write(b"P2 1 2 255 255")
323

324
    with Image.open(path) as im:
325
        with pytest.raises(ValueError):
326
            im.load()
327

328

329
@pytest.mark.parametrize("maxval", (b"0", b"65536"))
330
def test_invalid_maxval(maxval: bytes, tmp_path: Path) -> None:
331
    path = str(tmp_path / "temp.ppm")
332
    with open(path, "wb") as f:
333
        f.write(b"P6\n3 1 " + maxval)
334

335
    with pytest.raises(ValueError) as e:
336
        with Image.open(path):
337
            pass
338

339
    assert str(e.value) == "maxval must be greater than 0 and less than 65536"
340

341

342
def test_neg_ppm() -> None:
343
    # Storage.c accepted negative values for xsize, ysize.  the
344
    # internal open_ppm function didn't check for sanity but it
345
    # has been removed. The default opener doesn't accept negative
346
    # sizes.
347

348
    with pytest.raises(OSError):
349
        with Image.open("Tests/images/negative_size.ppm"):
350
            pass
351

352

353
def test_mimetypes(tmp_path: Path) -> None:
354
    path = str(tmp_path / "temp.pgm")
355

356
    with open(path, "wb") as f:
357
        f.write(b"P4\n128 128\n255")
358
    with Image.open(path) as im:
359
        assert im.get_format_mimetype() == "image/x-portable-bitmap"
360

361
    with open(path, "wb") as f:
362
        f.write(b"PyCMYK\n128 128\n255")
363
    with Image.open(path) as im:
364
        assert im.get_format_mimetype() == "image/x-portable-anymap"
365

366

367
@pytest.mark.parametrize("buffer", (True, False))
368
def test_save_stdout(buffer: bool) -> None:
369
    old_stdout = sys.stdout
370

371
    class MyStdOut:
372
        buffer = BytesIO()
373

374
    mystdout: MyStdOut | BytesIO = MyStdOut() if buffer else BytesIO()
375

376
    sys.stdout = mystdout
377

378
    with Image.open(TEST_FILE) as im:
379
        im.save(sys.stdout, "PPM")
380

381
    # Reset stdout
382
    sys.stdout = old_stdout
383

384
    if isinstance(mystdout, MyStdOut):
385
        mystdout = mystdout.buffer
386
    with Image.open(mystdout) as reloaded:
387
        assert_image_equal_tofile(reloaded, TEST_FILE)
388

Использование cookies

Мы используем файлы cookie в соответствии с Политикой конфиденциальности и Политикой использования cookies.

Нажимая кнопку «Принимаю», Вы даете АО «СберТех» согласие на обработку Ваших персональных данных в целях совершенствования нашего веб-сайта и Сервиса GitVerse, а также повышения удобства их использования.

Запретить использование cookies Вы можете самостоятельно в настройках Вашего браузера.