Magic encoder: fix codepage usage (#580)

* add unit test for issue pointed out by @scott-r in #570

* swap order of encoder search

As described by @scott-r in
Magic encoder does not use
previously used code pages
when possible #570
Thank you!
This commit is contained in:
Patrick Kanzler 2023-10-05 14:55:12 +02:00 committed by GitHub
parent 5018f7f377
commit a70e1604d6
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
4 changed files with 14 additions and 1 deletions

View File

@ -12,11 +12,15 @@ changes
- has
- changed
- fix the encoding search so that lower encodings are found first
contributors
^^^^^^^^^^^^
- list
- contributors
- Scott Rotondo in `#570 <https://github.com/python-escpos/python-escpos/issues/570>`_
2023-05-11 - Version 3.0a9 - "Pride Comes Before A Fall"
--------------------------------------------------------
This release is the 10th alpha release of the new version 3.0.

View File

@ -67,6 +67,7 @@ Heuel
Qian
Lehtonen
Kanzler
Rotondo
barcode
barcodes

View File

@ -155,7 +155,8 @@ class Encoder(object):
def __encoding_sort_func(self, item):
key, index = item
return (key in self.used_encodings, index)
used = key in self.used_encodings
return (not used, index)
def find_suitable_encoding(self, char):
"""Search in a specific order for a suitable encoding.

View File

@ -32,6 +32,13 @@ class TestEncoder:
assert not Encoder({"CP437": 1}).find_suitable_encoding("")
assert Encoder({"CP858": 1}).find_suitable_encoding("") == "CP858"
def test_find_suitable_encoding_unnecessary_codepage_swap(self):
enc = Encoder({"CP857": 1, "CP437": 2, "CP1252": 3, "CP852": 4, "CP858": 5})
# desired behavior would be that the encoder always stays in the lower
# available codepages if possible
for character in ("Á", "É", "Í", "Ó", "Ú"):
assert enc.find_suitable_encoding(character) == "CP857"
def test_get_encoding(self):
with pytest.raises(ValueError):
Encoder({}).get_encoding_name("latin1")