Debian Codegraph @

lib-python/3/test/test_c_locale_coercion.py

raw symbols SCIP
1 # Tests the attempted automatic coercion of the C locale to a UTF-8 locale
2
3 import locale
4 import os
5 import subprocess
6 import sys
7 import sysconfig
8 import unittest
9 from collections import namedtuple
10
11 from test import support
12 from test.support.script_helper import run_python_until_end
13
14
15 # Set the list of ways we expect to be able to ask for the "C" locale
16 EXPECTED_C_LOCALE_EQUIVALENTS = ["C", "invalid.ascii"]
17
18 # Set our expectation for the default encoding used in the C locale
19 # for the filesystem encoding and the standard streams
20 EXPECTED_C_LOCALE_STREAM_ENCODING = "ascii"
21 EXPECTED_C_LOCALE_FS_ENCODING = "ascii"
22
23 # Set our expectation for the default locale used when none is specified
24 EXPECT_COERCION_IN_DEFAULT_LOCALE = True
25
26 TARGET_LOCALES = ["C.UTF-8", "C.utf8", "UTF-8"]
27
28 # Apply some platform dependent overrides
29 if sys.platform.startswith("linux"):
30 if support.is_android:
31 # Android defaults to using UTF-8 for all system interfaces
32 EXPECTED_C_LOCALE_STREAM_ENCODING = "utf-8"
33 EXPECTED_C_LOCALE_FS_ENCODING = "utf-8"
34 else:
35 # Linux distros typically alias the POSIX locale directly to the C
36 # locale.
37 # TODO: Once https://bugs.python.org/issue30672 is addressed, we'll be
38 # able to check this case unconditionally
39 EXPECTED_C_LOCALE_EQUIVALENTS.append("POSIX")
40 elif sys.platform.startswith("aix"):
41 # AIX uses iso8859-1 in the C locale, other *nix platforms use ASCII
42 EXPECTED_C_LOCALE_STREAM_ENCODING = "iso8859-1"
43 EXPECTED_C_LOCALE_FS_ENCODING = "iso8859-1"
44 elif sys.platform == "darwin":
45 # FS encoding is UTF-8 on macOS
46 EXPECTED_C_LOCALE_FS_ENCODING = "utf-8"
47 elif sys.platform == "cygwin":
48 # Cygwin defaults to using C.UTF-8
49 # TODO: Work out a robust dynamic test for this that doesn't rely on
50 # CPython's own locale handling machinery
51 EXPECT_COERCION_IN_DEFAULT_LOCALE = False
52 elif sys.platform == "vxworks":
53 # VxWorks defaults to using UTF-8 for all system interfaces
54 EXPECTED_C_LOCALE_STREAM_ENCODING = "utf-8"
55 EXPECTED_C_LOCALE_FS_ENCODING = "utf-8"
56
57 # Note that the above expectations are still wrong in some cases, such as:
58 # * Windows when PYTHONLEGACYWINDOWSFSENCODING is set
59 # * Any platform other than AIX that uses latin-1 in the C locale
60 # * Any Linux distro where POSIX isn't a simple alias for the C locale
61 # * Any Linux distro where the default locale is something other than "C"
62 #
63 # Options for dealing with this:
64 # * Don't set the PY_COERCE_C_LOCALE preprocessor definition on
65 # such platforms (e.g. it isn't set on Windows)
66 # * Fix the test expectations to match the actual platform behaviour
67
68 # In order to get the warning messages to match up as expected, the candidate
69 # order here must much the target locale order in Python/pylifecycle.c
70 _C_UTF8_LOCALES = ("C.UTF-8", "C.utf8", "UTF-8")
71
72 # There's no reliable cross-platform way of checking locale alias
73 # lists, so the only way of knowing which of these locales will work
74 # is to try them with locale.setlocale(). We do that in a subprocess
75 # in setUpModule() below to avoid altering the locale of the test runner.
76 #
77 # If the relevant locale module attributes exist, and we're not on a platform
78 # where we expect it to always succeed, we also check that
79 # `locale.nl_langinfo(locale.CODESET)` works, as if it fails, the interpreter
80 # will skip locale coercion for that particular target locale
81 _check_nl_langinfo_CODESET = bool(
82 sys.platform not in ("darwin", "linux") and
83 hasattr(locale, "nl_langinfo") and
84 hasattr(locale, "CODESET")
85 )
86
87 def _set_locale_in_subprocess(locale_name):
88 cmd_fmt = "import locale; print(locale.setlocale(locale.LC_CTYPE, '{}'))"
89 if _check_nl_langinfo_CODESET:
90 # If there's no valid CODESET, we expect coercion to be skipped
91 cmd_fmt += "; import sys; sys.exit(not locale.nl_langinfo(locale.CODESET))"
92 cmd = cmd_fmt.format(locale_name)
93 result, py_cmd = run_python_until_end("-c", cmd, PYTHONCOERCECLOCALE='')
94 return result.rc == 0
95
96
97
98 _fields = "fsencoding stdin_info stdout_info stderr_info lang lc_ctype lc_all"
99 _EncodingDetails = namedtuple("EncodingDetails", _fields)
100
101 class EncodingDetails(_EncodingDetails):
102 # XXX (ncoghlan): Using JSON for child state reporting may be less fragile
103 CHILD_PROCESS_SCRIPT = ";".join([
104 "import sys, os",
105 "print(sys.getfilesystemencoding())",
106 "print(sys.stdin.encoding + ':' + sys.stdin.errors)",
107 "print(sys.stdout.encoding + ':' + sys.stdout.errors)",
108 "print(sys.stderr.encoding + ':' + sys.stderr.errors)",
109 "print(os.environ.get('LANG', 'not set'))",
110 "print(os.environ.get('LC_CTYPE', 'not set'))",
111 "print(os.environ.get('LC_ALL', 'not set'))",
112 ])
113
114 @classmethod
115 def get_expected_details(cls, coercion_expected, fs_encoding, stream_encoding, stream_errors, env_vars):
116 """Returns expected child process details for a given encoding"""
117 _stream = stream_encoding + ":{}"
118 if stream_errors is None:
119 # stdin and stdout should use surrogateescape either because the
120 # coercion triggered, or because the C locale was detected
121 stream_errors = "surrogateescape"
122
123 stream_info = [_stream.format(stream_errors)] * 2
124
125 # stderr should always use backslashreplace
126 stream_info.append(_stream.format("backslashreplace"))
127 expected_lang = env_vars.get("LANG", "not set")
128 if coercion_expected:
129 expected_lc_ctype = CLI_COERCION_TARGET
130 else:
131 expected_lc_ctype = env_vars.get("LC_CTYPE", "not set")
132 expected_lc_all = env_vars.get("LC_ALL", "not set")
133 env_info = expected_lang, expected_lc_ctype, expected_lc_all
134 return dict(cls(fs_encoding, *stream_info, *env_info)._asdict())
135
136 @classmethod
137 def get_child_details(cls, env_vars):
138 """Retrieves fsencoding and standard stream details from a child process
139
140 Returns (encoding_details, stderr_lines):
141
142 - encoding_details: EncodingDetails for eager decoding
143 - stderr_lines: result of calling splitlines() on the stderr output
144
145 The child is run in isolated mode if the current interpreter supports
146 that.
147 """
148 result, py_cmd = run_python_until_end(
149 "-X", "utf8=0", "-c", cls.CHILD_PROCESS_SCRIPT,
150 **env_vars
151 )
152 if not result.rc == 0:
153 result.fail(py_cmd)
154 # All subprocess outputs in this test case should be pure ASCII
155 stdout_lines = result.out.decode("ascii").splitlines()
156 child_encoding_details = dict(cls(*stdout_lines)._asdict())
157 stderr_lines = result.err.decode("ascii").rstrip().splitlines()
158 return child_encoding_details, stderr_lines
159
160
161 # Details of the shared library warning emitted at runtime
162 LEGACY_LOCALE_WARNING = (
163 "Python runtime initialized with LC_CTYPE=C (a locale with default ASCII "
164 "encoding), which may cause Unicode compatibility problems. Using C.UTF-8, "
165 "C.utf8, or UTF-8 (if available) as alternative Unicode-compatible "
166 "locales is recommended."
167 )
168
169 # Details of the CLI locale coercion warning emitted at runtime
170 CLI_COERCION_WARNING_FMT = (
171 "Python detected LC_CTYPE=C: LC_CTYPE coerced to {} (set another locale "
172 "or PYTHONCOERCECLOCALE=0 to disable this locale coercion behavior)."
173 )
174
175
176 AVAILABLE_TARGETS = None
177 CLI_COERCION_TARGET = None
178 CLI_COERCION_WARNING = None
179
180 def setUpModule():
181 global AVAILABLE_TARGETS
182 global CLI_COERCION_TARGET
183 global CLI_COERCION_WARNING
184
185 if AVAILABLE_TARGETS is not None:
186 # initialization already done
187 return
188 AVAILABLE_TARGETS = []
189
190 # Find the target locales available in the current system
191 for target_locale in _C_UTF8_LOCALES:
192 if _set_locale_in_subprocess(target_locale):
193 AVAILABLE_TARGETS.append(target_locale)
194
195 if AVAILABLE_TARGETS:
196 # Coercion is expected to use the first available target locale
197 CLI_COERCION_TARGET = AVAILABLE_TARGETS[0]
198 CLI_COERCION_WARNING = CLI_COERCION_WARNING_FMT.format(CLI_COERCION_TARGET)
199
200 if support.verbose:
201 print(f"AVAILABLE_TARGETS = {AVAILABLE_TARGETS!r}")
202 print(f"EXPECTED_C_LOCALE_EQUIVALENTS = {EXPECTED_C_LOCALE_EQUIVALENTS!r}")
203 print(f"EXPECTED_C_LOCALE_STREAM_ENCODING = {EXPECTED_C_LOCALE_STREAM_ENCODING!r}")
204 print(f"EXPECTED_C_LOCALE_FS_ENCODING = {EXPECTED_C_LOCALE_FS_ENCODING!r}")
205 print(f"EXPECT_COERCION_IN_DEFAULT_LOCALE = {EXPECT_COERCION_IN_DEFAULT_LOCALE!r}")
206 print(f"_C_UTF8_LOCALES = {_C_UTF8_LOCALES!r}")
207 print(f"_check_nl_langinfo_CODESET = {_check_nl_langinfo_CODESET!r}")
208
209
210 class _LocaleHandlingTestCase(unittest.TestCase):
211 # Base class to check expected locale handling behaviour
212
213 def _check_child_encoding_details(self,
214 env_vars,
215 expected_fs_encoding,
216 expected_stream_encoding,
217 expected_stream_errors,
218 expected_warnings,
219 coercion_expected):
220 """Check the C locale handling for the given process environment
221
222 Parameters:
223 expected_fs_encoding: expected sys.getfilesystemencoding() result
224 expected_stream_encoding: expected encoding for standard streams
225 expected_warning: stderr output to expect (if any)
226 """
227 result = EncodingDetails.get_child_details(env_vars)
228 encoding_details, stderr_lines = result
229 expected_details = EncodingDetails.get_expected_details(
230 coercion_expected,
231 expected_fs_encoding,
232 expected_stream_encoding,
233 expected_stream_errors,
234 env_vars
235 )
236 self.assertEqual(encoding_details, expected_details)
237 if expected_warnings is None:
238 expected_warnings = []
239 self.assertEqual(stderr_lines, expected_warnings)
240
241
242 class LocaleConfigurationTests(_LocaleHandlingTestCase):
243 # Test explicit external configuration via the process environment
244
245 @classmethod
246 def setUpClass(cls):
247 # This relies on setUpModule() having been run, so it can't be
248 # handled via the @unittest.skipUnless decorator
249 if not AVAILABLE_TARGETS:
250 raise unittest.SkipTest("No C-with-UTF-8 locale available")
251
252 def test_external_target_locale_configuration(self):
253
254 # Explicitly setting a target locale should give the same behaviour as
255 # is seen when implicitly coercing to that target locale
256 self.maxDiff = None
257
258 expected_fs_encoding = "utf-8"
259 expected_stream_encoding = "utf-8"
260
261 base_var_dict = {
262 "LANG": "",
263 "LC_CTYPE": "",
264 "LC_ALL": "",
265 "PYTHONCOERCECLOCALE": "",
266 "PYTHONIOENCODING": "",
267 }
268 for env_var in ("LANG", "LC_CTYPE"):
269 for locale_to_set in AVAILABLE_TARGETS:
270 # XXX (ncoghlan): LANG=UTF-8 doesn't appear to work as
271 # expected, so skip that combination for now
272 # See https://bugs.python.org/issue30672 for discussion
273 if env_var == "LANG" and locale_to_set == "UTF-8":
274 continue
275
276 with self.subTest(env_var=env_var,
277 configured_locale=locale_to_set):
278 var_dict = base_var_dict.copy()
279 var_dict[env_var] = locale_to_set
280 self._check_child_encoding_details(var_dict,
281 expected_fs_encoding,
282 expected_stream_encoding,
283 expected_stream_errors=None,
284 expected_warnings=None,
285 coercion_expected=False)
286
287 def test_with_ioencoding(self):
288 # Explicitly setting a target locale should give the same behaviour as
289 # is seen when implicitly coercing to that target locale
290 self.maxDiff = None
291
292 expected_fs_encoding = "utf-8"
293 expected_stream_encoding = "utf-8"
294
295 base_var_dict = {
296 "LANG": "",
297 "LC_CTYPE": "",
298 "LC_ALL": "",
299 "PYTHONCOERCECLOCALE": "",
300 "PYTHONIOENCODING": "UTF-8",
301 }
302 for env_var in ("LANG", "LC_CTYPE"):
303 for locale_to_set in AVAILABLE_TARGETS:
304 # XXX (ncoghlan): LANG=UTF-8 doesn't appear to work as
305 # expected, so skip that combination for now
306 # See https://bugs.python.org/issue30672 for discussion
307 if env_var == "LANG" and locale_to_set == "UTF-8":
308 continue
309
310 with self.subTest(env_var=env_var,
311 configured_locale=locale_to_set):
312 var_dict = base_var_dict.copy()
313 var_dict[env_var] = locale_to_set
314 self._check_child_encoding_details(var_dict,
315 expected_fs_encoding,
316 expected_stream_encoding,
317 expected_stream_errors="strict",
318 expected_warnings=None,
319 coercion_expected=False)
320
321 @support.cpython_only
322 @unittest.skipUnless(sysconfig.get_config_var("PY_COERCE_C_LOCALE"),
323 "C locale coercion disabled at build time")
324 class LocaleCoercionTests(_LocaleHandlingTestCase):
325 # Test implicit reconfiguration of the environment during CLI startup
326
327 def _check_c_locale_coercion(self,
328 fs_encoding, stream_encoding,
329 coerce_c_locale,
330 expected_warnings=None,
331 coercion_expected=True,
332 **extra_vars):
333 """Check the C locale handling for various configurations
334
335 Parameters:
336 fs_encoding: expected sys.getfilesystemencoding() result
337 stream_encoding: expected encoding for standard streams
338 coerce_c_locale: setting to use for PYTHONCOERCECLOCALE
339 None: don't set the variable at all
340 str: the value set in the child's environment
341 expected_warnings: expected warning lines on stderr
342 extra_vars: additional environment variables to set in subprocess
343 """
344 self.maxDiff = None
345
346 if not AVAILABLE_TARGETS:
347 # Locale coercion is disabled when there aren't any target locales
348 fs_encoding = EXPECTED_C_LOCALE_FS_ENCODING
349 stream_encoding = EXPECTED_C_LOCALE_STREAM_ENCODING
350 coercion_expected = False
351 if expected_warnings:
352 expected_warnings = [LEGACY_LOCALE_WARNING]
353
354 base_var_dict = {
355 "LANG": "",
356 "LC_CTYPE": "",
357 "LC_ALL": "",
358 "PYTHONCOERCECLOCALE": "",
359 "PYTHONIOENCODING": "",
360 }
361 base_var_dict.update(extra_vars)
362 if coerce_c_locale is not None:
363 base_var_dict["PYTHONCOERCECLOCALE"] = coerce_c_locale
364
365 # Check behaviour for the default locale
366 with self.subTest(default_locale=True,
367 PYTHONCOERCECLOCALE=coerce_c_locale):
368 if EXPECT_COERCION_IN_DEFAULT_LOCALE:
369 _expected_warnings = expected_warnings
370 _coercion_expected = coercion_expected
371 else:
372 _expected_warnings = None
373 _coercion_expected = False
374 # On Android CLI_COERCION_WARNING is not printed when all the
375 # locale environment variables are undefined or empty. When
376 # this code path is run with environ['LC_ALL'] == 'C', then
377 # LEGACY_LOCALE_WARNING is printed.
378 if (support.is_android and
379 _expected_warnings == [CLI_COERCION_WARNING]):
380 _expected_warnings = None
381 self._check_child_encoding_details(base_var_dict,
382 fs_encoding,
383 stream_encoding,
384 None,
385 _expected_warnings,
386 _coercion_expected)
387
388 # Check behaviour for explicitly configured locales
389 for locale_to_set in EXPECTED_C_LOCALE_EQUIVALENTS:
390 for env_var in ("LANG", "LC_CTYPE"):
391 with self.subTest(env_var=env_var,
392 nominal_locale=locale_to_set,
393 PYTHONCOERCECLOCALE=coerce_c_locale,
394 PYTHONIOENCODING=""):
395 var_dict = base_var_dict.copy()
396 var_dict[env_var] = locale_to_set
397 # Check behaviour on successful coercion
398 self._check_child_encoding_details(var_dict,
399 fs_encoding,
400 stream_encoding,
401 None,
402 expected_warnings,
403 coercion_expected)
404
405 def test_PYTHONCOERCECLOCALE_not_set(self):
406 # This should coerce to the first available target locale by default
407 self._check_c_locale_coercion("utf-8", "utf-8", coerce_c_locale=None)
408
409 def test_PYTHONCOERCECLOCALE_not_zero(self):
410 # *Any* string other than "0" is considered "set" for our purposes
411 # and hence should result in the locale coercion being enabled
412 for setting in ("", "1", "true", "false"):
413 self._check_c_locale_coercion("utf-8", "utf-8", coerce_c_locale=setting)
414
415 def test_PYTHONCOERCECLOCALE_set_to_warn(self):
416 # PYTHONCOERCECLOCALE=warn enables runtime warnings for legacy locales
417 self._check_c_locale_coercion("utf-8", "utf-8",
418 coerce_c_locale="warn",
419 expected_warnings=[CLI_COERCION_WARNING])
420
421
422 def test_PYTHONCOERCECLOCALE_set_to_zero(self):
423 # The setting "0" should result in the locale coercion being disabled
424 self._check_c_locale_coercion(EXPECTED_C_LOCALE_FS_ENCODING,
425 EXPECTED_C_LOCALE_STREAM_ENCODING,
426 coerce_c_locale="0",
427 coercion_expected=False)
428 # Setting LC_ALL=C shouldn't make any difference to the behaviour
429 self._check_c_locale_coercion(EXPECTED_C_LOCALE_FS_ENCODING,
430 EXPECTED_C_LOCALE_STREAM_ENCODING,
431 coerce_c_locale="0",
432 LC_ALL="C",
433 coercion_expected=False)
434
435 def test_LC_ALL_set_to_C(self):
436 # Setting LC_ALL should render the locale coercion ineffective
437 self._check_c_locale_coercion(EXPECTED_C_LOCALE_FS_ENCODING,
438 EXPECTED_C_LOCALE_STREAM_ENCODING,
439 coerce_c_locale=None,
440 LC_ALL="C",
441 coercion_expected=False)
442 # And result in a warning about a lack of locale compatibility
443 self._check_c_locale_coercion(EXPECTED_C_LOCALE_FS_ENCODING,
444 EXPECTED_C_LOCALE_STREAM_ENCODING,
445 coerce_c_locale="warn",
446 LC_ALL="C",
447 expected_warnings=[LEGACY_LOCALE_WARNING],
448 coercion_expected=False)
449
450 def test_PYTHONCOERCECLOCALE_set_to_one(self):
451 # skip the test if the LC_CTYPE locale is C or coerced
452 old_loc = locale.setlocale(locale.LC_CTYPE, None)
453 self.addCleanup(locale.setlocale, locale.LC_CTYPE, old_loc)
454 try:
455 loc = locale.setlocale(locale.LC_CTYPE, "")
456 except locale.Error as e:
457 self.skipTest(str(e))
458 if loc == "C":
459 self.skipTest("test requires LC_CTYPE locale different than C")
460 if loc in TARGET_LOCALES :
461 self.skipTest("coerced LC_CTYPE locale: %s" % loc)
462
463 # bpo-35336: PYTHONCOERCECLOCALE=1 must not coerce the LC_CTYPE locale
464 # if it's not equal to "C"
465 code = 'import locale; print(locale.setlocale(locale.LC_CTYPE, None))'
466 env = dict(os.environ, PYTHONCOERCECLOCALE='1')
467 cmd = subprocess.run([sys.executable, '-c', code],
468 stdout=subprocess.PIPE,
469 env=env,
470 text=True)
471 self.assertEqual(cmd.stdout.rstrip(), loc)
472
473
474 def tearDownModule():
475 support.reap_children()
476
477
478 if __name__ == "__main__":
479 unittest.main()