Debian Codegraph @

pylibdmtx/tests/test_pylibdmtx.py

raw
1 import unittest
2
3 from pathlib import Path
4
5 try:
6 from unittest.mock import call, patch
7 except ImportError:
8 # Python 2
9 from mock import call, patch
10
11 import numpy as np
12
13 from PIL import Image
14
15 try:
16 import cv2
17 except ImportError:
18 cv2 = None
19
20 try:
21 import imageio
22 except ImportError:
23 imageio = None
24
25 from pylibdmtx.pylibdmtx import (
26 decode, encode, Decoded, Encoded, Rect, EXTERNAL_DEPENDENCIES
27 )
28 from pylibdmtx.pylibdmtx_error import PyLibDMTXError
29
30
31 TESTDATA = Path(__file__).parent
32
33
34 class TestDecode(unittest.TestCase):
35 EXPECTED = [
36 Decoded(
37 data=b'Stegosaurus',
38 rect=Rect(left=5, top=6, width=96, height=95)
39 ),
40 Decoded(
41 data=b'Plesiosaurus',
42 rect=Rect(left=298, top=6, width=95, height=95)
43 )
44 ]
45
46 @classmethod
47 def setUpClass(cls):
48 cls.datamatrix = Image.open(str(TESTDATA.joinpath('datamatrix.png')))
49 cls.empty = Image.open(str(TESTDATA.joinpath('empty.png')))
50
51 # assertRaisesRegexp was a deprecated alias removed in Python 3.11
52 if not hasattr(cls, 'assertRaisesRegex'):
53 cls.assertRaisesRegex = cls.assertRaisesRegexp
54
55 @classmethod
56 def tearDownClass(cls):
57 cls.datamatrix = cls.empty = None
58
59 def test_decode(self):
60 "Read both barcodes in `datamatrix.png`"
61 res = decode(self.datamatrix)
62 self.assertEqual(self.EXPECTED, res)
63
64 def test_decode_single(self):
65 "Read just one of the barcodes in `datamatrix.png`"
66 res = decode(self.datamatrix, max_count=1)
67 self.assertEqual(self.EXPECTED[:1], res)
68
69 def test_decode_tuple(self):
70 "Read barcodes in pixels"
71 pixels = self.datamatrix.copy().convert('RGB').tobytes()
72 width, height = self.datamatrix.size[:2]
73 res = decode((pixels, width, height))
74 self.assertEqual(self.EXPECTED, res)
75
76 def test_empty(self):
77 "Do not show any output for an image that does not contain a barcode"
78 res = decode(self.empty)
79 self.assertEqual([], res)
80
81 def test_decode_numpy(self):
82 "Read image using Pillow and convert to numpy.ndarray"
83 res = decode(np.asarray(self.datamatrix))
84 self.assertEqual(self.EXPECTED, res)
85
86 @unittest.skipIf(imageio is None, 'imageio not installed')
87 def test_decode_imageio(self):
88 "Read image using imageio"
89 res = decode(imageio.imread(TESTDATA.joinpath('datamatrix.png')))
90 self.assertEqual(self.EXPECTED, res)
91
92 @unittest.skipIf(cv2 is None, 'OpenCV not installed')
93 def test_decode_opencv(self):
94 "Read image using OpenCV"
95 res = decode(cv2.imread(str(TESTDATA.joinpath('datamatrix.png'))))
96 self.assertEqual(self.EXPECTED, res)
97
98 def test_external_dependencies(self):
99 "External dependencies"
100 self.assertEqual(1, len(EXTERNAL_DEPENDENCIES))
101 self.assertIn('libdmtx', EXTERNAL_DEPENDENCIES[0]._name)
102
103 @patch('pylibdmtx.pylibdmtx.dmtxImageCreate')
104 def test_dmtxImageCreate_failed(self, dmtxImageCreate):
105 dmtxImageCreate.return_value = None
106 self.assertRaisesRegex(
107 PyLibDMTXError, 'Could not create image', decode, self.datamatrix
108 )
109 self.assertEqual(1, dmtxImageCreate.call_count)
110
111 @patch('pylibdmtx.pylibdmtx.dmtxDecodeCreate')
112 def test_dmtxDecodeCreate_failed(self, dmtxDecodeCreate):
113 dmtxDecodeCreate.return_value = None
114 self.assertRaisesRegex(
115 PyLibDMTXError, 'Could not create decoder', decode, self.datamatrix
116 )
117 self.assertEqual(1, dmtxDecodeCreate.call_count)
118
119 def test_unsupported_bits_per_pixel(self):
120 # 40 bits-per-pixel
121 data = (list(range(3 * 3 * 5)), 3, 3)
122 self.assertRaisesRegex(
123 PyLibDMTXError,
124 (
125 r'Unsupported bits-per-pixel: \[40\] Should be one of '
126 r'\[8, 16, 24, 32\]'
127 ),
128 decode, data
129 )
130
131 def test_inconsistent_dimensions(self):
132 # Image data has ten bytes. width x height indicates nine bytes
133 data = (list(range(10)), 3, 3)
134 self.assertRaisesRegex(
135 PyLibDMTXError,
136 (
137 r'Inconsistent dimensions: image data of 10 bytes is not '
138 r'divisible by \(width x height = 9\)'
139 ),
140 decode, data
141 )
142
143
144 class TestEncode(unittest.TestCase):
145 @classmethod
146 def setUpClass(cls):
147 # assertRaisesRegexp was a deprecated alias removed in Python 3.11
148 if not hasattr(cls, 'assertRaisesRegex'):
149 cls.assertRaisesRegex = cls.assertRaisesRegexp
150
151 def _assert_encoded_data(self, expected_data, encoded):
152 # Check encoded data
153 image = Image.frombytes(
154 'RGB', (encoded.width, encoded.height), encoded.pixels
155 )
156 decoded = decode(image)
157
158 self.assertEqual(1, len(decoded))
159 self.assertEqual(expected_data, decoded[0].data)
160
161 def test_encode_defaults(self):
162 data = b'hello world'
163 encoded = encode(data)
164
165 # Check returned data, with the exception of the pixel data
166 self.assertEqual(
167 Encoded(width=100, height=100, bpp=24, pixels=None),
168 encoded._replace(pixels=None)
169 )
170 self._assert_encoded_data(data, encoded)
171
172 def test_encode_size(self):
173 data = b'hello world'
174 encoded = encode(data, size='36x36')
175
176 # Check returned data, with the exception of the pixel data
177 self.assertEqual(
178 Encoded(width=200, height=200, bpp=24, pixels=None),
179 encoded._replace(pixels=None)
180 )
181
182 self._assert_encoded_data(data, encoded)
183
184 def test_encode_scheme(self):
185 data = b'hello world'
186 encoded = encode(data, scheme='Base256')
187
188 # Check returned data, with the exception of the pixel data
189 self.assertEqual(
190 Encoded(width=110, height=110, bpp=24, pixels=None),
191 encoded._replace(pixels=None)
192 )
193
194 self._assert_encoded_data(data, encoded)
195
196 def test_invalid_scheme(self):
197 self.assertRaisesRegex(
198 PyLibDMTXError,
199 r"Invalid scheme \[asdf\]: should be one of \['Ascii",
200 encode, b' ', scheme='asdf'
201 )
202
203 def test_invalid_size(self):
204 self.assertRaisesRegex(
205 PyLibDMTXError,
206 r"Invalid size \[9x9\]: should be one of \['RectAuto'",
207 encode, b' ', size='9x9'
208 )
209
210 def test_image_not_large_enough(self):
211 self.assertRaisesRegex(
212 PyLibDMTXError,
213 'Could not encode data, possibly because the image is not '
214 'large enough to contain the data',
215 encode, b' '*50, size='10x10'
216 )
217
218
219 if __name__ == '__main__':
220 unittest.main()