Skip to content

Commit 027aab6

Browse files
committed
test, contrib, refactor: use with when opening a file
1 parent 269dcad commit 027aab6

File tree

7 files changed

+56
-49
lines changed

7 files changed

+56
-49
lines changed

contrib/devtools/copyright_header.py

+4-6
Original file line numberDiff line numberDiff line change
@@ -320,15 +320,13 @@ def get_most_recent_git_change_year(filename):
320320
################################################################################
321321

322322
def read_file_lines(filename):
323-
f = open(filename, 'r', encoding="utf8")
324-
file_lines = f.readlines()
325-
f.close()
323+
with open(filename, 'r', encoding="utf8") as f:
324+
file_lines = f.readlines()
326325
return file_lines
327326

328327
def write_file_lines(filename, file_lines):
329-
f = open(filename, 'w', encoding="utf8")
330-
f.write(''.join(file_lines))
331-
f.close()
328+
with open(filename, 'w', encoding="utf8") as f:
329+
f.write(''.join(file_lines))
332330

333331
################################################################################
334332
# update header years execution

contrib/linearize/linearize-data.py

+18-19
Original file line numberDiff line numberDiff line change
@@ -34,12 +34,12 @@ def get_blk_dt(blk_hdr):
3434
# When getting the list of block hashes, undo any byte reversals.
3535
def get_block_hashes(settings):
3636
blkindex = []
37-
f = open(settings['hashlist'], "r", encoding="utf8")
38-
for line in f:
39-
line = line.rstrip()
40-
if settings['rev_hash_bytes'] == 'true':
41-
line = bytes.fromhex(line)[::-1].hex()
42-
blkindex.append(line)
37+
with open(settings['hashlist'], "r", encoding="utf8") as f:
38+
for line in f:
39+
line = line.rstrip()
40+
if settings['rev_hash_bytes'] == 'true':
41+
line = bytes.fromhex(line)[::-1].hex()
42+
blkindex.append(line)
4343

4444
print("Read " + str(len(blkindex)) + " hashes")
4545

@@ -249,19 +249,18 @@ def run(self):
249249
print("Usage: linearize-data.py CONFIG-FILE")
250250
sys.exit(1)
251251

252-
f = open(sys.argv[1], encoding="utf8")
253-
for line in f:
254-
# skip comment lines
255-
m = re.search(r'^\s*#', line)
256-
if m:
257-
continue
258-
259-
# parse key=value lines
260-
m = re.search(r'^(\w+)\s*=\s*(\S.*)$', line)
261-
if m is None:
262-
continue
263-
settings[m.group(1)] = m.group(2)
264-
f.close()
252+
with open(sys.argv[1], encoding="utf8") as f:
253+
for line in f:
254+
# skip comment lines
255+
m = re.search(r'^\s*#', line)
256+
if m:
257+
continue
258+
259+
# parse key=value lines
260+
m = re.search(r'^(\w+)\s*=\s*(\S.*)$', line)
261+
if m is None:
262+
continue
263+
settings[m.group(1)] = m.group(2)
265264

266265
# Force hash byte format setting to be lowercase to make comparisons easier.
267266
# Also place upfront in case any settings need to know about it.

contrib/linearize/linearize-hashes.py

+12-13
Original file line numberDiff line numberDiff line change
@@ -98,19 +98,18 @@ def get_rpc_cookie():
9898
print("Usage: linearize-hashes.py CONFIG-FILE")
9999
sys.exit(1)
100100

101-
f = open(sys.argv[1], encoding="utf8")
102-
for line in f:
103-
# skip comment lines
104-
m = re.search(r'^\s*#', line)
105-
if m:
106-
continue
107-
108-
# parse key=value lines
109-
m = re.search(r'^(\w+)\s*=\s*(\S.*)$', line)
110-
if m is None:
111-
continue
112-
settings[m.group(1)] = m.group(2)
113-
f.close()
101+
with open(sys.argv[1], encoding="utf8") as f:
102+
for line in f:
103+
# skip comment lines
104+
m = re.search(r'^\s*#', line)
105+
if m:
106+
continue
107+
108+
# parse key=value lines
109+
m = re.search(r'^(\w+)\s*=\s*(\S.*)$', line)
110+
if m is None:
111+
continue
112+
settings[m.group(1)] = m.group(2)
114113

115114
if 'host' not in settings:
116115
settings['host'] = '127.0.0.1'

contrib/verify-commits/verify-commits.py

