Skip to content

Commit 4465d1a

Browse files
committed
Fallback to default encoding when detection fails
Now, uses the default encoding (latin-1) when from_path(filename).best() returns None.
1 parent 74d8a42 commit 4465d1a

File tree

2 files changed

+17
-1
lines changed

2 files changed

+17
-1
lines changed

src/docformatter/encode.py

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -59,7 +59,8 @@ def do_detect_encoding(self, filename) -> None:
5959
The full path name of the file whose encoding is to be detected.
6060
"""
6161
try:
62-
self.encoding = from_path(filename).best().encoding
62+
detection_result = from_path(filename).best()
63+
self.encoding = detection_result.encoding if detection_result else self.DEFAULT_ENCODING
6364

6465
# Check for correctness of encoding.
6566
with self.do_open_with_encoding(filename) as check_file:

tests/test_encoding_functions.py

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -83,6 +83,21 @@ def test_detect_encoding_with_bad_encoding(self, temporary_file, contents):
8383

8484
assert "ascii" == uut.encoding
8585

86+
@pytest.mark.unit
87+
@pytest.mark.parametrize("contents", [""])
88+
def test_detect_encoding_with_undetectable_encoding(self, temporary_file):
89+
"""Default to latin-1 when encoding detection fails."""
90+
uut = Encoder()
91+
92+
# Simulate a file with undetectable encoding
93+
with open(temporary_file, "wb") as file:
94+
# Binary content unlikely to have a detectable encoding
95+
file.write(b"\xFF\xFE\xFD\xFC\x00\x00\x00\x00")
96+
97+
uut.do_detect_encoding(temporary_file)
98+
99+
assert uut.encoding == uut.DEFAULT_ENCODING
100+
86101

87102
class TestFindNewline:
88103
"""Class for testing the find_newline() function."""

0 commit comments

Comments
 (0)