Skip to content

Commit 1f151e7

Browse files
committed
Merge bitcoin/bitcoin#32929: qa: Clarify assert_start_raises_init_error output
356883f qa-tests: Log expected output in debug (Hodlinator) 7427a03 qa-tests: Add test for timeouts due to missing init errors (Hodlinator) d7f703c refactor(qa-tests): Extract InternalDurationTestMixin for use in next commit (Hodlinator) 69bcfca fix(qa-tests): Bring back decoding of exception field (Hodlinator) fb43b2f qa: Improve assert_start_raises_init_error output (Hodlinator) Pull request description: Raising a new exception from within a Python `except`-block, as `assert_start_raises_init_error()` does, causes the interpreter to generate extra error output which is unnecessary in this case. <details><summary>Example output before & after this PR</summary> Before: ``` 2025-07-08T20:05:48.407001Z TestFramework (ERROR): Assertion failed Traceback (most recent call last): File "/home/hodlinator/bitcoin/test/functional/test_framework/test_node.py", line 686, in assert_start_raises_init_error ret = self.process.wait(timeout=self.rpc_timeout) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/nix/store/fqm9bqqlmaqqr02qbalm1bazp810qfiw-python3-3.12.9/lib/python3.12/subprocess.py", line 1266, in wait return self._wait(timeout=timeout) ^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/nix/store/fqm9bqqlmaqqr02qbalm1bazp810qfiw-python3-3.12.9/lib/python3.12/subprocess.py", line 2053, in _wait raise TimeoutExpired(self.args, timeout) subprocess.TimeoutExpired: Command '['/home/hodlinator/bitcoin/build/bin/bitcoind', '-datadir=/tmp/bitcoin_func_test_v96lkcq8/eb2665c7/node0', '-logtimemicros', '-debug', '-debugexclude=libevent', '-debugexclude=leveldb', '-debugexclude=rand', '-uacomment=testnode0', '-disablewallet', '-logthreadnames', '-logsourcelocations', '-loglevel=trace', '-v2transport=0']' timed out after 3 seconds During handling of the above exception, another exception occurred: Traceback (most recent call last): File "/home/hodlinator/bitcoin/test/functional/test_framework/test_framework.py", line 186, in main self.setup() File "/home/hodlinator/bitcoin/test/functional/test_framework/test_framework.py", line 358, in setup self.setup_network() File "/home/hodlinator/bitcoin/build/test/functional/feature_framework_startup_failures.py", line 151, in setup_network self.nodes[0].assert_start_raises_init_error() File "/home/hodlinator/bitcoin/test/functional/test_framework/test_node.py", line 716, in assert_start_raises_init_error self._raise_assertion_error(assert_msg) File "/home/hodlinator/bitcoin/test/functional/test_framework/test_node.py", line 196, in _raise_assertion_error raise AssertionError(self._node_msg(msg)) AssertionError: [node 0] bitcoind should have exited within 3s with an error ``` After: ``` 2025-07-08T20:09:15.330589Z TestFramework (ERROR): Assertion failed Traceback (most recent call last): File "/home/hodlinator/bitcoin/test/functional/test_framework/test_framework.py", line 186, in main self.setup() File "/home/hodlinator/bitcoin/test/functional/test_framework/test_framework.py", line 358, in setup self.setup_network() File "/home/hodlinator/bitcoin/build/test/functional/feature_framework_startup_failures.py", line 151, in setup_network self.nodes[0].assert_start_raises_init_error() File "/home/hodlinator/bitcoin/test/functional/test_framework/test_node.py", line 720, in assert_start_raises_init_error self._raise_assertion_error(assert_msg) File "/home/hodlinator/bitcoin/test/functional/test_framework/test_node.py", line 196, in _raise_assertion_error raise AssertionError(self._node_msg(msg)) AssertionError: [node 0] bitcoind should have exited within 3s with an error (cmd: ['/home/hodlinator/bitcoin/build/bin/bitcoind', '-datadir=/tmp/bitcoin_func_test_v96lkcq8/eb2665c7/node0', '-logtimemicros', '-debug', '-debugexclude=libevent', '-debugexclude=leveldb', '-debugexclude=rand', '-uacomment=testnode0', '-disablewallet', '-logthreadnames', '-logsourcelocations', '-loglevel=trace', '-v2transport=0']) ``` </details> --- Can be tested on this PR by: 1. Execute test containing new test case: ```shell build/test/functional/feature_framework_startup_failures.py -ldebug > after.log ``` 2. Drop first commit which contains the fix. 3. Re-run test: ```shell build/test/functional/feature_framework_startup_failures.py -ldebug > before.log ``` 4. Diff logs, focusing on `TestInitErrorTimeout OUTPUT` sections. --- Found while testing #32835 using the suggested method (bitcoin/bitcoin#32835 (comment)) which triggered expected timeouts, but with the extra error noise. ACKs for top commit: l0rinc: ACK 356883f ryanofsky: Code review ACK 356883f. Thanks for the updates! Just rearranged commits and made minor changes in "missing init errors" test since last review furszy: Code ACK 356883f Tree-SHA512: 01f2f1f6a5e79cf83a39a143cfb8b2bb8360e0402e91a97a7df8254309fd4436a55468d11825093c052010bfce57f3461d912a578cd2594114aba435ab48b999
2 parents 315fdb4 + 356883f commit 1f151e7

