Skip to content

Commit 4d47cc6

Browse files
whitslackrustyrussell
authored andcommitted
tests: do not leak file descriptors
Changelog-None
1 parent f7204c8 commit 4d47cc6

File tree

10 files changed

+113
-105
lines changed

10 files changed

+113
-105
lines changed

contrib/pyln-testing/pyln/testing/utils.py

Lines changed: 9 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -940,7 +940,7 @@ def grpc(self):
940940

941941
import grpc
942942
p = Path(self.daemon.lightning_dir) / TEST_NETWORK
943-
cert, key, ca = [f.open('rb').read() for f in [
943+
cert, key, ca = [f.read_bytes() for f in [
944944
p / 'client.pem',
945945
p / 'client-key.pem',
946946
p / "ca.pem"]]
@@ -1691,16 +1691,16 @@ def get_node(self, node_id=None, options=None, dbfile=None,
16911691
self.nodes.append(node)
16921692
self.reserved_ports.append(port)
16931693
if dbfile:
1694-
out = open(os.path.join(node.daemon.lightning_dir, TEST_NETWORK,
1695-
'lightningd.sqlite3'), 'xb')
1696-
with lzma.open(os.path.join('tests/data', dbfile), 'rb') as f:
1697-
out.write(f.read())
1694+
with open(os.path.join(node.daemon.lightning_dir, TEST_NETWORK,
1695+
'lightningd.sqlite3'), 'xb') as out:
1696+
with lzma.open(os.path.join('tests/data', dbfile), 'rb') as f:
1697+
out.write(f.read())
16981698

16991699
if bkpr_dbfile:
1700-
out = open(os.path.join(node.daemon.lightning_dir, TEST_NETWORK,
1701-
'accounts.sqlite3'), 'xb')
1702-
with lzma.open(os.path.join('tests/data', bkpr_dbfile), 'rb') as f:
1703-
out.write(f.read())
1700+
with open(os.path.join(node.daemon.lightning_dir, TEST_NETWORK,
1701+
'accounts.sqlite3'), 'xb') as out:
1702+
with lzma.open(os.path.join('tests/data', bkpr_dbfile), 'rb') as f:
1703+
out.write(f.read())
17041704

17051705
if gossip_store_file:
17061706
shutil.copy(gossip_store_file, os.path.join(node.daemon.lightning_dir, TEST_NETWORK,

tests/fixtures.py

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -58,7 +58,8 @@ class CompatLevel(object):
5858
"""
5959
def __init__(self):
6060
makefile = os.path.join(os.path.dirname(__file__), "..", "Makefile")
61-
lines = [l for l in open(makefile, 'r') if l.startswith('COMPAT_CFLAGS')]
61+
with open(makefile, 'r') as f:
62+
lines = [l for l in f if l.startswith('COMPAT_CFLAGS')]
6263
assert(len(lines) == 1)
6364
line = lines[0]
6465
flags = re.findall(r'COMPAT_V([0-9]+)=1', line)

tests/test_bookkeeper.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -690,15 +690,15 @@ def test_bookkeeping_descriptions(node_factory, bitcoind, chainparams):
690690
l1.rpc.bkpr_dumpincomecsv('koinly', 'koinly.csv')
691691
l2.rpc.bkpr_dumpincomecsv('koinly', 'koinly.csv')
692692
koinly_path = os.path.join(l1.daemon.lightning_dir, TEST_NETWORK, 'koinly.csv')
693-
l1_koinly_csv = open(koinly_path, 'rb').read()
693+
l1_koinly_csv = Path(koinly_path).read_bytes()
694694
bolt11_exp = bytes('invoice,"test \'bolt11\' description, 🥰🪢",', 'utf-8')
695695
bolt12_exp = bytes('invoice,"test \'bolt12\' description, 🥰🪢",', 'utf-8')
696696

697697
assert l1_koinly_csv.find(bolt11_exp) >= 0
698698
assert l1_koinly_csv.find(bolt12_exp) >= 0
699699

700700
koinly_path = os.path.join(l2.daemon.lightning_dir, TEST_NETWORK, 'koinly.csv')
701-
l2_koinly_csv = open(koinly_path, 'rb').read()
701+
l2_koinly_csv = Path(koinly_path).read_bytes()
702702
assert l2_koinly_csv.find(bolt11_exp) >= 0
703703
assert l2_koinly_csv.find(bolt12_exp) >= 0
704704

tests/test_cln_rs.py

Lines changed: 8 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -129,9 +129,9 @@ def test_grpc_connect(node_factory):
129129
key_path = p / "client-key.pem"
130130
ca_cert_path = p / "ca.pem"
131131
creds = grpc.ssl_channel_credentials(
132-
root_certificates=ca_cert_path.open('rb').read(),
133-
private_key=key_path.open('rb').read(),
134-
certificate_chain=cert_path.open('rb').read()
132+
root_certificates=ca_cert_path.read_bytes(),
133+
private_key=key_path.read_bytes(),
134+
certificate_chain=cert_path.read_bytes()
135135
)
136136

137137
wait_for_grpc_start(l1)
@@ -196,15 +196,15 @@ def test_grpc_generate_certificate(node_factory):
196196
assert [f.exists() for f in files] == [True] * len(files)
197197

198198
# The files exist, restarting should not change them
199-
contents = [f.open().read() for f in files]
199+
contents = [f.read_bytes() for f in files]
200200
l1.restart()
201-
assert contents == [f.open().read() for f in files]
201+
assert contents == [f.read_bytes() for f in files]
202202

203203
# Now we delete the last file, we should regenerate it as well as its key
204204
files[-1].unlink()
205205
l1.restart()
206-
assert contents[-2] != files[-2].open().read()
207-
assert contents[-1] != files[-1].open().read()
206+
assert contents[-2] != files[-2].read_bytes()
207+
assert contents[-1] != files[-1].read_bytes()
208208

209209
keys = [f for f in files if f.name.endswith('-key.pem')]
210210
modes = [f.stat().st_mode for f in keys]
@@ -241,7 +241,7 @@ def test_grpc_wrong_auth(node_factory):
241241

242242
def connect(node):
243243
p = Path(node.daemon.lightning_dir) / TEST_NETWORK
244-
cert, key, ca = [f.open('rb').read() for f in [
244+
cert, key, ca = [f.read_bytes() for f in [
245245
p / 'client.pem',
246246
p / 'client-key.pem',
247247
p / "ca.pem"]]

tests/test_clnrest.py

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -105,22 +105,22 @@ def test_generate_certificate(node_factory):
105105
wait_for(lambda: [f.exists() for f in files] == [True] * len(files))
106106

107107
# the files exist, restarting should not change them
108-
contents = [f.open().read() for f in files]
108+
contents = [f.read_bytes() for f in files]
109109
l1.restart()
110-
assert contents == [f.open().read() for f in files]
110+
assert contents == [f.read_bytes() for f in files]
111111

112112
# remove client.pem file, so all certs are regenerated at restart
113113
files[2].unlink()
114114
l1.restart()
115115
wait_for(lambda: [f.exists() for f in files] == [True] * len(files))
116-
contents_1 = [f.open().read() for f in files]
116+
contents_1 = [f.read_bytes() for f in files]
117117
assert [c[0] != c[1] for c in zip(contents, contents_1)] == [True] * len(files)
118118

119119
# remove client-key.pem file, so all certs are regenerated at restart
120120
files[3].unlink()
121121
l1.restart()
122122
wait_for(lambda: [f.exists() for f in files] == [True] * len(files))
123-
contents_2 = [f.open().read() for f in files]
123+
contents_2 = [f.read_bytes() for f in files]
124124
assert [c[0] != c[1] for c in zip(contents, contents_2)] == [True] * len(files)
125125

126126

tests/test_connection.py

Lines changed: 7 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
from fixtures import * # noqa: F401,F403
22
from fixtures import TEST_NETWORK
33
from decimal import Decimal
4+
from pathlib import Path
45
from pyln.client import RpcError, Millisatoshi
56
import pyln.proto.wire as wire
67
from utils import (
@@ -3019,7 +3020,7 @@ def test_dataloss_protection(node_factory, bitcoind):
30193020

30203021
# Save copy of the db.
30213022
dbpath = os.path.join(l2.daemon.lightning_dir, TEST_NETWORK, "lightningd.sqlite3")
3022-
orig_db = open(dbpath, "rb").read()
3023+
orig_db = Path(dbpath).read_bytes()
30233024
l2.start()
30243025

30253026
# l1 should have sent WIRE_CHANNEL_REESTABLISH with extra fields.
@@ -3063,7 +3064,7 @@ def test_dataloss_protection(node_factory, bitcoind):
30633064
# Now, move l2 back in time.
30643065
l2.stop()
30653066
# Overwrite with OLD db.
3066-
open(dbpath, "wb").write(orig_db)
3067+
Path(dbpath).write_bytes(orig_db)
30673068
l2.start()
30683069

30693070
# l2 should freak out!
@@ -3118,7 +3119,7 @@ def test_dataloss_protection_no_broadcast(node_factory, bitcoind):
31183119

31193120
# Save copy of the db.
31203121
dbpath = os.path.join(l2.daemon.lightning_dir, TEST_NETWORK, "lightningd.sqlite3")
3121-
orig_db = open(dbpath, "rb").read()
3122+
orig_db = Path(dbpath).read_bytes()
31223123
l2.start()
31233124

31243125
l1.rpc.connect(l2.info['id'], 'localhost', l2.port)
@@ -3133,9 +3134,9 @@ def test_dataloss_protection_no_broadcast(node_factory, bitcoind):
31333134
# Now, move l2 back in time.
31343135
l2.stop()
31353136
# Save new db
3136-
new_db = open(dbpath, "rb").read()
3137+
new_db = Path(dbpath).read_bytes()
31373138
# Overwrite with OLD db.
3138-
open(dbpath, "wb").write(orig_db)
3139+
Path(dbpath).write_bytes(orig_db)
31393140
l2.start()
31403141

31413142
l1.rpc.connect(l2.info['id'], 'localhost', l2.port)
@@ -3149,7 +3150,7 @@ def test_dataloss_protection_no_broadcast(node_factory, bitcoind):
31493150

31503151
# fix up l2.
31513152
l2.stop()
3152-
open(dbpath, "wb").write(new_db)
3153+
Path(dbpath).write_bytes(new_db)
31533154
l2.start()
31543155

31553156
# All is forgiven

tests/test_misc.py

Lines changed: 62 additions & 57 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@
33
from decimal import Decimal
44
from fixtures import * # noqa: F401,F403
55
from fixtures import LightningNode, TEST_NETWORK
6+
from pathlib import Path
67
from pyln.client import RpcError, Millisatoshi
78
from threading import Event
89
from pyln.testing.utils import (
@@ -1899,11 +1900,13 @@ def test_logging(node_factory):
18991900
wait_for(lambda: os.path.exists(logpath_moved))
19001901
wait_for(lambda: os.path.exists(logpath))
19011902

1902-
log1 = open(logpath_moved).readlines()
1903+
with open(logpath_moved) as f:
1904+
log1 = f.readlines()
19031905
assert log1[-1].endswith("Ending log due to SIGHUP\n")
19041906

19051907
def check_new_log():
1906-
log2 = open(logpath).readlines()
1908+
with open(logpath) as f:
1909+
log2 = f.readlines()
19071910
return len(log2) > 0 and log2[0].endswith("Started log due to SIGHUP\n")
19081911
wait_for(check_new_log)
19091912

@@ -3106,7 +3109,7 @@ def test_recover_plugin(node_factory, bitcoind):
31063109

31073110
# Save copy of the db.
31083111
dbpath = os.path.join(l2.daemon.lightning_dir, TEST_NETWORK, "lightningd.sqlite3")
3109-
orig_db = open(dbpath, "rb").read()
3112+
orig_db = Path(dbpath).read_bytes()
31103113

31113114
l2.start()
31123115

@@ -3121,7 +3124,7 @@ def test_recover_plugin(node_factory, bitcoind):
31213124
l2.stop()
31223125

31233126
# Overwrite with OLD db.
3124-
open(dbpath, "wb").write(orig_db)
3127+
Path(dbpath).write_bytes(orig_db)
31253128

31263129
l2.start()
31273130

@@ -4917,45 +4920,46 @@ def test_tracing(node_factory):
49174920
traces = set()
49184921
suspended = set()
49194922
for fname in glob.glob(f"{trace_fnamebase}.*"):
4920-
for linenum, l in enumerate(open(fname, "rt").readlines(), 1):
4921-
# In case an assertion fails
4922-
print(f"Parsing {fname}:{linenum}")
4923-
parts = l.split(maxsplit=2)
4924-
cmd = parts[0]
4925-
spanid = parts[1]
4926-
if cmd == 'span_emit':
4927-
assert spanid in traces
4928-
assert spanid not in suspended
4929-
# Should be valid JSON
4930-
res = json.loads(parts[2])
4931-
4932-
# This is an array for some reason
4933-
assert len(res) == 1
4934-
res = res[0]
4935-
assert res['id'] == spanid
4936-
assert res['localEndpoint'] == {"serviceName": "lightningd"}
4937-
expected_keys = ['id', 'name', 'timestamp', 'duration', 'tags', 'traceId', 'localEndpoint']
4938-
if 'parentId' in res:
4939-
assert res['parentId'] in traces
4940-
expected_keys.append('parentId')
4941-
assert set(res.keys()) == set(expected_keys)
4942-
traces.remove(spanid)
4943-
elif cmd == 'span_end':
4944-
assert spanid in traces
4945-
elif cmd == 'span_start':
4946-
assert spanid not in traces
4947-
traces.add(spanid)
4948-
elif cmd == 'span_suspend':
4949-
assert spanid in traces
4950-
assert spanid not in suspended
4951-
suspended.add(spanid)
4952-
elif cmd == 'span_resume':
4953-
assert spanid in traces
4954-
suspended.remove(spanid)
4955-
elif cmd == 'destroying':
4956-
pass
4957-
else:
4958-
assert False, "Unknown trace line"
4923+
with open(fname, "rt") as f:
4924+
for linenum, l in enumerate(f.readlines(), 1):
4925+
# In case an assertion fails
4926+
print(f"Parsing {fname}:{linenum}")
4927+
parts = l.split(maxsplit=2)
4928+
cmd = parts[0]
4929+
spanid = parts[1]
4930+
if cmd == 'span_emit':
4931+
assert spanid in traces
4932+
assert spanid not in suspended
4933+
# Should be valid JSON
4934+
res = json.loads(parts[2])
4935+
4936+
# This is an array for some reason
4937+
assert len(res) == 1
4938+
res = res[0]
4939+
assert res['id'] == spanid
4940+
assert res['localEndpoint'] == {"serviceName": "lightningd"}
4941+
expected_keys = ['id', 'name', 'timestamp', 'duration', 'tags', 'traceId', 'localEndpoint']
4942+
if 'parentId' in res:
4943+
assert res['parentId'] in traces
4944+
expected_keys.append('parentId')
4945+
assert set(res.keys()) == set(expected_keys)
4946+
traces.remove(spanid)
4947+
elif cmd == 'span_end':
4948+
assert spanid in traces
4949+
elif cmd == 'span_start':
4950+
assert spanid not in traces
4951+
traces.add(spanid)
4952+
elif cmd == 'span_suspend':
4953+
assert spanid in traces
4954+
assert spanid not in suspended
4955+
suspended.add(spanid)
4956+
elif cmd == 'span_resume':
4957+
assert spanid in traces
4958+
suspended.remove(spanid)
4959+
elif cmd == 'destroying':
4960+
pass
4961+
else:
4962+
assert False, "Unknown trace line"
49594963

49604964
assert suspended == set()
49614965
assert traces == set()
@@ -4969,20 +4973,21 @@ def test_tracing(node_factory):
49694973

49704974
# The parent should set all the trace ids and span ids
49714975
for fname in glob.glob(f"{trace_fnamebase}.*"):
4972-
for linenum, l in enumerate(open(fname, "rt").readlines(), 1):
4973-
# In case an assertion fails
4974-
print(f"Parsing {fname}:{linenum}")
4975-
parts = l.split(maxsplit=2)
4976-
cmd = parts[0]
4977-
spanid = parts[1]
4978-
# This span doesn't actually appear anywhere
4979-
assert spanid != '0123456789abcdef'
4980-
if cmd == 'span_emit':
4981-
# Should be valid JSON
4982-
res = json.loads(parts[2])
4983-
assert res[0]['traceId'] == '00112233445566778899aabbccddeeff'
4984-
# Everyone has a parent!
4985-
assert 'parentId' in res[0]
4976+
with open(fname, "rt") as f:
4977+
for linenum, l in enumerate(f.readlines(), 1):
4978+
# In case an assertion fails
4979+
print(f"Parsing {fname}:{linenum}")
4980+
parts = l.split(maxsplit=2)
4981+
cmd = parts[0]
4982+
spanid = parts[1]
4983+
# This span doesn't actually appear anywhere
4984+
assert spanid != '0123456789abcdef'
4985+
if cmd == 'span_emit':
4986+
# Should be valid JSON
4987+
res = json.loads(parts[2])
4988+
assert res[0]['traceId'] == '00112233445566778899aabbccddeeff'
4989+
# Everyone has a parent!
4990+
assert 'parentId' in res[0]
49864991

49874992

49884993
def test_zero_locktime_blocks(node_factory, bitcoind):

tests/test_pay.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1241,7 +1241,7 @@ def test_forward(node_factory, bitcoind):
12411241
l1.rpc.bkpr_dumpincomecsv('koinly', 'koinly.csv')
12421242

12431243
koinly_path = os.path.join(l1.daemon.lightning_dir, TEST_NETWORK, 'koinly.csv')
1244-
koinly_csv = open(koinly_path, 'rb').read()
1244+
koinly_csv = Path(koinly_path).read_bytes()
12451245
expected_line = r'0.00100000000,.*,,,0.00000001001,.*,invoice'
12461246
assert only_one(re.findall(expected_line, str(koinly_csv)))
12471247

0 commit comments

Comments
 (0)