From 6cc8feba94ed905f375568703e6a6858bee157bd Mon Sep 17 00:00:00 2001 From: Michael Felt Date: Mon, 15 Apr 2019 13:36:05 +0000 Subject: [PATCH 1/4] example of what it could become --- Lib/test/support/__init__.py | 3 +++ Lib/test/test_c_locale_coercion.py | 3 ++- 2 files changed, 5 insertions(+), 1 deletion(-) diff --git a/Lib/test/support/__init__.py b/Lib/test/support/__init__.py index d6ed2215f38340..bffe1d0b6c1b75 100644 --- a/Lib/test/support/__init__.py +++ b/Lib/test/support/__init__.py @@ -101,6 +101,8 @@ # network "HOST", "IPV6_ENABLED", "find_unused_port", "bind_port", "open_urlresource", "bind_unix_socket", + # platform + "is_aix", # processes 'temp_umask', "reap_children", # logging @@ -815,6 +817,7 @@ def dec(*args, **kwargs): requires_lzma = unittest.skipUnless(lzma, 'requires lzma') is_jython = sys.platform.startswith('java') +is_aix = platform.system() == 'AIX' is_android = hasattr(sys, 'getandroidapilevel') diff --git a/Lib/test/test_c_locale_coercion.py b/Lib/test/test_c_locale_coercion.py index 35272b5c15aca7..0685ed85d2431b 100644 --- a/Lib/test/test_c_locale_coercion.py +++ b/Lib/test/test_c_locale_coercion.py @@ -10,6 +10,7 @@ from collections import namedtuple from test import support +is_aix = support.is_aix from test.support.script_helper import ( run_python_until_end, interpreter_requires_environment, @@ -40,7 +41,7 @@ # TODO: Once https://bugs.python.org/issue30672 is addressed, we'll be # able to check this case unconditionally EXPECTED_C_LOCALE_EQUIVALENTS.append("POSIX") -elif sys.platform.startswith("aix"): +elif is_aix: # AIX uses iso8859-1 in the C locale, other *nix platforms use ASCII EXPECTED_C_LOCALE_STREAM_ENCODING = "iso8859-1" EXPECTED_C_LOCALE_FS_ENCODING = "iso8859-1" From a2a5489b5b6f614f9b3c6975ec8d3e9ef1e3663f Mon Sep 17 00:00:00 2001 From: Michael Felt Date: Mon, 15 Apr 2019 15:13:50 +0000 Subject: [PATCH 2/4] Add constants in Lib/test/support to signify platform during testing --- Doc/whatsnew/3.8.rst | 10 ++++ Lib/test/_test_multiprocessing.py | 35 ++++++------ Lib/test/datetimetester.py | 8 +-- Lib/test/eintrdata/eintr_tester.py | 10 ++-- Lib/test/libregrtest/main.py | 2 +- Lib/test/libregrtest/setup.py | 2 +- Lib/test/support/__init__.py | 50 +++++++++-------- Lib/test/support/script_helper.py | 4 +- Lib/test/test___all__.py | 3 +- Lib/test/test__osx_support.py | 3 +- Lib/test/test_asynchat.py | 6 +-- Lib/test/test_asyncio/test_events.py | 54 +++++++++---------- Lib/test/test_asyncio/test_proactor_events.py | 3 +- Lib/test/test_asyncio/test_sendfile.py | 7 +-- Lib/test/test_asyncio/test_sock_lowlevel.py | 2 +- Lib/test/test_asyncio/test_streams.py | 4 +- Lib/test/test_asyncio/test_subprocess.py | 15 +++--- Lib/test/test_asyncio/test_unix_events.py | 2 +- Lib/test/test_asyncio/test_windows_events.py | 3 +- Lib/test/test_asyncio/test_windows_utils.py | 4 +- Lib/test/test_asyncore.py | 3 +- Lib/test/test_c_locale_coercion.py | 15 +++--- Lib/test/test_cmath.py | 4 +- Lib/test/test_cmd_line.py | 12 ++--- Lib/test/test_cmd_line_script.py | 4 +- Lib/test/test_codecs.py | 3 +- Lib/test/test_codeop.py | 8 +-- Lib/test/test_concurrent_futures.py | 5 +- Lib/test/test_decimal.py | 8 +-- Lib/test/test_email/test_utils.py | 4 +- Lib/test/test_exceptions.py | 8 ++- Lib/test/test_faulthandler.py | 22 +++----- Lib/test/test_fcntl.py | 4 +- Lib/test/test_fileio.py | 13 ++--- Lib/test/test_gdb.py | 4 +- Lib/test/test_genericpath.py | 6 +-- Lib/test/test_glob.py | 6 +-- Lib/test/test_httpservers.py | 9 ++-- Lib/test/test_imp.py | 4 +- Lib/test/test_import/__init__.py | 12 ++--- Lib/test/test_importlib/source/test_finder.py | 4 +- Lib/test/test_importlib/test_windows.py | 4 +- Lib/test/test_importlib/util.py | 2 +- Lib/test/test_io.py | 6 +-- Lib/test/test_largefile.py | 4 +- Lib/test/test_locale.py | 14 +++-- Lib/test/test_logging.py | 9 ++-- Lib/test/test_math.py | 4 +- Lib/test/test_mimetypes.py | 3 +- Lib/test/test_mmap.py | 13 ++--- Lib/test/test_multiprocessing_fork.py | 5 +- Lib/test/test_multiprocessing_forkserver.py | 2 +- Lib/test/test_ntpath.py | 6 +-- Lib/test/test_os.py | 49 +++++++++-------- Lib/test/test_osx_env.py | 5 +- Lib/test/test_pathlib.py | 5 +- Lib/test/test_platform.py | 9 ++-- Lib/test/test_posix.py | 7 +-- Lib/test/test_regrtest.py | 7 +-- Lib/test/test_resource.py | 3 +- Lib/test/test_select.py | 4 +- Lib/test/test_selectors.py | 6 +-- Lib/test/test_shutil.py | 9 ++-- Lib/test/test_signal.py | 19 +++---- Lib/test/test_site.py | 8 +-- Lib/test/test_smtplib.py | 4 +- Lib/test/test_socket.py | 33 ++++++------ Lib/test/test_ssl.py | 9 ++-- Lib/test/test_stat.py | 5 +- Lib/test/test_strftime.py | 5 +- Lib/test/test_strptime.py | 6 +-- Lib/test/test_subprocess.py | 34 ++++++------ Lib/test/test_sundry.py | 3 +- Lib/test/test_sys.py | 5 +- Lib/test/test_sysconfig.py | 17 +++--- Lib/test/test_tarfile.py | 12 ++--- Lib/test/test_tcl.py | 2 +- Lib/test/test_tempfile.py | 8 +-- Lib/test/test_threading.py | 4 +- Lib/test/test_threadsignals.py | 9 ++-- Lib/test/test_time.py | 5 +- Lib/test/test_tix.py | 2 +- Lib/test/test_tools/test_sundry.py | 2 +- Lib/test/test_unicode.py | 13 ++--- Lib/test/test_unicode_file_functions.py | 9 ++-- Lib/test/test_urllib.py | 2 +- Lib/test/test_urllib2.py | 3 +- Lib/test/test_utf8_mode.py | 6 +-- Lib/test/test_venv.py | 9 ++-- Lib/test/test_wait4.py | 4 +- Lib/test/test_winconsoleio.py | 3 +- Lib/test/test_zipapp.py | 8 ++- .../2019-04-15-14-48-48.bpo-36624.yjmwEK.rst | 4 ++ 93 files changed, 412 insertions(+), 402 deletions(-) create mode 100644 Misc/NEWS.d/next/Tests/2019-04-15-14-48-48.bpo-36624.yjmwEK.rst diff --git a/Doc/whatsnew/3.8.rst b/Doc/whatsnew/3.8.rst index d1305dc1e7dfb7..6e491e74ec458d 100644 --- a/Doc/whatsnew/3.8.rst +++ b/Doc/whatsnew/3.8.rst @@ -640,6 +640,16 @@ in a standardized and extensible format, and offers several other benefits. (Contributed by C.A.M. Gerlach in :issue:`36268`.) +test +---- + +The :mod:`test` module now uses ``CONSTANTS`` for the major platforms +(``AIX``, ``ANDROID``, ``LINUX``, ``JYTHON``, ``MACOS``, ``MS_WINDOWS``) +to standardize the style compared to the current practice of some constants +and different styles of sys.platform and platform.system(). +The constants are defined in `test.support`. +(Contributed by M. Felt in :issue:`36624`.) + threading --------- diff --git a/Lib/test/_test_multiprocessing.py b/Lib/test/_test_multiprocessing.py index 071b54a713e2d8..c30733be09ffc4 100644 --- a/Lib/test/_test_multiprocessing.py +++ b/Lib/test/_test_multiprocessing.py @@ -26,6 +26,7 @@ import test.support import test.support.script_helper from test import support +from test.support import LINUX, MACOS, MS_WINDOWS # Skip tests if _multiprocessing wasn't built. @@ -116,8 +117,6 @@ def _resource_unlink(name, rtype): HAVE_GETVALUE = not getattr(_multiprocessing, 'HAVE_BROKEN_SEM_GETVALUE', False) -WIN32 = (sys.platform == "win32") - from multiprocessing.connection import wait def wait_for_handle(handle, timeout): @@ -574,7 +573,7 @@ def test_many_processes(self): join_process(p) if os.name != 'nt': exitcodes = [-signal.SIGTERM] - if sys.platform == 'darwin': + if MACOS: # bpo-31510: On macOS, killing a freshly started process with # SIGTERM sometimes kills the process with SIGKILL. exitcodes.append(-signal.SIGKILL) @@ -1553,7 +1552,7 @@ def _test_wait_result(cls, c, pid): os.kill(pid, signal.SIGINT) def test_wait_result(self): - if isinstance(self, ProcessesMixin) and sys.platform != 'win32': + if isinstance(self, ProcessesMixin) and not MS_WINDOWS: pid = os.getpid() else: pid = None @@ -3162,8 +3161,7 @@ def test_fd_transfer(self): self.assertEqual(f.read(), b"foo") @unittest.skipUnless(HAS_REDUCTION, "test needs multiprocessing.reduction") - @unittest.skipIf(sys.platform == "win32", - "test semantics don't make sense on Windows") + @unittest.skipIf(MS_WINDOWS, "test semantics don't make sense on Windows") @unittest.skipIf(MAXFD <= 256, "largest assignable fd number is too small") @unittest.skipUnless(hasattr(os, "dup2"), @@ -3199,7 +3197,7 @@ def _send_data_without_fd(self, conn): os.write(conn.fileno(), b"\0") @unittest.skipUnless(HAS_REDUCTION, "test needs multiprocessing.reduction") - @unittest.skipIf(sys.platform == "win32", "doesn't make sense on Windows") + @unittest.skipIf(MS_WINDOWS, "doesn't make sense on Windows") def test_missing_fd_transfer(self): # Check that exception is raised when received data is not # accompanied by a file descriptor in ancillary data. @@ -3858,7 +3856,7 @@ def test_shared_memory_SharedMemoryManager_basics(self): self.assertGreaterEqual(len(doppleganger_shm0.buf), 32) held_name = lom[0].name smm1.shutdown() - if sys.platform != "win32": + if not MS_WINDOWS: # Calls to unlink() have no effect on Windows platform; shared # memory will only be released once final process exits. with self.assertRaises(FileNotFoundError): @@ -3869,7 +3867,7 @@ def test_shared_memory_SharedMemoryManager_basics(self): sl = smm2.ShareableList("howdy") shm = smm2.SharedMemory(size=128) held_name = sl.shm.name - if sys.platform != "win32": + if not MS_WINDOWS: with self.assertRaises(FileNotFoundError): # No longer there to be attached to again. absent_sl = shared_memory.ShareableList(name=held_name) @@ -4165,7 +4163,7 @@ def get_module_names(self): def test_import(self): modules = self.get_module_names() - if sys.platform == 'win32': + if MS_WINDOWS: modules.remove('multiprocessing.popen_fork') modules.remove('multiprocessing.popen_forkserver') modules.remove('multiprocessing.popen_spawn_posix') @@ -4298,7 +4296,7 @@ def record(*args): class TestInvalidHandle(unittest.TestCase): - @unittest.skipIf(WIN32, "skipped on Windows") + @unittest.skipIf(MS_WINDOWS, "skipped on Windows") def test_invalid_handles(self): conn = multiprocessing.connection.Connection(44977608) # check that poll() doesn't crash @@ -4624,12 +4622,12 @@ def test_neg_timeout(self): class TestInvalidFamily(unittest.TestCase): - @unittest.skipIf(WIN32, "skipped on Windows") + @unittest.skipIf(MS_WINDOWS, "skipped on Windows") def test_invalid_family(self): with self.assertRaises(ValueError): multiprocessing.connection.Listener(r'\\.\test') - @unittest.skipUnless(WIN32, "skipped on non-Windows platforms") + @unittest.skipUnless(MS_WINDOWS, "skipped on non-Windows platforms") def test_invalid_family_win32(self): with self.assertRaises(ValueError): multiprocessing.connection.Listener('/var/test.pipe') @@ -4755,7 +4753,7 @@ def test_lock(self): class TestCloseFds(unittest.TestCase): def get_high_socket_fd(self): - if WIN32: + if MS_WINDOWS: # The child process will not have any socket handles, so # calling socket.fromfd() should produce WSAENOTSOCK even # if there is a handle of the same number. @@ -4773,7 +4771,7 @@ def get_high_socket_fd(self): return fd def close(self, fd): - if WIN32: + if MS_WINDOWS: socket.socket(socket.AF_INET, socket.SOCK_STREAM, fileno=fd).close() else: os.close(fd) @@ -4936,7 +4934,7 @@ def test_set_get(self): def test_get_all(self): methods = multiprocessing.get_all_start_methods() - if sys.platform == 'win32': + if MS_WINDOWS: self.assertEqual(methods, ['spawn']) else: self.assertTrue(methods == ['fork', 'spawn'] or @@ -4955,8 +4953,7 @@ def test_preload_resources(self): self.fail("failed spawning forkserver or grandchild") -@unittest.skipIf(sys.platform == "win32", - "test semantics don't make sense on Windows") +@unittest.skipIf(MS_WINDOWS, "test semantics don't make sense on Windows") class TestResourceTracker(unittest.TestCase): def test_resource_tracker(self): @@ -5603,7 +5600,7 @@ def setUpModule(): raise unittest.SkipTest(start_method + ' start method not supported') - if sys.platform.startswith("linux"): + if LINUX: try: lock = multiprocessing.RLock() except OSError: diff --git a/Lib/test/datetimetester.py b/Lib/test/datetimetester.py index 239a0b5ac8308a..9c366cf5f638ce 100644 --- a/Lib/test/datetimetester.py +++ b/Lib/test/datetimetester.py @@ -2,7 +2,7 @@ See http://www.zope.org/Members/fdrake/DateTimeWiki/TestCases """ -from test.support import is_resource_enabled +from test.support import is_resource_enabled, MS_WINDOWS import itertools import bisect @@ -2453,13 +2453,13 @@ def test_insane_utcfromtimestamp(self): self.assertRaises(OverflowError, self.theclass.utcfromtimestamp, insane) - @unittest.skipIf(sys.platform == "win32", "Windows doesn't accept negative timestamps") + @unittest.skipIf(MS_WINDOWS, "Windows doesn't accept negative timestamps") def test_negative_float_fromtimestamp(self): # The result is tz-dependent; at least test that this doesn't # fail (like it did before bug 1646728 was fixed). self.theclass.fromtimestamp(-1.05) - @unittest.skipIf(sys.platform == "win32", "Windows doesn't accept negative timestamps") + @unittest.skipIf(MS_WINDOWS, "Windows doesn't accept negative timestamps") def test_negative_float_utcfromtimestamp(self): d = self.theclass.utcfromtimestamp(-1.05) self.assertEqual(d, self.theclass(1969, 12, 31, 23, 59, 58, 950000)) @@ -5700,7 +5700,7 @@ class ZoneInfoTest(unittest.TestCase): zonename = 'America/New_York' def setUp(self): - if sys.platform == "win32": + if MS_WINDOWS: self.skipTest("Skipping zoneinfo tests on Windows") try: self.tz = ZoneInfo.fromname(self.zonename) diff --git a/Lib/test/eintrdata/eintr_tester.py b/Lib/test/eintrdata/eintr_tester.py index 404934ce97a2bf..e76d7ffec200ea 100644 --- a/Lib/test/eintrdata/eintr_tester.py +++ b/Lib/test/eintrdata/eintr_tester.py @@ -22,6 +22,7 @@ import unittest from test import support +from test.support import MACOS @contextlib.contextmanager def kill_on_error(proc): @@ -347,8 +348,7 @@ def python_open(self, path): fp = open(path, 'w') fp.close() - @unittest.skipIf(sys.platform == "darwin", - "hangs under macOS; see bpo-25234, bpo-35363") + @unittest.skipIf(MACOS, "hangs under macOS; see bpo-25234, bpo-35363") def test_open(self): self._test_open("fp = open(path, 'r')\nfp.close()", self.python_open) @@ -357,8 +357,7 @@ def os_open(self, path): fd = os.open(path, os.O_WRONLY) os.close(fd) - @unittest.skipIf(sys.platform == "darwin", - "hangs under macOS; see bpo-25234, bpo-35363") + @unittest.skipIf(MACOS, "hangs under macOS; see bpo-25234, bpo-35363") def test_os_open(self): self._test_open("fd = os.open(path, os.O_RDONLY)\nos.close(fd)", self.os_open) @@ -439,8 +438,7 @@ def test_select(self): self.stop_alarm() self.assertGreaterEqual(dt, self.sleep_time) - @unittest.skipIf(sys.platform == "darwin", - "poll may fail on macOS; see issue #28087") + @unittest.skipIf(MACOS, "poll may fail on macOS; see issue #28087") @unittest.skipUnless(hasattr(select, 'poll'), 'need select.poll') def test_poll(self): poller = select.poll() diff --git a/Lib/test/libregrtest/main.py b/Lib/test/libregrtest/main.py index a9b2b352d120e6..be777a4ecf3b70 100644 --- a/Lib/test/libregrtest/main.py +++ b/Lib/test/libregrtest/main.py @@ -629,7 +629,7 @@ def _main(self, tests, kwargs): # If we're on windows and this is the parent runner (not a worker), # track the load average. - if sys.platform == 'win32' and self.worker_test_name is None: + if support.MS_WINDOWS and self.worker_test_name is None: from test.libregrtest.win_utils import WindowsLoadTracker try: diff --git a/Lib/test/libregrtest/setup.py b/Lib/test/libregrtest/setup.py index 84931140b10286..b08edfd281924a 100644 --- a/Lib/test/libregrtest/setup.py +++ b/Lib/test/libregrtest/setup.py @@ -64,7 +64,7 @@ def setup_tests(ns): # fix is to set the stack limit to 2048. # This approach may also be useful for other Unixy platforms that # suffer from small default stack limits. - if sys.platform == 'darwin': + if support.MACOS: try: import resource except ImportError: diff --git a/Lib/test/support/__init__.py b/Lib/test/support/__init__.py index bffe1d0b6c1b75..05bf71533c0656 100644 --- a/Lib/test/support/__init__.py +++ b/Lib/test/support/__init__.py @@ -36,6 +36,14 @@ import urllib.error import warnings +ANDROID = hasattr(sys, 'getandroidapilevel') +JYTHON = sys.platform.startswith('java') + +AIX = platform.system() == 'AIX' +LINUX = platform.system() == 'Linux' +MACOS = platform.system() == 'Darwin' +MS_WINDOWS = platform.system() == 'Windows' + from .testresult import get_test_runner try: @@ -96,13 +104,14 @@ "check__all__", "skip_unless_bind_unix_socket", "ignore_warnings", # sys - "is_jython", "is_android", "check_impl_detail", "unix_shell", + "check_impl_detail", "unix_shell", + "ANDROID", "JYTHON", "setswitchinterval", # network "HOST", "IPV6_ENABLED", "find_unused_port", "bind_port", "open_urlresource", "bind_unix_socket", # platform - "is_aix", + "AIX", "LINUX", "MACOS", "MS_WINDOWS", # processes 'temp_umask', "reap_children", # logging @@ -336,7 +345,7 @@ def _force_run(path, func, *args): os.chmod(path, stat.S_IRWXU) return func(*args) -if sys.platform.startswith("win"): +if MS_WINDOWS: def _waitfor(func, pathname, waitall=False): # Perform the operation func(pathname) @@ -487,7 +496,7 @@ def _is_gui_available(): if hasattr(_is_gui_available, 'result'): return _is_gui_available.result reason = None - if sys.platform.startswith('win'): + if MS_WINDOWS: # if Python is running as a service (such as the buildbot service), # gui interaction may be disallowed import ctypes @@ -513,7 +522,7 @@ class USEROBJECTFLAGS(ctypes.Structure): raise ctypes.WinError() if not bool(uof.dwFlags & WSF_VISIBLE): reason = "gui not available (WSF_VISIBLE flag not set)" - elif sys.platform == 'darwin': + elif MACOS: # The Aqua Tk implementations on OS X can abort the process if # being called in an environment where a window server connection # cannot be made, for instance when invoked by a buildbot or ssh @@ -629,7 +638,7 @@ def requires_mac_ver(*min_version): def decorator(func): @functools.wraps(func) def wrapper(*args, **kw): - if sys.platform == 'darwin': + if MACOS: version_txt = platform.mac_ver()[0] try: version = tuple(map(int, version_txt.split('.'))) @@ -816,13 +825,8 @@ def dec(*args, **kwargs): requires_lzma = unittest.skipUnless(lzma, 'requires lzma') -is_jython = sys.platform.startswith('java') -is_aix = platform.system() == 'AIX' - -is_android = hasattr(sys, 'getandroidapilevel') - -if sys.platform != 'win32': - unix_shell = '/system/bin/sh' if is_android else '/bin/sh' +if not MS_WINDOWS: + unix_shell = '/system/bin/sh' if ANDROID else '/bin/sh' else: unix_shell = None @@ -891,7 +895,7 @@ def dec(*args, **kwargs): # TESTFN_UNICODE is a non-ascii filename TESTFN_UNICODE = TESTFN + "-\xe0\xf2\u0258\u0141\u011f" -if sys.platform == 'darwin': +if MACOS: # In Mac OS X's VFS API file names are, by definition, canonically # decomposed Unicode, encoded using UTF-8. See QA1173: # http://developer.apple.com/mac/library/qa/qa2001/qa1173.html @@ -919,7 +923,7 @@ def dec(*args, **kwargs): % (TESTFN_UNENCODABLE, TESTFN_ENCODING)) TESTFN_UNENCODABLE = None # Mac OS X denies unencodable filenames (invalid utf-8) -elif sys.platform != 'darwin': +elif not MACOS: try: # ascii and utf-8 cannot encode the byte 0xff b'\xff'.decode(TESTFN_ENCODING) @@ -1628,7 +1632,7 @@ def gc_collect(): objects to disappear. """ gc.collect() - if is_jython: + if JYTHON: time.sleep(0.1) gc.collect() gc.collect() @@ -2092,7 +2096,7 @@ def _check_docstrings(): """Just used to check if docstrings are enabled""" MISSING_C_DOCSTRINGS = (check_impl_detail() and - sys.platform != 'win32' and + not MS_WINDOWS and not sysconfig.get_config_var('WITH_DOC_STRINGS')) HAVE_DOCSTRINGS = (_check_docstrings.__doc__ is not None and @@ -2664,7 +2668,7 @@ def __enter__(self): On UNIX, try to save the previous core file size limit, then set soft limit to 0. """ - if sys.platform.startswith('win'): + if MS_WINDOWS: # see http://msdn.microsoft.com/en-us/library/windows/desktop/ms680621.aspx # GetErrorMode is not available on Windows XP and Windows Server 2003, # but SetErrorMode returns the previous value, so we can use that @@ -2702,7 +2706,7 @@ def __enter__(self): except (ValueError, OSError): pass - if sys.platform == 'darwin': + if MACOS: # Check if the 'Crash Reporter' on OSX was configured # in 'Developer' mode and warn that it will get triggered # when it is. @@ -2727,7 +2731,7 @@ def __exit__(self, *ignore_exc): if self.old_value is None: return - if sys.platform.startswith('win'): + if MS_WINDOWS: self._k32.SetErrorMode(self.old_value) if self.old_modes: @@ -2846,7 +2850,7 @@ def setswitchinterval(interval): # Setting a very low gil interval on the Android emulator causes python # to hang (issue #26939). minimum_interval = 1e-5 - if is_android and interval < minimum_interval: + if ANDROID and interval < minimum_interval: global _is_android_emulator if _is_android_emulator is None: _is_android_emulator = (subprocess.check_output( @@ -2875,7 +2879,7 @@ def disable_faulthandler(): def fd_count(): """Count the number of open file descriptors. """ - if sys.platform.startswith(('linux', 'freebsd')): + if LINUX or sys.platform.startswith('freebsd'): try: names = os.listdir("/proc/self/fd") # Substract one because listdir() opens internally a file @@ -2892,7 +2896,7 @@ def fd_count(): pass old_modes = None - if sys.platform == 'win32': + if MACOS: # bpo-25306, bpo-31009: Call CrtSetReportMode() to not kill the process # on invalid file descriptor if Python is compiled in debug mode try: diff --git a/Lib/test/support/script_helper.py b/Lib/test/support/script_helper.py index 27a47f2c4e668c..02411b97a46e8c 100644 --- a/Lib/test/support/script_helper.py +++ b/Lib/test/support/script_helper.py @@ -11,7 +11,7 @@ import zipfile from importlib.util import source_from_cache -from test.support import make_legacy_pyc, strip_python_stderr +from test.support import make_legacy_pyc, strip_python_stderr, MS_WINDOWS # Cached result of the expensive test performed in the function below. @@ -105,7 +105,7 @@ def run_python_until_end(*args, **env_vars): # caller is responsible to pass the full environment. if env_vars.pop('__cleanenv', None): env = {} - if sys.platform == 'win32': + if MS_WINDOWS: # Windows requires at least the SYSTEMROOT environment variable to # start Python. env['SYSTEMROOT'] = os.environ['SYSTEMROOT'] diff --git a/Lib/test/test___all__.py b/Lib/test/test___all__.py index c077881511b8ce..b86396fd76bdf2 100644 --- a/Lib/test/test___all__.py +++ b/Lib/test/test___all__.py @@ -1,5 +1,6 @@ import unittest from test import support +from test.support import JYTHON import os import sys @@ -73,7 +74,7 @@ def test_all(self): '__future__', ]) - if not sys.platform.startswith('java'): + if not JYTHON: # In case _socket fails to build, make this test fail more gracefully # than an AttributeError somewhere deep in CGIHTTPServer. import _socket diff --git a/Lib/test/test__osx_support.py b/Lib/test/test__osx_support.py index 388a2b1a84b17c..4b5897232c2627 100644 --- a/Lib/test/test__osx_support.py +++ b/Lib/test/test__osx_support.py @@ -9,10 +9,11 @@ import unittest import test.support +from test.support import MACOS import _osx_support -@unittest.skipUnless(sys.platform.startswith("darwin"), "requires OS X") +@unittest.skipUnless(MACOS, "requires OS X") class Test_OSXSupport(unittest.TestCase): def setUp(self): diff --git a/Lib/test/test_asynchat.py b/Lib/test/test_asynchat.py index 1d147c741961e3..5b3cd0b32f90a9 100644 --- a/Lib/test/test_asynchat.py +++ b/Lib/test/test_asynchat.py @@ -1,6 +1,7 @@ # test asynchat from test import support +from test.support import HOST, MACOS import asynchat import asyncore @@ -13,7 +14,6 @@ import unittest import unittest.mock -HOST = support.HOST SERVER_QUIT = b'QUIT\n' TIMEOUT = 3.0 @@ -77,9 +77,9 @@ def __init__(self, terminator, server_port): def handle_connect(self): pass - if sys.platform == 'darwin': + if MACOS: # select.poll returns a select.POLLHUP at the end of the tests - # on darwin, so just ignore it + # on macOS, so just ignore it def handle_expt(self): pass diff --git a/Lib/test/test_asyncio/test_events.py b/Lib/test/test_asyncio/test_events.py index 045654e87a85a6..997f804ab2863d 100644 --- a/Lib/test/test_asyncio/test_events.py +++ b/Lib/test/test_asyncio/test_events.py @@ -22,7 +22,10 @@ from unittest import mock import weakref -if sys.platform != 'win32': +from test import support +from test.support import AIX, MACOS, MS_WINDOWS + +if not MS_WINDOWS: import tty import asyncio @@ -33,7 +36,6 @@ from asyncio import proactor_events from asyncio import selector_events from test.test_asyncio import utils as test_utils -from test import support def tearDownModule(): @@ -42,9 +44,9 @@ def tearDownModule(): def broken_unix_getsockname(): """Return True if the platform is Mac OS 10.4 or older.""" - if sys.platform.startswith("aix"): + if AIX: return True - elif sys.platform != 'darwin': + elif not MACOS: return False version = platform.mac_ver()[0] version = tuple(map(int, version.split('.'))) @@ -708,7 +710,7 @@ def client(): @unittest.skipIf(ssl is None, 'No ssl module') def test_ssl_connect_accepted_socket(self): - if (sys.platform == 'win32' and + if (MS_WINDOWS and sys.version_info < (3, 5) and isinstance(self.loop, proactor_events.BaseProactorEventLoop) ): @@ -1249,6 +1251,11 @@ def datagram_received(self, data, addr): server.transport.close() def test_create_datagram_endpoint_sock(self): + if (sys.platform == 'win32' and + isinstance(self.loop, proactor_events.BaseProactorEventLoop)): + raise unittest.SkipTest( + 'UDP is not supported with proactor event loops') + sock = None local_address = ('127.0.0.1', 0) infos = self.loop.run_until_complete( @@ -1286,8 +1293,7 @@ def test_internal_fds(self): self.assertIsNone(loop._csock) self.assertIsNone(loop._ssock) - @unittest.skipUnless(sys.platform != 'win32', - "Don't support pipes for Windows") + @unittest.skipIf(MS_WINDOWS, "Don't support pipes for Windows") def test_read_pipe(self): proto = MyReadPipeProto(loop=self.loop) @@ -1320,8 +1326,7 @@ async def connect(): # extra info is available self.assertIsNotNone(proto.transport.get_extra_info('pipe')) - @unittest.skipUnless(sys.platform != 'win32', - "Don't support pipes for Windows") + @unittest.skipIf(MS_WINDOWS, "Don't support pipes for Windows") def test_unclosed_pipe_transport(self): # This test reproduces the issue #314 on GitHub loop = self.create_event_loop() @@ -1354,8 +1359,7 @@ async def connect(): read_transport._pipe = None write_transport._pipe = None - @unittest.skipUnless(sys.platform != 'win32', - "Don't support pipes for Windows") + @unittest.skipIf(MS_WINDOWS, "Don't support pipes for Windows") def test_read_pty_output(self): proto = MyReadPipeProto(loop=self.loop) @@ -1389,8 +1393,7 @@ async def connect(): # extra info is available self.assertIsNotNone(proto.transport.get_extra_info('pipe')) - @unittest.skipUnless(sys.platform != 'win32', - "Don't support pipes for Windows") + @unittest.skipIf(MS_WINDOWS, "Don't support pipes for Windows") def test_write_pipe(self): rpipe, wpipe = os.pipe() pipeobj = io.open(wpipe, 'wb', 1024) @@ -1428,8 +1431,7 @@ def reader(data): self.loop.run_until_complete(proto.done) self.assertEqual('CLOSED', proto.state) - @unittest.skipUnless(sys.platform != 'win32', - "Don't support pipes for Windows") + @unittest.skipIf(MS_WINDOWS, "Don't support pipes for Windows") def test_write_pipe_disconnect_on_close(self): rsock, wsock = socket.socketpair() rsock.setblocking(False) @@ -1451,8 +1453,7 @@ def test_write_pipe_disconnect_on_close(self): self.loop.run_until_complete(proto.done) self.assertEqual('CLOSED', proto.state) - @unittest.skipUnless(sys.platform != 'win32', - "Don't support pipes for Windows") + @unittest.skipIf(MS_WINDOWS, "Don't support pipes for Windows") # select, poll and kqueue don't support character devices (PTY) on Mac OS X # older than 10.6 (Snow Leopard) @support.requires_mac_ver(10, 6) @@ -1495,8 +1496,7 @@ def reader(data): self.loop.run_until_complete(proto.done) self.assertEqual('CLOSED', proto.state) - @unittest.skipUnless(sys.platform != 'win32', - "Don't support pipes for Windows") + @unittest.skipIf(MS_WINDOWS, "Don't support pipes for Windows") # select, poll and kqueue don't support character devices (PTY) on Mac OS X # older than 10.6 (Snow Leopard) @support.requires_mac_ver(10, 6) @@ -1701,14 +1701,14 @@ async def test(): class SubprocessTestsMixin: def check_terminated(self, returncode): - if sys.platform == 'win32': + if MS_WINDOWS: self.assertIsInstance(returncode, int) # expect 1 but sometimes get 0 else: self.assertEqual(-signal.SIGTERM, returncode) def check_killed(self, returncode): - if sys.platform == 'win32': + if MS_WINDOWS: self.assertIsInstance(returncode, int) # expect 1 but sometimes get 0 else: @@ -1829,7 +1829,7 @@ def test_subprocess_terminate(self): self.check_terminated(proto.returncode) transp.close() - @unittest.skipIf(sys.platform == 'win32', "Don't have SIGHUP") + @unittest.skipIf(MS_WINDOWS, "Don't have SIGHUP") def test_subprocess_send_signal(self): # bpo-31034: Make sure that we get the default signal handler (killing # the process). The parent process may have decided to ignore SIGHUP, @@ -1915,7 +1915,7 @@ def test_subprocess_close_client_stream(self): self.loop.run_until_complete(proto.disconnects[1]) stdin.write(b'xxx') self.loop.run_until_complete(proto.got_data[2].wait()) - if sys.platform != 'win32': + if not MS_WINDOWS: self.assertEqual(b'ERR:BrokenPipeError', proto.data[2]) else: # After closing the read-end of a pipe, writing to the @@ -1972,7 +1972,7 @@ async def connect(cmd=None, **kwds): self.loop.run_until_complete(connect(shell=False)) -if sys.platform == 'win32': +if MS_WINDOWS: class SelectEventLoopTests(EventLoopTestsMixin, test_utils.TestCase): @@ -2588,14 +2588,14 @@ def setUp(self): self.loop = asyncio.new_event_loop() asyncio.set_event_loop(self.loop) - if sys.platform != 'win32': + if not MS_WINDOWS: watcher = asyncio.SafeChildWatcher() watcher.attach_loop(self.loop) asyncio.set_child_watcher(watcher) def tearDown(self): try: - if sys.platform != 'win32': + if not MS_WINDOWS: asyncio.set_child_watcher(None) super().tearDown() @@ -2613,7 +2613,7 @@ def tearDown(self): asyncio.get_running_loop = self.get_running_loop_saved asyncio.get_event_loop = self.get_event_loop_saved - if sys.platform != 'win32': + if not MS_WINDOWS: def test_get_event_loop_new_process(self): # Issue bpo-32126: The multiprocessing module used by diff --git a/Lib/test/test_asyncio/test_proactor_events.py b/Lib/test/test_asyncio/test_proactor_events.py index 2e9995d3280736..6b7b71348a912c 100644 --- a/Lib/test/test_asyncio/test_proactor_events.py +++ b/Lib/test/test_asyncio/test_proactor_events.py @@ -1143,8 +1143,7 @@ def test_datagram_loop_writing_aborted(self): close_transport(tr) -@unittest.skipIf(sys.platform != 'win32', - 'Proactor is supported on Windows only') +@unittest.skipUnless(support.MS_WINDOWS, 'Proactor is supported on Windows only') class ProactorEventLoopUnixSockSendfileTests(test_utils.TestCase): DATA = b"12345abcde" * 16 * 1024 # 160 KiB diff --git a/Lib/test/test_asyncio/test_sendfile.py b/Lib/test/test_asyncio/test_sendfile.py index f148fe27e6ad40..18afe1b6ff8a46 100644 --- a/Lib/test/test_asyncio/test_sendfile.py +++ b/Lib/test/test_asyncio/test_sendfile.py @@ -10,6 +10,7 @@ from asyncio import constants from unittest import mock from test import support +from test.support import MS_WINDOWS from test.test_asyncio import utils as test_utils try: @@ -281,7 +282,7 @@ def cleanup(): self.addCleanup(cleanup) return srv_proto, cli_proto - @unittest.skipIf(sys.platform == 'win32', "UDP sockets are not supported") + @unittest.skipIf(MS_WINDOWS, "UDP sockets are not supported") def test_sendfile_not_supported(self): tr, pr = self.run_loop( self.loop.create_datagram_endpoint( @@ -327,7 +328,7 @@ def sendfile_native(transp, file, offset, count): self.assertEqual(self.file.tell(), len(self.DATA)) def test_sendfile_force_unsupported_native(self): - if sys.platform == 'win32': + if MS_WINDOWS: if isinstance(self.loop, asyncio.ProactorEventLoop): self.skipTest("Fails on proactor event loop") srv_proto, cli_proto = self.prepare_sendfile() @@ -507,7 +508,7 @@ class SendfileTestsBase(SendfileMixin, SockSendfileMixin): pass -if sys.platform == 'win32': +if MS_WINDOWS: class SelectEventLoopTests(SendfileTestsBase, test_utils.TestCase): diff --git a/Lib/test/test_asyncio/test_sock_lowlevel.py b/Lib/test/test_asyncio/test_sock_lowlevel.py index 7b40a765e4a01f..04f939c9bac203 100644 --- a/Lib/test/test_asyncio/test_sock_lowlevel.py +++ b/Lib/test/test_asyncio/test_sock_lowlevel.py @@ -296,7 +296,7 @@ def test_create_connection_sock(self): tr.close() -if sys.platform == 'win32': +if support.MS_WINDOWS: class SelectEventLoopTests(BaseSockTestsMixin, test_utils.TestCase): diff --git a/Lib/test/test_asyncio/test_streams.py b/Lib/test/test_asyncio/test_streams.py index df3d7e7dfa455c..5636b062ab642a 100644 --- a/Lib/test/test_asyncio/test_streams.py +++ b/Lib/test/test_asyncio/test_streams.py @@ -12,6 +12,8 @@ import unittest from unittest import mock from test import support +from test.support import MS_WINDOWS + try: import ssl except ImportError: @@ -827,7 +829,7 @@ async def client(path): self.assertEqual(messages, []) - @unittest.skipIf(sys.platform == 'win32', "Don't have pipes") + @unittest.skipIf(MS_WINDOWS, "Don't have pipes") def test_read_all_from_pipe_reader(self): # See asyncio issue 168. This test is derived from the example # subprocess_attach_read_pipe.py, but we configure the diff --git a/Lib/test/test_asyncio/test_subprocess.py b/Lib/test/test_asyncio/test_subprocess.py index 7d72e6cde4e7a8..214f0417792f12 100644 --- a/Lib/test/test_asyncio/test_subprocess.py +++ b/Lib/test/test_asyncio/test_subprocess.py @@ -9,8 +9,9 @@ from asyncio import subprocess from test.test_asyncio import utils as test_utils from test import support +from test.support import MS_WINDOWS -if sys.platform != 'win32': +if not MS_WINDOWS: from asyncio import unix_events # Program blocking @@ -171,7 +172,7 @@ def test_kill(self): proc = self.loop.run_until_complete(create) proc.kill() returncode = self.loop.run_until_complete(proc.wait()) - if sys.platform == 'win32': + if MS_WINDOWS: self.assertIsInstance(returncode, int) # expect 1 but sometimes get 0 else: @@ -183,13 +184,13 @@ def test_terminate(self): proc = self.loop.run_until_complete(create) proc.terminate() returncode = self.loop.run_until_complete(proc.wait()) - if sys.platform == 'win32': + if MS_WINDOWS: self.assertIsInstance(returncode, int) # expect 1 but sometimes get 0 else: self.assertEqual(-signal.SIGTERM, returncode) - @unittest.skipIf(sys.platform == 'win32', "Don't have SIGHUP") + @unittest.skipIf(MS_WINDOWS, "Don't have SIGHUP") def test_send_signal(self): # bpo-31034: Make sure that we get the default signal handler (killing # the process). The parent process may have decided to ignore SIGHUP, @@ -521,12 +522,12 @@ async def kill_running(): # Unlike SafeChildWatcher, FastChildWatcher does not pop the # callbacks if waitpid() is called elsewhere. Let's clear them # manually to avoid a warning when the watcher is detached. - if (sys.platform != 'win32' and + if (not MS_WINDOWS and isinstance(self, SubprocessFastWatcherTests)): asyncio.get_child_watcher()._callbacks.clear() def _test_popen_error(self, stdin): - if sys.platform == 'win32': + if MS_WINDOWS: target = 'asyncio.windows_utils.Popen' else: target = 'subprocess.Popen' @@ -633,7 +634,7 @@ async def execute(): self.assertIsNone(self.loop.run_until_complete(execute())) -if sys.platform != 'win32': +if not MS_WINDOWS: # Unix class SubprocessWatcherMixin(SubprocessMixin): diff --git a/Lib/test/test_asyncio/test_unix_events.py b/Lib/test/test_asyncio/test_unix_events.py index ac84304ec99da6..36c12eab774144 100644 --- a/Lib/test/test_asyncio/test_unix_events.py +++ b/Lib/test/test_asyncio/test_unix_events.py @@ -16,7 +16,7 @@ from unittest import mock from test import support -if sys.platform == 'win32': +if support.MS_WINDOWS: raise unittest.SkipTest('UNIX only') diff --git a/Lib/test/test_asyncio/test_windows_events.py b/Lib/test/test_asyncio/test_windows_events.py index 13aef7cf1f776b..c58c1372fbffa7 100644 --- a/Lib/test/test_asyncio/test_windows_events.py +++ b/Lib/test/test_asyncio/test_windows_events.py @@ -7,8 +7,9 @@ import threading import unittest from unittest import mock +from test.support import MS_WINDOWS -if sys.platform != 'win32': +if not MS_WINDOWS: raise unittest.SkipTest('Windows only') import _overlapped diff --git a/Lib/test/test_asyncio/test_windows_utils.py b/Lib/test/test_asyncio/test_windows_utils.py index 45c09bb4a2d3a0..5bf399a4298b5c 100644 --- a/Lib/test/test_asyncio/test_windows_utils.py +++ b/Lib/test/test_asyncio/test_windows_utils.py @@ -3,8 +3,9 @@ import sys import unittest import warnings +from test import support -if sys.platform != 'win32': +if not support.MS_WINDOWS: raise unittest.SkipTest('Windows only') import _overlapped @@ -12,7 +13,6 @@ import asyncio from asyncio import windows_utils -from test import support def tearDownModule(): diff --git a/Lib/test/test_asyncore.py b/Lib/test/test_asyncore.py index 3fcedb58ec18a6..9516621390eab5 100644 --- a/Lib/test/test_asyncore.py +++ b/Lib/test/test_asyncore.py @@ -10,6 +10,7 @@ import threading from test import support +from test.support import MACOS from io import BytesIO if support.PGO: @@ -658,7 +659,7 @@ def test_handle_expt(self): if HAS_UNIX_SOCKETS and self.family == socket.AF_UNIX: self.skipTest("Not applicable to AF_UNIX sockets.") - if sys.platform == "darwin" and self.use_poll: + if MACOS and self.use_poll: self.skipTest("poll may fail on macOS; see issue #28087") class TestClient(BaseClient): diff --git a/Lib/test/test_c_locale_coercion.py b/Lib/test/test_c_locale_coercion.py index 0685ed85d2431b..8d3c0edf87a72e 100644 --- a/Lib/test/test_c_locale_coercion.py +++ b/Lib/test/test_c_locale_coercion.py @@ -10,7 +10,8 @@ from collections import namedtuple from test import support -is_aix = support.is_aix +from test.support import AIX, ANDROID, LINUX, MACOS + from test.support.script_helper import ( run_python_until_end, interpreter_requires_environment, @@ -30,8 +31,8 @@ TARGET_LOCALES = ["C.UTF-8", "C.utf8", "UTF-8"] # Apply some platform dependent overrides -if sys.platform.startswith("linux"): - if support.is_android: +if LINUX: + if ANDROID: # Android defaults to using UTF-8 for all system interfaces EXPECTED_C_LOCALE_STREAM_ENCODING = "utf-8" EXPECTED_C_LOCALE_FS_ENCODING = "utf-8" @@ -41,11 +42,11 @@ # TODO: Once https://bugs.python.org/issue30672 is addressed, we'll be # able to check this case unconditionally EXPECTED_C_LOCALE_EQUIVALENTS.append("POSIX") -elif is_aix: +elif AIX: # AIX uses iso8859-1 in the C locale, other *nix platforms use ASCII EXPECTED_C_LOCALE_STREAM_ENCODING = "iso8859-1" EXPECTED_C_LOCALE_FS_ENCODING = "iso8859-1" -elif sys.platform == "darwin": +elif MACOS: # FS encoding is UTF-8 on macOS EXPECTED_C_LOCALE_FS_ENCODING = "utf-8" elif sys.platform == "cygwin": @@ -79,7 +80,7 @@ # `locale.nl_langinfo(locale.CODESET)` works, as if it fails, the interpreter # will skip locale coercion for that particular target locale _check_nl_langinfo_CODESET = bool( - sys.platform not in ("darwin", "linux") and + not (MACOS or LINUX) and hasattr(locale, "nl_langinfo") and hasattr(locale, "CODESET") ) @@ -348,7 +349,7 @@ def _check_c_locale_coercion(self, # locale environment variables are undefined or empty. When # this code path is run with environ['LC_ALL'] == 'C', then # LEGACY_LOCALE_WARNING is printed. - if (support.is_android and + if (support.ANDROID and _expected_warnings == [CLI_COERCION_WARNING]): _expected_warnings = None self._check_child_encoding_details(base_var_dict, diff --git a/Lib/test/test_cmath.py b/Lib/test/test_cmath.py index 43a074b4b66353..81a1991e0c1b93 100644 --- a/Lib/test/test_cmath.py +++ b/Lib/test/test_cmath.py @@ -1,4 +1,4 @@ -from test.support import requires_IEEE_754, cpython_only +from test.support import requires_IEEE_754, cpython_only, MACOS from test.test_math import parse_testfile, test_file import test.test_math as test_math import unittest @@ -339,7 +339,7 @@ def test_specific_values(self): SKIP_ON_TIGER = {'tan0064'} osx_version = None - if sys.platform == 'darwin': + if MACOS: version_txt = platform.mac_ver()[0] try: osx_version = tuple(map(int, version_txt.split('.'))) diff --git a/Lib/test/test_cmd_line.py b/Lib/test/test_cmd_line.py index f7925eb795c71e..4db4cf6a616308 100644 --- a/Lib/test/test_cmd_line.py +++ b/Lib/test/test_cmd_line.py @@ -9,6 +9,7 @@ import tempfile import unittest from test import support +from test.support import MS_WINDOWS, MACOS, ANDROID from test.support.script_helper import ( spawn_python, kill_python, assert_python_ok, assert_python_failure, interpreter_requires_environment @@ -152,8 +153,7 @@ def test_non_ascii(self): # command line, but how subprocess does decode bytes to unicode. Python # doesn't decode the command line because Windows provides directly the # arguments as unicode (using wmain() instead of main()). - @unittest.skipIf(sys.platform == 'win32', - 'Windows has a native unicode API') + @unittest.skipIf(MS_WINDOWS, 'Windows has a native unicode API') def test_undecodable_code(self): undecodable = b"\xff" env = os.environ.copy() @@ -187,8 +187,7 @@ def test_undecodable_code(self): if not stdout.startswith(pattern): raise AssertionError("%a doesn't start with %a" % (stdout, pattern)) - @unittest.skipUnless((sys.platform == 'darwin' or - support.is_android), 'test specific to Mac OS X and Android') + @unittest.skipUnless((MACOS or ANDROID), 'test specific to Mac OS X and Android') def test_osx_android_utf8(self): def check_output(text): decoded = text.decode('utf-8', 'surrogateescape') @@ -331,7 +330,7 @@ def test_output_newline(self): print(4, file=sys.stderr)""" rc, out, err = assert_python_ok('-c', code) - if sys.platform == 'win32': + if MS_WINDOWS: self.assertEqual(b'1\r\n2\r\n', out) self.assertEqual(b'3\r\n4', err) else: @@ -729,8 +728,7 @@ def test_pythondevmode_env(self): self.assertEqual(proc.stdout.rstrip(), 'True') self.assertEqual(proc.returncode, 0, proc) - @unittest.skipUnless(sys.platform == 'win32', - 'bpo-32457 only applies on Windows') + @unittest.skipUnless(MS_WINDOWS, 'bpo-32457 only applies on Windows') def test_argv0_normalization(self): args = sys.executable, '-c', 'print(0)' prefix, exe = os.path.split(sys.executable) diff --git a/Lib/test/test_cmd_line_script.py b/Lib/test/test_cmd_line_script.py index d138ca027c6848..7d9d2e64f11cbe 100644 --- a/Lib/test/test_cmd_line_script.py +++ b/Lib/test/test_cmd_line_script.py @@ -14,6 +14,7 @@ import textwrap from test import support +from test.support import MACOS, MS_WINDOWS from test.support.script_helper import ( make_pkg, make_script, make_zip_pkg, make_zip_script, assert_python_ok, assert_python_failure, spawn_python, kill_python) @@ -532,8 +533,7 @@ def test_non_ascii(self): # Mac OS X denies the creation of a file with an invalid UTF-8 name. # Windows allows creating a name with an arbitrary bytes name, but # Python cannot a undecodable bytes argument to a subprocess. - if (support.TESTFN_UNDECODABLE - and sys.platform not in ('win32', 'darwin')): + if (support.TESTFN_UNDECODABLE and not (MACOS or MS_WINDOWS)): name = os.fsdecode(support.TESTFN_UNDECODABLE) elif support.TESTFN_NONASCII: name = support.TESTFN_NONASCII diff --git a/Lib/test/test_codecs.py b/Lib/test/test_codecs.py index f665febfc90a21..77139ad194f609 100644 --- a/Lib/test/test_codecs.py +++ b/Lib/test/test_codecs.py @@ -2867,8 +2867,7 @@ def decode_to_bytes(*args, **kwds): -@unittest.skipUnless(sys.platform == 'win32', - 'code pages are specific to Windows') +@unittest.skipUnless(support.MS_WINDOWS, 'code pages are specific to Windows') class CodePageTest(unittest.TestCase): # CP_UTF8 is already tested by CP65001Test CP_UTF8 = 65001 diff --git a/Lib/test/test_codeop.py b/Lib/test/test_codeop.py index 98da26fa5dab13..71d9432ddd1d2b 100644 --- a/Lib/test/test_codeop.py +++ b/Lib/test/test_codeop.py @@ -3,12 +3,12 @@ Nick Mathewson """ import unittest -from test.support import is_jython +from test.support import JYTHON from codeop import compile_command, PyCF_DONT_IMPLY_DEDENT import io -if is_jython: +if JYTHON: import sys def unify_callables(d): @@ -21,7 +21,7 @@ class CodeopTests(unittest.TestCase): def assertValid(self, str, symbol='single'): '''succeed iff str is a valid piece of code''' - if is_jython: + if JYTHON: code = compile_command(str, "", symbol) self.assertTrue(code) if symbol == "single": @@ -60,7 +60,7 @@ def test_valid(self): av = self.assertValid # special case - if not is_jython: + if not JYTHON: self.assertEqual(compile_command(""), compile("pass", "", 'single', PyCF_DONT_IMPLY_DEDENT)) diff --git a/Lib/test/test_concurrent_futures.py b/Lib/test/test_concurrent_futures.py index b27ae719482285..c66aa028882ab5 100644 --- a/Lib/test/test_concurrent_futures.py +++ b/Lib/test/test_concurrent_futures.py @@ -5,6 +5,7 @@ # Skip tests if sem_open implementation is broken. test.support.import_module('multiprocessing.synchronize') +from test.support import MS_WINDOWS from test.support.script_helper import assert_python_ok import contextlib @@ -156,7 +157,7 @@ class ProcessPoolForkMixin(ExecutorMixin): ctx = "fork" def get_context(self): - if sys.platform == "win32": + if MS_WINDOWS: self.skipTest("require unix system") return super().get_context() @@ -171,7 +172,7 @@ class ProcessPoolForkserverMixin(ExecutorMixin): ctx = "forkserver" def get_context(self): - if sys.platform == "win32": + if MS_WINDOWS: self.skipTest("require unix system") return super().get_context() diff --git a/Lib/test/test_decimal.py b/Lib/test/test_decimal.py index 1f37b5372a3e7e..56fd5418e7c626 100644 --- a/Lib/test/test_decimal.py +++ b/Lib/test/test_decimal.py @@ -35,7 +35,7 @@ from test.support import (run_unittest, run_doctest, is_resource_enabled, requires_IEEE_754, requires_docstrings) from test.support import (import_fresh_module, TestFailed, - run_with_locale, cpython_only) + run_with_locale, cpython_only, MS_WINDOWS) import random import inspect import threading @@ -4862,7 +4862,7 @@ def test_c_context_errors(self): for attr in ('prec', 'Emin', 'Emax', 'capitals', 'clamp'): self.assertRaises(OverflowError, setattr, c, attr, int_max+1) self.assertRaises(OverflowError, setattr, c, attr, -int_max-2) - if sys.platform != 'win32': + if not MS_WINDOWS: self.assertRaises(ValueError, setattr, c, attr, int_max) self.assertRaises(ValueError, setattr, c, attr, -int_max-1) @@ -4937,7 +4937,7 @@ def test_c_context_errors_extra(self): # OverflowError, general ValueError self.assertRaises(OverflowError, setattr, c, '_allcr', int_max+1) self.assertRaises(OverflowError, setattr, c, '_allcr', -int_max-2) - if sys.platform != 'win32': + if not MS_WINDOWS: self.assertRaises(ValueError, setattr, c, '_allcr', int_max) self.assertRaises(ValueError, setattr, c, '_allcr', -int_max-1) @@ -4945,7 +4945,7 @@ def test_c_context_errors_extra(self): for attr in ('_flags', '_traps'): self.assertRaises(OverflowError, setattr, c, attr, int_max+1) self.assertRaises(OverflowError, setattr, c, attr, -int_max-2) - if sys.platform != 'win32': + if not MS_WINDOWS: self.assertRaises(TypeError, setattr, c, attr, int_max) self.assertRaises(TypeError, setattr, c, attr, -int_max-1) diff --git a/Lib/test/test_email/test_utils.py b/Lib/test/test_email/test_utils.py index 4e3c3f3a195fc4..4fbdd47c2fa3cf 100644 --- a/Lib/test/test_email/test_utils.py +++ b/Lib/test/test_email/test_utils.py @@ -1,6 +1,7 @@ import datetime from email import utils import test.support +from test.support import MS_WINDOWS import time import unittest import sys @@ -124,8 +125,7 @@ def test_localtime_epoch_notz_daylight_false(self): self.assertEqual(t1, t2) # XXX: Need a more robust test for Olson's tzdata - @unittest.skipIf(sys.platform.startswith('win'), - "Windows does not use Olson's TZ database") + @unittest.skipIf(MS_WINDOWS, "Windows does not use Olson's TZ database") @unittest.skipUnless(os.path.exists('/usr/share/zoneinfo') or os.path.exists('/usr/lib/zoneinfo'), "Can't find the Olson's TZ database") diff --git a/Lib/test/test_exceptions.py b/Lib/test/test_exceptions.py index d7e11d2d30a87c..38452be6a97da9 100644 --- a/Lib/test/test_exceptions.py +++ b/Lib/test/test_exceptions.py @@ -11,10 +11,9 @@ from test.support import (TESTFN, captured_stderr, check_impl_detail, check_warnings, cpython_only, gc_collect, run_unittest, no_tracing, unlink, import_module, script_helper, - SuppressCrashReport) + SuppressCrashReport, JYTHON, MS_WINDOWS) from test import support - class NaiveException(Exception): def __init__(self, x): self.x = x @@ -273,7 +272,7 @@ def test_capi3(): self.assertRaises(SystemError, _testcapi.raise_exception, InvalidException, 1) - if not sys.platform.startswith('java'): + if not JYTHON: test_capi1() test_capi2() test_capi3() @@ -317,8 +316,7 @@ def test_WindowsError(self): self.assertEqual(w.filename, None) self.assertEqual(w.filename2, None) - @unittest.skipUnless(sys.platform == 'win32', - 'test specific to Windows') + @unittest.skipUnless(MS_WINDOWS, 'test specific to Windows') def test_windows_message(self): """Should fill in unknown error code in Windows error message""" ctypes = import_module('ctypes') diff --git a/Lib/test/test_faulthandler.py b/Lib/test/test_faulthandler.py index f0be91844ffa7c..f35fc0ff07a7c9 100644 --- a/Lib/test/test_faulthandler.py +++ b/Lib/test/test_faulthandler.py @@ -7,7 +7,7 @@ import sys import sysconfig from test import support -from test.support import script_helper, is_android +from test.support import script_helper, ANDROID, AIX, MS_WINDOWS import tempfile import threading import unittest @@ -19,7 +19,6 @@ _testcapi = None TIMEOUT = 0.5 -MS_WINDOWS = (os.name == 'nt') _cflags = sysconfig.get_config_var('CFLAGS') or '' _config_args = sysconfig.get_config_var('CONFIG_ARGS') or '' UB_SANITIZER = ( @@ -43,7 +42,7 @@ def expected_traceback(lineno1, lineno2, header, min_count=1): def skip_segfault_on_android(test): # Issue #32138: Raising SIGSEGV on Android may not cause a crash. - return unittest.skipIf(is_android, + return unittest.skipIf(ANDROID, 'raising SIGSEGV on Android is unreliable')(test) @contextmanager @@ -130,8 +129,7 @@ def check_windows_exception(self, code, line_number, name_regex, **kw): fatal_error = 'Windows fatal exception: %s' % name_regex self.check_error(code, line_number, fatal_error, **kw) - @unittest.skipIf(sys.platform.startswith('aix'), - "the first page of memory is a mapped read-only on AIX") + @unittest.skipIf(AIX, "the first page of memory is a mapped read-only on AIX") def test_read_null(self): if not MS_WINDOWS: self.check_fatal_error(""" @@ -182,7 +180,7 @@ def test_sigabrt(self): 3, 'Aborted') - @unittest.skipIf(sys.platform == 'win32', + @unittest.skipIf(MS_WINDOWS, "SIGFPE cannot be caught on Windows") def test_sigfpe(self): self.check_fatal_error(""" @@ -277,8 +275,7 @@ def test_enable_file(self): 'Segmentation fault', filename=filename) - @unittest.skipIf(sys.platform == "win32", - "subprocess doesn't support pass_fds on Windows") + @unittest.skipIf(MS_WINDOWS, "subprocess doesn't support pass_fds on Windows") @unittest.skipIf(UB_SANITIZER or MEMORY_SANITIZER, "sanitizer builds change crashing process output.") @skip_segfault_on_android @@ -434,8 +431,7 @@ def test_dump_traceback_file(self): with temporary_filename() as filename: self.check_dump_traceback(filename=filename) - @unittest.skipIf(sys.platform == "win32", - "subprocess doesn't support pass_fds on Windows") + @unittest.skipIf(MS_WINDOWS, "subprocess doesn't support pass_fds on Windows") def test_dump_traceback_fd(self): with tempfile.TemporaryFile('wb+') as fp: self.check_dump_traceback(fd=fp.fileno()) @@ -607,8 +603,7 @@ def test_dump_traceback_later_file(self): with temporary_filename() as filename: self.check_dump_traceback_later(filename=filename) - @unittest.skipIf(sys.platform == "win32", - "subprocess doesn't support pass_fds on Windows") + @unittest.skipIf(MS_WINDOWS, "subprocess doesn't support pass_fds on Windows") def test_dump_traceback_later_fd(self): with tempfile.TemporaryFile('wb+') as fp: self.check_dump_traceback_later(fd=fp.fileno()) @@ -709,8 +704,7 @@ def test_register_file(self): with temporary_filename() as filename: self.check_register(filename=filename) - @unittest.skipIf(sys.platform == "win32", - "subprocess doesn't support pass_fds on Windows") + @unittest.skipIf(MS_WINDOWS, "subprocess doesn't support pass_fds on Windows") def test_register_fd(self): with tempfile.TemporaryFile('wb+') as fp: self.check_register(fd=fp.fileno()) diff --git a/Lib/test/test_fcntl.py b/Lib/test/test_fcntl.py index 5d4abe388f7828..61148326e6e43d 100644 --- a/Lib/test/test_fcntl.py +++ b/Lib/test/test_fcntl.py @@ -6,7 +6,7 @@ import sys import unittest from test.support import (verbose, TESTFN, unlink, run_unittest, import_module, - cpython_only) + cpython_only, MACOS) # Skip test if no fcntl module. fcntl = import_module('fcntl') @@ -23,7 +23,7 @@ def get_lockdata(): start_len = "qq" if (sys.platform.startswith(('netbsd', 'freebsd', 'openbsd')) - or sys.platform == 'darwin'): + or MACOS): if struct.calcsize('l') == 8: off_t = 'l' pid_t = 'i' diff --git a/Lib/test/test_fileio.py b/Lib/test/test_fileio.py index 26e4500ae8cfcd..dc475ce0bde37a 100644 --- a/Lib/test/test_fileio.py +++ b/Lib/test/test_fileio.py @@ -10,7 +10,8 @@ from functools import wraps from test.support import (TESTFN, TESTFN_UNICODE, check_warnings, run_unittest, - make_bad_fd, cpython_only, swap_attr) + make_bad_fd, cpython_only, swap_attr, + AIX, MACOS, MS_WINDOWS) from collections import UserList import _io # C implementation of io @@ -371,7 +372,7 @@ def testAbles(self): self.assertEqual(f.isatty(), False) f.close() - if sys.platform != "win32": + if not MS_WINDOWS: try: f = self.FileIO("/dev/tty", "a") except OSError: @@ -382,9 +383,9 @@ def testAbles(self): else: self.assertEqual(f.readable(), False) self.assertEqual(f.writable(), True) - if sys.platform != "darwin" and \ - 'bsd' not in sys.platform and \ - not sys.platform.startswith(('sunos', 'aix')): + if not (AIX or MACOS) \ + and 'bsd' not in sys.platform \ + and not sys.platform.startswith('sunos'): # Somehow /dev/tty appears seekable on some BSDs self.assertEqual(f.seekable(), False) self.assertEqual(f.isatty(), True) @@ -464,7 +465,7 @@ def testConstructorHandlesNULChars(self): def testInvalidFd(self): self.assertRaises(ValueError, self.FileIO, -10) self.assertRaises(OSError, self.FileIO, make_bad_fd()) - if sys.platform == 'win32': + if MS_WINDOWS: import msvcrt self.assertRaises(OSError, msvcrt.get_osfhandle, make_bad_fd()) diff --git a/Lib/test/test_gdb.py b/Lib/test/test_gdb.py index dbcb5983e9ba1d..57918307ae7f49 100644 --- a/Lib/test/test_gdb.py +++ b/Lib/test/test_gdb.py @@ -13,7 +13,7 @@ import unittest from test import support -from test.support import run_unittest, findfile, python_is_optimized +from test.support import run_unittest, findfile, python_is_optimized, MACOS def get_gdb_version(): try: @@ -48,7 +48,7 @@ def get_gdb_version(): if not sysconfig.is_python_build(): raise unittest.SkipTest("test_gdb only works on source builds at the moment.") -if 'Clang' in platform.python_compiler() and sys.platform == 'darwin': +if 'Clang' in platform.python_compiler() and MACOS: raise unittest.SkipTest("test_gdb doesn't work correctly when python is" " built with LLVM clang") diff --git a/Lib/test/test_genericpath.py b/Lib/test/test_genericpath.py index 9d5ac44b6d06a7..ce44454318e55a 100644 --- a/Lib/test/test_genericpath.py +++ b/Lib/test/test_genericpath.py @@ -9,7 +9,7 @@ import warnings from test import support from test.support.script_helper import assert_python_ok -from test.support import FakePath +from test.support import FakePath, MACOS, MS_WINDOWS def create_file(filename, data=b'foo'): @@ -436,7 +436,7 @@ def test_abspath(self): self.assertIn(b"foo", self.pathmodule.abspath(b"foo")) # avoid UnicodeDecodeError on Windows - undecodable_path = b'' if sys.platform == 'win32' else b'f\xf2\xf2' + undecodable_path = b'' if MS_WINDOWS else b'f\xf2\xf2' # Abspath returns bytes when the arg is bytes with warnings.catch_warnings(): @@ -479,7 +479,7 @@ def test_nonascii_abspath(self): # UTF-8 name. Windows allows creating a directory with an # arbitrary bytes name, but fails to enter this directory # (when the bytes name is used). - and sys.platform not in ('win32', 'darwin')): + and not (MACOS or MS_WINDOWS)): name = support.TESTFN_UNDECODABLE elif support.TESTFN_NONASCII: name = support.TESTFN_NONASCII diff --git a/Lib/test/test_glob.py b/Lib/test/test_glob.py index 767bd3764b8925..43dc720a1cd4dd 100644 --- a/Lib/test/test_glob.py +++ b/Lib/test/test_glob.py @@ -4,7 +4,7 @@ import sys import unittest -from test.support import (TESTFN, skip_unless_symlink, +from test.support import (TESTFN, skip_unless_symlink, MS_WINDOWS, can_symlink, create_empty_file, change_cwd) @@ -161,7 +161,7 @@ def test_glob_broken_symlinks(self): eq(self.glob('sym1'), [self.norm('sym1')]) eq(self.glob('sym2'), [self.norm('sym2')]) - @unittest.skipUnless(sys.platform == "win32", "Win32 specific test") + @unittest.skipUnless(MS_WINDOWS, "Win32 specific test") def test_glob_magic_in_drive(self): eq = self.assertSequencesEqual_noorder eq(glob.glob('*:'), []) @@ -186,7 +186,7 @@ def test_escape(self): check('[[_/*?*/_]]', '[[][[]_/[*][?][*]/_]]') check('/[[_/*?*/_]]/', '/[[][[]_/[*][?][*]/_]]/') - @unittest.skipUnless(sys.platform == "win32", "Win32 specific test") + @unittest.skipUnless(MS_WINDOWS, "Win32 specific test") def test_escape_windows(self): check = self.check_escape check('?:?', '?:[?]') diff --git a/Lib/test/test_httpservers.py b/Lib/test/test_httpservers.py index 8357ee9145d7e5..abda3ad44cb93a 100644 --- a/Lib/test/test_httpservers.py +++ b/Lib/test/test_httpservers.py @@ -29,6 +29,7 @@ import unittest from test import support +from test.support import MACOS, MS_WINDOWS class NoLogRequestHandler: @@ -385,10 +386,8 @@ def close_conn(): reader.close() return body - @unittest.skipIf(sys.platform == 'darwin', - 'undecodable name cannot always be decoded on macOS') - @unittest.skipIf(sys.platform == 'win32', - 'undecodable name cannot be decoded on win32') + @unittest.skipIf(MACOS, 'undecodable name cannot always be decoded on macOS') + @unittest.skipIf(MS_WINDOWS, 'undecodable name cannot be decoded on win32') @unittest.skipUnless(support.TESTFN_UNDECODABLE, 'need support.TESTFN_UNDECODABLE') def test_undecodable_filename(self): @@ -397,7 +396,7 @@ def test_undecodable_filename(self): with open(os.path.join(self.tempdir, filename), 'wb') as f: f.write(support.TESTFN_UNDECODABLE) response = self.request(self.base_url + '/') - if sys.platform == 'darwin': + if MACOS: # On Mac OS the HFS+ filesystem replaces bytes that aren't valid # UTF-8 into a percent-encoded value. for name in os.listdir(self.tempdir): diff --git a/Lib/test/test_imp.py b/Lib/test/test_imp.py index fe394dc50c56b1..2cbfabd8c2c3bc 100644 --- a/Lib/test/test_imp.py +++ b/Lib/test/test_imp.py @@ -5,7 +5,7 @@ import py_compile import sys from test import support -from test.support import script_helper +from test.support import script_helper, MACOS import unittest import warnings with warnings.catch_warnings(): @@ -136,7 +136,7 @@ def test_issue5604(self): 'cp1258' : b'\xc0', } - if sys.platform == 'darwin': + if MACOS: self.assertEqual(fs_encoding, 'utf-8') # Mac OS X uses the Normal Form D decomposition # http://developer.apple.com/mac/library/qa/qa2001/qa1173.html diff --git a/Lib/test/test_import/__init__.py b/Lib/test/test_import/__init__.py index 84cd0da94b36bf..e67113eb718d00 100644 --- a/Lib/test/test_import/__init__.py +++ b/Lib/test/test_import/__init__.py @@ -23,10 +23,10 @@ import test.support from test.support import ( - EnvironmentVarGuard, TESTFN, check_warnings, forget, is_jython, + EnvironmentVarGuard, TESTFN, check_warnings, forget, JYTHON, make_legacy_pyc, rmtree, run_unittest, swap_attr, swap_item, temp_umask, unlink, unload, create_empty_file, cpython_only, TESTFN_UNENCODABLE, - temp_dir, DirsOnSysPath) + temp_dir, DirsOnSysPath, MS_WINDOWS) from test.support import script_helper from test.test_importlib.util import uncache @@ -151,7 +151,7 @@ def test_import(self): def test_with_extension(ext): # The extension is normally ".py", perhaps ".pyw". source = TESTFN + ext - if is_jython: + if JYTHON: pyc = TESTFN + "$py.class" else: pyc = TESTFN + ".pyc" @@ -185,7 +185,7 @@ def test_with_extension(ext): sys.path.insert(0, os.curdir) try: test_with_extension(".py") - if sys.platform.startswith("win"): + if MS_WINDOWS: for ext in [".PY", ".Py", ".pY", ".pyw", ".PYW", ".pYw"]: test_with_extension(ext) finally: @@ -463,7 +463,7 @@ def run(): finally: del sys.path[0] - @unittest.skipUnless(sys.platform == "win32", "Windows-specific") + @unittest.skipUnless(MS_WINDOWS, "Windows-specific") def test_dll_dependency_import(self): from _winapi import GetModuleFileName dllname = GetModuleFileName(sys.dllhandle) @@ -705,7 +705,7 @@ def test_trailing_slash(self): unload("test_trailing_slash") # Regression test for http://bugs.python.org/issue3677. - @unittest.skipUnless(sys.platform == 'win32', 'Windows-specific') + @unittest.skipUnless(MS_WINDOWS, 'Windows-specific') def test_UNC_path(self): with open(os.path.join(self.path, 'test_unc_path.py'), 'w') as f: f.write("testdata = 'test_unc_path'") diff --git a/Lib/test/test_importlib/source/test_finder.py b/Lib/test/test_importlib/source/test_finder.py index f372b850dc7c15..bdad0c69cfa334 100644 --- a/Lib/test/test_importlib/source/test_finder.py +++ b/Lib/test/test_importlib/source/test_finder.py @@ -9,7 +9,7 @@ import stat import sys import tempfile -from test.support import make_legacy_pyc +from test.support import make_legacy_pyc, MS_WINDOWS import unittest import warnings @@ -153,7 +153,7 @@ def test_dir_removal_handling(self): found = self._find(finder, 'mod', loader_only=True) self.assertIsNone(found) - @unittest.skipUnless(sys.platform != 'win32', + @unittest.skipIf(MS_WINDOWS, 'os.chmod() does not support the needed arguments under Windows') def test_no_read_directory(self): # Issue #16730 diff --git a/Lib/test/test_importlib/test_windows.py b/Lib/test/test_importlib/test_windows.py index 005b685cc03cd9..115b7f842823ec 100644 --- a/Lib/test/test_importlib/test_windows.py +++ b/Lib/test/test_importlib/test_windows.py @@ -54,7 +54,7 @@ def setup_module(machinery, name, path=None): delete_registry_tree(HKEY_CURRENT_USER, key) -@unittest.skipUnless(sys.platform.startswith('win'), 'requires Windows') +@unittest.skipUnless(support.MS_WINDOWS, 'requires Windows') class WindowsRegistryFinderTests: # The module name is process-specific, allowing for # simultaneous runs of the same test on a single machine. @@ -86,7 +86,7 @@ def test_module_not_found(self): Source_WindowsRegistryFinderTests ) = test_util.test_both(WindowsRegistryFinderTests, machinery=machinery) -@unittest.skipUnless(sys.platform.startswith('win'), 'requires Windows') +@unittest.skipUnless(support.MS_WINDOWS, 'requires Windows') class WindowsExtensionSuffixTests: def test_tagged_suffix(self): suffixes = self.machinery.EXTENSION_SUFFIXES diff --git a/Lib/test/test_importlib/util.py b/Lib/test/test_importlib/util.py index 196ea1c9d4dda5..b3f3fd5e85345e 100644 --- a/Lib/test/test_importlib/util.py +++ b/Lib/test/test_importlib/util.py @@ -92,7 +92,7 @@ def test_both(test_class, base=None, **kwargs): CASE_INSENSITIVE_FS = True # Windows is the only OS that is *always* case-insensitive # (OS X *can* be case-sensitive). -if sys.platform not in ('win32', 'cygwin'): +if not (support.MS_WINDOWS or support.MACOS): changed_name = __file__.upper() if changed_name == __file__: changed_name = __file__.lower() diff --git a/Lib/test/test_io.py b/Lib/test/test_io.py index 3a1f5ba5b6663d..dd981bb183f8bd 100644 --- a/Lib/test/test_io.py +++ b/Lib/test/test_io.py @@ -38,7 +38,7 @@ from itertools import cycle, count from test import support from test.support.script_helper import assert_python_ok, run_python_until_end -from test.support import FakePath +from test.support import FakePath, MACOS, MS_WINDOWS import codecs import io # C implementation of io @@ -500,7 +500,7 @@ class UnseekableWriter(self.MockUnseekableIO): else: self.assertRaises(OSError, obj.write, data) - if sys.platform.startswith("win") and test in ( + if MS_WINDOWS and test in ( pipe_reader, pipe_writer): # Pipes seem to appear as seekable on Windows continue @@ -596,7 +596,7 @@ def test_large_file_ops(self): # 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 # therefore the resource must be enabled to run this test. - if sys.platform[:3] == 'win' or sys.platform == 'darwin': + if MACOS or MS_WINDOWS: support.requires( 'largefile', 'test requires %s bytes and a long time to run' % self.LARGE) diff --git a/Lib/test/test_largefile.py b/Lib/test/test_largefile.py index 8870c721ab0efb..f278dc16cb2e22 100644 --- a/Lib/test/test_largefile.py +++ b/Lib/test/test_largefile.py @@ -5,7 +5,7 @@ import stat import sys import unittest -from test.support import TESTFN, requires, unlink, bigmemtest +from test.support import TESTFN, requires, unlink, bigmemtest, MACOS, MS_WINDOWS import io # C implementation of io import _pyio as pyio # Python implementation of io @@ -154,7 +154,7 @@ def setUpModule(): # 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. # If not, nothing after this line stanza will be executed. - if sys.platform[:3] == 'win' or sys.platform == 'darwin': + if MS_WINDOWS or MACOS: requires('largefile', 'test requires %s bytes and a long time to run' % str(size)) else: diff --git a/Lib/test/test_locale.py b/Lib/test/test_locale.py index e2c2178ae6cc30..27ae945d02ae89 100644 --- a/Lib/test/test_locale.py +++ b/Lib/test/test_locale.py @@ -1,4 +1,4 @@ -from test.support import verbose, is_android, check_warnings +from test.support import verbose, check_warnings, ANDROID, AIX, MACOS, MS_WINDOWS import unittest import locale import sys @@ -12,7 +12,7 @@ class BaseLocalizedTest(unittest.TestCase): @classmethod def setUpClass(cls): - if sys.platform == 'darwin': + if MACOS: import os tlocs = ("en_US.UTF-8", "en_US.ISO8859-1", "en_US") if int(os.uname().release.split('.')[0]) < 10: @@ -20,7 +20,7 @@ def setUpClass(cls): # haven't had time yet to verify if tests work on OSX 10.5 # (10.4 is known to be bad) raise unittest.SkipTest("Locale support on MacOSX is minimal") - elif sys.platform.startswith("win"): + elif MS_WINDOWS: tlocs = ("En", "English") else: tlocs = ("en_US.UTF-8", "en_US.ISO8859-1", @@ -365,18 +365,16 @@ def setUp(self): enc = codecs.lookup(locale.getpreferredencoding(False) or 'ascii').name if enc not in ('utf-8', 'iso8859-1', 'cp1252'): raise unittest.SkipTest('encoding not suitable') - if enc != 'iso8859-1' and (sys.platform == 'darwin' or is_android or + if enc != 'iso8859-1' and (MACOS or ANDROID or sys.platform.startswith('freebsd')): raise unittest.SkipTest('wcscoll/wcsxfrm have known bugs') BaseLocalizedTest.setUp(self) - @unittest.skipIf(sys.platform.startswith('aix'), - 'bpo-29972: broken test on AIX') + @unittest.skipIf(AIX, 'bpo-29972: broken test on AIX') def test_strcoll_with_diacritic(self): self.assertLess(locale.strcoll('à', 'b'), 0) - @unittest.skipIf(sys.platform.startswith('aix'), - 'bpo-29972: broken test on AIX') + @unittest.skipIf(AIX, 'bpo-29972: broken test on AIX') def test_strxfrm_with_diacritic(self): self.assertLess(locale.strxfrm('à'), locale.strxfrm('b')) diff --git a/Lib/test/test_logging.py b/Lib/test/test_logging.py index b884753ad39785..8ec8ed5c8f1e7d 100644 --- a/Lib/test/test_logging.py +++ b/Lib/test/test_logging.py @@ -42,6 +42,7 @@ import sys import tempfile from test.support.script_helper import assert_python_ok, assert_python_failure +from test.support import LINUX, MACOS, MS_WINDOWS from test import support import textwrap import threading @@ -543,7 +544,7 @@ def test_name(self): def test_builtin_handlers(self): # We can't actually *use* too many handlers in the tests, # but we can try instantiating them with various options - if sys.platform in ('linux', 'darwin'): + if LINUX or MACOS: for existing in (True, False): fd, fn = tempfile.mkstemp() os.close(fd) @@ -568,7 +569,7 @@ def test_builtin_handlers(self): h.close() if existing: os.unlink(fn) - if sys.platform == 'darwin': + if MACOS: sockname = '/var/run/syslog' else: sockname = '/dev/log' @@ -609,7 +610,7 @@ def test_path_objects(self): (logging.handlers.RotatingFileHandler, (pfn, 'a')), (logging.handlers.TimedRotatingFileHandler, (pfn, 'h')), ) - if sys.platform in ('linux', 'darwin'): + if LINUX or MACOS: cases += ((logging.handlers.WatchedFileHandler, (pfn, 'w')),) for cls, args in cases: h = cls(*args) @@ -617,7 +618,7 @@ def test_path_objects(self): h.close() os.unlink(fn) - @unittest.skipIf(os.name == 'nt', 'WatchedFileHandler not appropriate for Windows.') + @unittest.skipIf(MS_WINDOWS, 'WatchedFileHandler not appropriate for Windows.') def test_race(self): # Issue #14632 refers. def remove_loop(fname, tries): diff --git a/Lib/test/test_math.py b/Lib/test/test_math.py index 853a0e62f82351..1663c7be08711a 100644 --- a/Lib/test/test_math.py +++ b/Lib/test/test_math.py @@ -1,7 +1,7 @@ # Python test set -- math module # XXXX Should not do tests around zero only -from test.support import run_unittest, verbose, requires_IEEE_754 +from test.support import run_unittest, verbose, requires_IEEE_754, MACOS from test import support import unittest import itertools @@ -1530,7 +1530,7 @@ def test_testfile(self): SKIP_ON_TIGER = {'tan0064'} osx_version = None - if sys.platform == 'darwin': + if MACOS: version_txt = platform.mac_ver()[0] try: osx_version = tuple(map(int, version_txt.split('.'))) diff --git a/Lib/test/test_mimetypes.py b/Lib/test/test_mimetypes.py index c4b2fe2047a71d..e1896bdc638e18 100644 --- a/Lib/test/test_mimetypes.py +++ b/Lib/test/test_mimetypes.py @@ -7,6 +7,7 @@ from test import support from platform import win32_edition +from test.support import MS_WINDOWS # Tell it we don't know about external files: mimetypes.knownfiles = [] @@ -103,7 +104,7 @@ def test_keywords_args_api(self): type='image/jpg', strict=False), '.jpg') -@unittest.skipUnless(sys.platform.startswith("win"), "Windows only") +@unittest.skipUnless(MS_WINDOWS, "Windows only") class Win32MimeTypesTestCase(unittest.TestCase): def setUp(self): # ensure all entries actually come from the Windows registry diff --git a/Lib/test/test_mmap.py b/Lib/test/test_mmap.py index 88c501d81a07f9..8f5aa245df67a1 100644 --- a/Lib/test/test_mmap.py +++ b/Lib/test/test_mmap.py @@ -1,5 +1,6 @@ from test.support import (TESTFN, import_module, unlink, - requires, _2G, _4G, gc_collect, cpython_only) + requires, _2G, _4G, gc_collect, cpython_only, + LINUX, MACOS, MS_WINDOWS) import unittest import os import re @@ -185,14 +186,14 @@ def test_access_parameter(self): # CAUTION: This also changes the size of the file on disk, and # later tests assume that the length hasn't changed. We need to # repair that. - if sys.platform.startswith('win'): + if MS_WINDOWS: self.fail("Opening mmap with size+1 should work on Windows.") else: # we expect a ValueError on Unix, but not on Windows - if not sys.platform.startswith('win'): + if not MS_WINDOWS: self.fail("Opening mmap with size+1 should raise ValueError.") m.close() - if sys.platform.startswith('win'): + if MS_WINDOWS: # Repair damage from the resizing test. with open(TESTFN, 'r+b') as f: f.truncate(mapsize) @@ -735,7 +736,7 @@ def test_flush_return_value(self): mm.write(b'python') result = mm.flush() self.assertIsNone(result) - if sys.platform.startswith('linux'): + if LINUX: # 'offset' must be a multiple of mmap.PAGESIZE on Linux. # See bpo-34754 for details. self.assertRaises(OSError, mm.flush, 1, len(b'python')) @@ -769,7 +770,7 @@ def tearDown(self): unlink(TESTFN) def _make_test_file(self, num_zeroes, tail): - if sys.platform[:3] == 'win' or sys.platform == 'darwin': + if MACOS or MS_WINDOWS: requires('largefile', 'test requires %s bytes and a long time to run' % str(0x180000000)) f = open(TESTFN, 'w+b') diff --git a/Lib/test/test_multiprocessing_fork.py b/Lib/test/test_multiprocessing_fork.py index 5000edb7c5c299..378fd471817950 100644 --- a/Lib/test/test_multiprocessing_fork.py +++ b/Lib/test/test_multiprocessing_fork.py @@ -3,14 +3,15 @@ import sys from test import support +from test.support import MACOS, MS_WINDOWS if support.PGO: raise unittest.SkipTest("test is not helpful for PGO") -if sys.platform == "win32": +if MS_WINDOWS: raise unittest.SkipTest("fork is not available on Windows") -if sys.platform == 'darwin': +if MACOS: raise unittest.SkipTest("test may crash on macOS (bpo-33725)") test._test_multiprocessing.install_tests_in_module_dict(globals(), 'fork') diff --git a/Lib/test/test_multiprocessing_forkserver.py b/Lib/test/test_multiprocessing_forkserver.py index 6ad5faf9e8a329..884f434b56df1f 100644 --- a/Lib/test/test_multiprocessing_forkserver.py +++ b/Lib/test/test_multiprocessing_forkserver.py @@ -7,7 +7,7 @@ if support.PGO: raise unittest.SkipTest("test is not helpful for PGO") -if sys.platform == "win32": +if support.MS_WINDOWS: raise unittest.SkipTest("forkserver is not available on Windows") test._test_multiprocessing.install_tests_in_module_dict(globals(), 'forkserver') diff --git a/Lib/test/test_ntpath.py b/Lib/test/test_ntpath.py index fc2398c2d518ba..6f233047abad6d 100644 --- a/Lib/test/test_ntpath.py +++ b/Lib/test/test_ntpath.py @@ -3,7 +3,7 @@ import sys import unittest import warnings -from test.support import TestFailed, FakePath +from test.support import TestFailed, FakePath, MS_WINDOWS from test import support, test_genericpath from tempfile import TemporaryFile @@ -388,7 +388,7 @@ def test_sameopenfile(self): # Make sure different files are really different self.assertFalse(ntpath.sameopenfile(tf1.fileno(), tf2.fileno())) # Make sure invalid values don't cause issues on win32 - if sys.platform == "win32": + if MS_WINDOWS: with self.assertRaises(OSError): # Invalid file descriptors shouldn't display assert # dialogs (#4804) @@ -412,7 +412,7 @@ def test_ismount(self): with support.temp_dir() as d: self.assertFalse(ntpath.ismount(d)) - if sys.platform == "win32": + if MS_WINDOWS: # # Make sure the current folder isn't the root folder # (or any other volume root). The drive-relative diff --git a/Lib/test/test_os.py b/Lib/test/test_os.py index 353b9a50a2b7fb..c508ceda94d7da 100644 --- a/Lib/test/test_os.py +++ b/Lib/test/test_os.py @@ -29,6 +29,7 @@ import warnings from test import support from platform import win32_is_iot +from test.support import LINUX, MS_WINDOWS try: import resource @@ -181,8 +182,7 @@ def write_windows_console(self, *args): shell=True) self.assertEqual(retcode, 0) - @unittest.skipUnless(sys.platform == 'win32', - 'test specific to the Windows console') + @unittest.skipUnless(MS_WINDOWS, 'test specific to the Windows console') def test_write_windows_console(self): # Issue #11395: the Windows console returns an error (12: not enough # space error) on writing into stdout if stdout mode is binary and the @@ -381,7 +381,7 @@ def test_statvfs_result_pickle(self): unpickled = pickle.loads(p) self.assertEqual(result, unpickled) - @unittest.skipUnless(sys.platform == "win32", "Win32 specific tests") + @unittest.skipUnless(MS_WINDOWS, "Win32 specific tests") def test_1686475(self): # Verify that an open file can be stat'ed try: @@ -391,7 +391,7 @@ def test_1686475(self): except OSError as e: self.fail("Could not stat pagefile.sys") - @unittest.skipUnless(sys.platform == "win32", "Win32 specific tests") + @unittest.skipUnless(MS_WINDOWS, "Win32 specific tests") @unittest.skipUnless(hasattr(os, "pipe"), "requires os.pipe()") def test_15261(self): # Verify that stat'ing a closed fd does not cause crash @@ -410,8 +410,7 @@ def check_file_attributes(self, result): self.assertTrue(isinstance(result.st_file_attributes, int)) self.assertTrue(0 <= result.st_file_attributes <= 0xFFFFFFFF) - @unittest.skipUnless(sys.platform == "win32", - "st_file_attributes is Win32 specific") + @unittest.skipUnless(MS_WINDOWS, "st_file_attributes is Win32 specific") def test_file_attributes(self): # test file st_file_attributes (FILE_ATTRIBUTE_DIRECTORY not set) result = os.stat(self.fname) @@ -431,7 +430,7 @@ def test_file_attributes(self): result.st_file_attributes & stat.FILE_ATTRIBUTE_DIRECTORY, stat.FILE_ATTRIBUTE_DIRECTORY) - @unittest.skipUnless(sys.platform == "win32", "Win32 specific tests") + @unittest.skipUnless(MS_WINDOWS, "Win32 specific tests") def test_access_denied(self): # Default to FindFirstFile WIN32_FIND_DATA when access is # denied. See issue 28075. @@ -608,7 +607,7 @@ def set_time(filename): self._test_utime_current(set_time) def get_file_system(self, path): - if sys.platform == 'win32': + if MS_WINDOWS: root = os.path.splitdrive(os.path.abspath(path))[0] + '\\' import ctypes kernel32 = ctypes.windll.kernel32 @@ -809,7 +808,7 @@ def test_environb(self): # On OS X < 10.6, unsetenv() doesn't return a value (bpo-13415). @support.requires_mac_ver(10, 6) def test_unset_error(self): - if sys.platform == "win32": + if MS_WINDOWS: # an environment variable is limited to 32,767 characters key = 'x' * 50000 self.assertRaises(ValueError, os.environ.__delitem__, key) @@ -1614,7 +1613,7 @@ def test_execve_invalid_env(self): with self.assertRaises(ValueError): os.execve(args[0], args, newenv) - @unittest.skipUnless(sys.platform == "win32", "Win32-specific test") + @unittest.skipUnless(MS_WINDOWS, "Win32-specific test") def test_execve_with_empty_path(self): # bpo-32890: Check GetLastError() misuse try: @@ -1625,7 +1624,7 @@ def test_execve_with_empty_path(self): self.fail('No OSError raised') -@unittest.skipUnless(sys.platform == "win32", "Win32 specific tests") +@unittest.skipUnless(MS_WINDOWS, "Win32 specific tests") class Win32ErrorTests(unittest.TestCase): def setUp(self): try: @@ -1798,7 +1797,7 @@ def test_unicode_name(self): self.file2 = self.file1 + "2" self._test_link(self.file1, self.file2) -@unittest.skipIf(sys.platform == "win32", "Posix specific tests") +@unittest.skipIf(MS_WINDOWS, "Posix specific tests") class PosixUidGidTests(unittest.TestCase): # uid_t and gid_t are 32-bit unsigned integers on Linux UID_OVERFLOW = (1 << 32) @@ -1866,7 +1865,7 @@ def test_setregid_neg1(self): sys.executable, '-c', 'import os,sys;os.setregid(-1,-1);sys.exit(0)']) -@unittest.skipIf(sys.platform == "win32", "Posix specific tests") +@unittest.skipIf(MS_WINDOWS, "Posix specific tests") class Pep383Tests(unittest.TestCase): def setUp(self): if support.TESTFN_UNENCODABLE: @@ -1938,7 +1937,7 @@ def test_stat(self): for fn in self.unicodefn: os.stat(os.path.join(self.dir, fn)) -@unittest.skipUnless(sys.platform == "win32", "Win32 specific tests") +@unittest.skipUnless(MS_WINDOWS, "Win32 specific tests") class Win32KillTests(unittest.TestCase): def _kill(self, sig): # Start sys.executable as a subprocess and communicate from the @@ -2054,7 +2053,7 @@ def test_CTRL_BREAK_EVENT(self): self._kill_with_event(signal.CTRL_BREAK_EVENT, "CTRL_BREAK_EVENT") -@unittest.skipUnless(sys.platform == "win32", "Win32 specific tests") +@unittest.skipUnless(MS_WINDOWS, "Win32 specific tests") class Win32ListdirTests(unittest.TestCase): """Test listdir on Windows.""" @@ -2149,7 +2148,7 @@ def test_bytes(self): self.assertIsInstance(path, bytes) -@unittest.skipUnless(sys.platform == "win32", "Win32 specific tests") +@unittest.skipUnless(MS_WINDOWS, "Win32 specific tests") @support.skip_unless_symlink class Win32SymlinkTests(unittest.TestCase): filelink = 'filelinktest' @@ -2309,7 +2308,7 @@ def test_buffer_overflow(self): except OSError: pass -@unittest.skipUnless(sys.platform == "win32", "Win32 specific tests") +@unittest.skipUnless(MS_WINDOWS, "Win32 specific tests") class Win32JunctionTests(unittest.TestCase): junction = 'junctiontest' junction_target = os.path.dirname(os.path.abspath(__file__)) @@ -2339,7 +2338,7 @@ def test_unlink_removes_junction(self): os.unlink(self.junction) self.assertFalse(os.path.exists(self.junction)) -@unittest.skipUnless(sys.platform == "win32", "Win32 specific tests") +@unittest.skipUnless(MS_WINDOWS, "Win32 specific tests") class Win32NtTests(unittest.TestCase): def test_getfinalpathname_handles(self): nt = support.import_module('nt') @@ -2443,7 +2442,7 @@ def test_bad_fd(self): # Return None when an fd doesn't actually exist. self.assertIsNone(os.device_encoding(123456)) - @unittest.skipUnless(os.isatty(0) and not win32_is_iot() and (sys.platform.startswith('win') or + @unittest.skipUnless(os.isatty(0) and not win32_is_iot() and (MS_WINDOWS or (hasattr(locale, 'nl_langinfo') and hasattr(locale, 'CODESET'))), 'test requires a tty and either Windows or nl_langinfo(CODESET)') def test_device_encoding(self): @@ -2774,7 +2773,7 @@ def handle_error(self): class TestSendfile(unittest.TestCase): DATA = b"12345abcde" * 16 * 1024 # 160 KiB - SUPPORT_HEADERS_TRAILERS = not sys.platform.startswith("linux") and \ + SUPPORT_HEADERS_TRAILERS = not LINUX and \ not sys.platform.startswith("solaris") and \ not sys.platform.startswith("sunos") requires_headers_trailers = unittest.skipUnless(SUPPORT_HEADERS_TRAILERS, @@ -3088,7 +3087,7 @@ def test_does_not_crash(self): try: size = os.get_terminal_size() except OSError as e: - if sys.platform == "win32" or e.errno in (errno.EINVAL, errno.ENOTTY): + if MS_WINDOWS or e.errno in (errno.EINVAL, errno.ENOTTY): # Under win32 a generic OSError can be thrown if the # handle cannot be retrieved self.skipTest("failed to query terminal size") @@ -3114,7 +3113,7 @@ def test_stty_match(self): try: actual = os.get_terminal_size(sys.__stdin__.fileno()) except OSError as e: - if sys.platform == "win32" or e.errno in (errno.EINVAL, errno.ENOTTY): + if MS_WINDOWS or e.errno in (errno.EINVAL, errno.ENOTTY): # Under win32 a generic OSError can be thrown if the # handle cannot be retrieved self.skipTest("failed to query terminal size") @@ -3155,7 +3154,7 @@ def test_oserror_filename(self): (self.filenames, os.stat,), (self.filenames, os.unlink,), ] - if sys.platform == "win32": + if MS_WINDOWS: funcs.extend(( (self.bytes_filenames, os.rename, b"dst"), (self.bytes_filenames, os.replace, b"dst"), @@ -3182,7 +3181,7 @@ def test_oserror_filename(self): if hasattr(os, "chroot"): funcs.append((self.filenames, os.chroot,)) if hasattr(os, "link"): - if sys.platform == "win32": + if MS_WINDOWS: funcs.append((self.bytes_filenames, os.link, b"dst")) funcs.append((self.unicode_filenames, os.link, "dst")) else: @@ -3197,7 +3196,7 @@ def test_oserror_filename(self): if hasattr(os, "lchmod"): funcs.append((self.filenames, os.lchmod, 0o777)) if hasattr(os, "readlink"): - if sys.platform == "win32": + if MS_WINDOWS: funcs.append((self.unicode_filenames, os.readlink,)) else: funcs.append((self.filenames, os.readlink,)) diff --git a/Lib/test/test_osx_env.py b/Lib/test/test_osx_env.py index 8a3bc5a46e547b..a4918bb0f6798b 100644 --- a/Lib/test/test_osx_env.py +++ b/Lib/test/test_osx_env.py @@ -2,14 +2,13 @@ Test suite for OS X interpreter environment variables. """ -from test.support import EnvironmentVarGuard +from test.support import EnvironmentVarGuard, MACOS import subprocess import sys import sysconfig import unittest -@unittest.skipUnless(sys.platform == 'darwin' and - sysconfig.get_config_var('WITH_NEXT_FRAMEWORK'), +@unittest.skipUnless(MACOS and sysconfig.get_config_var('WITH_NEXT_FRAMEWORK'), 'unnecessary on this platform') class OSXEnvironmentVariableTestCase(unittest.TestCase): def _check_sys(self, ev, cond, sv, val = sys.executable + 'dummy'): diff --git a/Lib/test/test_pathlib.py b/Lib/test/test_pathlib.py index 069467a8459f00..76f5cb41433028 100644 --- a/Lib/test/test_pathlib.py +++ b/Lib/test/test_pathlib.py @@ -12,7 +12,7 @@ from unittest import mock from test import support -from test.support import TESTFN, FakePath +from test.support import TESTFN, FakePath, MACOS try: import grp, pwd @@ -2235,8 +2235,7 @@ def test_expanduser(self): self.assertEqual(p6.expanduser(), p6) self.assertRaises(RuntimeError, p7.expanduser) - @unittest.skipIf(sys.platform != "darwin", - "Bad file descriptor in /dev/fd affects only macOS") + @unittest.skipIf(MACOS, "Bad file descriptor in /dev/fd affects only macOS") def test_handling_bad_descriptor(self): try: file_descriptors = list(pathlib.Path('/dev/fd').rglob("*"))[3:] diff --git a/Lib/test/test_platform.py b/Lib/test/test_platform.py index 9cf17726d92e0d..2839340bbf3879 100644 --- a/Lib/test/test_platform.py +++ b/Lib/test/test_platform.py @@ -8,6 +8,7 @@ from unittest import mock from test import support +from test.support import JYTHON, MACOS, MS_WINDOWS class PlatformTest(unittest.TestCase): def clear_caches(self): @@ -23,7 +24,7 @@ def test_architecture_via_symlink(self): # issue3762 # On Windows, the EXE needs to know where pythonXY.dll and *.pyd is at # so we add the directory to the path, PYTHONHOME and PYTHONPATH. env = None - if sys.platform == "win32": + if MS_WINDOWS: env = {k.upper(): os.environ[k] for k in os.environ} env["PATH"] = "{};{}".format( os.path.dirname(sys.executable), env.get("PATH", "")) @@ -189,7 +190,7 @@ def test_uname(self): self.assertEqual(res[4], res.machine) self.assertEqual(res[5], res.processor) - @unittest.skipUnless(sys.platform.startswith('win'), "windows only test") + @unittest.skipUnless(MS_WINDOWS, "windows only test") def test_uname_win32_ARCHITEW6432(self): # Issue 7860: make sure we get architecture from the correct variable # on 64 bit Windows: if PROCESSOR_ARCHITEW6432 exists we should be @@ -212,7 +213,7 @@ def test_uname_win32_ARCHITEW6432(self): def test_java_ver(self): res = platform.java_ver() - if sys.platform == 'java': + if JYTHON: self.assertTrue(all(res)) def test_win32_ver(self): @@ -251,7 +252,7 @@ def test_mac_ver(self): self.assertEqual(res[2], 'PowerPC') - @unittest.skipUnless(sys.platform == 'darwin', "OSX only test") + @unittest.skipUnless(MACOS, "OSX only test") def test_mac_ver_with_fork(self): # Issue7895: platform.mac_ver() crashes when using fork without exec # diff --git a/Lib/test/test_posix.py b/Lib/test/test_posix.py index 5c93d0d507d252..be1ecfc9c3cf84 100644 --- a/Lib/test/test_posix.py +++ b/Lib/test/test_posix.py @@ -1,6 +1,7 @@ "Test posix functions" from test import support +from test.support import MACOS from test.support.script_helper import assert_python_ok # Skip these tests if there is no posix module. @@ -1041,7 +1042,7 @@ def test_getgroups(self): raise unittest.SkipTest("need working 'id -G'") # Issues 16698: OS X ABIs prior to 10.6 have limits on getgroups() - if sys.platform == 'darwin': + if MACOS: import sysconfig dt = sysconfig.get_config_var('MACOSX_DEPLOYMENT_TARGET') or '10.0' if tuple(int(n) for n in dt.split('.')[0:2]) < (10, 6): @@ -1285,7 +1286,7 @@ def test_sched_priority(self): self.assertIsInstance(hi, int) self.assertGreaterEqual(hi, lo) # OSX evidently just returns 15 without checking the argument. - if sys.platform != "darwin": + if not MACOS: self.assertRaises(OSError, posix.sched_get_priority_min, -23) self.assertRaises(OSError, posix.sched_get_priority_max, -23) @@ -1464,7 +1465,7 @@ def setUp(self): raise unittest.SkipTest("not enough privileges") if not hasattr(posix, 'getgroups'): raise unittest.SkipTest("need posix.getgroups") - if sys.platform == 'darwin': + if MACOS: raise unittest.SkipTest("getgroups(2) is broken on OSX") self.saved_groups = posix.getgroups() diff --git a/Lib/test/test_regrtest.py b/Lib/test/test_regrtest.py index 9155522c273d88..b4e3ea7c2e5c28 100644 --- a/Lib/test/test_regrtest.py +++ b/Lib/test/test_regrtest.py @@ -19,6 +19,7 @@ from test import libregrtest from test import support from test.libregrtest import utils +from test.support import MS_WINDOWS Py_DEBUG = hasattr(sys, 'gettotalrefcount') @@ -548,7 +549,7 @@ def setUp(self): '--testdir=%s' % self.tmptestdir] if hasattr(faulthandler, 'dump_traceback_later'): self.regrtest_args.extend(('--timeout', '3600', '-j4')) - if sys.platform == 'win32': + if MS_WINDOWS: self.regrtest_args.append('-n') def check_output(self, output): @@ -611,7 +612,7 @@ def run_batch(self, *args): @unittest.skipUnless(sysconfig.is_python_build(), 'test.bat script is not installed') - @unittest.skipUnless(sys.platform == 'win32', 'Windows only') + @unittest.skipUnless(MS_WINDOWS, 'Windows only') def test_tools_buildbot_test(self): # Tools\buildbot\test.bat script = os.path.join(ROOT_DIR, 'Tools', 'buildbot', 'test.bat') @@ -622,7 +623,7 @@ def test_tools_buildbot_test(self): test_args.append('+d') # Release build, use python.exe self.run_batch(script, *test_args, *self.tests) - @unittest.skipUnless(sys.platform == 'win32', 'Windows only') + @unittest.skipUnless(MS_WINDOWS, 'Windows only') def test_pcbuild_rt(self): # PCbuild\rt.bat script = os.path.join(ROOT_DIR, r'PCbuild\rt.bat') diff --git a/Lib/test/test_resource.py b/Lib/test/test_resource.py index e5ece5284cf15b..df8d0f44f06b41 100644 --- a/Lib/test/test_resource.py +++ b/Lib/test/test_resource.py @@ -2,6 +2,7 @@ import sys import unittest from test import support +from test.support import LINUX import time resource = support.import_module('resource') @@ -135,7 +136,7 @@ def test_pagesize(self): self.assertIsInstance(pagesize, int) self.assertGreaterEqual(pagesize, 0) - @unittest.skipUnless(sys.platform == 'linux', 'test requires Linux') + @unittest.skipUnless(LINUX, 'test requires Linux') def test_linux_constants(self): for attr in ['MSGQUEUE', 'NICE', 'RTPRIO', 'RTTIME', 'SIGPENDING']: with contextlib.suppress(AttributeError): diff --git a/Lib/test/test_select.py b/Lib/test/test_select.py index 458998a62fdf5e..8250c21ae1468d 100644 --- a/Lib/test/test_select.py +++ b/Lib/test/test_select.py @@ -4,9 +4,9 @@ import sys import unittest from test import support +from test.support import MS_WINDOWS -@unittest.skipIf((sys.platform[:3]=='win'), - "can't easily test on this system") +@unittest.skipIf(MS_WINDOWS, "can't easily test on this system") class SelectTestCase(unittest.TestCase): class Nope: diff --git a/Lib/test/test_selectors.py b/Lib/test/test_selectors.py index 31611224dc71e1..b43504135f2b25 100644 --- a/Lib/test/test_selectors.py +++ b/Lib/test/test_selectors.py @@ -6,6 +6,7 @@ import socket import sys from test import support +from test.support import MACOS, MS_WINDOWS from time import sleep import unittest import unittest.mock @@ -348,8 +349,7 @@ def test_selector(self): self.assertEqual(bufs, [MSG] * NUM_SOCKETS) - @unittest.skipIf(sys.platform == 'win32', - 'select.select() cannot be used with empty fd sets') + @unittest.skipIf(MS_WINDOWS, 'select.select() cannot be used with empty fd sets') def test_empty_select(self): # Issue #23009: Make sure EpollSelector.select() works when no FD is # registered. @@ -484,7 +484,7 @@ def test_above_fd_setsize(self): try: fds = s.select() except OSError as e: - if e.errno == errno.EINVAL and sys.platform == 'darwin': + if e.errno == errno.EINVAL and MACOS: # unexplainable errors on macOS don't need to fail the test self.skipTest("Invalid argument error calling poll()") raise diff --git a/Lib/test/test_shutil.py b/Lib/test/test_shutil.py index eeebb97ff6921c..130942f3e1bde1 100644 --- a/Lib/test/test_shutil.py +++ b/Lib/test/test_shutil.py @@ -30,11 +30,10 @@ posix = None from test import support -from test.support import TESTFN, FakePath +from test.support import TESTFN, FakePath, AIX, MACOS, MS_WINDOWS TESTFN2 = TESTFN + "2" -MACOS = sys.platform.startswith("darwin") -AIX = sys.platform[:3] == 'aix' + try: import grp import pwd @@ -1585,7 +1584,7 @@ def test_cwd(self): base_dir = os.path.dirname(self.dir) with support.change_cwd(path=self.dir): rv = shutil.which(self.file, path=base_dir) - if sys.platform == "win32": + if MS_WINDOWS: # Windows: current directory implicitly on PATH self.assertEqual(rv, os.path.join(self.curdir, self.file)) else: @@ -1613,7 +1612,7 @@ def test_nonexistent_file(self): rv = shutil.which("foo.exe", path=self.dir) self.assertIsNone(rv) - @unittest.skipUnless(sys.platform == "win32", + @unittest.skipUnless(MS_WINDOWS, "pathext check is Windows-only") def test_pathext_checking(self): # Ask for the file without the ".exe" extension, then ensure that diff --git a/Lib/test/test_signal.py b/Lib/test/test_signal.py index 063b35ca230f59..8e49e14c4d3dbf 100644 --- a/Lib/test/test_signal.py +++ b/Lib/test/test_signal.py @@ -10,6 +10,7 @@ import time import unittest from test import support +from test.support import MS_WINDOWS from test.support.script_helper import assert_python_ok, spawn_python try: import _testcapi @@ -33,7 +34,7 @@ def test_enums(self): self.assertEqual(sys.platform, "win32") -@unittest.skipIf(sys.platform == "win32", "Not valid on Windows") +@unittest.skipIf(MS_WINDOWS, "Not valid on Windows") class PosixTests(unittest.TestCase): def trivial_signal_handler(self, *args): pass @@ -95,7 +96,7 @@ def test_keyboard_interrupt_exit_code(self): # to confirm that our process died via a SIGINT proved too complex. -@unittest.skipUnless(sys.platform == "win32", "Windows specific") +@unittest.skipUnless(MS_WINDOWS, "Windows specific") class WindowsSignalTests(unittest.TestCase): def test_valid_signals(self): @@ -201,7 +202,7 @@ def test_set_wakeup_fd_socket_result(self): # On Windows, files are always blocking and Windows does not provide a # function to test if a socket is in non-blocking mode. - @unittest.skipIf(sys.platform == "win32", "tests specific to POSIX") + @unittest.skipIf(MS_WINDOWS, "tests specific to POSIX") def test_set_wakeup_fd_blocking(self): rfd, wfd = os.pipe() self.addCleanup(os.close, rfd) @@ -220,7 +221,7 @@ def test_set_wakeup_fd_blocking(self): signal.set_wakeup_fd(-1) -@unittest.skipIf(sys.platform == "win32", "Not valid on Windows") +@unittest.skipIf(MS_WINDOWS, "Not valid on Windows") class WakeupSignalTests(unittest.TestCase): @unittest.skipIf(_testcapi is None, 'need _testcapi') def check_wakeup(self, test_body, *signals, ordered=True): @@ -498,7 +499,7 @@ def test_warn_on_full_buffer(self): import sys import time import _testcapi - from test.support import captured_stderr + from test.support import captured_stderr, MS_WINDOWS signum = signal.SIGINT @@ -512,7 +513,7 @@ def handler(signum, frame): read, write = socket.socketpair() # Fill the socketpair buffer - if sys.platform == 'win32': + if MS_WINDOWS: # bpo-34130: On Windows, sometimes non-blocking send fails to fill # the full socketpair buffer, so use a timeout of 50 ms instead. write.settimeout(0.050) @@ -594,7 +595,7 @@ def handler(signum, frame): assert_python_ok('-c', code) -@unittest.skipIf(sys.platform == "win32", "Not valid on Windows") +@unittest.skipIf(MS_WINDOWS, "Not valid on Windows") class SiginterruptTest(unittest.TestCase): def readpipe_interrupted(self, interrupt): @@ -679,7 +680,7 @@ def test_siginterrupt_off(self): self.assertFalse(interrupted) -@unittest.skipIf(sys.platform == "win32", "Not valid on Windows") +@unittest.skipIf(MS_WINDOWS, "Not valid on Windows") class ItimerTest(unittest.TestCase): def setUp(self): self.hndl_called = False @@ -1250,7 +1251,7 @@ def test_sigint(self): with self.assertRaises(KeyboardInterrupt): signal.raise_signal(signal.SIGINT) - @unittest.skipIf(sys.platform != "win32", "Windows specific test") + @unittest.skipUnless(MS_WINDOWS, "Windows specific test") def test_invalid_argument(self): try: SIGHUP = 1 # not supported on win32 diff --git a/Lib/test/test_site.py b/Lib/test/test_site.py index 41c4229919507b..4fbd21580669dc 100644 --- a/Lib/test/test_site.py +++ b/Lib/test/test_site.py @@ -8,7 +8,7 @@ import test.support from test import support from test.support import (captured_stderr, TESTFN, EnvironmentVarGuard, - change_cwd) + change_cwd, MACOS, MS_WINDOWS) import builtins import os import sys @@ -186,7 +186,7 @@ def test__getuserbase(self): self.assertEqual(site._getuserbase(), sysconfig._getuserbase()) def test_get_path(self): - if sys.platform == 'darwin' and sys._framework: + if MACOS and sys._framework: scheme = 'osx_framework_user' else: scheme = os.name + '_user' @@ -470,7 +470,7 @@ def test_setting_help(self): self.assertTrue(hasattr(builtins, "help")) def test_aliasing_mbcs(self): - if sys.platform == "win32": + if MS_WINDOWS: import locale if locale.getdefaultlocale()[1].startswith('cp'): for value in encodings.aliases.aliases.values(): @@ -559,7 +559,7 @@ def test_startup_interactivehook_isolated_explicit(self): self.assertTrue(r, "'__interactivehook__' not added by enablerlcompleter()") -@unittest.skipUnless(sys.platform == 'win32', "only supported on Windows") +@unittest.skipUnless(MS_WINDOWS, "only supported on Windows") class _pthFileTests(unittest.TestCase): def _create_underpth_exe(self, lines): diff --git a/Lib/test/test_smtplib.py b/Lib/test/test_smtplib.py index fdcf6f21925645..5fe3bc967f2908 100644 --- a/Lib/test/test_smtplib.py +++ b/Lib/test/test_smtplib.py @@ -19,12 +19,12 @@ import unittest from test import support, mock_socket -from test.support import HOST, HOSTv4, HOSTv6 +from test.support import HOST, HOSTv4, HOSTv6, MACOS from test.support import threading_setup, threading_cleanup, join_thread from unittest.mock import Mock -if sys.platform == 'darwin': +if MACOS: # select.poll returns a select.POLLHUP at the end of the tests # on darwin, so just ignore it def handle_expt(self): diff --git a/Lib/test/test_socket.py b/Lib/test/test_socket.py index 0094cecb79cca6..7314908e7f6c09 100644 --- a/Lib/test/test_socket.py +++ b/Lib/test/test_socket.py @@ -1,5 +1,6 @@ import unittest from test import support +from test.support import AIX, LINUX, MACOS, MS_WINDOWS import errno import io @@ -40,7 +41,6 @@ MAIN_TIMEOUT = 60.0 VSOCKPORT = 1234 -AIX = platform.system() == "AIX" try: import _socket @@ -1048,7 +1048,7 @@ def testGetServBy(self): # I've ordered this by protocols that have both a tcp and udp # protocol, at least for modern Linuxes. if (sys.platform.startswith(('freebsd', 'netbsd', 'gnukfreebsd')) - or sys.platform in ('linux', 'darwin')): + or LINUX or MACOS): # avoid the 'echo' service on this platform, as there is an # assumption breaking non-standard port/protocol entry services = ('daytime', 'qotd', 'domain') @@ -1077,7 +1077,7 @@ def testGetServBy(self): eq(udpport, port) # Now make sure the lookup by port returns the same service name # Issue #26936: Android getservbyport() is broken. - if not support.is_android: + if not support.ANDROID: eq(socket.getservbyport(port2), service) eq(socket.getservbyport(port, 'tcp'), service) if udpport is not None: @@ -1162,7 +1162,7 @@ def testIPv6toString(self): except ImportError: self.skipTest('could not import needed symbols from socket') - if sys.platform == "win32": + if MS_WINDOWS: try: inet_pton(AF_INET6, '::') except OSError as e: @@ -1252,7 +1252,7 @@ def testStringToIPv6(self): except ImportError: self.skipTest('could not import needed symbols from socket') - if sys.platform == "win32": + if MS_WINDOWS: try: inet_ntop(AF_INET6, b'\x00' * 16) except OSError as e: @@ -1655,9 +1655,7 @@ def test_getaddrinfo_ipv6_scopeid_symbolic(self): self.assertEqual(sockaddr, ('ff02::1de:c0:face:8d', 1234, 0, ifindex)) @unittest.skipUnless(support.IPV6_ENABLED, 'IPv6 required for this test.') - @unittest.skipUnless( - sys.platform == 'win32', - 'Numeric scope id does not work or undocumented') + @unittest.skipUnless(MS_WINDOWS, 'Numeric scope id does not work or undocumented') def test_getaddrinfo_ipv6_scopeid_numeric(self): # Also works on Linux and Mac OS X, but is not documented (?) # Windows, Linux and Max OS X allow nonexistent interface numbers here. @@ -1684,8 +1682,7 @@ def test_getnameinfo_ipv6_scopeid_symbolic(self): self.assertEqual(nameinfo, ('ff02::1de:c0:face:8d%' + test_interface, '1234')) @unittest.skipUnless(support.IPV6_ENABLED, 'IPv6 required for this test.') - @unittest.skipUnless( sys.platform == 'win32', - 'Numeric scope id does not work or undocumented') + @unittest.skipUnless(MS_WINDOWS, 'Numeric scope id does not work or undocumented') def test_getnameinfo_ipv6_scopeid_numeric(self): # Also works on Linux (undocumented), but does not work on Mac OS X # Windows and Linux allow nonexistent interface numbers here. @@ -2742,7 +2739,7 @@ def _testSendmsgTimeout(self): # Linux supports MSG_DONTWAIT when sending, but in general, it # only works when receiving. Could add other platforms if they # support it too. - @skipWithClientIf(sys.platform not in {"linux"}, + @skipWithClientIf(not LINUX, "MSG_DONTWAIT not known to work on this platform when " "sending") def testSendmsgDontWait(self): @@ -3259,7 +3256,7 @@ def testFDPassCMSG_LEN(self): def _testFDPassCMSG_LEN(self): self.createAndSendFDs(1) - @unittest.skipIf(sys.platform == "darwin", "skipping, see issue #12958") + @unittest.skipIf(MACOS, "skipping, see issue #12958") @unittest.skipIf(AIX, "skipping, see issue #22397") @requireAttrs(socket, "CMSG_SPACE") def testFDPassSeparate(self): @@ -3270,7 +3267,7 @@ def testFDPassSeparate(self): maxcmsgs=2) @testFDPassSeparate.client_skip - @unittest.skipIf(sys.platform == "darwin", "skipping, see issue #12958") + @unittest.skipIf(MACOS, "skipping, see issue #12958") @unittest.skipIf(AIX, "skipping, see issue #22397") def _testFDPassSeparate(self): fd0, fd1 = self.newFDs(2) @@ -3283,7 +3280,7 @@ def _testFDPassSeparate(self): array.array("i", [fd1]))]), len(MSG)) - @unittest.skipIf(sys.platform == "darwin", "skipping, see issue #12958") + @unittest.skipIf(MACOS, "skipping, see issue #12958") @unittest.skipIf(AIX, "skipping, see issue #22397") @requireAttrs(socket, "CMSG_SPACE") def testFDPassSeparateMinSpace(self): @@ -3297,7 +3294,7 @@ def testFDPassSeparateMinSpace(self): maxcmsgs=2, ignoreflags=socket.MSG_CTRUNC) @testFDPassSeparateMinSpace.client_skip - @unittest.skipIf(sys.platform == "darwin", "skipping, see issue #12958") + @unittest.skipIf(MACOS, "skipping, see issue #12958") @unittest.skipIf(AIX, "skipping, see issue #22397") def _testFDPassSeparateMinSpace(self): fd0, fd1 = self.newFDs(2) @@ -3321,7 +3318,7 @@ def sendAncillaryIfPossible(self, msg, ancdata): nbytes = self.sendmsgToServer([msg]) self.assertEqual(nbytes, len(msg)) - @unittest.skipIf(sys.platform == "darwin", "see issue #24725") + @unittest.skipIf(MACOS, "see issue #24725") def testFDPassEmpty(self): # Try to pass an empty FD array. Can receive either no array # or an empty array. @@ -5021,7 +5018,7 @@ def test_setblocking_invalidfd(self): sock.setblocking(False) -@unittest.skipUnless(sys.platform == 'linux', 'Linux specific test') +@unittest.skipUnless(LINUX, 'Linux specific test') class TestLinuxAbstractNamespace(unittest.TestCase): UNIX_PATH_MAX = 108 @@ -6044,7 +6041,7 @@ def test_length_restriction(self): sock.bind(("type", "n" * 64)) -@unittest.skipUnless(sys.platform.startswith("win"), "requires Windows") +@unittest.skipUnless(MS_WINDOWS, "requires Windows") class TestMSWindowsTCPFlags(unittest.TestCase): knownTCPFlags = { # available since long time ago diff --git a/Lib/test/test_ssl.py b/Lib/test/test_ssl.py index d48d6e5569fc3e..1cc741a7decb72 100644 --- a/Lib/test/test_ssl.py +++ b/Lib/test/test_ssl.py @@ -3,6 +3,7 @@ import sys import unittest from test import support +from test.support import MS_WINDOWS import socket import select import time @@ -805,7 +806,7 @@ def test_get_default_verify_paths(self): self.assertEqual(paths.cafile, CERTFILE) self.assertEqual(paths.capath, CAPATH) - @unittest.skipUnless(sys.platform == "win32", "Windows specific") + @unittest.skipUnless(MS_WINDOWS, "Windows specific") def test_enum_certificates(self): self.assertTrue(ssl.enum_certificates("CA")) self.assertTrue(ssl.enum_certificates("ROOT")) @@ -830,7 +831,7 @@ def test_enum_certificates(self): serverAuth = "1.3.6.1.5.5.7.3.1" self.assertIn(serverAuth, trust_oids) - @unittest.skipUnless(sys.platform == "win32", "Windows specific") + @unittest.skipUnless(MS_WINDOWS, "Windows specific") def test_enum_crls(self): self.assertTrue(ssl.enum_crls("CA")) self.assertRaises(TypeError, ssl.enum_crls) @@ -1476,7 +1477,7 @@ def test_load_default_certs(self): self.assertRaises(TypeError, ctx.load_default_certs, None) self.assertRaises(TypeError, ctx.load_default_certs, 'SERVER_AUTH') - @unittest.skipIf(sys.platform == "win32", "not-Windows specific") + @unittest.skipIf(MS_WINDOWS, "not-Windows specific") @unittest.skipIf(IS_LIBRESSL, "LibreSSL doesn't support env vars") def test_load_default_certs_env(self): ctx = ssl.SSLContext(ssl.PROTOCOL_TLS_CLIENT) @@ -1486,7 +1487,7 @@ def test_load_default_certs_env(self): ctx.load_default_certs() self.assertEqual(ctx.cert_store_stats(), {"crl": 0, "x509": 1, "x509_ca": 0}) - @unittest.skipUnless(sys.platform == "win32", "Windows specific") + @unittest.skipUnless(MS_WINDOWS, "Windows specific") @unittest.skipIf(hasattr(sys, "gettotalrefcount"), "Debug build does not share environment between CRTs") def test_load_default_certs_env_windows(self): ctx = ssl.SSLContext(ssl.PROTOCOL_TLS_CLIENT) diff --git a/Lib/test/test_stat.py b/Lib/test/test_stat.py index 17443bed0738b5..45abfeb02ba8e3 100644 --- a/Lib/test/test_stat.py +++ b/Lib/test/test_stat.py @@ -1,8 +1,7 @@ -import unittest import os import socket import sys -from test.support import (TESTFN, import_fresh_module, +from test.support import (TESTFN, import_fresh_module, MS_WINDOWS, skip_unless_bind_unix_socket) c_stat = import_fresh_module('stat', fresh=['_stat']) @@ -219,7 +218,7 @@ def test_module_attributes(self): self.assertTrue(callable(func)) self.assertEqual(func(0), 0) - @unittest.skipUnless(sys.platform == "win32", + @unittest.skipUnless(MS_WINDOWS, "FILE_ATTRIBUTE_* constants are Win32 specific") def test_file_attribute_constants(self): for key, value in sorted(self.file_attributes.items()): diff --git a/Lib/test/test_strftime.py b/Lib/test/test_strftime.py index ec305e54ff24f0..f06e72addece7b 100644 --- a/Lib/test/test_strftime.py +++ b/Lib/test/test_strftime.py @@ -6,6 +6,7 @@ import sys import re from test import support +from test.support import AIX, MS_WINDOWS import time import unittest @@ -187,8 +188,8 @@ class Y1900Tests(unittest.TestCase): def test_y_before_1900(self): # Issue #13674, #19634 t = (1899, 1, 1, 0, 0, 0, 0, 0, 0) - if (sys.platform == "win32" - or sys.platform.startswith(("aix", "sunos", "solaris"))): + if (MS_WINDOWS or AIX + or sys.platform.startswith(("sunos", "solaris"))): with self.assertRaises(ValueError): time.strftime("%y", t) else: diff --git a/Lib/test/test_strptime.py b/Lib/test/test_strptime.py index 623da401eee4ff..64bf539efb3af6 100644 --- a/Lib/test/test_strptime.py +++ b/Lib/test/test_strptime.py @@ -7,6 +7,7 @@ import os import sys from test import support +from test.support import AIX from datetime import date as datetime_date import _strptime @@ -521,7 +522,7 @@ def test_day_of_week_calculation(self): "Calculation of day of the week failed; " "%s != %s" % (result.tm_wday, self.time_tuple.tm_wday)) - if support.is_android: + if support.ANDROID: # Issue #26929: strftime() on Android incorrectly formats %V or %G for # the last or the first incomplete week in a year. _ymd_excluded = ((1905, 1, 1), (1906, 12, 31), (2008, 12, 29), @@ -531,8 +532,7 @@ def test_day_of_week_calculation(self): _ymd_excluded = () _formats_excluded = () - @unittest.skipIf(sys.platform.startswith('aix'), - 'bpo-29972: broken test on AIX') + @unittest.skipIf(AIX, 'bpo-29972: broken test on AIX') def test_week_of_year_and_day_of_week_calculation(self): # Should be able to infer date if given year, week of year (%U or %W) # and day of the week diff --git a/Lib/test/test_subprocess.py b/Lib/test/test_subprocess.py index fca3ed62099bde..c8b722984f0c97 100644 --- a/Lib/test/test_subprocess.py +++ b/Lib/test/test_subprocess.py @@ -18,7 +18,7 @@ import threading import gc import textwrap -from test.support import FakePath +from test.support import FakePath, MACOS, MS_WINDOWS try: import ctypes @@ -35,13 +35,11 @@ if support.PGO: raise unittest.SkipTest("test is not helpful for PGO") -mswindows = (sys.platform == "win32") - # # Depends on the following external programs: Python # -if mswindows: +if MS_WINDOWS: SETBINARY = ('import msvcrt; msvcrt.setmode(sys.stdout.fileno(), ' 'os.O_BINARY);') else: @@ -326,7 +324,7 @@ def test_executable_takes_precedence(self): self._assert_python, pre_args, executable=NONEXISTING_CMD[0]) - @unittest.skipIf(mswindows, "executable argument replaces shell") + @unittest.skipIf(MS_WINDOWS, "executable argument replaces shell") def test_executable_replaces_shell(self): # Check that the executable argument replaces the default shell # when shell=True. @@ -390,7 +388,7 @@ def test_cwd_with_pathlike(self): temp_dir = self._normalize_cwd(temp_dir) self._assert_cwd(temp_dir, sys.executable, cwd=FakePath(temp_dir)) - @unittest.skipIf(mswindows, "pending resolution of issue #15533") + @unittest.skipIf(MS_WINDOWS, "pending resolution of issue #15533") def test_cwd_with_relative_arg(self): # Check that Popen looks for args[0] relative to cwd if args[0] # is relative. @@ -406,7 +404,7 @@ def test_cwd_with_relative_arg(self): python_dir = self._normalize_cwd(python_dir) self._assert_cwd(python_dir, rel_python, cwd=python_dir) - @unittest.skipIf(mswindows, "pending resolution of issue #15533") + @unittest.skipIf(MS_WINDOWS, "pending resolution of issue #15533") def test_cwd_with_relative_executable(self): # Check that Popen looks for executable relative to cwd if executable # is relative (and that executable takes precedence over args[0]). @@ -659,8 +657,7 @@ def test_env(self): # Windows requires at least the SYSTEMROOT environment variable to start # Python - @unittest.skipIf(sys.platform == 'win32', - 'cannot test an empty env on Windows') + @unittest.skipIf(MS_WINDOWS, 'cannot test an empty env on Windows') @unittest.skipIf(sysconfig.get_config_var('Py_ENABLE_SHARED') == 1, 'The Python shared library cannot be loaded ' 'with an empty environment.') @@ -1035,7 +1032,7 @@ def test_communicate_errors(self): def test_no_leaking(self): # Make sure we leak no resources - if not mswindows: + if not MS_WINDOWS: max_handles = 1026 # too much for most UNIX systems else: max_handles = 2050 # too much for (at least some) Windows setups @@ -1272,7 +1269,7 @@ def kill_proc_timer_thread(): t = threading.Timer(0.2, kill_proc_timer_thread) t.start() - if mswindows: + if MS_WINDOWS: expected_errorcode = 1 else: # Should be -9 because of the proc.kill() from the thread. @@ -1393,13 +1390,13 @@ def test_failed_child_execute_fd_leak(self): fds_after_exception = os.listdir(fd_directory) self.assertEqual(fds_before_popen, fds_after_exception) - @unittest.skipIf(mswindows, "behavior currently not supported on Windows") + @unittest.skipIf(MS_WINDOWS, "behavior currently not supported on Windows") def test_file_not_found_includes_filename(self): with self.assertRaises(FileNotFoundError) as c: subprocess.call(['/opt/nonexistent_binary', 'with', 'some', 'args']) self.assertEqual(c.exception.filename, '/opt/nonexistent_binary') - @unittest.skipIf(mswindows, "behavior currently not supported on Windows") + @unittest.skipIf(MS_WINDOWS, "behavior currently not supported on Windows") def test_file_not_found_with_bad_cwd(self): with self.assertRaises(FileNotFoundError) as c: subprocess.Popen(['exit', '0'], cwd='/some/nonexistent/directory') @@ -1561,7 +1558,7 @@ def test_stderr_with_capture_output_arg(self): self.assertIn('capture_output', c.exception.args[0]) -@unittest.skipIf(mswindows, "POSIX specific tests") +@unittest.skipIf(MS_WINDOWS, "POSIX specific tests") class POSIXProcessTestCase(BaseTestCase): def setUp(self): @@ -1848,8 +1845,7 @@ def raise_runtime_error(): if not enabled: gc.disable() - @unittest.skipIf( - sys.platform == 'darwin', 'setrlimit() seems to fail on OS X') + @unittest.skipIf(MACOS, 'setrlimit() seems to fail on OS X') def test_preexec_fork_failure(self): # The internal code did not preserve the previous exception when # re-enabling garbage collection @@ -2870,7 +2866,7 @@ def test_stopped(self): self.assertEqual(returncode, -3) -@unittest.skipUnless(mswindows, "Windows specific tests") +@unittest.skipUnless(MS_WINDOWS, "Windows specific tests") class Win32ProcessTestCase(BaseTestCase): def test_startupinfo(self): @@ -3202,7 +3198,7 @@ def test_getoutput(self): dir = tempfile.mkdtemp() name = os.path.join(dir, "foo") status, output = subprocess.getstatusoutput( - ("type " if mswindows else "cat ") + name) + ("type " if MS_WINDOWS else "cat ") + name) self.assertNotEqual(status, 0) finally: if dir is not None: @@ -3236,7 +3232,7 @@ def tearDown(self): ProcessTestCase.tearDown(self) -@unittest.skipUnless(mswindows, "Windows-specific tests") +@unittest.skipUnless(MS_WINDOWS, "Windows-specific tests") class CommandsWithSpaces (BaseTestCase): def setUp(self): diff --git a/Lib/test/test_sundry.py b/Lib/test/test_sundry.py index 2accad1aeebd4f..fe8a342e0a4631 100644 --- a/Lib/test/test_sundry.py +++ b/Lib/test/test_sundry.py @@ -1,7 +1,6 @@ """Do a minimal test of all the modules that aren't otherwise tested.""" import importlib import platform -import sys from test import support import unittest @@ -26,7 +25,7 @@ def test_untested_modules_can_be_imported(self): import distutils.unixccompiler import distutils.command.bdist_dumb - if sys.platform.startswith('win') and not platform.win32_is_iot(): + if support.MS_WINDOWS and not platform.win32_is_iot(): import distutils.command.bdist_msi import distutils.command.bdist import distutils.command.bdist_rpm diff --git a/Lib/test/test_sys.py b/Lib/test/test_sys.py index dfe63b1aade2eb..ae8990af1b1676 100644 --- a/Lib/test/test_sys.py +++ b/Lib/test/test_sys.py @@ -1,4 +1,5 @@ import unittest, test.support +from test.support import MACOS, MS_WINDOWS from test.support.script_helper import assert_python_ok, assert_python_failure import sys, io, os import struct @@ -486,7 +487,7 @@ def test_attributes(self): self.assertTrue(vi > (1,0,0)) self.assertIsInstance(sys.float_repr_style, str) self.assertIn(sys.float_repr_style, ('short', 'legacy')) - if not sys.platform.startswith('win'): + if not MS_WINDOWS: self.assertIsInstance(sys.abiflags, str) def test_thread_info(self): @@ -647,7 +648,7 @@ def check_fsencoding(self, fs_encoding, expected=None): def test_getfilesystemencoding(self): fs_encoding = sys.getfilesystemencoding() - if sys.platform == 'darwin': + if MACOS: expected = 'utf-8' else: expected = None diff --git a/Lib/test/test_sysconfig.py b/Lib/test/test_sysconfig.py index 1b1929885edd6b..1eca2f459f7127 100644 --- a/Lib/test/test_sysconfig.py +++ b/Lib/test/test_sysconfig.py @@ -6,7 +6,8 @@ from copy import copy from test.support import (import_module, TESTFN, unlink, check_warnings, - captured_stdout, skip_unless_symlink, change_cwd) + captured_stdout, skip_unless_symlink, change_cwd, + LINUX, MACOS, MS_WINDOWS) import sysconfig from sysconfig import (get_paths, get_platform, get_config_vars, @@ -236,7 +237,7 @@ def test_symlink(self): # On Windows, the EXE needs to know where pythonXY.dll is at so we have # to add the directory to the path. env = None - if sys.platform == "win32": + if MS_WINDOWS: env = {k.upper(): os.environ[k] for k in os.environ} env["PATH"] = "{};{}".format( os.path.dirname(sys.executable), env.get("PATH", "")) @@ -294,14 +295,14 @@ def test_main(self): _main() self.assertTrue(len(output.getvalue().split('\n')) > 0) - @unittest.skipIf(sys.platform == "win32", "Does not apply to Windows") + @unittest.skipIf(MS_WINDOWS, "Does not apply to Windows") def test_ldshared_value(self): ldflags = sysconfig.get_config_var('LDFLAGS') ldshared = sysconfig.get_config_var('LDSHARED') self.assertIn(ldflags, ldshared) - @unittest.skipUnless(sys.platform == "darwin", "test only relevant on MacOSX") + @unittest.skipUnless(MACOS, "test only relevant on MacOSX") def test_platform_in_subprocess(self): my_platform = sysconfig.get_platform() @@ -391,8 +392,7 @@ def test_SO_in_vars(self): self.assertIsNotNone(vars['SO']) self.assertEqual(vars['SO'], vars['EXT_SUFFIX']) - @unittest.skipUnless(sys.platform == 'linux' and - hasattr(sys.implementation, '_multiarch'), + @unittest.skipUnless(LINUX and hasattr(sys.implementation, '_multiarch'), 'multiarch-specific test') def test_triplet_in_ext_suffix(self): ctypes = import_module('ctypes') @@ -409,15 +409,14 @@ def test_triplet_in_ext_suffix(self): else: # 8 byte pointer size self.assertTrue(suffix.endswith('x86_64-linux-gnu.so'), suffix) - @unittest.skipUnless(sys.platform == 'darwin', 'OS X-specific test') + @unittest.skipUnless(MACOS, 'OS X-specific test') def test_osx_ext_suffix(self): suffix = sysconfig.get_config_var('EXT_SUFFIX') self.assertTrue(suffix.endswith('-darwin.so'), suffix) class MakefileTests(unittest.TestCase): - @unittest.skipIf(sys.platform.startswith('win'), - 'Test is not Windows compatible') + @unittest.skipIf(MS_WINDOWS, 'Test is not Windows compatible') def test_get_makefile_filename(self): makefile = sysconfig.get_makefile_filename() self.assertTrue(os.path.isfile(makefile), makefile) diff --git a/Lib/test/test_tarfile.py b/Lib/test/test_tarfile.py index 7e32cbccd6c56d..b2130c982970db 100644 --- a/Lib/test/test_tarfile.py +++ b/Lib/test/test_tarfile.py @@ -11,7 +11,7 @@ import tarfile from test import support -from test.support import script_helper +from test.support import script_helper, LINUX, MS_WINDOWS # Check for our compression modules. try: @@ -562,7 +562,7 @@ def test_extractall(self): tar.extractall(DIR, directories) for tarinfo in directories: path = os.path.join(DIR, tarinfo.name) - if sys.platform != "win32": + if not MS_WINDOWS: # Win32 has no support for fine grained permissions. self.assertEqual(tarinfo.mode & 0o777, os.stat(path).st_mode & 0o777) @@ -591,7 +591,7 @@ def test_extract_directory(self): tar.extract(tarinfo, path=DIR) extracted = os.path.join(DIR, dirtype) self.assertEqual(os.path.getmtime(extracted), tarinfo.mtime) - if sys.platform != "win32": + if not MS_WINDOWS: self.assertEqual(os.stat(extracted).st_mode & 0o777, 0o755) finally: support.rmtree(DIR) @@ -974,7 +974,7 @@ def _fs_supports_holes(): # # The function returns False if page size is larger than 4 KiB. # For example, ppc64 uses pages of 64 KiB. - if sys.platform.startswith("linux"): + if LINUX: # Linux evidentially has 512 byte st_blocks units. name = os.path.join(TEMPDIR, "sparse-test") with open(name, "wb") as fobj: @@ -1334,7 +1334,7 @@ def test_pathnames(self): self._test_pathname("foo" + os.sep + os.sep, "foo", dir=True) def test_abs_pathnames(self): - if sys.platform == "win32": + if MS_WINDOWS: self._test_pathname("C:\\foo", "foo") else: self._test_pathname("/foo", "foo") @@ -1404,7 +1404,7 @@ def test_stream_padding(self): self.assertEqual(data.count(b"\0"), tarfile.RECORDSIZE, "incorrect zero padding") - @unittest.skipUnless(sys.platform != "win32" and hasattr(os, "umask"), + @unittest.skipUnless(not MS_WINDOWS and hasattr(os, "umask"), "Missing umask implementation") def test_file_mode(self): # Test for issue #8464: Create files with correct diff --git a/Lib/test/test_tcl.py b/Lib/test/test_tcl.py index 80f1668bcecab8..c12f694ba7b501 100644 --- a/Lib/test/test_tcl.py +++ b/Lib/test/test_tcl.py @@ -226,7 +226,7 @@ def testPackageRequireException(self): tcl = self.interp self.assertRaises(TclError,tcl.eval,'package require DNE') - @unittest.skipUnless(sys.platform == 'win32', 'Requires Windows') + @unittest.skipUnless(support.MS_WINDOWS, 'Requires Windows') def testLoadWithUNC(self): # Build a UNC path from the regular path. # Something like diff --git a/Lib/test/test_tempfile.py b/Lib/test/test_tempfile.py index 489141d6ad726a..9e1b86d259a08e 100644 --- a/Lib/test/test_tempfile.py +++ b/Lib/test/test_tempfile.py @@ -14,7 +14,7 @@ import unittest from test import support -from test.support import script_helper +from test.support import script_helper, MS_WINDOWS has_textmode = (tempfile._text_openflags != tempfile._bin_openflags) @@ -434,7 +434,7 @@ def test_file_mode(self): file = self.do_create() mode = stat.S_IMODE(os.stat(file.name).st_mode) expected = 0o600 - if sys.platform == 'win32': + if MS_WINDOWS: # There's no distinction among 'user', 'group' and 'world'; # replicate the 'user' bits. user = expected >> 6 @@ -468,7 +468,7 @@ def test_noinherit(self): # On Windows a spawn* /path/ with embedded spaces shouldn't be quoted, # but an arg with embedded spaces should be decorated with double # quotes on each end - if sys.platform == 'win32': + if MS_WINDOWS: decorated = '"%s"' % sys.executable tester = '"%s"' % tester else: @@ -739,7 +739,7 @@ def test_mode(self): mode = stat.S_IMODE(os.stat(dir).st_mode) mode &= 0o777 # Mask off sticky bits inherited from /tmp expected = 0o700 - if sys.platform == 'win32': + if MS_WINDOWS: # There's no distinction among 'user', 'group' and 'world'; # replicate the 'user' bits. user = expected >> 6 diff --git a/Lib/test/test_threading.py b/Lib/test/test_threading.py index 8c8cc128b0513b..f68369ce874a1e 100644 --- a/Lib/test/test_threading.py +++ b/Lib/test/test_threading.py @@ -3,7 +3,7 @@ """ import test.support -from test.support import (verbose, import_module, cpython_only, +from test.support import (verbose, import_module, cpython_only, MACOS, requires_type_collecting) from test.support.script_helper import assert_python_ok, assert_python_failure @@ -976,7 +976,7 @@ def test_releasing_unacquired_lock(self): lock = threading.Lock() self.assertRaises(RuntimeError, lock.release) - @unittest.skipUnless(sys.platform == 'darwin' and test.support.python_is_optimized(), + @unittest.skipUnless(MACOS and test.support.python_is_optimized(), 'test macosx problem') def test_recursion_limit(self): # Issue 9670 diff --git a/Lib/test/test_threadsignals.py b/Lib/test/test_threadsignals.py index eeacd3698cb138..a1fd870eaf3106 100644 --- a/Lib/test/test_threadsignals.py +++ b/Lib/test/test_threadsignals.py @@ -5,10 +5,11 @@ import os import sys from test import support +from test.support import LINUX, MS_WINDOWS import _thread as thread import time -if (sys.platform[:3] == 'win'): +if MS_WINDOWS: raise unittest.SkipTest("Can't test signal on %s" % sys.platform) process_pid = os.getpid() @@ -78,8 +79,7 @@ def alarm_interrupt(self, sig, frame): @unittest.skipIf(USING_PTHREAD_COND, 'POSIX condition variables cannot be interrupted') - @unittest.skipIf(sys.platform.startswith('linux') and - not sys.thread_info.version, + @unittest.skipIf(LINUX and not sys.thread_info.version, 'Issue 34004: musl does not allow interruption of locks ' 'by signals.') # Issue #20564: sem_timedwait() cannot be interrupted on OpenBSD @@ -109,8 +109,7 @@ def test_lock_acquire_interruption(self): @unittest.skipIf(USING_PTHREAD_COND, 'POSIX condition variables cannot be interrupted') - @unittest.skipIf(sys.platform.startswith('linux') and - not sys.thread_info.version, + @unittest.skipIf(LINUX and not sys.thread_info.version, 'Issue 34004: musl does not allow interruption of locks ' 'by signals.') # Issue #20564: sem_timedwait() cannot be interrupted on OpenBSD diff --git a/Lib/test/test_time.py b/Lib/test/test_time.py index f790d43b6f4746..9679639fa3ffee 100644 --- a/Lib/test/test_time.py +++ b/Lib/test/test_time.py @@ -1,4 +1,5 @@ from test import support +from test.support import LINUX, MS_WINDOWS import decimal import enum import locale @@ -486,7 +487,7 @@ def test_process_time(self): def test_thread_time(self): if not hasattr(time, 'thread_time'): - if sys.platform.startswith(('linux', 'win')): + if LINUX or MS_WINDOWS: self.fail("time.thread_time() should be available on %r" % (sys.platform,)) else: @@ -929,7 +930,7 @@ def timeval_converter(ns): us = us_converter(ns) return divmod(us, SEC_TO_US) - if sys.platform == 'win32': + if MS_WINDOWS: from _testcapi import LONG_MIN, LONG_MAX # On Windows, timeval.tv_sec type is a C long diff --git a/Lib/test/test_tix.py b/Lib/test/test_tix.py index e6ea3d07444ce7..983a9ec62567db 100644 --- a/Lib/test/test_tix.py +++ b/Lib/test/test_tix.py @@ -17,7 +17,7 @@ def setUp(self): try: self.root = tix.Tk() except TclError: - if sys.platform.startswith('win'): + if support.MS_WINDOWS: self.fail('Tix should always be available on Windows') self.skipTest('Tix not available') else: diff --git a/Lib/test/test_tools/test_sundry.py b/Lib/test/test_tools/test_sundry.py index f5fed01491e3f6..7bad03256306a1 100644 --- a/Lib/test/test_tools/test_sundry.py +++ b/Lib/test/test_tools/test_sundry.py @@ -45,7 +45,7 @@ def test_sundry(self): # Unload all modules loaded in this test support.modules_cleanup(*old_modules) - @unittest.skipIf(sys.platform != "win32", "Windows-only test") + @unittest.skipUnless(support.MS_WINDOWS, "Windows-only test") def test_sundry_windows(self): for name in self.windows_only: import_tool(name) diff --git a/Lib/test/test_unicode.py b/Lib/test/test_unicode.py index 36b72e40c7e419..ab95a6412d7f2b 100644 --- a/Lib/test/test_unicode.py +++ b/Lib/test/test_unicode.py @@ -14,6 +14,7 @@ import unittest import warnings from test import support, string_tests +from test.support import JYTHON # Error handling (bad decoder return) def search_function(encoding): @@ -81,7 +82,7 @@ def test_literals(self): self.assertNotEqual(r"\u0020", " ") def test_ascii(self): - if not sys.platform.startswith('java'): + if not support.JYTHON: # Test basic sanity of repr() self.assertEqual(ascii('abc'), "'abc'") self.assertEqual(ascii('ab\\c'), "'ab\\\\c'") @@ -123,7 +124,7 @@ def __repr__(self): self.assertRaises(TypeError, ascii, WrongRepr()) def test_repr(self): - if not sys.platform.startswith('java'): + if not support.JYTHON: # Test basic sanity of repr() self.assertEqual(repr('abc'), "'abc'") self.assertEqual(repr('ab\\c'), "'ab\\\\c'") @@ -584,7 +585,7 @@ def test_islower(self): def test_isupper(self): super().test_isupper() - if not sys.platform.startswith('java'): + if not support.JYTHON: self.checkequalnofix(False, '\u1FFc', 'isupper') self.assertTrue('\u2167'.isupper()) self.assertFalse('\u2177'.isupper()) @@ -1344,7 +1345,7 @@ def test_formatting(self): self.assertEqual("%s, %s, %i, %f, %5.2f" % ("abc", "abc", -1, -2, 3.5), 'abc, abc, -1, -2.000000, 3.50') self.assertEqual("%s, %s, %i, %f, %5.2f" % ("abc", "abc", -1, -2, 3.57), 'abc, abc, -1, -2.000000, 3.57') self.assertEqual("%s, %s, %i, %f, %5.2f" % ("abc", "abc", -1, -2, 1003.57), 'abc, abc, -1, -2.000000, 1003.57') - if not sys.platform.startswith('java'): + if not support.JYTHON: self.assertEqual("%r, %r" % (b"abc", "abc"), "b'abc', 'abc'") self.assertEqual("%r" % ("\u1234",), "'\u1234'") self.assertEqual("%a" % ("\u1234",), "'\\u1234'") @@ -1537,7 +1538,7 @@ def __str__(self): # unicode(obj, encoding, error) tests (this maps to # PyUnicode_FromEncodedObject() at C level) - if not sys.platform.startswith('java'): + if not support.JYTHON: self.assertRaises( TypeError, str, @@ -1551,7 +1552,7 @@ def __str__(self): 'strings are decoded to unicode' ) - if not sys.platform.startswith('java'): + if not support.JYTHON: self.assertEqual( str( memoryview(b'character buffers are decoded to unicode'), diff --git a/Lib/test/test_unicode_file_functions.py b/Lib/test/test_unicode_file_functions.py index 1cd0d621cd4b3a..d61090293a18af 100644 --- a/Lib/test/test_unicode_file_functions.py +++ b/Lib/test/test_unicode_file_functions.py @@ -6,6 +6,7 @@ import warnings from unicodedata import normalize from test import support +from test.support import MACOS, MS_WINDOWS filenames = [ '1_abc', @@ -27,7 +28,7 @@ # these normal forms. For example, HFS Plus uses a variant of Normal Form D # in which U+2000 through U+2FFF, U+F900 through U+FAFF, and U+2F800 through # U+2FAFF are not decomposed." -if sys.platform != 'darwin': +if not MACOS: filenames.extend([ # Specific code points: NFC(fn), NFD(fn), NFKC(fn) and NFKD(fn) all different '11_\u0385\u03d3\u03d4', @@ -103,7 +104,7 @@ def test_failures(self): self._apply_failure(os.remove, name) self._apply_failure(os.listdir, name) - if sys.platform == 'win32': + if MS_WINDOWS: # Windows is lunatic. Issue #13366. _listdir_failure = NotADirectoryError, FileNotFoundError else: @@ -121,7 +122,7 @@ def test_open(self): # NFD (a variant of Unicode NFD form). Normalize the filename to NFC, NFKC, # NFKD in Python is useless, because darwin will normalize it later and so # open(), os.stat(), etc. don't raise any exception. - @unittest.skipIf(sys.platform == 'darwin', 'irrelevant test on Mac OS X') + @unittest.skipIf(MACOS, 'irrelevant test on Mac OS X') def test_normalize(self): files = set(self.files) others = set() @@ -139,7 +140,7 @@ def test_normalize(self): # Skip the test on darwin, because darwin uses a normalization different # than Python NFD normalization: filenames are different even if we use # Python NFD normalization. - @unittest.skipIf(sys.platform == 'darwin', 'irrelevant test on Mac OS X') + @unittest.skipIf(MACOS, 'irrelevant test on Mac OS X') def test_listdir(self): sf0 = set(self.files) with warnings.catch_warnings(): diff --git a/Lib/test/test_urllib.py b/Lib/test/test_urllib.py index f9b2799d25bfd0..3224e779d73f1f 100644 --- a/Lib/test/test_urllib.py +++ b/Lib/test/test_urllib.py @@ -1420,7 +1420,7 @@ def test_quoting(self): "url2pathname() failed; %s != %s" % (expect, result)) - @unittest.skipUnless(sys.platform == 'win32', + @unittest.skipUnless(support.MS_WINDOWS, 'test specific to the urllib.url2path function.') def test_ntpath(self): given = ('/C:/', '///C:/', '/C|//') diff --git a/Lib/test/test_urllib2.py b/Lib/test/test_urllib2.py index c6d275e16b097f..2beddfecc3567a 100644 --- a/Lib/test/test_urllib2.py +++ b/Lib/test/test_urllib2.py @@ -1,6 +1,7 @@ import unittest from test import support from test import test_urllib +from test.support import MACOS import os import io @@ -1421,7 +1422,7 @@ def test_proxy_https_proxy_authorization(self): self.assertEqual(req.host, "proxy.example.com:3128") self.assertEqual(req.get_header("Proxy-authorization"), "FooBar") - @unittest.skipUnless(sys.platform == 'darwin', "only relevant for OSX") + @unittest.skipUnless(MACOS, "only relevant for OSX") def test_osx_proxy_bypass(self): bypass = { 'exclude_simple': False, diff --git a/Lib/test/test_utf8_mode.py b/Lib/test/test_utf8_mode.py index bdb93457cfc405..08b0a1808f5f18 100644 --- a/Lib/test/test_utf8_mode.py +++ b/Lib/test/test_utf8_mode.py @@ -7,10 +7,10 @@ import textwrap import unittest from test import support +from test.support import AIX, ANDROID, MACOS, MS_WINDOWS from test.support.script_helper import assert_python_ok, assert_python_failure -MS_WINDOWS = (sys.platform == 'win32') POSIX_LOCALES = ('C', 'POSIX') VXWORKS = (sys.platform == "vxworks") @@ -225,9 +225,9 @@ def check(utf8_opt, expected, **kw): with self.subTest(LC_ALL=loc): check('utf8', [arg_utf8], LC_ALL=loc) - if sys.platform == 'darwin' or support.is_android or VXWORKS: + if MACOS or ANDROID or VXWORKS: c_arg = arg_utf8 - elif sys.platform.startswith("aix"): + elif AIX: c_arg = arg.decode('iso-8859-1') else: c_arg = arg_ascii diff --git a/Lib/test/test_venv.py b/Lib/test/test_venv.py index 6822d567e42b58..7d5630848e1989 100644 --- a/Lib/test/test_venv.py +++ b/Lib/test/test_venv.py @@ -14,7 +14,8 @@ import sys import tempfile from test.support import (captured_stdout, captured_stderr, requires_zlib, - can_symlink, EnvironmentVarGuard, rmtree) + can_symlink, EnvironmentVarGuard, rmtree, + MACOS, MS_WINDOWS) import threading import unittest import venv @@ -94,8 +95,8 @@ def test_defaults(self): self.isdir(*self.lib) # Issue 21197 p = self.get_env_file('lib64') - conditions = ((struct.calcsize('P') == 8) and (os.name == 'posix') and - (sys.platform != 'darwin')) + conditions = ((struct.calcsize('P') == 8) + and (os.name == 'posix') and not MACOS) if conditions: self.assertTrue(os.path.islink(p)) else: @@ -153,7 +154,7 @@ def test_prefixes(self): out, err = check_output(cmd) self.assertEqual(out.strip(), expected.encode()) - if sys.platform == 'win32': + if MS_WINDOWS: ENV_SUBDIRS = ( ('Scripts',), ('Include',), diff --git a/Lib/test/test_wait4.py b/Lib/test/test_wait4.py index 3e6a79df463cb4..15582f28d1f022 100644 --- a/Lib/test/test_wait4.py +++ b/Lib/test/test_wait4.py @@ -6,7 +6,7 @@ import sys import unittest from test.fork_wait import ForkWait -from test.support import reap_children, get_attribute +from test.support import reap_children, get_attribute, AIX # If either of these do not exist, skip this test. get_attribute(os, 'fork') @@ -16,7 +16,7 @@ class Wait4Test(ForkWait): def wait_impl(self, cpid): option = os.WNOHANG - if sys.platform.startswith('aix'): + if AIX: # Issue #11185: wait4 is broken on AIX and will always return 0 # with WNOHANG. option = 0 diff --git a/Lib/test/test_winconsoleio.py b/Lib/test/test_winconsoleio.py index a78fa4d7d919ff..894659887304cd 100644 --- a/Lib/test/test_winconsoleio.py +++ b/Lib/test/test_winconsoleio.py @@ -7,8 +7,9 @@ import tempfile import unittest from test import support +from test.support import MS_WINDOWS -if sys.platform != 'win32': +if not MS_WINDOWS: raise unittest.SkipTest("test only relevant on win32") from _testconsole import write_input diff --git a/Lib/test/test_zipapp.py b/Lib/test/test_zipapp.py index 73bddc79c17ab6..8119d29aa18a6a 100644 --- a/Lib/test/test_zipapp.py +++ b/Lib/test/test_zipapp.py @@ -8,7 +8,7 @@ import unittest import zipapp import zipfile -from test.support import requires_zlib +from test.support import requires_zlib, MS_WINDOWS from unittest.mock import patch @@ -299,8 +299,7 @@ def test_content_of_copied_archive(self): self.assertEqual(set(z.namelist()), {'__main__.py'}) # (Unix only) tests that archives with shebang lines are made executable - @unittest.skipIf(sys.platform == 'win32', - 'Windows does not support an executable bit') + @unittest.skipIf(MS_WINDOWS, 'Windows does not support an executable bit') def test_shebang_is_executable(self): # Test that an archive with a shebang line is made executable. source = self.tmpdir / 'source' @@ -310,8 +309,7 @@ def test_shebang_is_executable(self): zipapp.create_archive(str(source), str(target), interpreter='python') self.assertTrue(target.stat().st_mode & stat.S_IEXEC) - @unittest.skipIf(sys.platform == 'win32', - 'Windows does not support an executable bit') + @unittest.skipIf(MS_WINDOWS, 'Windows does not support an executable bit') def test_no_shebang_is_not_executable(self): # Test that an archive with no shebang line is not made executable. source = self.tmpdir / 'source' diff --git a/Misc/NEWS.d/next/Tests/2019-04-15-14-48-48.bpo-36624.yjmwEK.rst b/Misc/NEWS.d/next/Tests/2019-04-15-14-48-48.bpo-36624.yjmwEK.rst new file mode 100644 index 00000000000000..fb9014fb9f4e56 --- /dev/null +++ b/Misc/NEWS.d/next/Tests/2019-04-15-14-48-48.bpo-36624.yjmwEK.rst @@ -0,0 +1,4 @@ +Add constants in Lib/test/support to support platform determination. +From platform.system() determine AIX, LINUX, MACOS, WINDOWS. +From sys determine ANDROID (was is_android) and JYTHON (was is_jython). +Patch by M. Felt. From 2970e8b2dd6cf40d353e331aafe4f5b4b80da11b Mon Sep 17 00:00:00 2001 From: Tal Einat Date: Wed, 29 May 2019 11:09:23 +0300 Subject: [PATCH 3/4] move constant definitions after imports and __all__ --- Lib/test/support/__init__.py | 18 ++++++++++-------- 1 file changed, 10 insertions(+), 8 deletions(-) diff --git a/Lib/test/support/__init__.py b/Lib/test/support/__init__.py index 05bf71533c0656..2079c83eb0770f 100644 --- a/Lib/test/support/__init__.py +++ b/Lib/test/support/__init__.py @@ -36,14 +36,6 @@ import urllib.error import warnings -ANDROID = hasattr(sys, 'getandroidapilevel') -JYTHON = sys.platform.startswith('java') - -AIX = platform.system() == 'AIX' -LINUX = platform.system() == 'Linux' -MACOS = platform.system() == 'Darwin' -MS_WINDOWS = platform.system() == 'Windows' - from .testresult import get_test_runner try: @@ -126,6 +118,16 @@ "run_with_tz", "PGO", "missing_compiler_executable", "fd_count", ] + +ANDROID = hasattr(sys, 'getandroidapilevel') +JYTHON = sys.platform.startswith('java') + +AIX = platform.system() == 'AIX' +LINUX = platform.system() == 'Linux' +MACOS = platform.system() == 'Darwin' +MS_WINDOWS = platform.system() == 'Windows' + + class Error(Exception): """Base class for regression test exceptions.""" From 1c5e8b6fd45a9ee69d3a307cf9f1dc11a61848e8 Mon Sep 17 00:00:00 2001 From: Tal Einat Date: Wed, 29 May 2019 11:57:45 +0300 Subject: [PATCH 4/4] two small fixes for tests broken by previous commits --- Lib/test/test_stat.py | 1 + Lib/test/test_subprocess.py | 6 +++--- 2 files changed, 4 insertions(+), 3 deletions(-) diff --git a/Lib/test/test_stat.py b/Lib/test/test_stat.py index 45abfeb02ba8e3..fc5acb63c531ff 100644 --- a/Lib/test/test_stat.py +++ b/Lib/test/test_stat.py @@ -1,3 +1,4 @@ +import unittest import os import socket import sys diff --git a/Lib/test/test_subprocess.py b/Lib/test/test_subprocess.py index c8b722984f0c97..f913ead839b77e 100644 --- a/Lib/test/test_subprocess.py +++ b/Lib/test/test_subprocess.py @@ -330,12 +330,12 @@ def test_executable_replaces_shell(self): # when shell=True. self._assert_python([], executable=sys.executable, shell=True) - @unittest.skipIf(mswindows, "executable argument replaces shell") + @unittest.skipIf(MS_WINDOWS, "executable argument replaces shell") def test_bytes_executable_replaces_shell(self): self._assert_python([], executable=os.fsencode(sys.executable), shell=True) - @unittest.skipIf(mswindows, "executable argument replaces shell") + @unittest.skipIf(MS_WINDOWS, "executable argument replaces shell") def test_pathlike_executable_replaces_shell(self): self._assert_python([], executable=FakePath(sys.executable), shell=True) @@ -1501,7 +1501,7 @@ def test_run_with_pathlike_path(self): # bpo-31961: test run(pathlike_object) # the name of a command that can be run without # any argumenets that exit fast - prog = 'tree.com' if mswindows else 'ls' + prog = 'tree.com' if MS_WINDOWS else 'ls' path = shutil.which(prog) if path is None: self.skipTest(f'{prog} required for this test')