Skip to content

Commit

Permalink
test encoding warning with env var
Browse files Browse the repository at this point in the history
  • Loading branch information
DanielYang59 committed Dec 20, 2024
1 parent 3e1ffc5 commit 2cd39ce
Show file tree
Hide file tree
Showing 2 changed files with 21 additions and 4 deletions.
7 changes: 4 additions & 3 deletions src/monty/io.py
Original file line number Diff line number Diff line change
Expand Up @@ -76,11 +76,12 @@ def zopen(
stacklevel=2,
)

# Warn against default `encoding` in text mode if `PYTHONWARNDEFAULTENCODING` is set
# Warn against default `encoding` in text mode if
# `PYTHONWARNDEFAULTENCODING` environment variable is set (PEP 597)
if (
os.getenv("PYTHONWARNDEFAULTENCODING", False)
and "t" in mode
"t" in mode
and kwargs.get("encoding", None) is None
and os.getenv("PYTHONWARNDEFAULTENCODING", False)
):
warnings.warn(
"We strongly encourage explicit `encoding`, "
Expand Down
18 changes: 17 additions & 1 deletion tests/test_io.py
Original file line number Diff line number Diff line change
Expand Up @@ -426,23 +426,39 @@ def test_lzw_files(self):
# Cannot decompress a real LZW file
with (
pytest.raises(gzip.BadGzipFile, match="Not a gzipped file"),
pytest.warns(FutureWarning, match="compress LZW-compressed files"),
zopen(f"{TEST_DIR}/real_lzw_file.txt.Z", "rt", encoding="utf-8") as f,
):
f.read()

@pytest.mark.parametrize("extension", [".txt", ".bz2", ".gz", ".xz", ".lzma"])
def test_warnings(self, extension):
def test_warnings(self, extension, monkeypatch):
filename = f"test_warning{extension}"
content = "Test warning"

with ScratchDir("."):
monkeypatch.setenv("PYTHONWARNDEFAULTENCODING", "1")

# Default `encoding` warning
with (
pytest.warns(EncodingWarning, match="use UTF-8 by default"),
zopen(filename, "wt") as f,
):
f.write(content)

# No encoding warning if `PYTHONWARNDEFAULTENCODING` not set
monkeypatch.delenv("PYTHONWARNDEFAULTENCODING", raising=False)

with warnings.catch_warnings():
warnings.filterwarnings(
"error",
"We strongly encourage explicit `encoding`",
EncodingWarning,
)

with zopen(filename, "wt") as f:
f.write(content)

# Implicit text/binary `mode` warning
warnings.filterwarnings(
"ignore", category=EncodingWarning, message="argument not specified"
Expand Down

0 comments on commit 2cd39ce

Please sign in to comment.