Repository: bitcoin/bitcoin
File: test/functional/test_framework/test_node.py (Python)

Code before:

    def __call__(self, *options, input=None):
        # TestNodeCLI is callable with bitcoin-cli command-line options
        cli = TestNodeCLI(self.binaries, self.datadir)
        cli.options = [str(o) for o in options]
        cli.input = input
        return cli

    def __getattr__(self, command):
        return TestNodeCLIAttr(self, command)

    def batch(self, requests):
        results = []
        for request in requests:
            try:
                results.append(dict(result=request()))
            except JSONRPCException as e:
                results.append(dict(error=e))
        return results

    def send_cli(self, clicommand=None, *args, **kwargs):
        """Run bitcoin-cli command. Deserializes returned string as python object."""
        pos_args = [arg_to_cli(arg) for arg in args]
        named_args = [str(key) + "=" + arg_to_cli(value) for (key, value) in kwargs.items()]
        p_args = self.binaries.rpc_argv() + [f"-datadir={self.datadir}"] + self.options
        if named_args:
            p_args += ["-named"]
        if clicommand is not None:
            p_args += [clicommand]
        p_args += pos_args + named_args
        self.log.debug("Running bitcoin-cli {}".format(p_args[2:]))
        process = subprocess.Popen(p_args, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True)
        cli_stdout, cli_stderr = process.communicate(input=self.input)
        returncode = process.poll()
        if returncode:
            match = re.match(r'error code: ([-0-9]+)\nerror message:\n(.*)', cli_stderr)
            if match:
                code, message = match.groups()
                raise JSONRPCException(dict(code=int(code), message=message))
            # Ignore cli_stdout, raise with cli_stderr
            raise subprocess.CalledProcessError(returncode, p_args, output=cli_stderr)
        try:
            if not cli_stdout.strip():
                return None
            return json.loads(cli_stdout, parse_float=decimal.Decimal)
        except (json.JSONDecodeError, decimal.InvalidOperation):
            return cli_stdout.rstrip("\n")


Review comment (suggestion):
completely unrelated, but converting a value to string is confusing when it:

* must be of type string and can't be any other type
* wouldn't make sense to be of non-string type

.

It could make sense to drop that:

```diff
diff --git a/test/functional/test_framework/test_node.py b/test/functional/test_framework/test_node.py
index 9449d3808b..c49bfcffcd 100755
--- a/test/functional/test_framework/test_node.py
+++ b/test/functional/test_framework/test_node.py
@@ -918,7 +918,7 @@ class TestNodeCLI():
     def send_cli(self, clicommand=None, *args, **kwargs):
         """Run bitcoin-cli command. Deserializes returned string as python object."""
         pos_args = [arg_to_cli(arg) for arg in args]
-        named_args = [str(key) + "=" + arg_to_cli(value) for (key, value) in kwargs.items() if value is not None]
+        named_args = [key + "=" + arg_to_cli(value) for (key, value) in kwargs.items() if value is not None]
         p_args = self.binaries.rpc_argv() + [f"-datadir={self.datadir}"] + self.options
         if named_args:
             p_args += ["-named"]


Code after:
        self.input = None
        self.log = logging.getLogger('TestFramework.bitcoincli')

    def __call__(self, *options, input=None):
        # TestNodeCLI is callable with bitcoin-cli command-line options
        cli = TestNodeCLI(self.binaries, self.datadir)
        cli.options = [str(o) for o in options]
        cli.input = input
        return cli

    def __getattr__(self, command):
        return TestNodeCLIAttr(self, command)

    def batch(self, requests):
        results = []
        for request in requests:
            try:
                results.append(dict(result=request()))
            except JSONRPCException as e:
                results.append(dict(error=e))
        return results

    def send_cli(self, clicommand=None, *args, **kwargs):
        """Run bitcoin-cli command. Deserializes returned string as python object."""
        pos_args = [arg_to_cli(arg) for arg in args]
        named_args = [key + "=" + arg_to_cli(value) for (key, value) in kwargs.items() if value is not None]
        p_args = self.binaries.rpc_argv() + [f"-datadir={self.datadir}"] + self.options
        if named_args:
            p_args += ["-named"]
        base_arg_pos = len(p_args)
        if clicommand is not None:
            p_args += [clicommand]
        p_args += pos_args + named_args
        max_arg_size = max(len(arg) for arg in p_args)
        stdin_data = self.input
        if max_arg_size > CLI_MAX_ARG_SIZE:
            self.log.debug(f"Cli: Command size {max_arg_size} too large, using stdin")
            rpc_args = "\n".join([arg for arg in p_args[base_arg_pos:]])
            if stdin_data is not None:
                stdin_data += "\n" + rpc_args
            else:
                stdin_data = rpc_args
            p_args = p_args[:base_arg_pos] + ['-stdin']

        self.log.debug("Running bitcoin-cli {}".format(p_args[2:]))
        process = subprocess.Popen(p_args, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True)
        cli_stdout, cli_stderr = process.communicate(input=stdin_data)
        returncode = process.poll()
        if returncode:
            match = re.match(r'error code: ([-0-9]+)\nerror message:\n(.*)', cli_stderr)
            if match: