Skip to content

Commit b21680b

Browse files
committed
test/contrib: Fix invalid escapes in regex strings
Flagged by flake8 v3.6.0, as W605, plus a few others identified incidentally, e.g. 59ffecf. Note that r"\n" matches to "\n" under re.match/search.
1 parent 6e43129 commit b21680b

14 files changed

+38
-41
lines changed

contrib/devtools/clang-format-diff.py

+2-2
Original file line numberDiff line numberDiff line change
@@ -106,7 +106,7 @@ def main():
106106
filename = None
107107
lines_by_file = {}
108108
for line in sys.stdin:
109-
match = re.search('^\+\+\+\ (.*?/){%s}(\S*)' % args.p, line)
109+
match = re.search(r'^\+\+\+\ (.*?/){%s}(\S*)' % args.p, line)
110110
if match:
111111
filename = match.group(2)
112112
if filename is None:
@@ -119,7 +119,7 @@ def main():
119119
if not re.match('^%s$' % args.iregex, filename, re.IGNORECASE):
120120
continue
121121

122-
match = re.search('^@@.*\+(\d+)(,(\d+))?', line)
122+
match = re.search(r'^@@.*\+(\d+)(,(\d+))?', line)
123123
if match:
124124
start_line = int(match.group(1))
125125
line_count = 1

contrib/devtools/copyright_header.py

+15-15
Original file line numberDiff line numberDiff line change
@@ -71,7 +71,7 @@ def get_filenames_to_examine(base_directory):
7171
################################################################################
7272

7373

74-
COPYRIGHT_WITH_C = 'Copyright \(c\)'
74+
COPYRIGHT_WITH_C = r'Copyright \(c\)'
7575
COPYRIGHT_WITHOUT_C = 'Copyright'
7676
ANY_COPYRIGHT_STYLE = '(%s|%s)' % (COPYRIGHT_WITH_C, COPYRIGHT_WITHOUT_C)
7777

@@ -85,21 +85,21 @@ def get_filenames_to_examine(base_directory):
8585
ANY_COPYRIGHT_COMPILED = re.compile(ANY_COPYRIGHT_STYLE_OR_YEAR_STYLE)
8686

8787
def compile_copyright_regex(copyright_style, year_style, name):
88-
return re.compile('%s %s,? %s' % (copyright_style, year_style, name))
88+
return re.compile('%s %s,? %s\n' % (copyright_style, year_style, name))
8989

9090
EXPECTED_HOLDER_NAMES = [
91-
"Satoshi Nakamoto\n",
92-
"The Bitcoin Core developers\n",
93-
"BitPay Inc\.\n",
94-
"University of Illinois at Urbana-Champaign\.\n",
95-
"Pieter Wuille\n",
96-
"Wladimir J. van der Laan\n",
97-
"Jeff Garzik\n",
98-
"Jan-Klaas Kollhof\n",
99-
"ArtForz -- public domain half-a-node\n",
100-
"Intel Corporation",
101-
"The Zcash developers",
102-
"Jeremy Rubin",
91+
r"Satoshi Nakamoto",
92+
r"The Bitcoin Core developers",
93+
r"BitPay Inc\.",
94+
r"University of Illinois at Urbana-Champaign\.",
95+
r"Pieter Wuille",
96+
r"Wladimir J\. van der Laan",
97+
r"Jeff Garzik",
98+
r"Jan-Klaas Kollhof",
99+
r"ArtForz -- public domain half-a-node",
100+
r"Intel Corporation ?",
101+
r"The Zcash developers",
102+
r"Jeremy Rubin",
103103
]
104104

105105
DOMINANT_STYLE_COMPILED = {}
@@ -329,7 +329,7 @@ def write_file_lines(filename, file_lines):
329329
# update header years execution
330330
################################################################################
331331

