bpo-40275: Use new test.support helper submodules in tests (GH-21452)

This commit is contained in:
Hai Shi 2020-08-04 23:51:43 +08:00 committed by GitHub
parent da4e09fff6
commit 604bba1f8f
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
6 changed files with 62 additions and 54 deletions

View File

@ -22,6 +22,7 @@ import time
import unittest
from test import support
from test.support import os_helper
from test.support import socket_helper
@contextlib.contextmanager
@ -314,16 +315,16 @@ class SocketEINTRTest(EINTRBaseTest):
@support.requires_freebsd_version(10, 3)
@unittest.skipUnless(hasattr(os, 'mkfifo'), 'needs mkfifo()')
def _test_open(self, do_open_close_reader, do_open_close_writer):
filename = support.TESTFN
filename = os_helper.TESTFN
# Use a fifo: until the child opens it for reading, the parent will
# block when trying to open it for writing.
support.unlink(filename)
os_helper.unlink(filename)
try:
os.mkfifo(filename)
except PermissionError as e:
self.skipTest('os.mkfifo(): %s' % e)
self.addCleanup(support.unlink, filename)
self.addCleanup(os_helper.unlink, filename)
code = '\n'.join((
'import os, time',
@ -486,16 +487,16 @@ class SelectEINTRTest(EINTRBaseTest):
class FNTLEINTRTest(EINTRBaseTest):
def _lock(self, lock_func, lock_name):
self.addCleanup(support.unlink, support.TESTFN)
self.addCleanup(os_helper.unlink, os_helper.TESTFN)
code = '\n'.join((
"import fcntl, time",
"with open('%s', 'wb') as f:" % support.TESTFN,
"with open('%s', 'wb') as f:" % os_helper.TESTFN,
" fcntl.%s(f, fcntl.LOCK_EX)" % lock_name,
" time.sleep(%s)" % self.sleep_time))
start_time = time.monotonic()
proc = self.subprocess(code)
with kill_on_error(proc):
with open(support.TESTFN, 'wb') as f:
with open(os_helper.TESTFN, 'wb') as f:
while True: # synchronize the subprocess
dt = time.monotonic() - start_time
if dt > 60.0:

View File

@ -38,7 +38,7 @@ from email import base64mime
from email import quoprimime
from test.support import threading_helper
from test.support import unlink
from test.support.os_helper import unlink
from test.test_email import openfile, TestEmailBase
# These imports are documented to work, but we are testing them using a

View File

@ -4,7 +4,8 @@
#
from test import support
from test.support import TESTFN
from test.support import os_helper
from test.support.os_helper import TESTFN
import unittest, io, codecs, sys
import _multibytecodec
@ -57,7 +58,7 @@ class Test_MultibyteCodec(unittest.TestCase):
code = '# coding: {}\n'.format(enc)
exec(code)
finally:
support.unlink(TESTFN)
os_helper.unlink(TESTFN)
def test_init_segfault(self):
# bug #3305: this used to segfault
@ -296,7 +297,7 @@ class Test_StreamReader(unittest.TestCase):
finally:
f.close()
finally:
support.unlink(TESTFN)
os_helper.unlink(TESTFN)
class Test_StreamWriter(unittest.TestCase):
def test_gb18030(self):

View File

@ -12,7 +12,7 @@ import textwrap
from contextlib import ExitStack
from io import StringIO
from test import support
from test.support import os_helper
# This little helper class is essential for testing pdb under doctest.
from test.test_doctest import _FakeInput
from unittest.mock import patch
@ -1188,10 +1188,10 @@ def test_pdb_issue_20766():
class PdbTestCase(unittest.TestCase):
def tearDown(self):
support.unlink(support.TESTFN)
os_helper.unlink(os_helper.TESTFN)
def _run_pdb(self, pdb_args, commands):
self.addCleanup(support.rmtree, '__pycache__')
self.addCleanup(os_helper.rmtree, '__pycache__')
cmd = [sys.executable, '-m', 'pdb'] + pdb_args
with subprocess.Popen(
cmd,
@ -1210,13 +1210,13 @@ class PdbTestCase(unittest.TestCase):
filename = 'main.py'
with open(filename, 'w') as f:
f.write(textwrap.dedent(script))
self.addCleanup(support.unlink, filename)
self.addCleanup(os_helper.unlink, filename)
return self._run_pdb([filename], commands)
def run_pdb_module(self, script, commands):
"""Runs the script code as part of a module"""
self.module_name = 't_main'
support.rmtree(self.module_name)
os_helper.rmtree(self.module_name)
main_file = self.module_name + '/__main__.py'
init_file = self.module_name + '/__init__.py'
os.mkdir(self.module_name)
@ -1224,17 +1224,17 @@ class PdbTestCase(unittest.TestCase):
pass
with open(main_file, 'w') as f:
f.write(textwrap.dedent(script))
self.addCleanup(support.rmtree, self.module_name)
self.addCleanup(os_helper.rmtree, self.module_name)
return self._run_pdb(['-m', self.module_name], commands)
def _assert_find_function(self, file_content, func_name, expected):
with open(support.TESTFN, 'wb') as f:
with open(os_helper.TESTFN, 'wb') as f:
f.write(file_content)
expected = None if not expected else (
expected[0], support.TESTFN, expected[1])
expected[0], os_helper.TESTFN, expected[1])
self.assertEqual(
expected, pdb.find_function(func_name, support.TESTFN))
expected, pdb.find_function(func_name, os_helper.TESTFN))
def test_find_function_empty_file(self):
self._assert_find_function(b'', 'foo', None)
@ -1284,9 +1284,9 @@ def bœr():
def test_issue7964(self):
# open the file as binary so we can force \r\n newline
with open(support.TESTFN, 'wb') as f:
with open(os_helper.TESTFN, 'wb') as f:
f.write(b'print("testing my pdb")\r\n')
cmd = [sys.executable, '-m', 'pdb', support.TESTFN]
cmd = [sys.executable, '-m', 'pdb', os_helper.TESTFN]
proc = subprocess.Popen(cmd,
stdout=subprocess.PIPE,
stdin=subprocess.PIPE,
@ -1327,7 +1327,7 @@ def bœr():
"""
with open('bar.py', 'w') as f:
f.write(textwrap.dedent(bar))
self.addCleanup(support.unlink, 'bar.py')
self.addCleanup(os_helper.unlink, 'bar.py')
stdout, stderr = self.run_pdb_script(script, commands)
self.assertTrue(
any('main.py(5)foo()->None' in l for l in stdout.splitlines()),
@ -1337,7 +1337,7 @@ def bœr():
# Invoking "continue" on a non-main thread triggered an exception
# inside signal.signal.
with open(support.TESTFN, 'wb') as f:
with open(os_helper.TESTFN, 'wb') as f:
f.write(textwrap.dedent("""
import threading
import pdb
@ -1349,7 +1349,7 @@ def bœr():
t = threading.Thread(target=start_pdb)
t.start()""").encode('ascii'))
cmd = [sys.executable, '-u', support.TESTFN]
cmd = [sys.executable, '-u', os_helper.TESTFN]
proc = subprocess.Popen(cmd,
stdout=subprocess.PIPE,
stdin=subprocess.PIPE,
@ -1363,7 +1363,7 @@ def bœr():
def test_issue36250(self):
with open(support.TESTFN, 'wb') as f:
with open(os_helper.TESTFN, 'wb') as f:
f.write(textwrap.dedent("""
import threading
import pdb
@ -1379,7 +1379,7 @@ def bœr():
pdb.Pdb(readrc=False).set_trace()
evt.set()
t.join()""").encode('ascii'))
cmd = [sys.executable, '-u', support.TESTFN]
cmd = [sys.executable, '-u', os_helper.TESTFN]
proc = subprocess.Popen(cmd,
stdout=subprocess.PIPE,
stdin=subprocess.PIPE,
@ -1412,7 +1412,7 @@ def bœr():
save_home = os.environ.pop('HOME', None)
try:
with support.temp_cwd():
with os_helper.temp_cwd():
with open('.pdbrc', 'w') as f:
f.write("invalid\n")
@ -1437,7 +1437,7 @@ def bœr():
def test_readrc_homedir(self):
save_home = os.environ.pop("HOME", None)
with support.temp_dir() as temp_dir, patch("os.path.expanduser"):
with os_helper.temp_dir() as temp_dir, patch("os.path.expanduser"):
rc_path = os.path.join(temp_dir, ".pdbrc")
os.path.expanduser.return_value = rc_path
try:
@ -1506,12 +1506,12 @@ def bœr():
def test_module_without_a_main(self):
module_name = 't_main'
support.rmtree(module_name)
os_helper.rmtree(module_name)
init_file = module_name + '/__init__.py'
os.mkdir(module_name)
with open(init_file, 'w') as f:
pass
self.addCleanup(support.rmtree, module_name)
self.addCleanup(os_helper.rmtree, module_name)
stdout, stderr = self._run_pdb(['-m', module_name], "")
self.assertIn("ImportError: No module named t_main.__main__",
stdout.splitlines())
@ -1531,11 +1531,11 @@ def bœr():
def test_relative_imports(self):
self.module_name = 't_main'
support.rmtree(self.module_name)
os_helper.rmtree(self.module_name)
main_file = self.module_name + '/__main__.py'
init_file = self.module_name + '/__init__.py'
module_file = self.module_name + '/module.py'
self.addCleanup(support.rmtree, self.module_name)
self.addCleanup(os_helper.rmtree, self.module_name)
os.mkdir(self.module_name)
with open(init_file, 'w') as f:
f.write(textwrap.dedent("""
@ -1569,11 +1569,11 @@ def bœr():
def test_relative_imports_on_plain_module(self):
# Validates running a plain module. See bpo32691
self.module_name = 't_main'
support.rmtree(self.module_name)
os_helper.rmtree(self.module_name)
main_file = self.module_name + '/runme.py'
init_file = self.module_name + '/__init__.py'
module_file = self.module_name + '/module.py'
self.addCleanup(support.rmtree, self.module_name)
self.addCleanup(os_helper.rmtree, self.module_name)
os.mkdir(self.module_name)
with open(init_file, 'w') as f:
f.write(textwrap.dedent("""

View File

@ -8,9 +8,9 @@ import threading
import unittest
import hashlib
from test import support
from test.support import hashlib_helper
from test.support import threading_helper
from test.support import warnings_helper
try:
import ssl
@ -567,7 +567,7 @@ class TestUrlopen(unittest.TestCase):
def test_https_with_cafile(self):
handler = self.start_https_server(certfile=CERT_localhost)
with support.check_warnings(('', DeprecationWarning)):
with warnings_helper.check_warnings(('', DeprecationWarning)):
# Good cert
data = self.urlopen("https://localhost:%s/bizarre" % handler.port,
cafile=CERT_localhost)
@ -585,7 +585,7 @@ class TestUrlopen(unittest.TestCase):
def test_https_with_cadefault(self):
handler = self.start_https_server(certfile=CERT_localhost)
# Self-signed cert should fail verification with system certificate store
with support.check_warnings(('', DeprecationWarning)):
with warnings_helper.check_warnings(('', DeprecationWarning)):
with self.assertRaises(urllib.error.URLError) as cm:
self.urlopen("https://localhost:%s/bizarre" % handler.port,
cadefault=True)

View File

@ -7,14 +7,20 @@ import sys
import textwrap
import unittest
from test import support
from test.support import import_helper
from test.support import os_helper
from test.support import warnings_helper
from test.support.script_helper import assert_python_ok, assert_python_failure
from test.test_warnings.data import stacklevel as warning_tests
import warnings as original_warnings
py_warnings = support.import_fresh_module('warnings', blocked=['_warnings'])
c_warnings = support.import_fresh_module('warnings', fresh=['_warnings'])
py_warnings = import_helper.import_fresh_module('warnings',
blocked=['_warnings'])
c_warnings = import_helper.import_fresh_module('warnings',
fresh=['_warnings'])
Py_DEBUG = hasattr(sys, 'gettotalrefcount')
@ -440,7 +446,7 @@ class WarnTests(BaseTest):
def test_stacklevel_import(self):
# Issue #24305: With stacklevel=2, module-level warnings should work.
support.unload('test.test_warnings.data.import_warning')
import_helper.unload('test.test_warnings.data.import_warning')
with warnings_state(self.module):
with original_warnings.catch_warnings(record=True,
module=self.module) as w:
@ -543,7 +549,7 @@ class CWarnTests(WarnTests, unittest.TestCase):
module = c_warnings
# As an early adopter, we sanity check the
# test.support.import_fresh_module utility function
# test.import_helper.import_fresh_module utility function
def test_accelerated(self):
self.assertIsNot(original_warnings, self.module)
self.assertFalse(hasattr(self.module.warn, '__code__'))
@ -552,7 +558,7 @@ class PyWarnTests(WarnTests, unittest.TestCase):
module = py_warnings
# As an early adopter, we sanity check the
# test.support.import_fresh_module utility function
# test.import_helper.import_fresh_module utility function
def test_pure_python(self):
self.assertIsNot(original_warnings, self.module)
self.assertTrue(hasattr(self.module.warn, '__code__'))
@ -927,9 +933,9 @@ class PyWarningsDisplayTests(WarningsDisplayTests, unittest.TestCase):
module = py_warnings
def test_tracemalloc(self):
self.addCleanup(support.unlink, support.TESTFN)
self.addCleanup(os_helper.unlink, os_helper.TESTFN)
with open(support.TESTFN, 'w') as fp:
with open(os_helper.TESTFN, 'w') as fp:
fp.write(textwrap.dedent("""
def func():
f = open(__file__)
@ -949,8 +955,8 @@ class PyWarningsDisplayTests(WarningsDisplayTests, unittest.TestCase):
return stderr
# tracemalloc disabled
filename = os.path.abspath(support.TESTFN)
stderr = run('-Wd', support.TESTFN)
filename = os.path.abspath(os_helper.TESTFN)
stderr = run('-Wd', os_helper.TESTFN)
expected = textwrap.dedent(f'''
{filename}:5: ResourceWarning: unclosed file <...>
f = None
@ -959,7 +965,7 @@ class PyWarningsDisplayTests(WarningsDisplayTests, unittest.TestCase):
self.assertEqual(stderr, expected)
# tracemalloc enabled
stderr = run('-Wd', '-X', 'tracemalloc=2', support.TESTFN)
stderr = run('-Wd', '-X', 'tracemalloc=2', os_helper.TESTFN)
expected = textwrap.dedent(f'''
{filename}:5: ResourceWarning: unclosed file <...>
f = None
@ -1093,7 +1099,7 @@ class CatchWarningTests(BaseTest):
wmod = self.module
if wmod is not sys.modules['warnings']:
self.skipTest('module to test is not loaded warnings module')
with support.check_warnings(quiet=False) as w:
with warnings_helper.check_warnings(quiet=False) as w:
self.assertEqual(w.warnings, [])
wmod.simplefilter("always")
wmod.warn("foo")
@ -1105,18 +1111,18 @@ class CatchWarningTests(BaseTest):
w.reset()
self.assertEqual(w.warnings, [])
with support.check_warnings():
with warnings_helper.check_warnings():
# defaults to quiet=True without argument
pass
with support.check_warnings(('foo', UserWarning)):
with warnings_helper.check_warnings(('foo', UserWarning)):
wmod.warn("foo")
with self.assertRaises(AssertionError):
with support.check_warnings(('', RuntimeWarning)):
with warnings_helper.check_warnings(('', RuntimeWarning)):
# defaults to quiet=False with argument
pass
with self.assertRaises(AssertionError):
with support.check_warnings(('foo', RuntimeWarning)):
with warnings_helper.check_warnings(('foo', RuntimeWarning)):
wmod.warn("foo")
class CCatchWarningTests(CatchWarningTests, unittest.TestCase):
@ -1198,7 +1204,7 @@ class EnvironmentVariableTests(BaseTest):
@unittest.skipUnless(sys.getfilesystemencoding() != 'ascii',
'requires non-ascii filesystemencoding')
def test_nonascii(self):
PYTHONWARNINGS="ignore:DeprecationWarning" + support.FS_NONASCII
PYTHONWARNINGS="ignore:DeprecationWarning" + os_helper.FS_NONASCII
rc, stdout, stderr = assert_python_ok("-c",
"import sys; sys.stdout.write(str(sys.warnoptions))",
PYTHONIOENCODING="utf-8",
@ -1218,7 +1224,7 @@ class BootstrapTest(unittest.TestCase):
# "import encodings" emits a warning whereas the warnings is not loaded
# or not completely loaded (warnings imports indirectly encodings by
# importing linecache) yet
with support.temp_cwd() as cwd, support.temp_cwd('encodings'):
with os_helper.temp_cwd() as cwd, os_helper.temp_cwd('encodings'):
# encodings loaded by initfsencoding()
assert_python_ok('-c', 'pass', PYTHONPATH=cwd)