Why is the `return_value` for CliRunner().invoke(...) object null?
Asked Answered
T

1

5

I'm using click v8.1.3 and I'm trying to create some pytests, but I'm not getting my expected return_value when using click.testing.CliRunner().invoke

import click.testing
import mycli

def test_return_ctx():
  @mycli.cli.command()
  def foo():
    return "Potato"
  
  runner = click.testing.CliRunner()
  result = runner.invoke(mycli.cli, ["foo"])

  assert result.return_value == "Potato" # this fails. b/c the actual value is None

I tried updating the root command to return some random value as well to see if we get a value there

# mycli
import click

@click.group()
def cli():
  return "Potato"

But it didn't help. return_value for the Result object is still None

Am I misunderstanding how I should return a value from a command?

https://click.palletsprojects.com/en/8.1.x/api/#click.testing.Result.return_value

Thissa answered 27/8, 2022 at 0:14 Comment(0)
L
7

Click command handlers do not return a value unless you use: standalone_mode=False. You can do that during testing like:

result = CliRunner().invoke(foo, standalone_mode=False)

Test code:

import click
from click.testing import CliRunner


def test_return_value():
    @click.command()
    def foo():
        return "bar"

    result = CliRunner().invoke(foo, standalone_mode=False)

    assert result.return_value == "bar"

Test Results:

============================= test session starts ============================
collecting ... collected 1 item

test_code.py::test_return_value PASSED                                   [100%]

============================== 1 passed in 0.03s ==============================
Lashing answered 27/8, 2022 at 14:9 Comment(2)
It's so cool that there are people who this kind of secret stuff! ;D I read both links and I have no idea how you figured out that by setting standalone_mode to False will make return_value work since the documentation only mentions that system.exit() won't be called, but not that other stuff will start to work.Outlaw
@t3chb0t, I learned this, as well many of "the secrets" of the other answers I built for click, by spending a considerable amount of time reading the click code.Lashing

© 2022 - 2024 — McMap. All rights reserved.