File tree

2 files changed

+55
-17
lines changed

2 files changed

+55
-17
lines changed

test/functional/feature_framework_startup_failures.py

Lines changed: 47 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -36,22 +36,24 @@ def setup_network(self):
3636
# Launches a child test process that runs this same file, but instantiates
3737
# a child test. Verifies that it raises only the expected exception, once.
3838
def _verify_startup_failure(self, test, internal_args, expected_exception):
39+
name = test.__name__
40+
def format_child_output(output):
41+
return f"\n<{name} OUTPUT BEGIN>\n{output.strip()}\n<{name} OUTPUT END>\n"
42+
3943
# Inherit sys.argv from parent, only overriding tmpdir to a subdirectory
4044
# so children don't fail due to colliding with the parent dir.
4145
assert self.options.tmpdir, "Framework should always set tmpdir."
4246
subdir = md5(expected_exception.encode('utf-8')).hexdigest()[:8]
43-
args = [sys.executable] + sys.argv + [f"--tmpdir={self.options.tmpdir}/{subdir}", f"--internal_test={test.__name__}"] + internal_args
47+
args = [sys.executable] + sys.argv + [f"--tmpdir={self.options.tmpdir}/{subdir}", f"--internal_test={name}"] + internal_args
4448

4549
try:
4650
output = subprocess.run(args, timeout=60 * self.options.timeout_factor,
4751
stdout=subprocess.PIPE, stderr=subprocess.STDOUT, text=True).stdout
4852
except subprocess.TimeoutExpired as e:
49-
print("Unexpected child process timeout!\n"
50-
"WARNING: Timeouts like this halt execution of TestNode logic, "
51-
"meaning dangling bitcoind processes are to be expected.\n"
52-
f"<CHILD OUTPUT BEGIN>\n{e.output}\n<CHILD OUTPUT END>",
53-
file=sys.stderr)
54-
raise
53+
sys.exit("Unexpected child process timeout!\n"
54+
"WARNING: Timeouts like this halt execution of TestNode logic, "
55+
"meaning dangling bitcoind processes are to be expected.\n" +
56+
(format_child_output(e.output.decode("utf-8")) if e.output else "<EMPTY OUTPUT>"))
5557

5658
errors = []
5759
if (n := output.count("Traceback")) != 1:
@@ -61,13 +63,17 @@ def _verify_startup_failure(self, test, internal_args, expected_exception):
6163
if (n := output.count("Test failed. Test logging available at")) != 1:
6264
errors.append(f"Found {n}/1 test failure output messages.")
6365

64-
assert not errors, f"Child test didn't contain (only) expected errors:\n{linesep.join(errors)}\n<CHILD OUTPUT BEGIN>\n{output}\n<CHILD OUTPUT END>\n"
66+
assert not errors, (f"Child test did NOT contain (only) expected errors:\n{linesep.join(errors)}\n" +
67+
format_child_output(output))
68+
69+
self.log.debug("Child test did contain (only) expected errors:\n" +
70+
format_child_output(output))
6571

6672
def run_test(self):
6773
self.log.info("Verifying _verify_startup_failure() functionality (self-check).")
6874
assert_raises_message(
6975
AssertionError,
70-
( "Child test didn't contain (only) expected errors:\n"
76+
( "Child test did NOT contain (only) expected errors:\n"
7177
f"Found 0/1 tracebacks - expecting exactly one with no knock-on exceptions.{linesep}"
7278
f"Found 0/1 occurrences of the specific exception: NonExistentError{linesep}"
7379
"Found 0/1 test failure output messages."),
@@ -76,7 +82,7 @@ def run_test(self):
7682
"NonExistentError",
7783
)
7884

79-
self.log.info("Parent process is measuring node startup duration in order to obtain a reasonable timeout value for later test...")
85+
self.log.info("Parent process is measuring node startup duration in order to obtain a reasonable timeout value for later tests...")
8086
node_start_time = time.time()
8187
self.nodes[0].start()
8288
self.nodes[0].wait_for_rpc_connection()
@@ -90,6 +96,12 @@ def run_test(self):
9096
r"AssertionError: \[node 0\] Unable to connect to bitcoind after \d+s \(ignored errors: {[^}]*'OSError \w+'?: \d+[^}]*}, latest: '[\w ]+'/\w+\([^)]+\)\)"
9197
)
9298

99+
self.log.info("Verifying timeout while waiting for init errors that do not occur results in only one exception.")
100+
self._verify_startup_failure(
101+
TestMissingInitErrorTimeout, [f"--internal_node_start_duration={node_start_duration}"],
102+
r"AssertionError: \[node 0\] bitcoind should have exited within \d+s with an error \(cmd:"
103+
)
104+
93105
self.log.info("Verifying startup failure due to invalid arg results in only one exception.")
94106
self._verify_startup_failure(
95107
TestInitErrorStartupFailure, [],
@@ -107,20 +119,41 @@ def add_options(self, parser):
107119
# Just here to silence unrecognized argument error, we actually read the value in the if-main at the bottom.
108120
parser.add_argument("--internal_test", dest="internal_never_read", help="ONLY TO BE USED WHEN TEST RELAUNCHES ITSELF")
109121

110-
class TestWrongRpcPortStartupFailure(InternalTestMixin, BitcoinTestFramework):
122+
class InternalDurationTestMixin(InternalTestMixin):
111123
def add_options(self, parser):
124+
# Receives the previously measured duration for node startup + RPC connection establishment.
112125
parser.add_argument("--internal_node_start_duration", dest="node_start_duration", help="ONLY TO BE USED WHEN TEST RELAUNCHES ITSELF", type=float)
113126
InternalTestMixin.add_options(self, parser)
114127

128+
def get_reasonable_rpc_timeout(self):
129+
# 2 * the measured test startup duration should be enough.
130+
# Divide by timeout_factor to counter multiplication in BitcoinTestFramework.
131+
return max(3, 2 * self.options.node_start_duration) / self.options.timeout_factor
132+
133+
class TestWrongRpcPortStartupFailure(InternalDurationTestMixin, BitcoinTestFramework):
115134
def set_test_params(self):
116135
self.num_nodes = 1
117136
# Override RPC listen port to something TestNode isn't expecting so that
118137
# we are unable to establish an RPC connection.
119138
self.extra_args = [[f"-rpcport={rpc_port(2)}"]]
120139
# Override the timeout to avoid waiting unnecessarily long to realize
121-
# nothing is on that port. Divide by timeout_factor to counter
122-
# multiplication in base, 2 * node_start_duration should be enough.
123-
self.rpc_timeout = max(3, 2 * self.options.node_start_duration) / self.options.timeout_factor
140+
# nothing is on that port.
141+
self.rpc_timeout = self.get_reasonable_rpc_timeout()
142+
143+
def run_test(self):
144+
assert False, "Should have failed earlier during startup."
145+
146+
class TestMissingInitErrorTimeout(InternalDurationTestMixin, BitcoinTestFramework):
147+
def set_test_params(self):
148+
self.num_nodes = 1
149+
# Override the timeout to avoid waiting unnecessarily long for an init
150+
# error which never occurs.
151+
self.rpc_timeout = self.get_reasonable_rpc_timeout()
152+
153+
def setup_network(self):
154+
self.add_nodes(self.num_nodes, self.extra_args)
155+
self.nodes[0].assert_start_raises_init_error()
156+
assert False, "assert_start_raises_init_error() should raise an exception due to timeout since we don't expect an init error."
124157

125158
def run_test(self):
126159
assert False, "Should have failed earlier during startup."

test/functional/test_framework/test_node.py

Lines changed: 8 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -717,11 +717,12 @@ def assert_start_raises_init_error(self, extra_args=None, expected_msg=None, mat
717717
extra_args: extra arguments to pass through to bitcoind
718718
expected_msg: regex that stderr should match when bitcoind fails
719719
720-
Will throw if bitcoind starts without an error.
721-
Will throw if an expected_msg is provided and it does not match bitcoind's stdout."""
720+
Will raise if bitcoind starts without an error.
721+
Will raise if an expected_msg is provided and it does not match bitcoind's stdout."""
722722
assert not self.running
723723
with tempfile.NamedTemporaryFile(dir=self.stderr_dir, delete=False) as log_stderr, \
724724
tempfile.NamedTemporaryFile(dir=self.stdout_dir, delete=False) as log_stdout:
725+
assert_msg = None
725726
try:
726727
self.start(extra_args, stdout=log_stdout, stderr=log_stderr, *args, **kwargs)
727728
ret = self.process.wait(timeout=self.rpc_timeout)
@@ -745,7 +746,7 @@ def assert_start_raises_init_error(self, extra_args=None, expected_msg=None, mat
745746
if expected_msg != stderr:
746747
self._raise_assertion_error(
747748
'Expected message "{}" does not fully match stderr:\n"{}"'.format(expected_msg, stderr))
748-
except subprocess.TimeoutExpired:
749+
except subprocess.TimeoutExpired as e:
749750
self.process.kill()
750751
self.running = False
751752
self.process = None
@@ -754,6 +755,10 @@ def assert_start_raises_init_error(self, extra_args=None, expected_msg=None, mat
754755
assert_msg += "with an error"
755756
else:
756757
assert_msg += "with expected error " + expected_msg
758+
assert_msg += f" (cmd: {e.cmd})"
759+
760+
# Raise assertion outside of except-block above in order for it not to be treated as a knock-on exception.
761+
if assert_msg:
757762
self._raise_assertion_error(assert_msg)
758763

759764
def add_p2p_connection(self, p2p_conn, *, wait_for_verack=True, send_version=True, supports_v2_p2p=None, wait_for_v2_handshake=True, expect_success=True, **kwargs):

0 commit comments

Comments
 (0)