GH-128520: pathlib ABCs: raise text encoding warnings at correct stack level (#133051)

Ensure that warnings about unspecified text encodings are emitted from
`ReadablePath.read_text()`, `WritablePath.write_text()` and `magic_open()`
with the correct stack level set.
This commit is contained in:
Barney Gale 2025-04-28 19:04:20 +01:00 committed by GitHub
parent 6f04325992
commit fbffd70328
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
4 changed files with 59 additions and 4 deletions

View file

@ -4,6 +4,7 @@ Tests for pathlib.types._WritablePath
import io
import os
import sys
import unittest
from .support import is_pypi
@ -35,6 +36,17 @@ class WriteTestBase:
f.write('this is file A\n')
self.assertEqual(self.ground.readtext(p), 'this is file A\n')
@unittest.skipIf(
not getattr(sys.flags, 'warn_default_encoding', 0),
"Requires warn_default_encoding",
)
def test_open_w_encoding_warning(self):
p = self.root / 'fileA'
with self.assertWarns(EncodingWarning) as wc:
with magic_open(p, 'w'):
pass
self.assertEqual(wc.filename, __file__)
def test_open_wb(self):
p = self.root / 'fileA'
with magic_open(p, 'wb') as f:
@ -61,6 +73,16 @@ class WriteTestBase:
self.assertRaises(TypeError, p.write_text, b'somebytes')
self.assertEqual(self.ground.readbytes(p), b'\xe4bcdefg')
@unittest.skipIf(
not getattr(sys.flags, 'warn_default_encoding', 0),
"Requires warn_default_encoding",
)
def test_write_text_encoding_warning(self):
p = self.root / 'fileA'
with self.assertWarns(EncodingWarning) as wc:
p.write_text('abcdefg')
self.assertEqual(wc.filename, __file__)
def test_write_text_with_newlines(self):
# Check that `\n` character change nothing
p = self.root / 'fileA'