Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 7 additions & 7 deletions Lib/test/support/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -705,9 +705,8 @@ def find_unused_port(family=socket.AF_INET, socktype=socket.SOCK_STREAM):
issue if/when we come across it.
"""

tempsock = socket.socket(family, socktype)
port = bind_port(tempsock)
tempsock.close()
with socket.socket(family, socktype) as tempsock:
port = bind_port(tempsock)
del tempsock
return port

Expand Down Expand Up @@ -1752,10 +1751,11 @@ def start(self):
sys.stderr.flush()
return

watchdog_script = findfile("memory_watchdog.py")
self.mem_watchdog = subprocess.Popen([sys.executable, watchdog_script],
stdin=f, stderr=subprocess.DEVNULL)
f.close()
with f:
watchdog_script = findfile("memory_watchdog.py")
self.mem_watchdog = subprocess.Popen([sys.executable, watchdog_script],
stdin=f,
stderr=subprocess.DEVNULL)
self.started = True

def stop(self):
Expand Down
51 changes: 23 additions & 28 deletions Lib/test/support/script_helper.py
Original file line number Diff line number Diff line change
Expand Up @@ -205,31 +205,28 @@ def make_script(script_dir, script_basename, source, omit_suffix=False):
script_filename += os.extsep + 'py'
script_name = os.path.join(script_dir, script_filename)
# The script should be encoded to UTF-8, the default string encoding
script_file = open(script_name, 'w', encoding='utf-8')
script_file.write(source)
script_file.close()
with open(script_name, 'w', encoding='utf-8') as script_file:
script_file.write(source)
importlib.invalidate_caches()
return script_name

def make_zip_script(zip_dir, zip_basename, script_name, name_in_zip=None):
zip_filename = zip_basename+os.extsep+'zip'
zip_name = os.path.join(zip_dir, zip_filename)
zip_file = zipfile.ZipFile(zip_name, 'w')
if name_in_zip is None:
parts = script_name.split(os.sep)
if len(parts) >= 2 and parts[-2] == '__pycache__':
legacy_pyc = make_legacy_pyc(source_from_cache(script_name))
name_in_zip = os.path.basename(legacy_pyc)
script_name = legacy_pyc
else:
name_in_zip = os.path.basename(script_name)
zip_file.write(script_name, name_in_zip)
zip_file.close()
with zipfile.ZipFile(zip_name, 'w') as zip_file:
if name_in_zip is None:
parts = script_name.split(os.sep)
if len(parts) >= 2 and parts[-2] == '__pycache__':
legacy_pyc = make_legacy_pyc(source_from_cache(script_name))
name_in_zip = os.path.basename(legacy_pyc)
script_name = legacy_pyc
else:
name_in_zip = os.path.basename(script_name)
zip_file.write(script_name, name_in_zip)
#if test.support.verbose:
# zip_file = zipfile.ZipFile(zip_name, 'r')
# print 'Contents of %r:' % zip_name
# zip_file.printdir()
# zip_file.close()
# with zipfile.ZipFile(zip_name, 'r') as zip_file:
# print 'Contents of %r:' % zip_name
# zip_file.printdir()
return zip_name, os.path.join(zip_name, name_in_zip)

def make_pkg(pkg_dir, init_source=''):
Expand All @@ -252,17 +249,15 @@ def make_zip_pkg(zip_dir, zip_basename, pkg_name, script_basename,
script_name_in_zip = os.path.join(pkg_names[-1], os.path.basename(script_name))
zip_filename = zip_basename+os.extsep+'zip'
zip_name = os.path.join(zip_dir, zip_filename)
zip_file = zipfile.ZipFile(zip_name, 'w')
for name in pkg_names:
init_name_in_zip = os.path.join(name, init_basename)
zip_file.write(init_name, init_name_in_zip)
zip_file.write(script_name, script_name_in_zip)
zip_file.close()
with zipfile.ZipFile(zip_name, 'w') as zip_file:
for name in pkg_names:
init_name_in_zip = os.path.join(name, init_basename)
zip_file.write(init_name, init_name_in_zip)
zip_file.write(script_name, script_name_in_zip)
for name in unlink:
os.unlink(name)
#if test.support.verbose:
# zip_file = zipfile.ZipFile(zip_name, 'r')
# print 'Contents of %r:' % zip_name
# zip_file.printdir()
# zip_file.close()
# with zipfile.ZipFile(zip_name, 'r') as zip_file:
# print 'Contents of %r:' % zip_name
# zip_file.printdir()
return zip_name, os.path.join(zip_name, script_name_in_zip)
20 changes: 8 additions & 12 deletions Lib/test/test_argparse.py
Original file line number Diff line number Diff line change
Expand Up @@ -1379,9 +1379,8 @@ def setUp(self):
('invalid', '@no-such-path\n'),
]
for path, text in file_texts:
file = open(path, 'w')
file.write(text)
file.close()
with open(path, 'w') as file:
file.write(text)

parser_signature = Sig(fromfile_prefix_chars='@')
argument_signatures = [
Expand Down Expand Up @@ -1410,9 +1409,8 @@ def setUp(self):
('hello', 'hello world!\n'),
]
for path, text in file_texts:
file = open(path, 'w')
file.write(text)
file.close()
with open(path, 'w') as file:
file.write(text)

class FromFileConverterArgumentParser(ErrorRaisingArgumentParser):

Expand Down Expand Up @@ -1493,9 +1491,8 @@ class TestFileTypeR(TempDirMixin, ParserTestCase):
def setUp(self):
super(TestFileTypeR, self).setUp()
for file_name in ['foo', 'bar']:
file = open(os.path.join(self.temp_dir, file_name), 'w')
file.write(file_name)
file.close()
with open(os.path.join(self.temp_dir, file_name), 'w') as file:
file.write(file_name)
self.create_readonly_file('readonly')

argument_signatures = [
Expand Down Expand Up @@ -1534,9 +1531,8 @@ class TestFileTypeRB(TempDirMixin, ParserTestCase):
def setUp(self):
super(TestFileTypeRB, self).setUp()
for file_name in ['foo', 'bar']:
file = open(os.path.join(self.temp_dir, file_name), 'w')
file.write(file_name)
file.close()
with open(os.path.join(self.temp_dir, file_name), 'w') as file:
file.write(file_name)

argument_signatures = [
Sig('-x', type=argparse.FileType('rb')),
Expand Down
10 changes: 4 additions & 6 deletions Lib/test/test_binhex.py
Original file line number Diff line number Diff line change
Expand Up @@ -23,17 +23,15 @@ def tearDown(self):
DATA = b'Jack is my hero'

def test_binhex(self):
f = open(self.fname1, 'wb')
f.write(self.DATA)
f.close()
with open(self.fname1, 'wb') as f:
f.write(self.DATA)

binhex.binhex(self.fname1, self.fname2)

binhex.hexbin(self.fname2, self.fname1)

f = open(self.fname1, 'rb')
finish = f.readline()
f.close()
with open(self.fname1, 'rb') as f:
finish = f.readline()

self.assertEqual(self.DATA, finish)

Expand Down
15 changes: 6 additions & 9 deletions Lib/test/test_bool.py
Original file line number Diff line number Diff line change
Expand Up @@ -20,13 +20,11 @@ class C(bool):

def test_print(self):
try:
fo = open(support.TESTFN, "w")
print(False, True, file=fo)
fo.close()
fo = open(support.TESTFN, "r")
self.assertEqual(fo.read(), 'False True\n')
with open(support.TESTFN, "w") as fo:
print(False, True, file=fo)
with open(support.TESTFN, "r") as fi:
self.assertEqual(fi.read(), 'False True\n')
finally:
fo.close()
os.remove(support.TESTFN)

def test_repr(self):
Expand Down Expand Up @@ -245,9 +243,8 @@ def test_boolean(self):

def test_fileclosed(self):
try:
f = open(support.TESTFN, "w")
self.assertIs(f.closed, False)
f.close()
with open(support.TESTFN, "w") as f:
self.assertIs(f.closed, False)
self.assertIs(f.closed, True)
finally:
os.remove(support.TESTFN)
Expand Down
5 changes: 2 additions & 3 deletions Lib/test/test_codecs.py
Original file line number Diff line number Diff line change
Expand Up @@ -1242,9 +1242,8 @@ def test_errors(self):
class RecodingTest(unittest.TestCase):
def test_recoding(self):
f = io.BytesIO()
f2 = codecs.EncodedFile(f, "unicode_internal", "utf-8")
f2.write("a")
f2.close()
with codecs.EncodedFile(f, "unicode_internal", "utf-8") as f2:
f2.write("a")
# Python used to crash on this at exit because of a refcount
# bug in _codecsmodule.c

Expand Down
17 changes: 8 additions & 9 deletions Lib/test/test_epoll.py
Original file line number Diff line number Diff line change
Expand Up @@ -143,18 +143,17 @@ def test_add(self):
def test_fromfd(self):
server, client = self._connected_pair()

ep = select.epoll(2)
ep2 = select.epoll.fromfd(ep.fileno())
with select.epoll(2) as ep:
ep2 = select.epoll.fromfd(ep.fileno())

ep2.register(server.fileno(), select.EPOLLIN | select.EPOLLOUT)
ep2.register(client.fileno(), select.EPOLLIN | select.EPOLLOUT)
ep2.register(server.fileno(), select.EPOLLIN | select.EPOLLOUT)
ep2.register(client.fileno(), select.EPOLLIN | select.EPOLLOUT)

events = ep.poll(1, 4)
events2 = ep2.poll(0.9, 4)
self.assertEqual(len(events), 2)
self.assertEqual(len(events2), 2)
events = ep.poll(1, 4)
events2 = ep2.poll(0.9, 4)
self.assertEqual(len(events), 2)
self.assertEqual(len(events2), 2)

ep.close()
try:
ep2.poll(1, 4)
except OSError as e:
Expand Down
17 changes: 8 additions & 9 deletions Lib/test/test_float.py
Original file line number Diff line number Diff line change
Expand Up @@ -722,15 +722,14 @@ def test_issue35560(self):

class ReprTestCase(unittest.TestCase):
def test_repr(self):
floats_file = open(os.path.join(os.path.split(__file__)[0],
'floating_points.txt'))
for line in floats_file:
line = line.strip()
if not line or line.startswith('#'):
continue
v = eval(line)
self.assertEqual(v, eval(repr(v)))
floats_file.close()
with open(os.path.join(os.path.split(__file__)[0],
'floating_points.txt')) as floats_file:
for line in floats_file:
line = line.strip()
if not line or line.startswith('#'):
continue
v = eval(line)
self.assertEqual(v, eval(repr(v)))

@unittest.skipUnless(getattr(sys, 'float_repr_style', '') == 'short',
"applies only when using short float repr style")
Expand Down
6 changes: 3 additions & 3 deletions Lib/test/test_ioctl.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,9 +11,9 @@
except OSError:
raise unittest.SkipTest("Unable to open /dev/tty")
else:
# Skip if another process is in foreground
r = fcntl.ioctl(tty, termios.TIOCGPGRP, " ")
tty.close()
with tty:
# Skip if another process is in foreground
r = fcntl.ioctl(tty, termios.TIOCGPGRP, " ")
rpgrp = struct.unpack("i", r)[0]
if rpgrp not in (os.getpgrp(), os.getsid(0)):
raise unittest.SkipTest("Neither the process group nor the session "
Expand Down
5 changes: 2 additions & 3 deletions Lib/test/test_os.py
Original file line number Diff line number Diff line change
Expand Up @@ -1201,9 +1201,8 @@ def test_exist_ok_s_isgid_directory(self):
def test_exist_ok_existing_regular_file(self):
base = support.TESTFN
path = os.path.join(support.TESTFN, 'dir1')
f = open(path, 'w')
f.write('abc')
f.close()
with open(path, 'w') as f:
f.write('abc')
self.assertRaises(OSError, os.makedirs, path)
self.assertRaises(OSError, os.makedirs, path, exist_ok=False)
self.assertRaises(OSError, os.makedirs, path, exist_ok=True)
Expand Down
5 changes: 2 additions & 3 deletions Lib/test/test_pipes.py
Original file line number Diff line number Diff line change
Expand Up @@ -23,9 +23,8 @@ def testSimplePipe1(self):
self.skipTest('tr is not available')
t = pipes.Template()
t.append(s_command, pipes.STDIN_STDOUT)
f = t.open(TESTFN, 'w')
f.write('hello world #1')
f.close()
with t.open(TESTFN, 'w') as f:
f.write('hello world #1')
with open(TESTFN) as f:
self.assertEqual(f.read(), 'HELLO WORLD #1')

Expand Down
13 changes: 6 additions & 7 deletions Lib/test/test_poll.py
Original file line number Diff line number Diff line change
Expand Up @@ -83,13 +83,12 @@ def test_poll_unit_tests(self):
r = p.poll()
self.assertEqual(r[0], (FD, select.POLLNVAL))

f = open(TESTFN, 'w')
fd = f.fileno()
p = select.poll()
p.register(f)
r = p.poll()
self.assertEqual(r[0][0], fd)
f.close()
with open(TESTFN, 'w') as f:
fd = f.fileno()
p = select.poll()
p.register(f)
r = p.poll()
self.assertEqual(r[0][0], fd)
r = p.poll()
self.assertEqual(r[0], (fd, select.POLLNVAL))
os.unlink(TESTFN)
Expand Down
5 changes: 2 additions & 3 deletions Lib/test/test_random.py
Original file line number Diff line number Diff line change
Expand Up @@ -268,9 +268,8 @@ def test_bug_1727780(self):
("randv2_64.pck", 866),
("randv3.pck", 343)]
for file, value in files:
f = open(support.findfile(file),"rb")
r = pickle.load(f)
f.close()
with open(support.findfile(file),"rb") as f:
r = pickle.load(f)
self.assertEqual(int(r.random()*1000), value)

def test_bug_9025(self):
Expand Down
5 changes: 2 additions & 3 deletions Lib/test/test_runpy.py
Original file line number Diff line number Diff line change
Expand Up @@ -238,9 +238,8 @@ def _make_pkg(self, source, depth, mod_base="runpy_test",
if verbose > 1: print(" Next level in:", sub_dir)
if verbose > 1: print(" Created:", pkg_fname)
mod_fname = os.path.join(sub_dir, test_fname)
mod_file = open(mod_fname, "w")
mod_file.write(source)
mod_file.close()
with open(mod_fname, "w") as mod_file:
mod_file.write(source)
if verbose > 1: print(" Created:", mod_fname)
mod_name = (pkg_name+".")*depth + mod_base
mod_spec = importlib.util.spec_from_file_location(mod_name,
Expand Down
31 changes: 15 additions & 16 deletions Lib/test/test_select.py
Original file line number Diff line number Diff line change
Expand Up @@ -46,24 +46,23 @@ def test_returned_list_identity(self):

def test_select(self):
cmd = 'for i in 0 1 2 3 4 5 6 7 8 9; do echo testing...; sleep 1; done'
p = os.popen(cmd, 'r')
for tout in (0, 1, 2, 4, 8, 16) + (None,)*10:
if support.verbose:
print('timeout =', tout)
rfd, wfd, xfd = select.select([p], [], [], tout)
if (rfd, wfd, xfd) == ([], [], []):
continue
if (rfd, wfd, xfd) == ([p], [], []):
line = p.readline()
with os.popen(cmd) as p:
for tout in (0, 1, 2, 4, 8, 16) + (None,)*10:
if support.verbose:
print(repr(line))
if not line:
print('timeout =', tout)
rfd, wfd, xfd = select.select([p], [], [], tout)
if (rfd, wfd, xfd) == ([], [], []):
continue
if (rfd, wfd, xfd) == ([p], [], []):
line = p.readline()
if support.verbose:
print('EOF')
break
continue
self.fail('Unexpected return values from select():', rfd, wfd, xfd)
p.close()
print(repr(line))
if not line:
if support.verbose:
print('EOF')
break
continue
self.fail('Unexpected return values from select():', rfd, wfd, xfd)

# Issue 16230: Crash on select resized list
def test_select_mutated(self):
Expand Down
Loading