Commit 937ee9e7 authored by Victor Stinner's avatar Victor Stinner Committed by GitHub

Revert "bpo-33671: Add support.MS_WINDOWS and support.MACOS (GH-7800)" (GH-7919)

This reverts commit 8fbbdf0c.
parent fdd6e0bf
...@@ -103,6 +103,8 @@ else: ...@@ -103,6 +103,8 @@ else:
HAVE_GETVALUE = not getattr(_multiprocessing, HAVE_GETVALUE = not getattr(_multiprocessing,
'HAVE_BROKEN_SEM_GETVALUE', False) 'HAVE_BROKEN_SEM_GETVALUE', False)
WIN32 = (sys.platform == "win32")
from multiprocessing.connection import wait from multiprocessing.connection import wait
def wait_for_handle(handle, timeout): def wait_for_handle(handle, timeout):
...@@ -3804,7 +3806,7 @@ class _TestPollEintr(BaseTestCase): ...@@ -3804,7 +3806,7 @@ class _TestPollEintr(BaseTestCase):
class TestInvalidHandle(unittest.TestCase): class TestInvalidHandle(unittest.TestCase):
@unittest.skipIf(support.MS_WINDOWS, "skipped on Windows") @unittest.skipIf(WIN32, "skipped on Windows")
def test_invalid_handles(self): def test_invalid_handles(self):
conn = multiprocessing.connection.Connection(44977608) conn = multiprocessing.connection.Connection(44977608)
# check that poll() doesn't crash # check that poll() doesn't crash
...@@ -4132,12 +4134,12 @@ class TestWait(unittest.TestCase): ...@@ -4132,12 +4134,12 @@ class TestWait(unittest.TestCase):
class TestInvalidFamily(unittest.TestCase): class TestInvalidFamily(unittest.TestCase):
@unittest.skipIf(support.MS_WINDOWS, "skipped on Windows") @unittest.skipIf(WIN32, "skipped on Windows")
def test_invalid_family(self): def test_invalid_family(self):
with self.assertRaises(ValueError): with self.assertRaises(ValueError):
multiprocessing.connection.Listener(r'\\.\test') multiprocessing.connection.Listener(r'\\.\test')
@unittest.skipUnless(support.MS_WINDOWS, "skipped on non-Windows platforms") @unittest.skipUnless(WIN32, "skipped on non-Windows platforms")
def test_invalid_family_win32(self): def test_invalid_family_win32(self):
with self.assertRaises(ValueError): with self.assertRaises(ValueError):
multiprocessing.connection.Listener('/var/test.pipe') multiprocessing.connection.Listener('/var/test.pipe')
...@@ -4263,7 +4265,7 @@ class TestForkAwareThreadLock(unittest.TestCase): ...@@ -4263,7 +4265,7 @@ class TestForkAwareThreadLock(unittest.TestCase):
class TestCloseFds(unittest.TestCase): class TestCloseFds(unittest.TestCase):
def get_high_socket_fd(self): def get_high_socket_fd(self):
if support.MS_WINDOWS: if WIN32:
# The child process will not have any socket handles, so # The child process will not have any socket handles, so
# calling socket.fromfd() should produce WSAENOTSOCK even # calling socket.fromfd() should produce WSAENOTSOCK even
# if there is a handle of the same number. # if there is a handle of the same number.
...@@ -4281,7 +4283,7 @@ class TestCloseFds(unittest.TestCase): ...@@ -4281,7 +4283,7 @@ class TestCloseFds(unittest.TestCase):
return fd return fd
def close(self, fd): def close(self, fd):
if support.MS_WINDOWS: if WIN32:
socket.socket(socket.AF_INET, socket.SOCK_STREAM, fileno=fd).close() socket.socket(socket.AF_INET, socket.SOCK_STREAM, fileno=fd).close()
else: else:
os.close(fd) os.close(fd)
......
...@@ -90,8 +90,8 @@ __all__ = [ ...@@ -90,8 +90,8 @@ __all__ = [
"anticipate_failure", "load_package_tests", "detect_api_mismatch", "anticipate_failure", "load_package_tests", "detect_api_mismatch",
"check__all__", "skip_unless_bind_unix_socket", "check__all__", "skip_unless_bind_unix_socket",
# sys # sys
"JYTHON", "ANDROID", "check_impl_detail", "unix_shell", "is_jython", "is_android", "check_impl_detail", "unix_shell",
"setswitchinterval", "MS_WINDOWS", "MACOS", "setswitchinterval",
# network # network
"HOST", "IPV6_ENABLED", "find_unused_port", "bind_port", "open_urlresource", "HOST", "IPV6_ENABLED", "find_unused_port", "bind_port", "open_urlresource",
"bind_unix_socket", "bind_unix_socket",
...@@ -108,21 +108,6 @@ __all__ = [ ...@@ -108,21 +108,6 @@ __all__ = [
"run_with_tz", "PGO", "missing_compiler_executable", "fd_count", "run_with_tz", "PGO", "missing_compiler_executable", "fd_count",
] ]
# True if Python is running on Microsoft Windows.
MS_WINDOWS = (sys.platform == 'win32')
# True if Python is running on Apple macOS.
MACOS = (sys.platform == 'darwin')
# True if Python runs on Jython
# (Python implemented in Java running in a Java VM)
JYTHON = sys.platform.startswith('java')
# True if Python runs on Android
ANDROID = hasattr(sys, 'getandroidapilevel')
class Error(Exception): class Error(Exception):
"""Base class for regression test exceptions.""" """Base class for regression test exceptions."""
...@@ -499,7 +484,7 @@ def _is_gui_available(): ...@@ -499,7 +484,7 @@ def _is_gui_available():
raise ctypes.WinError() raise ctypes.WinError()
if not bool(uof.dwFlags & WSF_VISIBLE): if not bool(uof.dwFlags & WSF_VISIBLE):
reason = "gui not available (WSF_VISIBLE flag not set)" reason = "gui not available (WSF_VISIBLE flag not set)"
elif MACOS: elif sys.platform == 'darwin':
# The Aqua Tk implementations on OS X can abort the process if # The Aqua Tk implementations on OS X can abort the process if
# being called in an environment where a window server connection # being called in an environment where a window server connection
# cannot be made, for instance when invoked by a buildbot or ssh # cannot be made, for instance when invoked by a buildbot or ssh
...@@ -615,7 +600,7 @@ def requires_mac_ver(*min_version): ...@@ -615,7 +600,7 @@ def requires_mac_ver(*min_version):
def decorator(func): def decorator(func):
@functools.wraps(func) @functools.wraps(func)
def wrapper(*args, **kw): def wrapper(*args, **kw):
if MACOS: if sys.platform == 'darwin':
version_txt = platform.mac_ver()[0] version_txt = platform.mac_ver()[0]
try: try:
version = tuple(map(int, version_txt.split('.'))) version = tuple(map(int, version_txt.split('.')))
...@@ -803,12 +788,14 @@ requires_bz2 = unittest.skipUnless(bz2, 'requires bz2') ...@@ -803,12 +788,14 @@ requires_bz2 = unittest.skipUnless(bz2, 'requires bz2')
requires_lzma = unittest.skipUnless(lzma, 'requires lzma') requires_lzma = unittest.skipUnless(lzma, 'requires lzma')
if MS_WINDOWS: is_jython = sys.platform.startswith('java')
unix_shell = None
elif ANDROID: is_android = hasattr(sys, 'getandroidapilevel')
unix_shell = '/system/bin/sh'
if sys.platform != 'win32':
unix_shell = '/system/bin/sh' if is_android else '/bin/sh'
else: else:
unix_shell = '/bin/sh' unix_shell = None
# Filename used for testing # Filename used for testing
if os.name == 'java': if os.name == 'java':
...@@ -867,7 +854,7 @@ for character in ( ...@@ -867,7 +854,7 @@ for character in (
# TESTFN_UNICODE is a non-ascii filename # TESTFN_UNICODE is a non-ascii filename
TESTFN_UNICODE = TESTFN + "-\xe0\xf2\u0258\u0141\u011f" TESTFN_UNICODE = TESTFN + "-\xe0\xf2\u0258\u0141\u011f"
if MACOS: if sys.platform == 'darwin':
# In Mac OS X's VFS API file names are, by definition, canonically # In Mac OS X's VFS API file names are, by definition, canonically
# decomposed Unicode, encoded using UTF-8. See QA1173: # decomposed Unicode, encoded using UTF-8. See QA1173:
# http://developer.apple.com/mac/library/qa/qa2001/qa1173.html # http://developer.apple.com/mac/library/qa/qa2001/qa1173.html
...@@ -879,7 +866,7 @@ TESTFN_ENCODING = sys.getfilesystemencoding() ...@@ -879,7 +866,7 @@ TESTFN_ENCODING = sys.getfilesystemencoding()
# encoded by the filesystem encoding (in strict mode). It can be None if we # encoded by the filesystem encoding (in strict mode). It can be None if we
# cannot generate such filename. # cannot generate such filename.
TESTFN_UNENCODABLE = None TESTFN_UNENCODABLE = None
if MS_WINDOWS: if os.name == 'nt':
# skip win32s (0) or Windows 9x/ME (1) # skip win32s (0) or Windows 9x/ME (1)
if sys.getwindowsversion().platform >= 2: if sys.getwindowsversion().platform >= 2:
# Different kinds of characters from various languages to minimize the # Different kinds of characters from various languages to minimize the
...@@ -894,8 +881,8 @@ if MS_WINDOWS: ...@@ -894,8 +881,8 @@ if MS_WINDOWS:
'Unicode filename tests may not be effective' 'Unicode filename tests may not be effective'
% (TESTFN_UNENCODABLE, TESTFN_ENCODING)) % (TESTFN_UNENCODABLE, TESTFN_ENCODING))
TESTFN_UNENCODABLE = None TESTFN_UNENCODABLE = None
# macOS denies unencodable filenames (invalid utf-8) # Mac OS X denies unencodable filenames (invalid utf-8)
elif not MACOS: elif sys.platform != 'darwin':
try: try:
# ascii and utf-8 cannot encode the byte 0xff # ascii and utf-8 cannot encode the byte 0xff
b'\xff'.decode(TESTFN_ENCODING) b'\xff'.decode(TESTFN_ENCODING)
...@@ -1536,7 +1523,7 @@ def gc_collect(): ...@@ -1536,7 +1523,7 @@ def gc_collect():
objects to disappear. objects to disappear.
""" """
gc.collect() gc.collect()
if JYTHON: if is_jython:
time.sleep(0.1) time.sleep(0.1)
gc.collect() gc.collect()
gc.collect() gc.collect()
...@@ -1995,7 +1982,7 @@ def _check_docstrings(): ...@@ -1995,7 +1982,7 @@ def _check_docstrings():
"""Just used to check if docstrings are enabled""" """Just used to check if docstrings are enabled"""
MISSING_C_DOCSTRINGS = (check_impl_detail() and MISSING_C_DOCSTRINGS = (check_impl_detail() and
not MS_WINDOWS and sys.platform != 'win32' and
not sysconfig.get_config_var('WITH_DOC_STRINGS')) not sysconfig.get_config_var('WITH_DOC_STRINGS'))
HAVE_DOCSTRINGS = (_check_docstrings.__doc__ is not None and HAVE_DOCSTRINGS = (_check_docstrings.__doc__ is not None and
...@@ -2605,7 +2592,7 @@ class SuppressCrashReport: ...@@ -2605,7 +2592,7 @@ class SuppressCrashReport:
except (ValueError, OSError): except (ValueError, OSError):
pass pass
if MACOS: if sys.platform == 'darwin':
# Check if the 'Crash Reporter' on OSX was configured # Check if the 'Crash Reporter' on OSX was configured
# in 'Developer' mode and warn that it will get triggered # in 'Developer' mode and warn that it will get triggered
# when it is. # when it is.
...@@ -2749,7 +2736,7 @@ def setswitchinterval(interval): ...@@ -2749,7 +2736,7 @@ def setswitchinterval(interval):
# Setting a very low gil interval on the Android emulator causes python # Setting a very low gil interval on the Android emulator causes python
# to hang (issue #26939). # to hang (issue #26939).
minimum_interval = 1e-5 minimum_interval = 1e-5
if ANDROID and interval < minimum_interval: if is_android and interval < minimum_interval:
global _is_android_emulator global _is_android_emulator
if _is_android_emulator is None: if _is_android_emulator is None:
_is_android_emulator = (subprocess.check_output( _is_android_emulator = (subprocess.check_output(
...@@ -2795,7 +2782,7 @@ def fd_count(): ...@@ -2795,7 +2782,7 @@ def fd_count():
pass pass
old_modes = None old_modes = None
if MS_WINDOWS: if sys.platform == 'win32':
# bpo-25306, bpo-31009: Call CrtSetReportMode() to not kill the process # bpo-25306, bpo-31009: Call CrtSetReportMode() to not kill the process
# on invalid file descriptor if Python is compiled in debug mode # on invalid file descriptor if Python is compiled in debug mode
try: try:
......
...@@ -27,7 +27,7 @@ EXPECT_COERCION_IN_DEFAULT_LOCALE = True ...@@ -27,7 +27,7 @@ EXPECT_COERCION_IN_DEFAULT_LOCALE = True
# Apply some platform dependent overrides # Apply some platform dependent overrides
if sys.platform.startswith("linux"): if sys.platform.startswith("linux"):
if test.support.ANDROID: if test.support.is_android:
# Android defaults to using UTF-8 for all system interfaces # Android defaults to using UTF-8 for all system interfaces
EXPECTED_C_LOCALE_STREAM_ENCODING = "utf-8" EXPECTED_C_LOCALE_STREAM_ENCODING = "utf-8"
EXPECTED_C_LOCALE_FS_ENCODING = "utf-8" EXPECTED_C_LOCALE_FS_ENCODING = "utf-8"
...@@ -335,7 +335,7 @@ class LocaleCoercionTests(_LocaleHandlingTestCase): ...@@ -335,7 +335,7 @@ class LocaleCoercionTests(_LocaleHandlingTestCase):
# locale environment variables are undefined or empty. When # locale environment variables are undefined or empty. When
# this code path is run with environ['LC_ALL'] == 'C', then # this code path is run with environ['LC_ALL'] == 'C', then
# LEGACY_LOCALE_WARNING is printed. # LEGACY_LOCALE_WARNING is printed.
if (test.support.ANDROID and if (test.support.is_android and
_expected_warnings == [CLI_COERCION_WARNING]): _expected_warnings == [CLI_COERCION_WARNING]):
_expected_warnings = None _expected_warnings = None
self._check_child_encoding_details(base_var_dict, self._check_child_encoding_details(base_var_dict,
......
...@@ -187,8 +187,8 @@ class CmdLineTest(unittest.TestCase): ...@@ -187,8 +187,8 @@ class CmdLineTest(unittest.TestCase):
if not stdout.startswith(pattern): if not stdout.startswith(pattern):
raise AssertionError("%a doesn't start with %a" % (stdout, pattern)) raise AssertionError("%a doesn't start with %a" % (stdout, pattern))
@unittest.skipUnless((support.MACOS or support.ANDROID), @unittest.skipUnless((sys.platform == 'darwin' or
'test specific to macOS and Android') support.is_android), 'test specific to Mac OS X and Android')
def test_osx_android_utf8(self): def test_osx_android_utf8(self):
def check_output(text): def check_output(text):
decoded = text.decode('utf-8', 'surrogateescape') decoded = text.decode('utf-8', 'surrogateescape')
......
...@@ -3,12 +3,12 @@ ...@@ -3,12 +3,12 @@
Nick Mathewson Nick Mathewson
""" """
import unittest import unittest
from test import support from test.support import is_jython
from codeop import compile_command, PyCF_DONT_IMPLY_DEDENT from codeop import compile_command, PyCF_DONT_IMPLY_DEDENT
import io import io
if support.JYTHON: if is_jython:
import sys import sys
def unify_callables(d): def unify_callables(d):
...@@ -21,7 +21,7 @@ class CodeopTests(unittest.TestCase): ...@@ -21,7 +21,7 @@ class CodeopTests(unittest.TestCase):
def assertValid(self, str, symbol='single'): def assertValid(self, str, symbol='single'):
'''succeed iff str is a valid piece of code''' '''succeed iff str is a valid piece of code'''
if support.JYTHON: if is_jython:
code = compile_command(str, "<input>", symbol) code = compile_command(str, "<input>", symbol)
self.assertTrue(code) self.assertTrue(code)
if symbol == "single": if symbol == "single":
...@@ -60,7 +60,7 @@ class CodeopTests(unittest.TestCase): ...@@ -60,7 +60,7 @@ class CodeopTests(unittest.TestCase):
av = self.assertValid av = self.assertValid
# special case # special case
if not support.JYTHON: if not is_jython:
self.assertEqual(compile_command(""), self.assertEqual(compile_command(""),
compile("pass", "<input>", 'single', compile("pass", "<input>", 'single',
PyCF_DONT_IMPLY_DEDENT)) PyCF_DONT_IMPLY_DEDENT))
......
...@@ -6,7 +6,7 @@ import signal ...@@ -6,7 +6,7 @@ import signal
import subprocess import subprocess
import sys import sys
from test import support from test import support
from test.support import script_helper from test.support import script_helper, is_android
import tempfile import tempfile
import threading import threading
import unittest import unittest
...@@ -18,6 +18,7 @@ except ImportError: ...@@ -18,6 +18,7 @@ except ImportError:
_testcapi = None _testcapi = None
TIMEOUT = 0.5 TIMEOUT = 0.5
MS_WINDOWS = (os.name == 'nt')
def expected_traceback(lineno1, lineno2, header, min_count=1): def expected_traceback(lineno1, lineno2, header, min_count=1):
regex = header regex = header
...@@ -30,7 +31,7 @@ def expected_traceback(lineno1, lineno2, header, min_count=1): ...@@ -30,7 +31,7 @@ def expected_traceback(lineno1, lineno2, header, min_count=1):
def skip_segfault_on_android(test): def skip_segfault_on_android(test):
# Issue #32138: Raising SIGSEGV on Android may not cause a crash. # Issue #32138: Raising SIGSEGV on Android may not cause a crash.
return unittest.skipIf(support.ANDROID, return unittest.skipIf(is_android,
'raising SIGSEGV on Android is unreliable')(test) 'raising SIGSEGV on Android is unreliable')(test)
@contextmanager @contextmanager
...@@ -120,7 +121,7 @@ class FaultHandlerTests(unittest.TestCase): ...@@ -120,7 +121,7 @@ class FaultHandlerTests(unittest.TestCase):
@unittest.skipIf(sys.platform.startswith('aix'), @unittest.skipIf(sys.platform.startswith('aix'),
"the first page of memory is a mapped read-only on AIX") "the first page of memory is a mapped read-only on AIX")
def test_read_null(self): def test_read_null(self):
if not support.MS_WINDOWS: if not MS_WINDOWS:
self.check_fatal_error(""" self.check_fatal_error("""
import faulthandler import faulthandler
faulthandler.enable() faulthandler.enable()
...@@ -731,7 +732,7 @@ class FaultHandlerTests(unittest.TestCase): ...@@ -731,7 +732,7 @@ class FaultHandlerTests(unittest.TestCase):
with self.check_stderr_none(): with self.check_stderr_none():
faulthandler.register(signal.SIGUSR1) faulthandler.register(signal.SIGUSR1)
@unittest.skipUnless(support.MS_WINDOWS, 'specific to Windows') @unittest.skipUnless(MS_WINDOWS, 'specific to Windows')
def test_raise_exception(self): def test_raise_exception(self):
for exc, name in ( for exc, name in (
('EXCEPTION_ACCESS_VIOLATION', 'access violation'), ('EXCEPTION_ACCESS_VIOLATION', 'access violation'),
...@@ -746,7 +747,7 @@ class FaultHandlerTests(unittest.TestCase): ...@@ -746,7 +747,7 @@ class FaultHandlerTests(unittest.TestCase):
3, 3,
name) name)
@unittest.skipUnless(support.MS_WINDOWS, 'specific to Windows') @unittest.skipUnless(MS_WINDOWS, 'specific to Windows')
def test_ignore_exception(self): def test_ignore_exception(self):
for exc_code in ( for exc_code in (
0xE06D7363, # MSC exception ("Emsc") 0xE06D7363, # MSC exception ("Emsc")
...@@ -762,7 +763,7 @@ class FaultHandlerTests(unittest.TestCase): ...@@ -762,7 +763,7 @@ class FaultHandlerTests(unittest.TestCase):
self.assertEqual(output, []) self.assertEqual(output, [])
self.assertEqual(exitcode, exc_code) self.assertEqual(exitcode, exc_code)
@unittest.skipUnless(support.MS_WINDOWS, 'specific to Windows') @unittest.skipUnless(MS_WINDOWS, 'specific to Windows')
def test_raise_nonfatal_exception(self): def test_raise_nonfatal_exception(self):
# These exceptions are not strictly errors. Letting # These exceptions are not strictly errors. Letting
# faulthandler display the traceback when they are # faulthandler display the traceback when they are
...@@ -790,7 +791,7 @@ class FaultHandlerTests(unittest.TestCase): ...@@ -790,7 +791,7 @@ class FaultHandlerTests(unittest.TestCase):
self.assertIn(exitcode, self.assertIn(exitcode,
(exc, exc & ~0x10000000)) (exc, exc & ~0x10000000))
@unittest.skipUnless(support.MS_WINDOWS, 'specific to Windows') @unittest.skipUnless(MS_WINDOWS, 'specific to Windows')
def test_disable_windows_exc_handler(self): def test_disable_windows_exc_handler(self):
code = dedent(""" code = dedent("""
import faulthandler import faulthandler
......
...@@ -20,7 +20,7 @@ import contextlib ...@@ -20,7 +20,7 @@ import contextlib
import test.support import test.support
from test.support import ( from test.support import (
EnvironmentVarGuard, TESTFN, check_warnings, forget, JYTHON, EnvironmentVarGuard, TESTFN, check_warnings, forget, is_jython,
make_legacy_pyc, rmtree, run_unittest, swap_attr, swap_item, temp_umask, make_legacy_pyc, rmtree, run_unittest, swap_attr, swap_item, temp_umask,
unlink, unload, create_empty_file, cpython_only, TESTFN_UNENCODABLE, unlink, unload, create_empty_file, cpython_only, TESTFN_UNENCODABLE,
temp_dir, DirsOnSysPath) temp_dir, DirsOnSysPath)
...@@ -148,7 +148,7 @@ class ImportTests(unittest.TestCase): ...@@ -148,7 +148,7 @@ class ImportTests(unittest.TestCase):
def test_with_extension(ext): def test_with_extension(ext):
# The extension is normally ".py", perhaps ".pyw". # The extension is normally ".py", perhaps ".pyw".
source = TESTFN + ext source = TESTFN + ext
if JYTHON: if is_jython:
pyc = TESTFN + "$py.class" pyc = TESTFN + "$py.class"
else: else:
pyc = TESTFN + ".pyc" pyc = TESTFN + ".pyc"
......
...@@ -583,7 +583,7 @@ class IOTest(unittest.TestCase): ...@@ -583,7 +583,7 @@ class IOTest(unittest.TestCase):
# On Windows and Mac OSX this test consumes large resources; It takes # On Windows and Mac OSX this test consumes large resources; It takes
# a long time to build the >2 GiB file and takes >2 GiB of disk space # a long time to build the >2 GiB file and takes >2 GiB of disk space
# therefore the resource must be enabled to run this test. # therefore the resource must be enabled to run this test.
if support.MS_WINDOWS or support.MACOS: if sys.platform[:3] == 'win' or sys.platform == 'darwin':
support.requires( support.requires(
'largefile', 'largefile',
'test requires %s bytes and a long time to run' % self.LARGE) 'test requires %s bytes and a long time to run' % self.LARGE)
......
...@@ -5,7 +5,6 @@ import os ...@@ -5,7 +5,6 @@ import os
import stat import stat
import sys import sys
import unittest import unittest
from test import support
from test.support import TESTFN, requires, unlink from test.support import TESTFN, requires, unlink
import io # C implementation of io import io # C implementation of io
import _pyio as pyio # Python implementation of io import _pyio as pyio # Python implementation of io
...@@ -146,7 +145,7 @@ def setUpModule(): ...@@ -146,7 +145,7 @@ def setUpModule():
# takes a long time to build the >2 GiB file and takes >2 GiB of disk # takes a long time to build the >2 GiB file and takes >2 GiB of disk
# space therefore the resource must be enabled to run this test. # space therefore the resource must be enabled to run this test.
# If not, nothing after this line stanza will be executed. # If not, nothing after this line stanza will be executed.
if support.MS_WINDOWS or support.MACOS: if sys.platform[:3] == 'win' or sys.platform == 'darwin':
requires('largefile', requires('largefile',
'test requires %s bytes and a long time to run' % str(size)) 'test requires %s bytes and a long time to run' % str(size))
else: else:
......
import codecs from test.support import verbose, is_android, check_warnings
import unittest
import locale import locale
import sys import sys
import unittest import codecs
import warnings import warnings
from test import support
class BaseLocalizedTest(unittest.TestCase): class BaseLocalizedTest(unittest.TestCase):
# #
...@@ -13,7 +12,7 @@ class BaseLocalizedTest(unittest.TestCase): ...@@ -13,7 +12,7 @@ class BaseLocalizedTest(unittest.TestCase):
@classmethod @classmethod
def setUpClass(cls): def setUpClass(cls):
if support.MACOS: if sys.platform == 'darwin':
import os import os
tlocs = ("en_US.UTF-8", "en_US.ISO8859-1", "en_US") tlocs = ("en_US.UTF-8", "en_US.ISO8859-1", "en_US")
if int(os.uname().release.split('.')[0]) < 10: if int(os.uname().release.split('.')[0]) < 10:
...@@ -45,7 +44,7 @@ class BaseLocalizedTest(unittest.TestCase): ...@@ -45,7 +44,7 @@ class BaseLocalizedTest(unittest.TestCase):
oldlocale = locale.setlocale(self.locale_type) oldlocale = locale.setlocale(self.locale_type)
self.addCleanup(locale.setlocale, self.locale_type, oldlocale) self.addCleanup(locale.setlocale, self.locale_type, oldlocale)
locale.setlocale(self.locale_type, self.enUS_locale) locale.setlocale(self.locale_type, self.enUS_locale)
if support.verbose: if verbose:
print("testing with %r..." % self.enUS_locale, end=' ', flush=True) print("testing with %r..." % self.enUS_locale, end=' ', flush=True)
...@@ -145,7 +144,7 @@ class BaseFormattingTest(object): ...@@ -145,7 +144,7 @@ class BaseFormattingTest(object):
func(format, value, **format_opts), out) func(format, value, **format_opts), out)
def _test_format(self, format, value, out, **format_opts): def _test_format(self, format, value, out, **format_opts):
with support.check_warnings(('', DeprecationWarning)): with check_warnings(('', DeprecationWarning)):
self._test_formatfunc(format, value, out, self._test_formatfunc(format, value, out,
func=locale.format, **format_opts) func=locale.format, **format_opts)
...@@ -234,7 +233,7 @@ class TestFormatPatternArg(unittest.TestCase): ...@@ -234,7 +233,7 @@ class TestFormatPatternArg(unittest.TestCase):
# Test handling of pattern argument of format # Test handling of pattern argument of format
def test_onlyOnePattern(self): def test_onlyOnePattern(self):
with support.check_warnings(('', DeprecationWarning)): with check_warnings(('', DeprecationWarning)):
# Issue 2522: accept exactly one % pattern, and no extra chars. # Issue 2522: accept exactly one % pattern, and no extra chars.
self.assertRaises(ValueError, locale.format, "%f\n", 'foo') self.assertRaises(ValueError, locale.format, "%f\n", 'foo')
self.assertRaises(ValueError, locale.format, "%f\r", 'foo') self.assertRaises(ValueError, locale.format, "%f\r", 'foo')
...@@ -366,7 +365,7 @@ class TestEnUSCollation(BaseLocalizedTest, TestCollation): ...@@ -366,7 +365,7 @@ class TestEnUSCollation(BaseLocalizedTest, TestCollation):
enc = codecs.lookup(locale.getpreferredencoding(False) or 'ascii').name enc = codecs.lookup(locale.getpreferredencoding(False) or 'ascii').name
if enc not in ('utf-8', 'iso8859-1', 'cp1252'): if enc not in ('utf-8', 'iso8859-1', 'cp1252'):
raise unittest.SkipTest('encoding not suitable') raise unittest.SkipTest('encoding not suitable')
if enc != 'iso8859-1' and (support.MACOS or support.ANDROID or if enc != 'iso8859-1' and (sys.platform == 'darwin' or is_android or
sys.platform.startswith('freebsd')): sys.platform.startswith('freebsd')):
raise unittest.SkipTest('wcscoll/wcsxfrm have known bugs') raise unittest.SkipTest('wcscoll/wcsxfrm have known bugs')
BaseLocalizedTest.setUp(self) BaseLocalizedTest.setUp(self)
...@@ -527,7 +526,7 @@ class TestMiscellaneous(unittest.TestCase): ...@@ -527,7 +526,7 @@ class TestMiscellaneous(unittest.TestCase):
# Unsupported locale on this system # Unsupported locale on this system
self.skipTest('test needs Turkish locale') self.skipTest('test needs Turkish locale')
loc = locale.getlocale(locale.LC_CTYPE) loc = locale.getlocale(locale.LC_CTYPE)
if support.verbose: if verbose:
print('testing with %a' % (loc,), end=' ', flush=True) print('testing with %a' % (loc,), end=' ', flush=True)
locale.setlocale(locale.LC_CTYPE, loc) locale.setlocale(locale.LC_CTYPE, loc)
self.assertEqual(loc, locale.getlocale(locale.LC_CTYPE)) self.assertEqual(loc, locale.getlocale(locale.LC_CTYPE))
......
...@@ -270,7 +270,9 @@ class PlatformTest(unittest.TestCase): ...@@ -270,7 +270,9 @@ class PlatformTest(unittest.TestCase):
res = platform.libc_ver(executable) res = platform.libc_ver(executable)
def test_popen(self): def test_popen(self):
if support.MS_WINDOWS: mswindows = (sys.platform == "win32")
if mswindows:
command = '"{}" -c "print(\'Hello\')"'.format(sys.executable) command = '"{}" -c "print(\'Hello\')"'.format(sys.executable)
else: else:
command = "'{}' -c 'print(\"Hello\")'".format(sys.executable) command = "'{}' -c 'print(\"Hello\")'".format(sys.executable)
...@@ -282,7 +284,7 @@ class PlatformTest(unittest.TestCase): ...@@ -282,7 +284,7 @@ class PlatformTest(unittest.TestCase):
self.assertEqual(hello, "Hello") self.assertEqual(hello, "Hello")
data = 'plop' data = 'plop'
if support.MS_WINDOWS: if mswindows:
command = '"{}" -c "import sys; data=sys.stdin.read(); exit(len(data))"' command = '"{}" -c "import sys; data=sys.stdin.read(); exit(len(data))"'
else: else:
command = "'{}' -c 'import sys; data=sys.stdin.read(); exit(len(data))'" command = "'{}' -c 'import sys; data=sys.stdin.read(); exit(len(data))'"
......
...@@ -33,6 +33,7 @@ from test import support ...@@ -33,6 +33,7 @@ from test import support
from test.support import TESTFN, FakePath from test.support import TESTFN, FakePath
TESTFN2 = TESTFN + "2" TESTFN2 = TESTFN + "2"
MACOS = sys.platform.startswith("darwin")
try: try:
import grp import grp
import pwd import pwd
...@@ -1807,7 +1808,7 @@ class TestCopyFile(unittest.TestCase): ...@@ -1807,7 +1808,7 @@ class TestCopyFile(unittest.TestCase):
self.assertRaises(OSError, shutil.copyfile, 'srcfile', 'destfile') self.assertRaises(OSError, shutil.copyfile, 'srcfile', 'destfile')
@unittest.skipIf(support.MACOS, "skipped on macOS") @unittest.skipIf(MACOS, "skipped on macOS")
def test_w_dest_open_fails(self): def test_w_dest_open_fails(self):
srcfile = self.Faux() srcfile = self.Faux()
...@@ -1827,7 +1828,7 @@ class TestCopyFile(unittest.TestCase): ...@@ -1827,7 +1828,7 @@ class TestCopyFile(unittest.TestCase):
self.assertEqual(srcfile._exited_with[1].args, self.assertEqual(srcfile._exited_with[1].args,
('Cannot open "destfile"',)) ('Cannot open "destfile"',))
@unittest.skipIf(support.MACOS, "skipped on macOS") @unittest.skipIf(MACOS, "skipped on macOS")
def test_w_dest_close_fails(self): def test_w_dest_close_fails(self):
srcfile = self.Faux() srcfile = self.Faux()
...@@ -1850,7 +1851,7 @@ class TestCopyFile(unittest.TestCase): ...@@ -1850,7 +1851,7 @@ class TestCopyFile(unittest.TestCase):
self.assertEqual(srcfile._exited_with[1].args, self.assertEqual(srcfile._exited_with[1].args,
('Cannot close',)) ('Cannot close',))
@unittest.skipIf(support.MACOS, "skipped on macOS") @unittest.skipIf(MACOS, "skipped on macOS")
def test_w_source_close_fails(self): def test_w_source_close_fails(self):
srcfile = self.Faux(True) srcfile = self.Faux(True)
...@@ -2184,7 +2185,7 @@ class TestZeroCopySendfile(_ZeroCopyFileTest, unittest.TestCase): ...@@ -2184,7 +2185,7 @@ class TestZeroCopySendfile(_ZeroCopyFileTest, unittest.TestCase):
shutil._HAS_SENDFILE = True shutil._HAS_SENDFILE = True
@unittest.skipIf(not support.MACOS, 'macOS only') @unittest.skipIf(not MACOS, 'macOS only')
class TestZeroCopyMACOS(_ZeroCopyFileTest, unittest.TestCase): class TestZeroCopyMACOS(_ZeroCopyFileTest, unittest.TestCase):
PATCHPOINT = "posix._fcopyfile" PATCHPOINT = "posix._fcopyfile"
......
...@@ -1038,7 +1038,7 @@ class GeneralModuleTests(unittest.TestCase): ...@@ -1038,7 +1038,7 @@ class GeneralModuleTests(unittest.TestCase):
eq(udpport, port) eq(udpport, port)
# Now make sure the lookup by port returns the same service name # Now make sure the lookup by port returns the same service name
# Issue #26936: Android getservbyport() is broken. # Issue #26936: Android getservbyport() is broken.
if not support.ANDROID: if not support.is_android:
eq(socket.getservbyport(port2), service) eq(socket.getservbyport(port2), service)
eq(socket.getservbyport(port, 'tcp'), service) eq(socket.getservbyport(port, 'tcp'), service)
if udpport is not None: if udpport is not None:
......
...@@ -521,7 +521,7 @@ class CalculationTests(unittest.TestCase): ...@@ -521,7 +521,7 @@ class CalculationTests(unittest.TestCase):
"Calculation of day of the week failed;" "Calculation of day of the week failed;"
"%s != %s" % (result.tm_wday, self.time_tuple.tm_wday)) "%s != %s" % (result.tm_wday, self.time_tuple.tm_wday))
if support.ANDROID: if support.is_android:
# Issue #26929: strftime() on Android incorrectly formats %V or %G for # Issue #26929: strftime() on Android incorrectly formats %V or %G for
# the last or the first incomplete week in a year. # the last or the first incomplete week in a year.
_ymd_excluded = ((1905, 1, 1), (1906, 12, 31), (2008, 12, 29), _ymd_excluded = ((1905, 1, 1), (1906, 12, 31), (2008, 12, 29),
......
...@@ -35,11 +35,13 @@ except ImportError: ...@@ -35,11 +35,13 @@ except ImportError:
if support.PGO: if support.PGO:
raise unittest.SkipTest("test is not helpful for PGO") raise unittest.SkipTest("test is not helpful for PGO")
mswindows = (sys.platform == "win32")
# #
# Depends on the following external programs: Python # Depends on the following external programs: Python
# #
if support.MS_WINDOWS: if mswindows:
SETBINARY = ('import msvcrt; msvcrt.setmode(sys.stdout.fileno(), ' SETBINARY = ('import msvcrt; msvcrt.setmode(sys.stdout.fileno(), '
'os.O_BINARY);') 'os.O_BINARY);')
else: else:
...@@ -312,7 +314,7 @@ class ProcessTestCase(BaseTestCase): ...@@ -312,7 +314,7 @@ class ProcessTestCase(BaseTestCase):
self._assert_python, pre_args, self._assert_python, pre_args,
executable=NONEXISTING_CMD[0]) executable=NONEXISTING_CMD[0])
@unittest.skipIf(support.MS_WINDOWS, "executable argument replaces shell") @unittest.skipIf(mswindows, "executable argument replaces shell")
def test_executable_replaces_shell(self): def test_executable_replaces_shell(self):
# Check that the executable argument replaces the default shell # Check that the executable argument replaces the default shell
# when shell=True. # when shell=True.
...@@ -361,7 +363,7 @@ class ProcessTestCase(BaseTestCase): ...@@ -361,7 +363,7 @@ class ProcessTestCase(BaseTestCase):
temp_dir = self._normalize_cwd(temp_dir) temp_dir = self._normalize_cwd(temp_dir)
self._assert_cwd(temp_dir, sys.executable, cwd=FakePath(temp_dir)) self._assert_cwd(temp_dir, sys.executable, cwd=FakePath(temp_dir))
@unittest.skipIf(support.MS_WINDOWS, "pending resolution of issue #15533") @unittest.skipIf(mswindows, "pending resolution of issue #15533")
def test_cwd_with_relative_arg(self): def test_cwd_with_relative_arg(self):
# Check that Popen looks for args[0] relative to cwd if args[0] # Check that Popen looks for args[0] relative to cwd if args[0]
# is relative. # is relative.
...@@ -377,7 +379,7 @@ class ProcessTestCase(BaseTestCase): ...@@ -377,7 +379,7 @@ class ProcessTestCase(BaseTestCase):
python_dir = self._normalize_cwd(python_dir) python_dir = self._normalize_cwd(python_dir)
self._assert_cwd(python_dir, rel_python, cwd=python_dir) self._assert_cwd(python_dir, rel_python, cwd=python_dir)
@unittest.skipIf(support.MS_WINDOWS, "pending resolution of issue #15533") @unittest.skipIf(mswindows, "pending resolution of issue #15533")
def test_cwd_with_relative_executable(self): def test_cwd_with_relative_executable(self):
# Check that Popen looks for executable relative to cwd if executable # Check that Popen looks for executable relative to cwd if executable
# is relative (and that executable takes precedence over args[0]). # is relative (and that executable takes precedence over args[0]).
...@@ -1006,7 +1008,7 @@ class ProcessTestCase(BaseTestCase): ...@@ -1006,7 +1008,7 @@ class ProcessTestCase(BaseTestCase):
def test_no_leaking(self): def test_no_leaking(self):
# Make sure we leak no resources # Make sure we leak no resources
if not support.MS_WINDOWS: if not mswindows:
max_handles = 1026 # too much for most UNIX systems max_handles = 1026 # too much for most UNIX systems
else: else:
max_handles = 2050 # too much for (at least some) Windows setups max_handles = 2050 # too much for (at least some) Windows setups
...@@ -1242,7 +1244,7 @@ class ProcessTestCase(BaseTestCase): ...@@ -1242,7 +1244,7 @@ class ProcessTestCase(BaseTestCase):
t = threading.Timer(0.2, kill_proc_timer_thread) t = threading.Timer(0.2, kill_proc_timer_thread)
t.start() t.start()
if support.MS_WINDOWS: if mswindows:
expected_errorcode = 1 expected_errorcode = 1
else: else:
# Should be -9 because of the proc.kill() from the thread. # Should be -9 because of the proc.kill() from the thread.
...@@ -1363,13 +1365,13 @@ class ProcessTestCase(BaseTestCase): ...@@ -1363,13 +1365,13 @@ class ProcessTestCase(BaseTestCase):
fds_after_exception = os.listdir(fd_directory) fds_after_exception = os.listdir(fd_directory)
self.assertEqual(fds_before_popen, fds_after_exception) self.assertEqual(fds_before_popen, fds_after_exception)
@unittest.skipIf(support.MS_WINDOWS, "behavior currently not supported on Windows") @unittest.skipIf(mswindows, "behavior currently not supported on Windows")
def test_file_not_found_includes_filename(self): def test_file_not_found_includes_filename(self):
with self.assertRaises(FileNotFoundError) as c: with self.assertRaises(FileNotFoundError) as c:
subprocess.call(['/opt/nonexistent_binary', 'with', 'some', 'args']) subprocess.call(['/opt/nonexistent_binary', 'with', 'some', 'args'])
self.assertEqual(c.exception.filename, '/opt/nonexistent_binary') self.assertEqual(c.exception.filename, '/opt/nonexistent_binary')
@unittest.skipIf(support.MS_WINDOWS, "behavior currently not supported on Windows") @unittest.skipIf(mswindows, "behavior currently not supported on Windows")
def test_file_not_found_with_bad_cwd(self): def test_file_not_found_with_bad_cwd(self):
with self.assertRaises(FileNotFoundError) as c: with self.assertRaises(FileNotFoundError) as c:
subprocess.Popen(['exit', '0'], cwd='/some/nonexistent/directory') subprocess.Popen(['exit', '0'], cwd='/some/nonexistent/directory')
...@@ -1503,7 +1505,7 @@ class RunFuncTestCase(BaseTestCase): ...@@ -1503,7 +1505,7 @@ class RunFuncTestCase(BaseTestCase):
self.assertIn('capture_output', c.exception.args[0]) self.assertIn('capture_output', c.exception.args[0])
@unittest.skipIf(support.MS_WINDOWS, "POSIX specific tests") @unittest.skipIf(mswindows, "POSIX specific tests")
class POSIXProcessTestCase(BaseTestCase): class POSIXProcessTestCase(BaseTestCase):
def setUp(self): def setUp(self):
...@@ -2786,7 +2788,7 @@ class POSIXProcessTestCase(BaseTestCase): ...@@ -2786,7 +2788,7 @@ class POSIXProcessTestCase(BaseTestCase):
self.assertEqual(returncode, -3) self.assertEqual(returncode, -3)
@unittest.skipUnless(support.MS_WINDOWS, "Windows specific tests") @unittest.skipUnless(mswindows, "Windows specific tests")
class Win32ProcessTestCase(BaseTestCase): class Win32ProcessTestCase(BaseTestCase):
def test_startupinfo(self): def test_startupinfo(self):
...@@ -3091,7 +3093,7 @@ class MiscTests(unittest.TestCase): ...@@ -3091,7 +3093,7 @@ class MiscTests(unittest.TestCase):
dir = tempfile.mkdtemp() dir = tempfile.mkdtemp()
name = os.path.join(dir, "foo") name = os.path.join(dir, "foo")
status, output = subprocess.getstatusoutput( status, output = subprocess.getstatusoutput(
("type " if support.MS_WINDOWS else "cat ") + name) ("type " if mswindows else "cat ") + name)
self.assertNotEqual(status, 0) self.assertNotEqual(status, 0)
finally: finally:
if dir is not None: if dir is not None:
...@@ -3125,7 +3127,7 @@ class ProcessTestCaseNoPoll(ProcessTestCase): ...@@ -3125,7 +3127,7 @@ class ProcessTestCaseNoPoll(ProcessTestCase):
ProcessTestCase.tearDown(self) ProcessTestCase.tearDown(self)
@unittest.skipUnless(support.MS_WINDOWS, "Windows-specific tests") @unittest.skipUnless(mswindows, "Windows-specific tests")
class CommandsWithSpaces (BaseTestCase): class CommandsWithSpaces (BaseTestCase):
def setUp(self): def setUp(self):
......
...@@ -11,6 +11,9 @@ from test import support ...@@ -11,6 +11,9 @@ from test import support
from test.support.script_helper import assert_python_ok, assert_python_failure from test.support.script_helper import assert_python_ok, assert_python_failure
MS_WINDOWS = (sys.platform == 'win32')
class UTF8ModeTests(unittest.TestCase): class UTF8ModeTests(unittest.TestCase):
DEFAULT_ENV = { DEFAULT_ENV = {
'PYTHONUTF8': '', 'PYTHONUTF8': '',
...@@ -32,7 +35,7 @@ class UTF8ModeTests(unittest.TestCase): ...@@ -32,7 +35,7 @@ class UTF8ModeTests(unittest.TestCase):
out = out[1] out = out[1]
return out.decode().rstrip("\n\r") return out.decode().rstrip("\n\r")
@unittest.skipIf(support.MS_WINDOWS, 'Windows has no POSIX locale') @unittest.skipIf(MS_WINDOWS, 'Windows has no POSIX locale')
def test_posix_locale(self): def test_posix_locale(self):
code = 'import sys; print(sys.flags.utf8_mode)' code = 'import sys; print(sys.flags.utf8_mode)'
...@@ -52,7 +55,7 @@ class UTF8ModeTests(unittest.TestCase): ...@@ -52,7 +55,7 @@ class UTF8ModeTests(unittest.TestCase):
out = self.get_output('-X', 'utf8=0', '-c', code) out = self.get_output('-X', 'utf8=0', '-c', code)
self.assertEqual(out, '0') self.assertEqual(out, '0')
if support.MS_WINDOWS: if MS_WINDOWS:
# PYTHONLEGACYWINDOWSFSENCODING disables the UTF-8 Mode # PYTHONLEGACYWINDOWSFSENCODING disables the UTF-8 Mode
# and has the priority over -X utf8 # and has the priority over -X utf8
out = self.get_output('-X', 'utf8', '-c', code, out = self.get_output('-X', 'utf8', '-c', code,
...@@ -72,7 +75,7 @@ class UTF8ModeTests(unittest.TestCase): ...@@ -72,7 +75,7 @@ class UTF8ModeTests(unittest.TestCase):
out = self.get_output('-X', 'utf8=0', '-c', code, PYTHONUTF8='1') out = self.get_output('-X', 'utf8=0', '-c', code, PYTHONUTF8='1')
self.assertEqual(out, '0') self.assertEqual(out, '0')
if support.MS_WINDOWS: if MS_WINDOWS:
# PYTHONLEGACYWINDOWSFSENCODING disables the UTF-8 mode # PYTHONLEGACYWINDOWSFSENCODING disables the UTF-8 mode
# and has the priority over PYTHONUTF8 # and has the priority over PYTHONUTF8
out = self.get_output('-X', 'utf8', '-c', code, PYTHONUTF8='1', out = self.get_output('-X', 'utf8', '-c', code, PYTHONUTF8='1',
...@@ -98,7 +101,7 @@ class UTF8ModeTests(unittest.TestCase): ...@@ -98,7 +101,7 @@ class UTF8ModeTests(unittest.TestCase):
sys.getfilesystemencodeerrors())) sys.getfilesystemencodeerrors()))
''') ''')
if support.MS_WINDOWS: if MS_WINDOWS:
expected = 'utf-8/surrogatepass' expected = 'utf-8/surrogatepass'
else: else:
expected = 'utf-8/surrogateescape' expected = 'utf-8/surrogateescape'
...@@ -106,7 +109,7 @@ class UTF8ModeTests(unittest.TestCase): ...@@ -106,7 +109,7 @@ class UTF8ModeTests(unittest.TestCase):
out = self.get_output('-X', 'utf8', '-c', code) out = self.get_output('-X', 'utf8', '-c', code)
self.assertEqual(out, expected) self.assertEqual(out, expected)
if support.MS_WINDOWS: if MS_WINDOWS:
# PYTHONLEGACYWINDOWSFSENCODING disables the UTF-8 mode # PYTHONLEGACYWINDOWSFSENCODING disables the UTF-8 mode
# and has the priority over -X utf8 and PYTHONUTF8 # and has the priority over -X utf8 and PYTHONUTF8
out = self.get_output('-X', 'utf8', '-c', code, out = self.get_output('-X', 'utf8', '-c', code,
...@@ -201,7 +204,7 @@ class UTF8ModeTests(unittest.TestCase): ...@@ -201,7 +204,7 @@ class UTF8ModeTests(unittest.TestCase):
out = self.get_output('-X', 'utf8', '-c', code, LC_ALL='C') out = self.get_output('-X', 'utf8', '-c', code, LC_ALL='C')
self.assertEqual(out, 'UTF-8 UTF-8') self.assertEqual(out, 'UTF-8 UTF-8')
@unittest.skipIf(support.MS_WINDOWS, 'test specific to Unix') @unittest.skipIf(MS_WINDOWS, 'test specific to Unix')
def test_cmd_line(self): def test_cmd_line(self):
arg = 'h\xe9\u20ac'.encode('utf-8') arg = 'h\xe9\u20ac'.encode('utf-8')
arg_utf8 = arg.decode('utf-8') arg_utf8 = arg.decode('utf-8')
...@@ -214,7 +217,7 @@ class UTF8ModeTests(unittest.TestCase): ...@@ -214,7 +217,7 @@ class UTF8ModeTests(unittest.TestCase):
self.assertEqual(args, ascii(expected), out) self.assertEqual(args, ascii(expected), out)
check('utf8', [arg_utf8]) check('utf8', [arg_utf8])
if support.MACOS or support.ANDROID: if sys.platform == 'darwin' or support.is_android:
c_arg = arg_utf8 c_arg = arg_utf8
else: else:
c_arg = arg_ascii c_arg = arg_ascii
......
Markdown is supported
0%
or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment