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

This commit is contained in:
Hai Shi 2020-07-06 20:29:49 +08:00 committed by GitHub
parent b4a9263708
commit deb016224c
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
18 changed files with 128 additions and 110 deletions

View File

@ -6,7 +6,7 @@ import tempfile
import unittest import unittest
import sysconfig import sysconfig
from copy import deepcopy from copy import deepcopy
import test.support from test.support import os_helper
from distutils import log from distutils import log
from distutils.log import DEBUG, INFO, WARN, ERROR, FATAL from distutils.log import DEBUG, INFO, WARN, ERROR, FATAL
@ -64,7 +64,7 @@ class TempdirManager(object):
super().tearDown() super().tearDown()
while self.tempdirs: while self.tempdirs:
tmpdir = self.tempdirs.pop() tmpdir = self.tempdirs.pop()
test.support.rmtree(tmpdir) os_helper.rmtree(tmpdir)
def mkdtemp(self): def mkdtemp(self):
"""Create a temporary directory that will be cleaned up. """Create a temporary directory that will be cleaned up.

View File

@ -15,6 +15,7 @@ from distutils.errors import (
import unittest import unittest
from test import support from test import support
from test.support import os_helper
from test.support.script_helper import assert_python_ok from test.support.script_helper import assert_python_ok
# http://bugs.python.org/issue4373 # http://bugs.python.org/issue4373
@ -38,7 +39,7 @@ class BuildExtTestCase(TempdirManager,
# bpo-30132: On Windows, a .pdb file may be created in the current # bpo-30132: On Windows, a .pdb file may be created in the current
# working directory. Create a temporary working directory to cleanup # working directory. Create a temporary working directory to cleanup
# everything at the end of the test. # everything at the end of the test.
change_cwd = support.change_cwd(self.tmp_dir) change_cwd = os_helper.change_cwd(self.tmp_dir)
change_cwd.__enter__() change_cwd.__enter__()
self.addCleanup(change_cwd.__exit__, None, None, None) self.addCleanup(change_cwd.__exit__, None, None, None)

View File

@ -8,7 +8,6 @@ from distutils.errors import DistutilsTemplateError
from distutils.filelist import glob_to_re, translate_pattern, FileList from distutils.filelist import glob_to_re, translate_pattern, FileList
from distutils import filelist from distutils import filelist
import test.support
from test.support import os_helper from test.support import os_helper
from test.support import captured_stdout, run_unittest from test.support import captured_stdout, run_unittest
from distutils.tests import support from distutils.tests import support
@ -298,7 +297,7 @@ class FileListTestCase(support.LoggingSilencer,
class FindAllTestCase(unittest.TestCase): class FindAllTestCase(unittest.TestCase):
@os_helper.skip_unless_symlink @os_helper.skip_unless_symlink
def test_missing_symlink(self): def test_missing_symlink(self):
with test.support.temp_cwd(): with os_helper.temp_cwd():
os.symlink('foo', 'bar') os.symlink('foo', 'bar')
self.assertEqual(filelist.findall(), []) self.assertEqual(filelist.findall(), [])
@ -308,13 +307,13 @@ class FindAllTestCase(unittest.TestCase):
'.' as the parameter, the dot should be omitted from '.' as the parameter, the dot should be omitted from
the results. the results.
""" """
with test.support.temp_cwd(): with os_helper.temp_cwd():
os.mkdir('foo') os.mkdir('foo')
file1 = os.path.join('foo', 'file1.txt') file1 = os.path.join('foo', 'file1.txt')
test.support.create_empty_file(file1) os_helper.create_empty_file(file1)
os.mkdir('bar') os.mkdir('bar')
file2 = os.path.join('bar', 'file2.txt') file2 = os.path.join('bar', 'file2.txt')
test.support.create_empty_file(file2) os_helper.create_empty_file(file2)
expected = [file2, file1] expected = [file2, file1]
self.assertEqual(sorted(filelist.findall()), expected) self.assertEqual(sorted(filelist.findall()), expected)
@ -323,9 +322,9 @@ class FindAllTestCase(unittest.TestCase):
When findall is called with another path, the full When findall is called with another path, the full
path name should be returned. path name should be returned.
""" """
with test.support.temp_dir() as temp_dir: with os_helper.temp_dir() as temp_dir:
file1 = os.path.join(temp_dir, 'file1.txt') file1 = os.path.join(temp_dir, 'file1.txt')
test.support.create_empty_file(file1) os_helper.create_empty_file(file1)
expected = [file1] expected = [file1]
self.assertEqual(filelist.findall(temp_dir), expected) self.assertEqual(filelist.findall(temp_dir), expected)

View File

@ -4,7 +4,7 @@ import stat
import sys import sys
import unittest.mock import unittest.mock
from test.support import run_unittest, unix_shell from test.support import run_unittest, unix_shell
from test import support as test_support from test.support import os_helper
from distutils.spawn import find_executable from distutils.spawn import find_executable
from distutils.spawn import spawn from distutils.spawn import spawn
@ -44,9 +44,9 @@ class SpawnTestCase(support.TempdirManager,
spawn([exe]) # should work without any error spawn([exe]) # should work without any error
def test_find_executable(self): def test_find_executable(self):
with test_support.temp_dir() as tmp_dir: with os_helper.temp_dir() as tmp_dir:
# use TESTFN to get a pseudo-unique filename # use TESTFN to get a pseudo-unique filename
program_noeext = test_support.TESTFN program_noeext = os_helper.TESTFN
# Give the temporary program an ".exe" suffix for all. # Give the temporary program an ".exe" suffix for all.
# It's needed on Windows and not harmful on other platforms. # It's needed on Windows and not harmful on other platforms.
program = program_noeext + ".exe" program = program_noeext + ".exe"
@ -66,7 +66,7 @@ class SpawnTestCase(support.TempdirManager,
self.assertEqual(rv, filename) self.assertEqual(rv, filename)
# test find in the current directory # test find in the current directory
with test_support.change_cwd(tmp_dir): with os_helper.change_cwd(tmp_dir):
rv = find_executable(program) rv = find_executable(program)
self.assertEqual(rv, program) self.assertEqual(rv, program)
@ -76,7 +76,7 @@ class SpawnTestCase(support.TempdirManager,
self.assertIsNone(rv) self.assertIsNone(rv)
# PATH='': no match, except in the current directory # PATH='': no match, except in the current directory
with test_support.EnvironmentVarGuard() as env: with os_helper.EnvironmentVarGuard() as env:
env['PATH'] = '' env['PATH'] = ''
with unittest.mock.patch('distutils.spawn.os.confstr', with unittest.mock.patch('distutils.spawn.os.confstr',
return_value=tmp_dir, create=True), \ return_value=tmp_dir, create=True), \
@ -86,12 +86,12 @@ class SpawnTestCase(support.TempdirManager,
self.assertIsNone(rv) self.assertIsNone(rv)
# look in current directory # look in current directory
with test_support.change_cwd(tmp_dir): with os_helper.change_cwd(tmp_dir):
rv = find_executable(program) rv = find_executable(program)
self.assertEqual(rv, program) self.assertEqual(rv, program)
# PATH=':': explicitly looks in the current directory # PATH=':': explicitly looks in the current directory
with test_support.EnvironmentVarGuard() as env: with os_helper.EnvironmentVarGuard() as env:
env['PATH'] = os.pathsep env['PATH'] = os.pathsep
with unittest.mock.patch('distutils.spawn.os.confstr', with unittest.mock.patch('distutils.spawn.os.confstr',
return_value='', create=True), \ return_value='', create=True), \
@ -100,12 +100,12 @@ class SpawnTestCase(support.TempdirManager,
self.assertIsNone(rv) self.assertIsNone(rv)
# look in current directory # look in current directory
with test_support.change_cwd(tmp_dir): with os_helper.change_cwd(tmp_dir):
rv = find_executable(program) rv = find_executable(program)
self.assertEqual(rv, program) self.assertEqual(rv, program)
# missing PATH: test os.confstr("CS_PATH") and os.defpath # missing PATH: test os.confstr("CS_PATH") and os.defpath
with test_support.EnvironmentVarGuard() as env: with os_helper.EnvironmentVarGuard() as env:
env.pop('PATH', None) env.pop('PATH', None)
# without confstr # without confstr

View File

@ -1,5 +1,6 @@
from test import support from test import support
gdbm = support.import_module("dbm.gnu") #skip if not supported from test.support import import_helper
gdbm = import_helper.import_module("dbm.gnu") #skip if not supported
import unittest import unittest
import os import os
from test.support import TESTFN, TESTFN_NONASCII, unlink from test.support import TESTFN, TESTFN_NONASCII, unlink

View File

@ -2,6 +2,7 @@
import sys import sys
from test import support from test import support
from test.support import os_helper
from test.support import script_helper from test.support import script_helper
import unittest import unittest
@ -48,7 +49,7 @@ class EOFTestCase(unittest.TestCase):
@unittest.skipIf(not sys.executable, "sys.executable required") @unittest.skipIf(not sys.executable, "sys.executable required")
def test_line_continuation_EOF_from_file_bpo2180(self): def test_line_continuation_EOF_from_file_bpo2180(self):
"""Ensure tok_nextc() does not add too many ending newlines.""" """Ensure tok_nextc() does not add too many ending newlines."""
with support.temp_dir() as temp_dir: with os_helper.temp_dir() as temp_dir:
file_name = script_helper.make_script(temp_dir, 'foo', '\\') file_name = script_helper.make_script(temp_dir, 'foo', '\\')
rc, out, err = script_helper.assert_python_failure(file_name) rc, out, err = script_helper.assert_python_failure(file_name)
self.assertIn(b'unexpected EOF while parsing', err) self.assertIn(b'unexpected EOF while parsing', err)

View File

@ -18,7 +18,8 @@ import threading
import unittest import unittest
import warnings import warnings
from test import support from test import support
from test.support import _4G, bigmemtest, import_fresh_module from test.support import _4G, bigmemtest
from test.support.import_helper import import_fresh_module
from test.support import threading_helper from test.support import threading_helper
from http.client import HTTPException from http.client import HTTPException

View File

@ -1,5 +1,5 @@
import unittest import unittest
from test.support import import_module from test.support.import_helper import import_module
# Skip test_idle if _tkinter wasn't built, if tkinter is missing, # Skip test_idle if _tkinter wasn't built, if tkinter is missing,
# if tcl/tk is not the 8.5+ needed for ttk widgets, # if tcl/tk is not the 8.5+ needed for ttk widgets,

View File

@ -14,6 +14,7 @@ from test.support import (verbose,
run_with_tz, run_with_locale, cpython_only) run_with_tz, run_with_locale, cpython_only)
from test.support import hashlib_helper from test.support import hashlib_helper
from test.support import threading_helper from test.support import threading_helper
from test.support import warnings_helper
import unittest import unittest
from unittest import mock from unittest import mock
from datetime import datetime, timezone, timedelta from datetime import datetime, timezone, timedelta
@ -575,7 +576,7 @@ class NewIMAPSSLTests(NewIMAPTestsMixin, unittest.TestCase):
# to CPython stdlib # to CPython stdlib
@cpython_only @cpython_only
def test_certfile_arg_warn(self): def test_certfile_arg_warn(self):
with support.check_warnings(('', DeprecationWarning)): with warnings_helper.check_warnings(('', DeprecationWarning)):
with mock.patch.object(self.imap_class, 'open'): with mock.patch.object(self.imap_class, 'open'):
with mock.patch.object(self.imap_class, '_connect'): with mock.patch.object(self.imap_class, '_connect'):
self.imap_class('localhost', 143, certfile=CERTFILE) self.imap_class('localhost', 143, certfile=CERTFILE)

View File

@ -1,4 +1,5 @@
from test import support from test import support
from test.support import os_helper
import array import array
import io import io
import marshal import marshal
@ -17,13 +18,13 @@ class HelperMixin:
new = marshal.loads(marshal.dumps(sample, *extra)) new = marshal.loads(marshal.dumps(sample, *extra))
self.assertEqual(sample, new) self.assertEqual(sample, new)
try: try:
with open(support.TESTFN, "wb") as f: with open(os_helper.TESTFN, "wb") as f:
marshal.dump(sample, f, *extra) marshal.dump(sample, f, *extra)
with open(support.TESTFN, "rb") as f: with open(os_helper.TESTFN, "rb") as f:
new = marshal.load(f) new = marshal.load(f)
self.assertEqual(sample, new) self.assertEqual(sample, new)
finally: finally:
support.unlink(support.TESTFN) os_helper.unlink(os_helper.TESTFN)
class IntTestCase(unittest.TestCase, HelperMixin): class IntTestCase(unittest.TestCase, HelperMixin):
def test_ints(self): def test_ints(self):
@ -281,20 +282,20 @@ class BugsTestCase(unittest.TestCase):
ilen = len(interleaved) ilen = len(interleaved)
positions = [] positions = []
try: try:
with open(support.TESTFN, 'wb') as f: with open(os_helper.TESTFN, 'wb') as f:
for d in data: for d in data:
marshal.dump(d, f) marshal.dump(d, f)
if ilen: if ilen:
f.write(interleaved) f.write(interleaved)
positions.append(f.tell()) positions.append(f.tell())
with open(support.TESTFN, 'rb') as f: with open(os_helper.TESTFN, 'rb') as f:
for i, d in enumerate(data): for i, d in enumerate(data):
self.assertEqual(d, marshal.load(f)) self.assertEqual(d, marshal.load(f))
if ilen: if ilen:
f.read(ilen) f.read(ilen)
self.assertEqual(positions[i], f.tell()) self.assertEqual(positions[i], f.tell())
finally: finally:
support.unlink(support.TESTFN) os_helper.unlink(os_helper.TESTFN)
def test_loads_reject_unicode_strings(self): def test_loads_reject_unicode_strings(self):
# Issue #14177: marshal.loads() should not accept unicode strings # Issue #14177: marshal.loads() should not accept unicode strings
@ -516,81 +517,81 @@ class CAPI_TestCase(unittest.TestCase, HelperMixin):
def test_write_long_to_file(self): def test_write_long_to_file(self):
for v in range(marshal.version + 1): for v in range(marshal.version + 1):
_testcapi.pymarshal_write_long_to_file(0x12345678, support.TESTFN, v) _testcapi.pymarshal_write_long_to_file(0x12345678, os_helper.TESTFN, v)
with open(support.TESTFN, 'rb') as f: with open(os_helper.TESTFN, 'rb') as f:
data = f.read() data = f.read()
support.unlink(support.TESTFN) os_helper.unlink(os_helper.TESTFN)
self.assertEqual(data, b'\x78\x56\x34\x12') self.assertEqual(data, b'\x78\x56\x34\x12')
def test_write_object_to_file(self): def test_write_object_to_file(self):
obj = ('\u20ac', b'abc', 123, 45.6, 7+8j, 'long line '*1000) obj = ('\u20ac', b'abc', 123, 45.6, 7+8j, 'long line '*1000)
for v in range(marshal.version + 1): for v in range(marshal.version + 1):
_testcapi.pymarshal_write_object_to_file(obj, support.TESTFN, v) _testcapi.pymarshal_write_object_to_file(obj, os_helper.TESTFN, v)
with open(support.TESTFN, 'rb') as f: with open(os_helper.TESTFN, 'rb') as f:
data = f.read() data = f.read()
support.unlink(support.TESTFN) os_helper.unlink(os_helper.TESTFN)
self.assertEqual(marshal.loads(data), obj) self.assertEqual(marshal.loads(data), obj)
def test_read_short_from_file(self): def test_read_short_from_file(self):
with open(support.TESTFN, 'wb') as f: with open(os_helper.TESTFN, 'wb') as f:
f.write(b'\x34\x12xxxx') f.write(b'\x34\x12xxxx')
r, p = _testcapi.pymarshal_read_short_from_file(support.TESTFN) r, p = _testcapi.pymarshal_read_short_from_file(os_helper.TESTFN)
support.unlink(support.TESTFN) os_helper.unlink(os_helper.TESTFN)
self.assertEqual(r, 0x1234) self.assertEqual(r, 0x1234)
self.assertEqual(p, 2) self.assertEqual(p, 2)
with open(support.TESTFN, 'wb') as f: with open(os_helper.TESTFN, 'wb') as f:
f.write(b'\x12') f.write(b'\x12')
with self.assertRaises(EOFError): with self.assertRaises(EOFError):
_testcapi.pymarshal_read_short_from_file(support.TESTFN) _testcapi.pymarshal_read_short_from_file(os_helper.TESTFN)
support.unlink(support.TESTFN) os_helper.unlink(os_helper.TESTFN)
def test_read_long_from_file(self): def test_read_long_from_file(self):
with open(support.TESTFN, 'wb') as f: with open(os_helper.TESTFN, 'wb') as f:
f.write(b'\x78\x56\x34\x12xxxx') f.write(b'\x78\x56\x34\x12xxxx')
r, p = _testcapi.pymarshal_read_long_from_file(support.TESTFN) r, p = _testcapi.pymarshal_read_long_from_file(os_helper.TESTFN)
support.unlink(support.TESTFN) os_helper.unlink(os_helper.TESTFN)
self.assertEqual(r, 0x12345678) self.assertEqual(r, 0x12345678)
self.assertEqual(p, 4) self.assertEqual(p, 4)
with open(support.TESTFN, 'wb') as f: with open(os_helper.TESTFN, 'wb') as f:
f.write(b'\x56\x34\x12') f.write(b'\x56\x34\x12')
with self.assertRaises(EOFError): with self.assertRaises(EOFError):
_testcapi.pymarshal_read_long_from_file(support.TESTFN) _testcapi.pymarshal_read_long_from_file(os_helper.TESTFN)
support.unlink(support.TESTFN) os_helper.unlink(os_helper.TESTFN)
def test_read_last_object_from_file(self): def test_read_last_object_from_file(self):
obj = ('\u20ac', b'abc', 123, 45.6, 7+8j) obj = ('\u20ac', b'abc', 123, 45.6, 7+8j)
for v in range(marshal.version + 1): for v in range(marshal.version + 1):
data = marshal.dumps(obj, v) data = marshal.dumps(obj, v)
with open(support.TESTFN, 'wb') as f: with open(os_helper.TESTFN, 'wb') as f:
f.write(data + b'xxxx') f.write(data + b'xxxx')
r, p = _testcapi.pymarshal_read_last_object_from_file(support.TESTFN) r, p = _testcapi.pymarshal_read_last_object_from_file(os_helper.TESTFN)
support.unlink(support.TESTFN) os_helper.unlink(os_helper.TESTFN)
self.assertEqual(r, obj) self.assertEqual(r, obj)
with open(support.TESTFN, 'wb') as f: with open(os_helper.TESTFN, 'wb') as f:
f.write(data[:1]) f.write(data[:1])
with self.assertRaises(EOFError): with self.assertRaises(EOFError):
_testcapi.pymarshal_read_last_object_from_file(support.TESTFN) _testcapi.pymarshal_read_last_object_from_file(os_helper.TESTFN)
support.unlink(support.TESTFN) os_helper.unlink(os_helper.TESTFN)
def test_read_object_from_file(self): def test_read_object_from_file(self):
obj = ('\u20ac', b'abc', 123, 45.6, 7+8j) obj = ('\u20ac', b'abc', 123, 45.6, 7+8j)
for v in range(marshal.version + 1): for v in range(marshal.version + 1):
data = marshal.dumps(obj, v) data = marshal.dumps(obj, v)
with open(support.TESTFN, 'wb') as f: with open(os_helper.TESTFN, 'wb') as f:
f.write(data + b'xxxx') f.write(data + b'xxxx')
r, p = _testcapi.pymarshal_read_object_from_file(support.TESTFN) r, p = _testcapi.pymarshal_read_object_from_file(os_helper.TESTFN)
support.unlink(support.TESTFN) os_helper.unlink(os_helper.TESTFN)
self.assertEqual(r, obj) self.assertEqual(r, obj)
self.assertEqual(p, len(data)) self.assertEqual(p, len(data))
with open(support.TESTFN, 'wb') as f: with open(os_helper.TESTFN, 'wb') as f:
f.write(data[:1]) f.write(data[:1])
with self.assertRaises(EOFError): with self.assertRaises(EOFError):
_testcapi.pymarshal_read_object_from_file(support.TESTFN) _testcapi.pymarshal_read_object_from_file(os_helper.TESTFN)
support.unlink(support.TESTFN) os_helper.unlink(os_helper.TESTFN)
if __name__ == "__main__": if __name__ == "__main__":

View File

@ -102,7 +102,7 @@ class PyCompileTestsBase:
self.assertTrue(os.path.exists(self.cache_path)) self.assertTrue(os.path.exists(self.cache_path))
def test_cwd(self): def test_cwd(self):
with support.change_cwd(self.directory): with os_helper.change_cwd(self.directory):
py_compile.compile(os.path.basename(self.source_path), py_compile.compile(os.path.basename(self.source_path),
os.path.basename(self.pyc_path)) os.path.basename(self.pyc_path))
self.assertTrue(os.path.exists(self.pyc_path)) self.assertTrue(os.path.exists(self.pyc_path))

View File

@ -1,5 +1,6 @@
import unittest import unittest
from test import support from test import support
from test.support import warnings_helper
import gc import gc
import weakref import weakref
import operator import operator
@ -953,7 +954,7 @@ class TestBasicOpsBytes(TestBasicOps, unittest.TestCase):
class TestBasicOpsMixedStringBytes(TestBasicOps, unittest.TestCase): class TestBasicOpsMixedStringBytes(TestBasicOps, unittest.TestCase):
def setUp(self): def setUp(self):
self._warning_filters = support.check_warnings() self._warning_filters = warnings_helper.check_warnings()
self._warning_filters.__enter__() self._warning_filters.__enter__()
warnings.simplefilter('ignore', BytesWarning) warnings.simplefilter('ignore', BytesWarning)
self.case = "string and bytes set" self.case = "string and bytes set"

View File

@ -1,5 +1,6 @@
import unittest import unittest
from test import support from test import support
from test.support import os_helper
from test.support import socket_helper from test.support import socket_helper
from test.support import threading_helper from test.support import threading_helper
@ -697,7 +698,7 @@ class UnixSocketTestBase(SocketTestBase):
def bindSock(self, sock): def bindSock(self, sock):
path = tempfile.mktemp(dir=self.dir_path) path = tempfile.mktemp(dir=self.dir_path)
socket_helper.bind_unix_socket(sock, path) socket_helper.bind_unix_socket(sock, path)
self.addCleanup(support.unlink, path) self.addCleanup(os_helper.unlink, path)
class UnixStreamBase(UnixSocketTestBase): class UnixStreamBase(UnixSocketTestBase):
"""Base class for Unix-domain SOCK_STREAM tests.""" """Base class for Unix-domain SOCK_STREAM tests."""
@ -1917,14 +1918,14 @@ class GeneralModuleTests(unittest.TestCase):
def test_socket_fileno_requires_valid_fd(self): def test_socket_fileno_requires_valid_fd(self):
WSAENOTSOCK = 10038 WSAENOTSOCK = 10038
with self.assertRaises(OSError) as cm: with self.assertRaises(OSError) as cm:
socket.socket(fileno=support.make_bad_fd()) socket.socket(fileno=os_helper.make_bad_fd())
self.assertIn(cm.exception.errno, (errno.EBADF, WSAENOTSOCK)) self.assertIn(cm.exception.errno, (errno.EBADF, WSAENOTSOCK))
with self.assertRaises(OSError) as cm: with self.assertRaises(OSError) as cm:
socket.socket( socket.socket(
socket.AF_INET, socket.AF_INET,
socket.SOCK_STREAM, socket.SOCK_STREAM,
fileno=support.make_bad_fd()) fileno=os_helper.make_bad_fd())
self.assertIn(cm.exception.errno, (errno.EBADF, WSAENOTSOCK)) self.assertIn(cm.exception.errno, (errno.EBADF, WSAENOTSOCK))
def test_socket_fileno_requires_socket_fd(self): def test_socket_fileno_requires_socket_fd(self):
@ -5458,35 +5459,35 @@ class TestUnixDomain(unittest.TestCase):
def testStrAddr(self): def testStrAddr(self):
# Test binding to and retrieving a normal string pathname. # Test binding to and retrieving a normal string pathname.
path = os.path.abspath(support.TESTFN) path = os.path.abspath(os_helper.TESTFN)
self.bind(self.sock, path) self.bind(self.sock, path)
self.addCleanup(support.unlink, path) self.addCleanup(os_helper.unlink, path)
self.assertEqual(self.sock.getsockname(), path) self.assertEqual(self.sock.getsockname(), path)
def testBytesAddr(self): def testBytesAddr(self):
# Test binding to a bytes pathname. # Test binding to a bytes pathname.
path = os.path.abspath(support.TESTFN) path = os.path.abspath(os_helper.TESTFN)
self.bind(self.sock, self.encoded(path)) self.bind(self.sock, self.encoded(path))
self.addCleanup(support.unlink, path) self.addCleanup(os_helper.unlink, path)
self.assertEqual(self.sock.getsockname(), path) self.assertEqual(self.sock.getsockname(), path)
def testSurrogateescapeBind(self): def testSurrogateescapeBind(self):
# Test binding to a valid non-ASCII pathname, with the # Test binding to a valid non-ASCII pathname, with the
# non-ASCII bytes supplied using surrogateescape encoding. # non-ASCII bytes supplied using surrogateescape encoding.
path = os.path.abspath(support.TESTFN_UNICODE) path = os.path.abspath(os_helper.TESTFN_UNICODE)
b = self.encoded(path) b = self.encoded(path)
self.bind(self.sock, b.decode("ascii", "surrogateescape")) self.bind(self.sock, b.decode("ascii", "surrogateescape"))
self.addCleanup(support.unlink, path) self.addCleanup(os_helper.unlink, path)
self.assertEqual(self.sock.getsockname(), path) self.assertEqual(self.sock.getsockname(), path)
def testUnencodableAddr(self): def testUnencodableAddr(self):
# Test binding to a pathname that cannot be encoded in the # Test binding to a pathname that cannot be encoded in the
# file system encoding. # file system encoding.
if support.TESTFN_UNENCODABLE is None: if os_helper.TESTFN_UNENCODABLE is None:
self.skipTest("No unencodable filename available") self.skipTest("No unencodable filename available")
path = os.path.abspath(support.TESTFN_UNENCODABLE) path = os.path.abspath(os_helper.TESTFN_UNENCODABLE)
self.bind(self.sock, path) self.bind(self.sock, path)
self.addCleanup(support.unlink, path) self.addCleanup(os_helper.unlink, path)
self.assertEqual(self.sock.getsockname(), path) self.assertEqual(self.sock.getsockname(), path)
@ -5960,16 +5961,16 @@ class SendfileUsingSendTest(ThreadedTCPSocketTest):
chunk = b"".join([random.choice(string.ascii_letters).encode() chunk = b"".join([random.choice(string.ascii_letters).encode()
for i in range(cls.BUFSIZE)]) for i in range(cls.BUFSIZE)])
with open(support.TESTFN, 'wb') as f: with open(os_helper.TESTFN, 'wb') as f:
for csize in chunks(cls.FILESIZE, cls.BUFSIZE): for csize in chunks(cls.FILESIZE, cls.BUFSIZE):
f.write(chunk) f.write(chunk)
with open(support.TESTFN, 'rb') as f: with open(os_helper.TESTFN, 'rb') as f:
cls.FILEDATA = f.read() cls.FILEDATA = f.read()
assert len(cls.FILEDATA) == cls.FILESIZE assert len(cls.FILEDATA) == cls.FILESIZE
@classmethod @classmethod
def tearDownClass(cls): def tearDownClass(cls):
support.unlink(support.TESTFN) os_helper.unlink(os_helper.TESTFN)
def accept_conn(self): def accept_conn(self):
self.serv.settimeout(support.LONG_TIMEOUT) self.serv.settimeout(support.LONG_TIMEOUT)
@ -5996,7 +5997,7 @@ class SendfileUsingSendTest(ThreadedTCPSocketTest):
def _testRegularFile(self): def _testRegularFile(self):
address = self.serv.getsockname() address = self.serv.getsockname()
file = open(support.TESTFN, 'rb') file = open(os_helper.TESTFN, 'rb')
with socket.create_connection(address) as sock, file as file: with socket.create_connection(address) as sock, file as file:
meth = self.meth_from_sock(sock) meth = self.meth_from_sock(sock)
sent = meth(file) sent = meth(file)
@ -6031,9 +6032,9 @@ class SendfileUsingSendTest(ThreadedTCPSocketTest):
def _testEmptyFileSend(self): def _testEmptyFileSend(self):
address = self.serv.getsockname() address = self.serv.getsockname()
filename = support.TESTFN + "2" filename = os_helper.TESTFN + "2"
with open(filename, 'wb'): with open(filename, 'wb'):
self.addCleanup(support.unlink, filename) self.addCleanup(os_helper.unlink, filename)
file = open(filename, 'rb') file = open(filename, 'rb')
with socket.create_connection(address) as sock, file as file: with socket.create_connection(address) as sock, file as file:
meth = self.meth_from_sock(sock) meth = self.meth_from_sock(sock)
@ -6050,7 +6051,7 @@ class SendfileUsingSendTest(ThreadedTCPSocketTest):
def _testOffset(self): def _testOffset(self):
address = self.serv.getsockname() address = self.serv.getsockname()
file = open(support.TESTFN, 'rb') file = open(os_helper.TESTFN, 'rb')
with socket.create_connection(address) as sock, file as file: with socket.create_connection(address) as sock, file as file:
meth = self.meth_from_sock(sock) meth = self.meth_from_sock(sock)
sent = meth(file, offset=5000) sent = meth(file, offset=5000)
@ -6067,7 +6068,7 @@ class SendfileUsingSendTest(ThreadedTCPSocketTest):
def _testCount(self): def _testCount(self):
address = self.serv.getsockname() address = self.serv.getsockname()
file = open(support.TESTFN, 'rb') file = open(os_helper.TESTFN, 'rb')
sock = socket.create_connection(address, sock = socket.create_connection(address,
timeout=support.LOOPBACK_TIMEOUT) timeout=support.LOOPBACK_TIMEOUT)
with sock, file: with sock, file:
@ -6088,7 +6089,7 @@ class SendfileUsingSendTest(ThreadedTCPSocketTest):
def _testCountSmall(self): def _testCountSmall(self):
address = self.serv.getsockname() address = self.serv.getsockname()
file = open(support.TESTFN, 'rb') file = open(os_helper.TESTFN, 'rb')
sock = socket.create_connection(address, sock = socket.create_connection(address,
timeout=support.LOOPBACK_TIMEOUT) timeout=support.LOOPBACK_TIMEOUT)
with sock, file: with sock, file:
@ -6109,7 +6110,7 @@ class SendfileUsingSendTest(ThreadedTCPSocketTest):
def _testCountWithOffset(self): def _testCountWithOffset(self):
address = self.serv.getsockname() address = self.serv.getsockname()
file = open(support.TESTFN, 'rb') file = open(os_helper.TESTFN, 'rb')
with socket.create_connection(address, timeout=2) as sock, file as file: with socket.create_connection(address, timeout=2) as sock, file as file:
count = 100007 count = 100007
meth = self.meth_from_sock(sock) meth = self.meth_from_sock(sock)
@ -6128,7 +6129,7 @@ class SendfileUsingSendTest(ThreadedTCPSocketTest):
def _testNonBlocking(self): def _testNonBlocking(self):
address = self.serv.getsockname() address = self.serv.getsockname()
file = open(support.TESTFN, 'rb') file = open(os_helper.TESTFN, 'rb')
with socket.create_connection(address) as sock, file as file: with socket.create_connection(address) as sock, file as file:
sock.setblocking(False) sock.setblocking(False)
meth = self.meth_from_sock(sock) meth = self.meth_from_sock(sock)
@ -6144,7 +6145,7 @@ class SendfileUsingSendTest(ThreadedTCPSocketTest):
def _testWithTimeout(self): def _testWithTimeout(self):
address = self.serv.getsockname() address = self.serv.getsockname()
file = open(support.TESTFN, 'rb') file = open(os_helper.TESTFN, 'rb')
sock = socket.create_connection(address, sock = socket.create_connection(address,
timeout=support.LOOPBACK_TIMEOUT) timeout=support.LOOPBACK_TIMEOUT)
with sock, file: with sock, file:
@ -6162,7 +6163,7 @@ class SendfileUsingSendTest(ThreadedTCPSocketTest):
def _testWithTimeoutTriggeredSend(self): def _testWithTimeoutTriggeredSend(self):
address = self.serv.getsockname() address = self.serv.getsockname()
with open(support.TESTFN, 'rb') as file: with open(os_helper.TESTFN, 'rb') as file:
with socket.create_connection(address) as sock: with socket.create_connection(address) as sock:
sock.settimeout(0.01) sock.settimeout(0.01)
meth = self.meth_from_sock(sock) meth = self.meth_from_sock(sock)
@ -6178,17 +6179,17 @@ class SendfileUsingSendTest(ThreadedTCPSocketTest):
pass pass
def test_errors(self): def test_errors(self):
with open(support.TESTFN, 'rb') as file: with open(os_helper.TESTFN, 'rb') as file:
with socket.socket(type=socket.SOCK_DGRAM) as s: with socket.socket(type=socket.SOCK_DGRAM) as s:
meth = self.meth_from_sock(s) meth = self.meth_from_sock(s)
self.assertRaisesRegex( self.assertRaisesRegex(
ValueError, "SOCK_STREAM", meth, file) ValueError, "SOCK_STREAM", meth, file)
with open(support.TESTFN, 'rt') as file: with open(os_helper.TESTFN, 'rt') as file:
with socket.socket() as s: with socket.socket() as s:
meth = self.meth_from_sock(s) meth = self.meth_from_sock(s)
self.assertRaisesRegex( self.assertRaisesRegex(
ValueError, "binary mode", meth, file) ValueError, "binary mode", meth, file)
with open(support.TESTFN, 'rb') as file: with open(os_helper.TESTFN, 'rb') as file:
with socket.socket() as s: with socket.socket() as s:
meth = self.meth_from_sock(s) meth = self.meth_from_sock(s)
self.assertRaisesRegex(TypeError, "positive integer", self.assertRaisesRegex(TypeError, "positive integer",

View File

@ -5,9 +5,11 @@ import subprocess
import shutil import shutil
from copy import copy from copy import copy
from test.support import (import_module, TESTFN, unlink, check_warnings, from test.support import (captured_stdout, PythonSymlink)
captured_stdout, skip_unless_symlink, change_cwd, from test.support.import_helper import import_module
PythonSymlink) from test.support.os_helper import (TESTFN, unlink, skip_unless_symlink,
change_cwd)
from test.support.warnings_helper import check_warnings
import sysconfig import sysconfig
from sysconfig import (get_paths, get_platform, get_config_vars, from sysconfig import (get_paths, get_platform, get_config_vars,

View File

@ -7,7 +7,8 @@ import sys
import unittest import unittest
import re import re
from test import support from test import support
from test.support import TESTFN, Error, captured_output, unlink, cpython_only, ALWAYS_EQ from test.support import Error, captured_output, cpython_only, ALWAYS_EQ
from test.support.os_helper import TESTFN, unlink
from test.support.script_helper import assert_python_ok from test.support.script_helper import assert_python_ok
import textwrap import textwrap

View File

@ -15,6 +15,8 @@ import textwrap
import unicodedata import unicodedata
import unittest import unittest
import warnings import warnings
from test.support import import_helper
from test.support import warnings_helper
from test import support, string_tests from test import support, string_tests
from test.support.script_helper import assert_python_failure from test.support.script_helper import assert_python_failure
@ -504,7 +506,7 @@ class UnicodeTest(string_tests.CommonTest,
self.assertIs(text.replace(pattern, pattern), text) self.assertIs(text.replace(pattern, pattern), text)
def test_bytes_comparison(self): def test_bytes_comparison(self):
with support.check_warnings(): with warnings_helper.check_warnings():
warnings.simplefilter('ignore', BytesWarning) warnings.simplefilter('ignore', BytesWarning)
self.assertEqual('abc' == b'abc', False) self.assertEqual('abc' == b'abc', False)
self.assertEqual('abc' != b'abc', True) self.assertEqual('abc' != b'abc', True)
@ -725,7 +727,7 @@ class UnicodeTest(string_tests.CommonTest,
import _testcapi import _testcapi
u = '𝖀𝖓𝖎𝖈𝖔𝖉𝖊' u = '𝖀𝖓𝖎𝖈𝖔𝖉𝖊'
self.assertTrue(u.isidentifier()) self.assertTrue(u.isidentifier())
with support.check_warnings(): with warnings_helper.check_warnings():
warnings.simplefilter('ignore', DeprecationWarning) warnings.simplefilter('ignore', DeprecationWarning)
self.assertTrue(_testcapi.unicode_legacy_string(u).isidentifier()) self.assertTrue(_testcapi.unicode_legacy_string(u).isidentifier())
@ -2507,7 +2509,7 @@ class CAPITest(unittest.TestCase):
# Test PyUnicode_FromFormat() # Test PyUnicode_FromFormat()
def test_from_format(self): def test_from_format(self):
support.import_module('ctypes') import_helper.import_module('ctypes')
from ctypes import ( from ctypes import (
pythonapi, py_object, sizeof, pythonapi, py_object, sizeof,
c_int, c_long, c_longlong, c_ssize_t, c_int, c_long, c_longlong, c_ssize_t,
@ -2748,7 +2750,7 @@ class CAPITest(unittest.TestCase):
@support.cpython_only @support.cpython_only
def test_aswidechar(self): def test_aswidechar(self):
from _testcapi import unicode_aswidechar from _testcapi import unicode_aswidechar
support.import_module('ctypes') import_helper.import_module('ctypes')
from ctypes import c_wchar, sizeof from ctypes import c_wchar, sizeof
wchar, size = unicode_aswidechar('abcdef', 2) wchar, size = unicode_aswidechar('abcdef', 2)
@ -2786,7 +2788,7 @@ class CAPITest(unittest.TestCase):
@support.cpython_only @support.cpython_only
def test_aswidecharstring(self): def test_aswidecharstring(self):
from _testcapi import unicode_aswidecharstring from _testcapi import unicode_aswidecharstring
support.import_module('ctypes') import_helper.import_module('ctypes')
from ctypes import c_wchar, sizeof from ctypes import c_wchar, sizeof
wchar, size = unicode_aswidecharstring('abc') wchar, size = unicode_aswidecharstring('abc')

View File

@ -24,7 +24,12 @@ import weakref
from functools import partial from functools import partial
from itertools import product, islice from itertools import product, islice
from test import support from test import support
from test.support import TESTFN, findfile, import_fresh_module, gc_collect, swap_attr from test.support import os_helper
from test.support import warnings_helper
from test.support import findfile, gc_collect, swap_attr
from test.support.import_helper import import_fresh_module
from test.support.os_helper import TESTFN
# pyET is the pure-Python implementation. # pyET is the pure-Python implementation.
# #
@ -601,7 +606,7 @@ class ElementTreeTest(unittest.TestCase):
self.assertFalse(f.closed) self.assertFalse(f.closed)
self.assertEqual(str(cm.exception), "unknown event 'bogus'") self.assertEqual(str(cm.exception), "unknown event 'bogus'")
with support.check_no_resource_warning(self): with warnings_helper.check_no_resource_warning(self):
with self.assertRaises(ValueError) as cm: with self.assertRaises(ValueError) as cm:
iterparse(SIMPLE_XMLFILE, events) iterparse(SIMPLE_XMLFILE, events)
self.assertEqual(str(cm.exception), "unknown event 'bogus'") self.assertEqual(str(cm.exception), "unknown event 'bogus'")
@ -627,13 +632,13 @@ class ElementTreeTest(unittest.TestCase):
self.assertEqual(str(cm.exception), self.assertEqual(str(cm.exception),
'junk after document element: line 1, column 12') 'junk after document element: line 1, column 12')
self.addCleanup(support.unlink, TESTFN) self.addCleanup(os_helper.unlink, TESTFN)
with open(TESTFN, "wb") as f: with open(TESTFN, "wb") as f:
f.write(b"<document />junk") f.write(b"<document />junk")
it = iterparse(TESTFN) it = iterparse(TESTFN)
action, elem = next(it) action, elem = next(it)
self.assertEqual((action, elem.tag), ('end', 'document')) self.assertEqual((action, elem.tag), ('end', 'document'))
with support.check_no_resource_warning(self): with warnings_helper.check_no_resource_warning(self):
with self.assertRaises(ET.ParseError) as cm: with self.assertRaises(ET.ParseError) as cm:
next(it) next(it)
self.assertEqual(str(cm.exception), self.assertEqual(str(cm.exception),
@ -3641,14 +3646,14 @@ class IOTest(unittest.TestCase):
"<tag key=\"åöö&lt;&gt;\" />" % enc).encode(enc)) "<tag key=\"åöö&lt;&gt;\" />" % enc).encode(enc))
def test_write_to_filename(self): def test_write_to_filename(self):
self.addCleanup(support.unlink, TESTFN) self.addCleanup(os_helper.unlink, TESTFN)
tree = ET.ElementTree(ET.XML('''<site />''')) tree = ET.ElementTree(ET.XML('''<site />'''))
tree.write(TESTFN) tree.write(TESTFN)
with open(TESTFN, 'rb') as f: with open(TESTFN, 'rb') as f:
self.assertEqual(f.read(), b'''<site />''') self.assertEqual(f.read(), b'''<site />''')
def test_write_to_text_file(self): def test_write_to_text_file(self):
self.addCleanup(support.unlink, TESTFN) self.addCleanup(os_helper.unlink, TESTFN)
tree = ET.ElementTree(ET.XML('''<site />''')) tree = ET.ElementTree(ET.XML('''<site />'''))
with open(TESTFN, 'w', encoding='utf-8') as f: with open(TESTFN, 'w', encoding='utf-8') as f:
tree.write(f, encoding='unicode') tree.write(f, encoding='unicode')
@ -3657,7 +3662,7 @@ class IOTest(unittest.TestCase):
self.assertEqual(f.read(), b'''<site />''') self.assertEqual(f.read(), b'''<site />''')
def test_write_to_binary_file(self): def test_write_to_binary_file(self):
self.addCleanup(support.unlink, TESTFN) self.addCleanup(os_helper.unlink, TESTFN)
tree = ET.ElementTree(ET.XML('''<site />''')) tree = ET.ElementTree(ET.XML('''<site />'''))
with open(TESTFN, 'wb') as f: with open(TESTFN, 'wb') as f:
tree.write(f) tree.write(f)
@ -3666,7 +3671,7 @@ class IOTest(unittest.TestCase):
self.assertEqual(f.read(), b'''<site />''') self.assertEqual(f.read(), b'''<site />''')
def test_write_to_binary_file_with_bom(self): def test_write_to_binary_file_with_bom(self):
self.addCleanup(support.unlink, TESTFN) self.addCleanup(os_helper.unlink, TESTFN)
tree = ET.ElementTree(ET.XML('''<site />''')) tree = ET.ElementTree(ET.XML('''<site />'''))
# test BOM writing to buffered file # test BOM writing to buffered file
with open(TESTFN, 'wb') as f: with open(TESTFN, 'wb') as f:

View File

@ -19,9 +19,10 @@ from tempfile import TemporaryFile
from random import randint, random, randbytes from random import randint, random, randbytes
from test.support import script_helper from test.support import script_helper
from test.support import (TESTFN, findfile, unlink, rmtree, temp_dir, temp_cwd, from test.support import (findfile, requires_zlib, requires_bz2,
requires_zlib, requires_bz2, requires_lzma, requires_lzma, captured_stdout)
captured_stdout) from test.support.os_helper import TESTFN, unlink, rmtree, temp_dir, temp_cwd
TESTFN2 = TESTFN + "2" TESTFN2 = TESTFN + "2"
TESTFNDIR = TESTFN + "d" TESTFNDIR = TESTFN + "d"