diff --git a/qrcode/main.py b/qrcode/main.py index be62de81..28070284 100644 --- a/qrcode/main.py +++ b/qrcode/main.py @@ -81,6 +81,7 @@ def __init__( ): _check_box_size(box_size) _check_border(border) + self.clear() self.version = version self.error_correction = int(error_correction) self.box_size = int(box_size) @@ -91,7 +92,6 @@ def __init__( self.image_factory = image_factory if image_factory is not None: assert issubclass(image_factory, BaseImage) - self.clear() @property def version(self) -> int: @@ -123,6 +123,7 @@ def clear(self): self.modules_count = 0 self.data_cache = None self.data_list = [] + self._version = None def add_data(self, data, optimize=20): """ diff --git a/qrcode/tests/regression/__init__.py b/qrcode/tests/regression/__init__.py new file mode 100644 index 00000000..e69de29b diff --git a/qrcode/tests/regression/test_pil_clear.py b/qrcode/tests/regression/test_pil_clear.py new file mode 100644 index 00000000..220284e9 --- /dev/null +++ b/qrcode/tests/regression/test_pil_clear.py @@ -0,0 +1,55 @@ +from __future__ import annotations + +from typing import TYPE_CHECKING + +import pytest + +import qrcode +from qrcode.constants import PIL_AVAILABLE + +if TYPE_CHECKING: + from pathlib import Path + + +@pytest.mark.skipif(not PIL_AVAILABLE, reason="PIL is not installed") +def test_qrcode_clear_resets_size(tmp_path: Path): + """ + Test that QRCode.clear() properly resets the QRCode object. + + Regression test for: + + QRCode class not resizing down between runs + https://github.com/lincolnloop/python-qrcode/issues/392 + """ + test1_path = tmp_path / "test1.png" + test2_path = tmp_path / "test2.png" + test3_path = tmp_path / "test3.png" + + # Create a QR code instance + qr = qrcode.QRCode(version=None) + + # Generate first QR code + qr.add_data("https://example.com/") + qr.make(fit=True) + img1 = qr.make_image() + img1.save(test1_path) + + # Clear and generate second QR code with different data + qr.clear() + qr.add_data("https://example.net/some/other/path") + qr.make(fit=True) + img2 = qr.make_image() + img2.save(test2_path) + + # Clear and generate third QR code with same data as first + qr.clear() + qr.add_data("https://example.com/") + qr.make(fit=True) + img3 = qr.make_image() + img3.save(test3_path) + + # Check that the first and third QR codes are identical. + with test1_path.open("rb") as file1, test3_path.open("rb") as file3: + assert file1.read() == file3.read(), ( + "First and third QR codes should be identical after clearing" + )