diff --git a/qrcode/console_scripts.py b/qrcode/console_scripts.py index 424fe6fd..a9f23751 100755 --- a/qrcode/console_scripts.py +++ b/qrcode/console_scripts.py @@ -110,6 +110,11 @@ def raise_error(msg: str) -> NoReturn: else: qr.add_data(data, optimize=opts.optimize) + try: + qr.make() + except qrcode.exceptions.DataOverflowError: + raise_error("too much data to fit in QR code") + if opts.output: img = qr.make_image() with open(opts.output, "wb") as out: diff --git a/qrcode/main.py b/qrcode/main.py index 0ac91bbb..cfc1e3ce 100644 --- a/qrcode/main.py +++ b/qrcode/main.py @@ -156,8 +156,8 @@ def make(self, fit=True): :param fit: If ``True`` (or if a size has not been provided), find the best fit for the data to avoid data overflow errors. """ - if fit or (self.version is None): - self.best_fit(start=self.version) + if fit or (self._version is None): + self.best_fit(start=self._version) if self.mask_pattern is None: self.makeImpl(False, self.best_mask_pattern()) else: @@ -229,11 +229,12 @@ def best_fit(self, start=None): data.write(buffer) needed_bits = len(buffer) - self.version = bisect_left( + new_version = bisect_left( util.BIT_LIMIT_TABLE[self.error_correction], needed_bits, start ) - if self.version == 41: + if new_version == 41: raise exceptions.DataOverflowError() + self.version = new_version # Now check whether we need more bits for the mode sizes, recursing if # our guess was too low diff --git a/qrcode/tests/test_qrcode.py b/qrcode/tests/test_qrcode.py index 5c1ea35b..27d0a329 100644 --- a/qrcode/tests/test_qrcode.py +++ b/qrcode/tests/test_qrcode.py @@ -66,6 +66,12 @@ def test_fit(self): qr.make() self.assertEqual(qr.version, 2) + def test_fit_overflow(self): + # Alphanumeric. Version 40 with ERROR_CORRECT_LOW has max 4296 characters. + qr = qrcode.QRCode(error_correction=qrcode.constants.ERROR_CORRECT_L) + qr.add_data("A" * 4297) + self.assertRaises(DataOverflowError, qr.make) + def test_mode_number(self): qr = qrcode.QRCode() qr.add_data("1234567890123456789012345678901234", optimize=0)