bpo-42236: os.device_encoding() respects UTF-8 Mode (GH-23119)

On Unix, the os.device_encoding() function now returns 'UTF-8' rather
than the device encoding if the Python UTF-8 Mode is enabled.
This commit is contained in:
Victor Stinner 2020-11-04 11:20:10 +01:00 committed by GitHub
parent 0001a1b69e
commit 3529718925
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
5 changed files with 52 additions and 17 deletions

View file

@ -3,11 +3,13 @@ Test the implementation of the PEP 540: the UTF-8 Mode.
"""
import locale
import subprocess
import sys
import textwrap
import unittest
from test import support
from test.support.script_helper import assert_python_ok, assert_python_failure
from test.support import os_helper
MS_WINDOWS = (sys.platform == 'win32')
@ -250,6 +252,31 @@ class UTF8ModeTests(unittest.TestCase):
out = self.get_output('-X', 'utf8', '-E', '-c', code)
self.assertEqual(out, '1')
@unittest.skipIf(MS_WINDOWS,
"os.device_encoding() doesn't implement "
"the UTF-8 Mode on Windows")
def test_device_encoding(self):
# Use stdout as TTY
if not sys.stdout.isatty():
self.skipTest("sys.stdout is not a TTY")
filename = 'out.txt'
self.addCleanup(os_helper.unlink, filename)
code = (f'import os, sys; fd = sys.stdout.fileno(); '
f'out = open({filename!r}, "w", encoding="utf-8"); '
f'print(os.isatty(fd), os.device_encoding(fd), file=out); '
f'out.close()')
cmd = [sys.executable, '-X', 'utf8', '-c', code]
# The stdout TTY is inherited to the child process
proc = subprocess.run(cmd, text=True)
self.assertEqual(proc.returncode, 0, proc)
# In UTF-8 Mode, device_encoding(fd) returns "UTF-8" if fd is a TTY
with open(filename, encoding="utf8") as fp:
out = fp.read().rstrip()
self.assertEqual(out, 'True UTF-8')
if __name__ == "__main__":
unittest.main()