+10-5
Original file line numberDiff line numberDiff line change
@@ -82,11 +82,16 @@ def main():
8282
# get directory of this program and read data files
8383
dirname = os.path.dirname(os.path.abspath(__file__))
8484
print("Using verify-commits data from " + dirname)
85-
verified_root = open(dirname + "/trusted-git-root", "r", encoding="utf8").read().splitlines()[0]
86-
verified_sha512_root = open(dirname + "/trusted-sha512-root-commit", "r", encoding="utf8").read().splitlines()[0]
87-
revsig_allowed = open(dirname + "/allow-revsig-commits", "r", encoding="utf-8").read().splitlines()
88-
unclean_merge_allowed = open(dirname + "/allow-unclean-merge-commits", "r", encoding="utf-8").read().splitlines()
89-
incorrect_sha512_allowed = open(dirname + "/allow-incorrect-sha512-commits", "r", encoding="utf-8").read().splitlines()
85+
with open(dirname + "/trusted-git-root", "r", encoding="utf8") as f:
86+
verified_root = f.read().splitlines()[0]
87+
with open(dirname + "/trusted-sha512-root-commit", "r", encoding="utf8") as f:
88+
verified_sha512_root = f.read().splitlines()[0]
89+
with open(dirname + "/allow-revsig-commits", "r", encoding="utf8") as f:
90+
revsig_allowed = f.read().splitlines()
91+
with open(dirname + "/allow-unclean-merge-commit", "r", encoding="utf8") as f:
92+
unclean_merge_allowed = f.read().splitlines()
93+
with open(dirname + "/allow-incorrect-sha512-commits", "r", encoding="utf8") as f:
94+
incorrect_sha512_allowed = f.read().splitlines()
9095

9196
# Set commit and branch and set variables
9297
current_commit = args.commit

test/functional/feature_config_args.py

+2-1
Original file line numberDiff line numberDiff line change
@@ -247,7 +247,8 @@ def run_test(self):
247247
conf_file = os.path.join(default_data_dir, "bitcoin.conf")
248248

249249
# datadir needs to be set before [chain] section
250-
conf_file_contents = open(conf_file, encoding='utf8').read()
250+
with open(conf_file, encoding='utf8') as f:
251+
conf_file_contents = f.read()
251252
with open(conf_file, 'w', encoding='utf8') as f:
252253
f.write(f"datadir={new_data_dir}\n")
253254
f.write(conf_file_contents)

test/functional/feature_versionbits_warning.py

+2-1
Original file line numberDiff line numberDiff line change
@@ -58,7 +58,8 @@ def send_blocks_with_version(self, peer, numblocks, version):
5858

5959
def versionbits_in_alert_file(self):
6060
"""Test that the versionbits warning has been written to the alert file."""
61-
alert_text = open(self.alert_filename, 'r', encoding='utf8').read()
61+
with open(self.alert_filename, 'r', encoding='utf8') as f:
62+
alert_text = f.read()
6263
return VB_PATTERN.search(alert_text) is not None
6364

6465
def run_test(self):

test/util/test_runner.py

+8-4
Original file line numberDiff line numberDiff line change
@@ -22,7 +22,8 @@
2222
def main():
2323
config = configparser.ConfigParser()
2424
config.optionxform = str
25-
config.read_file(open(os.path.join(os.path.dirname(__file__), "../config.ini"), encoding="utf8"))
25+
with open(os.path.join(os.path.dirname(__file__), "../config.ini"), encoding="utf8") as f:
26+
config.read_file(f)
2627
env_conf = dict(config.items('environment'))
2728

2829
parser = argparse.ArgumentParser(description=__doc__)
@@ -43,7 +44,8 @@ def main():
4344
def bctester(testDir, input_basename, buildenv):
4445
""" Loads and parses the input file, runs all tests and reports results"""
4546
input_filename = os.path.join(testDir, input_basename)
46-
raw_data = open(input_filename, encoding="utf8").read()
47+
with open(input_filename, encoding="utf8") as f:
48+
raw_data = f.read()
4749
input_data = json.loads(raw_data)
4850

4951
failed_testcases = []
@@ -80,7 +82,8 @@ def bctest(testDir, testObj, buildenv):
8082
inputData = None
8183
if "input" in testObj:
8284
filename = os.path.join(testDir, testObj["input"])
83-
inputData = open(filename, encoding="utf8").read()
85+
with open(filename, encoding="utf8") as f:
86+
inputData = f.read()
8487
stdinCfg = subprocess.PIPE
8588

8689
# Read the expected output data (if there is any)
@@ -91,7 +94,8 @@ def bctest(testDir, testObj, buildenv):
9194
outputFn = testObj['output_cmp']
9295
outputType = os.path.splitext(outputFn)[1][1:] # output type from file extension (determines how to compare)
9396
try:
94-
outputData = open(os.path.join(testDir, outputFn), encoding="utf8").read()
97+
with open(os.path.join(testDir, outputFn), encoding="utf8") as f:
98+
outputData = f.read()
9599
except:
96100
logging.error("Output file " + outputFn + " cannot be opened")
97101
raise

0 commit comments

Comments
 (0)