Repository navigation
Expand file tree
/
Copy pathtest_decode.py
More file actions
477 lines (350 loc) · 14.3 KB
/
Copy pathtest_decode.py
File metadata and controls
477 lines (350 loc) · 14.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
import ctypes
import pathlib
import re
from typing import Self
import cv2
import numpy as np
import pytest
from PIL import Image
import pyrxing
ASSETS: dict[str, dict[str, str]] = {
"assets/test_aztec.png": {"format": "MicroQRCode", "value": "Code Code Data"},
"assets/test_codabar.png": {"format": "Codabar", "value": "A-12656-D"},
"assets/test_code128.png": {
"format": "Code128",
"value": "Python Barcode Random World",
},
"assets/test_code39.png": {"format": "Code39", "value": "QD9MZ5O"},
"assets/test_code93.png": {"format": "Code93", "value": "ABC-1234-/+"},
"assets/test_data_bar.png": {
"format": "DataBarOmni",
"value": "(01)01234567890128",
},
"assets/test_data_bar_expanded.png": {
"format": "DataBarExpanded",
"value": "011234567890123-ABCabc",
},
"assets/test_data_bar_limited.png": {
"format": "DataBarLimited",
"value": "(01)01234567890128",
},
"assets/test_data_matrix.png": {
"format": "DataMatrix",
"value": "DataMatrix_31802",
},
"assets/test_dx_film_edge.png": {
"format": "Code128",
"value": "DXFilmEdge_6086",
},
"assets/test_ean13.png": {"format": "EAN13", "value": "2708639496369"},
"assets/test_ean8.png": {"format": "EAN8", "value": "07727931"},
"assets/test_itf.png": {"format": "ITF", "value": "4577279804"},
"assets/test_maxi_code.png": {
"format": "MaxiCode",
"value": "MaxiCode_46753",
},
"assets/test_micro_qr.png": {
"format": "MicroQRCode",
"value": "0ZFXY9",
},
"assets/test_pdf417.png": {"format": "PDF417", "value": "PDF417_12417"},
"assets/test_qr_code.png": {
"format": "QRCode",
"value": "https://demo.net/demo/7809",
},
"assets/test_rmqr.png": {"format": "MicroQRCode", "value": "V4GQ68D2"},
"assets/test_upc_a.png": {"format": "EAN13", "value": "0041935974561"},
"assets/test_upc_e.png": {"format": "UPCE", "value": "0182749000074"},
}
def test_read() -> None:
for path, v in ASSETS.items():
i = Image.open(path)
res = pyrxing.read_barcode(i)
assert res is not None
assert res.text == v['value']
assert res.format == v['format']
res = pyrxing.read_barcodes(i)
assert len(res) == 1
assert res[0].text == v['value']
assert res[0].format == v['format']
@pytest.mark.parametrize(("path", "expected"), ASSETS.items())
def test_read_opencv_numpy_arrays(path: str, expected: dict[str, str]) -> None:
image = cv2.imread(path, cv2.IMREAD_GRAYSCALE)
assert image is not None
assert image.dtype == np.uint8
assert image.ndim == 2
result = pyrxing.read_barcode(image)
assert result is not None
assert result.text == expected["value"]
assert result.format == expected["format"]
results = pyrxing.read_barcodes(image)
assert len(results) == 1
assert results[0].text == expected["value"]
assert results[0].format == expected["format"]
@pytest.mark.parametrize(
("image", "message"),
[
(np.zeros((2, 2), dtype=np.float32), "array dtype must be uint8"),
(np.zeros((2, 2, 3), dtype=np.uint8), "array must be single-channel grayscale"),
(np.zeros((2,), dtype=np.uint8), "array shape must be"),
(np.zeros((1, 1, 1, 1), dtype=np.uint8), "array shape must be"),
(np.zeros((0, 2), dtype=np.uint8), "greater than zero"),
],
)
def test_rejects_unsupported_numpy_arrays(image: np.ndarray, message: str) -> None:
with pytest.raises(pyrxing.ImageError, match=message):
pyrxing.read_barcode(image)
class InvalidArrayData:
__array_interface__ = {
"shape": (2, 2),
"typestr": "|u1",
"version": 3,
}
def tobytes(self) -> bytes:
return b"\x00" * 3
class CountingArray:
"""An array interface implementation counting its tobytes calls."""
def __init__(self, height: int, width: int, data: bytes) -> None:
self.__array_interface__ = {
"shape": (height, width),
"typestr": "|u1",
"version": 3,
}
self._data = data
self.tobytes_calls = 0
def tobytes(self) -> bytes:
self.tobytes_calls += 1
return self._data
def test_rejects_an_oversized_array_before_reading_the_pixels() -> None:
image = CountingArray(1, 0x10000, b"")
with pytest.raises(pyrxing.ImageError, match="is 65535, got 65536x1"):
pyrxing.read_barcode(image)
assert image.tobytes_calls == 0
def test_rejects_mismatched_array_data() -> None:
with pytest.raises(pyrxing.ImageError, match="expected 4, got 3"):
pyrxing.read_barcode(InvalidArrayData())
QR_CODE: str = "assets/test_qr_code.png"
QR_CODE_VALUE: str = "https://demo.net/demo/7809"
class SizedImage:
"""An ImageProtocol implementation reporting a size of its own choosing."""
mode: str = "L"
def __init__(self, width: int, height: int, data: bytes) -> None:
self.width = width
self.height = height
self._data = data
self.tobytes_calls = 0
def tobytes(self) -> bytes:
self.tobytes_calls += 1
return self._data
def convert(self, mode: str) -> Self:
return self
def load(self) -> None:
pass
# Subformat names of pyrxing.pyi none of which a QR code carries.
NAMES_MISSING_FROM_A_QR_CODE: list[str] = [
"AztecCode",
"AztecRune",
"CompactPDF417",
"EAN2",
"EAN5",
"EANUPC",
"ISBN",
"MicroPDF417",
"PZN",
"QRCodeModel1",
]
def test_read_barcode_filters_by_a_subformat_name() -> None:
# A name the extension drops leaves `formats` empty, and an empty list means
# every format, so the QR code below would decode instead of being filtered out.
image = Image.open(QR_CODE)
matched = [
name
for name in NAMES_MISSING_FROM_A_QR_CODE
if pyrxing.read_barcode(image, formats=[name]) is not None
]
assert matched == []
assert pyrxing.read_barcode(image, formats=["QRCodeModel2"]).text == QR_CODE_VALUE
def stub_image_protocol_members() -> set[str]:
"""Returns the member names the ImageProtocol of pyrxing.pyi declares."""
stub = pathlib.Path(__file__).with_name("pyrxing.pyi").read_text()
body = stub.split("class ImageProtocol(Protocol):", 1)[1].split("\nclass ", 1)[0]
return set(re.findall(r"def ([a-z_]+)\(", body))
class StubConformantImage:
"""An ImageProtocol implementation with exactly the members pyrxing.pyi declares."""
def __init__(self, pil: Image.Image) -> None:
self._pil = pil.convert("L")
@property
def mode(self) -> str:
return self._pil.mode
@property
def width(self) -> int:
return self._pil.width
@property
def height(self) -> int:
return self._pil.height
def tobytes(self) -> bytes:
return self._pil.tobytes()
def convert(self, mode: str) -> Image.Image:
return self._pil.convert(mode)
def load(self) -> None:
self._pil.load()
def test_stub_declares_the_members_the_extension_requires() -> None:
assert stub_image_protocol_members() == {
"mode",
"width",
"height",
"tobytes",
"convert",
"load",
}
image = StubConformantImage(Image.open(QR_CODE))
assert pyrxing.read_barcode(image).text == QR_CODE_VALUE
def stub_barcode_format_names() -> list[str]:
"""Returns the names the BarcodeFormat Literal of pyrxing.pyi declares."""
stub = pathlib.Path(__file__).with_name("pyrxing.pyi").read_text()
literal = stub.split("BarcodeFormat = Literal[", 1)[1].split("]", 1)[0]
return re.findall(r'"([A-Za-z0-9]+)"', literal)
def test_stub_declares_only_names_the_extension_accepts() -> None:
image = Image.open(QR_CODE)
names = stub_barcode_format_names()
assert len(names) == 35
for name in names:
pyrxing.read_barcode(image, formats=[name])
pyrxing.read_barcodes(image, formats=[name])
@pytest.mark.parametrize(
("formats", "reported"),
[
(["Bogus"], "Bogus"),
(["QRCode", "Bogus"], "Bogus"),
(["Bogus", "AlsoBogus"], "Bogus"),
(["qrcode"], "qrcode"),
],
)
def test_read_barcode_rejects_an_unknown_format_name(
formats: list[str], reported: str
) -> None:
image = Image.open(QR_CODE)
with pytest.raises(pyrxing.UnsupportedFormatError) as caught:
pyrxing.read_barcode(image, formats=formats)
assert caught.value.format == reported
assert reported in str(caught.value)
def test_unsupported_format_error_derives_from_the_module_base() -> None:
assert issubclass(pyrxing.UnsupportedFormatError, pyrxing.Error)
assert not issubclass(pyrxing.UnsupportedFormatError, pyrxing.ImageError)
@pytest.mark.parametrize("formats", [None, []])
def test_read_barcode_searches_every_format_without_a_filter(
formats: list[str] | None,
) -> None:
image = Image.open(QR_CODE)
assert pyrxing.read_barcode(image, formats=formats).text == QR_CODE_VALUE
def test_read_barcode_accepts_more_formats_than_the_zxing_format_count() -> None:
image = Image.open(QR_CODE)
assert pyrxing.read_barcode(image, formats=["QRCode"] * 33).text == QR_CODE_VALUE
def test_read_barcode_rejects_a_size_disagreeing_with_the_pixel_data() -> None:
image = Image.open(QR_CODE).convert("L")
truncated = SizedImage(image.width, image.height, image.tobytes()[:-1])
with pytest.raises(pyrxing.ImageError, match="expected 122500, got 122499"):
pyrxing.read_barcode(truncated)
class PointerInterfaceImage:
"""An ImageProtocol implementation exposing the NumPy form of __array_interface__.
NumPy reports `data` as a (address, read-only) pair rather than a bytes object.
"""
mode: str = "L"
def __init__(self, pil: Image.Image) -> None:
self._data = pil.convert("L").tobytes()
self.width = pil.width
self.height = pil.height
def tobytes(self) -> bytes | bytearray:
return self._data
def convert(self, mode: str) -> Self:
return self
def load(self) -> None:
pass
@property
def __array_interface__(self) -> dict[str, object]:
address = ctypes.cast(ctypes.c_char_p(self._data), ctypes.c_void_p).value
return {
"version": 3,
"typestr": "|u1",
"shape": (self.height, self.width),
"data": (address, True),
}
class BytearrayImage(PointerInterfaceImage):
"""An ImageProtocol implementation returning a buffer other than bytes."""
def tobytes(self) -> bytearray:
return bytearray(self._data)
def test_read_barcode_accepts_a_pointer_shaped_array_interface() -> None:
image = PointerInterfaceImage(Image.open(QR_CODE))
assert pyrxing.read_barcode(image).text == QR_CODE_VALUE
def test_read_barcode_accepts_a_buffer_other_than_bytes() -> None:
image = BytearrayImage(Image.open(QR_CODE))
assert pyrxing.read_barcode(image).text == QR_CODE_VALUE
def test_read_barcode_rejects_a_side_wrapping_a_u32_product() -> None:
# 0x80000000 * 2 is 2**32, so a wrapping multiplication would report zero pixels
# and let an empty buffer through.
with pytest.raises(pyrxing.ImageError, match="is 65535, got 2147483648x2"):
pyrxing.read_barcode(SizedImage(0x80000000, 2, b""))
def test_module_exceptions_derive_from_the_module_base() -> None:
assert issubclass(pyrxing.ImageError, pyrxing.Error)
assert issubclass(pyrxing.BarcodeDecodeError, pyrxing.Error)
assert issubclass(pyrxing.Error, Exception)
def test_image_error_carries_its_message() -> None:
image = Image.open(QR_CODE).convert("CMYK")
with pytest.raises(pyrxing.Error) as caught:
pyrxing.read_barcode(image)
assert isinstance(caught.value, pyrxing.ImageError)
assert "image mode must be grayscale, RGB(A), or palette, got CMYK" in str(caught.value)
assert not hasattr(caught.value, "message")
@pytest.mark.parametrize("factory", [str, pathlib.Path])
def test_read_barcode_accepts_a_path_like_argument(factory) -> None:
assert pyrxing.read_barcode(factory(QR_CODE)).text == QR_CODE_VALUE
def test_read_barcode_accepts_an_fspath_implementation() -> None:
class PathHolder:
def __fspath__(self) -> str:
return QR_CODE
assert pyrxing.read_barcode(PathHolder()).text == QR_CODE_VALUE
@pytest.mark.parametrize(
"image", [123, None, b"assets/test_qr_code.png", object(), ["assets/test_qr_code.png"]]
)
def test_read_barcode_rejects_an_argument_of_another_type(image: object) -> None:
with pytest.raises(TypeError, match="str, os.PathLike, ImageProtocol value, or uint8 array"):
pyrxing.read_barcode(image)
def test_read_barcode_rejects_an_incomplete_image_protocol() -> None:
class WithoutMode:
width = 4
height = 3
def tobytes(self) -> bytes:
return bytes(12)
def convert(self, mode: str) -> Self:
return self
def load(self) -> None:
pass
with pytest.raises(TypeError):
pyrxing.read_barcode(WithoutMode())
def test_read_barcode_rejects_a_dimension_beyond_the_reader_limit() -> None:
image = SizedImage(0x10000, 1, bytes(0x10000))
with pytest.raises(pyrxing.ImageError, match="is 65535, got 65536x1"):
pyrxing.read_barcode(image)
assert image.tobytes_calls == 0
def stub_exception_bases() -> dict[str, str]:
"""Returns the base class each exception of pyrxing.pyi declares."""
stub = pathlib.Path(__file__).with_name("pyrxing.pyi").read_text()
return dict(re.findall(r"^class (Error|\w+Error)\((\w+)\):", stub, re.MULTILINE))
def test_stub_declares_the_exception_hierarchy() -> None:
declared = stub_exception_bases()
assert declared == {
"Error": "Exception",
"BarcodeDecodeError": "Error",
"ImageError": "Error",
"UnsupportedFormatError": "Error",
}
for name, base in declared.items():
actual = getattr(pyrxing, name)
expected = Exception if base == "Exception" else getattr(pyrxing, base)
assert actual.__bases__ == (expected,), name
def test_readme_repeats_the_type_stub() -> None:
def api_block(path: pathlib.Path) -> str:
text = path.read_text(encoding="utf-8")
return text.split("class ImageProtocol(Protocol):", 1)[1].split("def read_barcode", 1)[0]
here = pathlib.Path(__file__).parent
assert api_block(here / "README.md") == api_block(here / "pyrxing.pyi")