332-
COPYRIGHT = 'Copyright \(c\)'
332+
COPYRIGHT = r'Copyright \(c\)'
333333
YEAR = "20[0-9][0-9]"
334334
YEAR_RANGE = '(%s)(-%s)?' % (YEAR, YEAR)
335335
HOLDER = 'The Bitcoin Core developers'

contrib/devtools/symbol-check.py

+1-3
Original file line numberDiff line numberDiff line change
@@ -141,7 +141,7 @@ def read_libraries(filename):
141141
for line in stdout.splitlines():
142142
tokens = line.split()
143143
if len(tokens)>2 and tokens[1] == '(NEEDED)':
144-
match = re.match('^Shared library: \[(.*)\]$', ' '.join(tokens[2:]))
144+
match = re.match(r'^Shared library: \[(.*)\]$', ' '.join(tokens[2:]))
145145
if match:
146146
libraries.append(match.group(1))
147147
else:
@@ -171,5 +171,3 @@ def read_libraries(filename):
171171
retval = 1
172172

173173
sys.exit(retval)
174-
175-

contrib/linearize/linearize-data.py

+2-2
Original file line numberDiff line numberDiff line change
@@ -263,12 +263,12 @@ def run(self):
263263
f = open(sys.argv[1], encoding="utf8")
264264
for line in f:
265265
# skip comment lines
266-
m = re.search('^\s*#', line)
266+
m = re.search(r'^\s*#', line)
267267
if m:
268268
continue
269269

270270
# parse key=value lines
271-
m = re.search('^(\w+)\s*=\s*(\S.*)$', line)
271+
m = re.search(r'^(\w+)\s*=\s*(\S.*)$', line)
272272
if m is None:
273273
continue
274274
settings[m.group(1)] = m.group(2)

contrib/linearize/linearize-hashes.py

+2-2
Original file line numberDiff line numberDiff line change
@@ -106,12 +106,12 @@ def get_rpc_cookie():
106106
f = open(sys.argv[1], encoding="utf8")
107107
for line in f:
108108
# skip comment lines
109-
m = re.search('^\s*#', line)
109+
m = re.search(r'^\s*#', line)
110110
if m:
111111
continue
112112

113113
# parse key=value lines
114-
m = re.search('^(\w+)\s*=\s*(\S.*)$', line)
114+
m = re.search(r'^(\w+)\s*=\s*(\S.*)$', line)
115115
if m is None:
116116
continue
117117
settings[m.group(1)] = m.group(2)

contrib/macdeploy/macdeployqtplus

+2-2
Original file line numberDiff line numberDiff line change
@@ -765,8 +765,8 @@ if config.dmg is not None:
765765
output = runHDIUtil("attach", dmg_name + ".temp", readwrite=True, noverify=True, noautoopen=True, capture_stdout=True)
766766
except subprocess.CalledProcessError as e:
767767
sys.exit(e.returncode)
768-
769-
m = re.search("/Volumes/(.+$)", output)
768+
769+
m = re.search(r"/Volumes/(.+$)", output)
770770
disk_root = m.group(0)
771771
disk_name = m.group(1)
772772

contrib/seeds/generate-seeds.py

+1-2
Original file line numberDiff line numberDiff line change
@@ -74,7 +74,7 @@ def name_to_ipv6(addr):
7474
raise ValueError('Could not parse address %s' % addr)
7575

7676
def parse_spec(s, defaultport):
77-
match = re.match('\[([0-9a-fA-F:]+)\](?::([0-9]+))?$', s)
77+
match = re.match(r'\[([0-9a-fA-F:]+)\](?::([0-9]+))?$', s)
7878
if match: # ipv6
7979
host = match.group(1)
8080
port = match.group(2)
@@ -136,4 +136,3 @@ def main():
136136

137137
if __name__ == '__main__':
138138
main()
139-

