Skip to content

Commit ed871c6

Browse files
author
Rémi Lapeyre
committed
Add fd leakage tests
1 parent 6cae5c5 commit ed871c6

File tree

1 file changed

+55
-0
lines changed

1 file changed

+55
-0
lines changed

Lib/test/test_json/test_tool.py

Lines changed: 55 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,13 @@
1+
import io
12
import os
23
import sys
34
import textwrap
45
import unittest
6+
import types
57
from subprocess import Popen, PIPE
68
from test import support
79
from test.support.script_helper import assert_python_ok, assert_python_failure
10+
from unittest import mock
811

912

1013
class TestTool(unittest.TestCase):
@@ -121,3 +124,55 @@ def test_sort_keys_flag(self):
121124
self.assertEqual(out.splitlines(),
122125
self.expect_without_sort_keys.encode().splitlines())
123126
self.assertEqual(err, b'')
127+
128+
def test_no_fd_leak_infile_outfile(self):
129+
closed = []
130+
opened = []
131+
io_open = io.open
132+
133+
def open(*args, **kwargs):
134+
fd = io_open(*args, **kwargs)
135+
opened.append(fd)
136+
fd_close = fd.close
137+
def close(self):
138+
closed.append(self)
139+
fd_close()
140+
fd.close = types.MethodType(close, fd)
141+
return fd
142+
143+
infile = self._create_infile()
144+
with mock.patch('builtins.open', side_effect=open):
145+
with mock.patch.object(sys, 'argv', ['tool.py', infile, infile + '.out']):
146+
import json.tool
147+
json.tool.main()
148+
149+
os.unlink(infile + '.out')
150+
self.assertEqual(opened, closed)
151+
self.assertEqual(len(opened), len(closed))
152+
153+
def test_no_fd_leak_same_infile_outfile(self):
154+
closed = []
155+
opened = []
156+
io_open = io.open
157+
158+
def open(*args, **kwargs):
159+
fd = io_open(*args, **kwargs)
160+
opened.append(fd)
161+
fd_close = fd.close
162+
def close(self):
163+
closed.append(self)
164+
fd_close()
165+
fd.close = types.MethodType(close, fd)
166+
return fd
167+
168+
infile = self._create_infile()
169+
with mock.patch('builtins.open', side_effect=open):
170+
with mock.patch.object(sys, 'argv', ['tool.py', infile, infile]):
171+
try:
172+
import json.tool
173+
json.tool.main()
174+
except SystemExit: # We expect SystemExit to happen on c9d43c
175+
pass
176+
177+
self.assertEqual(opened, closed)
178+
self.assertEqual(len(opened), len(closed))

0 commit comments

Comments
 (0)