Search code examples
pythoncommand-line-interfacepytestpython-click

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


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


Solution

  • 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 ==============================