test/functional/combine_logs.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -81,7 +81,7 @@ def read_logs(tmp_dir):
8181
chain = glob.glob("{}/node0/*/debug.log".format(tmp_dir))
8282
if chain:
8383
chain = chain[0] # pick the first one if more than one chain was found (should never happen)
84-
chain = re.search('node0/(.+?)/debug\.log$', chain).group(1) # extract the chain name
84+
chain = re.search(r'node0/(.+?)/debug\.log$', chain).group(1) # extract the chain name
8585
else:
8686
chain = 'regtest' # fallback to regtest (should only happen when none exists)
8787

test/functional/feature_logging.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -36,7 +36,7 @@ def run_test(self):
3636
invdir = self.relative_log_path("foo")
3737
invalidname = os.path.join("foo", "foo.log")
3838
self.stop_node(0)
39-
exp_stderr = "Error: Could not open debug log file \S+$"
39+
exp_stderr = r"Error: Could not open debug log file \S+$"
4040
self.nodes[0].assert_start_raises_init_error(["-debuglogfile=%s" % (invalidname)], exp_stderr, match=ErrorMatch.FULL_REGEX)
4141
assert not os.path.isfile(os.path.join(invdir, "foo.log"))
4242

test/functional/feature_uacomment.py

+2-2
Original file line numberDiff line numberDiff line change
@@ -27,12 +27,12 @@ def run_test(self):
2727

2828
self.log.info("test -uacomment max length")
2929
self.stop_node(0)
30-
expected = "Error: Total length of network version string \([0-9]+\) exceeds maximum length \(256\). Reduce the number or size of uacomments."
30+
expected = r"Error: Total length of network version string \([0-9]+\) exceeds maximum length \(256\). Reduce the number or size of uacomments."
3131
self.nodes[0].assert_start_raises_init_error(["-uacomment=" + 'a' * 256], expected, match=ErrorMatch.FULL_REGEX)
3232

3333
self.log.info("test -uacomment unsafe characters")
3434
for unsafe_char in ['/', ':', '(', ')', '₿', '🏃']:
35-
expected = "Error: User Agent comment \(" + re.escape(unsafe_char) + "\) contains unsafe characters."
35+
expected = r"Error: User Agent comment \(" + re.escape(unsafe_char) + r"\) contains unsafe characters."
3636
self.nodes[0].assert_start_raises_init_error(["-uacomment=" + unsafe_char], expected, match=ErrorMatch.FULL_REGEX)
3737

3838

test/functional/wallet_multiwallet.py

+3-3
Original file line numberDiff line numberDiff line change
@@ -93,12 +93,12 @@ def wallet_file(name):
9393

9494
# should not initialize if one wallet is a copy of another
9595
shutil.copyfile(wallet_dir('w8'), wallet_dir('w8_copy'))
96-
exp_stderr = "BerkeleyBatch: Can't open database w8_copy \(duplicates fileid \w+ from w8\)"
96+
exp_stderr = r"BerkeleyBatch: Can't open database w8_copy \(duplicates fileid \w+ from w8\)"
9797
self.nodes[0].assert_start_raises_init_error(['-wallet=w8', '-wallet=w8_copy'], exp_stderr, match=ErrorMatch.PARTIAL_REGEX)
9898

9999
# should not initialize if wallet file is a symlink
100100
os.symlink('w8', wallet_dir('w8_symlink'))
101-
self.nodes[0].assert_start_raises_init_error(['-wallet=w8_symlink'], 'Error: Invalid -wallet path \'w8_symlink\'\. .*', match=ErrorMatch.FULL_REGEX)
101+
self.nodes[0].assert_start_raises_init_error(['-wallet=w8_symlink'], r'Error: Invalid -wallet path \'w8_symlink\'\. .*', match=ErrorMatch.FULL_REGEX)
102102

103103
# should not initialize if the specified walletdir does not exist
104104
self.nodes[0].assert_start_raises_init_error(['-walletdir=bad'], 'Error: Specified -walletdir "bad" does not exist')
@@ -139,7 +139,7 @@ def wallet_file(name):
139139
competing_wallet_dir = os.path.join(self.options.tmpdir, 'competing_walletdir')
140140
os.mkdir(competing_wallet_dir)
141141
self.restart_node(0, ['-walletdir=' + competing_wallet_dir])
142-
exp_stderr = "Error: Error initializing wallet database environment \"\S+competing_walletdir\"!"
142+
exp_stderr = r"Error: Error initializing wallet database environment \"\S+competing_walletdir\"!"
143143
self.nodes[1].assert_start_raises_init_error(['-walletdir=' + competing_wallet_dir], exp_stderr, match=ErrorMatch.PARTIAL_REGEX)
144144

145145
self.restart_node(0, extra_args)

test/lint/check-doc.py

+2-2
Original file line numberDiff line numberDiff line change
@@ -15,8 +15,8 @@
1515

1616
FOLDER_GREP = 'src'
1717
FOLDER_TEST = 'src/test/'
18-
REGEX_ARG = '(?:ForceSet|SoftSet|Get|Is)(?:Bool)?Args?(?:Set)?\("(-[^"]+)"'
19-
REGEX_DOC = 'AddArg\("(-[^"=]+?)(?:=|")'
18+
REGEX_ARG = r'(?:ForceSet|SoftSet|Get|Is)(?:Bool)?Args?(?:Set)?\("(-[^"]+)"'
19+
REGEX_DOC = r'AddArg\("(-[^"=]+?)(?:=|")'
2020
CMD_ROOT_DIR = '$(git rev-parse --show-toplevel)/{}'.format(FOLDER_GREP)
2121
CMD_GREP_ARGS = r"git grep --perl-regexp '{}' -- {} ':(exclude){}'".format(REGEX_ARG, CMD_ROOT_DIR, FOLDER_TEST)
2222
CMD_GREP_WALLET_ARGS = r"git grep --function-context 'void WalletInit::AddWalletOptions' -- {} | grep AddArg".format(CMD_ROOT_DIR)

test/lint/check-rpc-mappings.py

+3-3
Original file line numberDiff line numberDiff line change
@@ -48,13 +48,13 @@ def process_commands(fname):
4848
for line in f:
4949
line = line.rstrip()
5050
if not in_rpcs:
51-
if re.match("static const CRPCCommand .*\[\] =", line):
51+
if re.match(r"static const CRPCCommand .*\[\] =", line):
5252
in_rpcs = True
5353
else:
5454
if line.startswith('};'):
5555
in_rpcs = False
5656
elif '{' in line and '"' in line:
57-
m = re.search('{ *("[^"]*"), *("[^"]*"), *&([^,]*), *{([^}]*)} *},', line)
57+
m = re.search(r'{ *("[^"]*"), *("[^"]*"), *&([^,]*), *{([^}]*)} *},', line)
5858
assert m, 'No match to table expression: %s' % line
5959
name = parse_string(m.group(2))
6060
args_str = m.group(4).strip()
@@ -80,7 +80,7 @@ def process_mapping(fname):
8080
if line.startswith('};'):
8181
in_rpcs = False
8282
elif '{' in line and '"' in line:
83-
m = re.search('{ *("[^"]*"), *([0-9]+) *, *("[^"]*") *},', line)
83+
m = re.search(r'{ *("[^"]*"), *([0-9]+) *, *("[^"]*") *},', line)
8484
assert m, 'No match to table expression: %s' % line
8585
name = parse_string(m.group(1))
8686
idx = int(m.group(2))

test/lint/lint-format-strings.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -55,7 +55,7 @@ def normalize(s):
5555
assert type(s) is str
5656
s = s.replace("\n", " ")
5757
s = s.replace("\t", " ")
58-
s = re.sub("/\*.*?\*/", " ", s)
58+
s = re.sub(r"/\*.*?\*/", " ", s)
5959
s = re.sub(" {2,}", " ", s)
6060
return s.strip()
6161

0 commit comments

Comments
 (0)