pythontestingpython-click

How to test cli command with Python Click options


I have this function that I'm trying to test. In cli.py I have

import myfunction
import click
@click.command(name="run")
@click.option("--param", required=True, type=int)
@click.option("--plot", required=False, default=False)
def run(param, plot):
    myfunction(param, plot) 

In my test_cli.py

from click.testing import CliRunner
from cli import run

def test_cli():
    kwargs = {"int": 5, "plot": False}
    runner = CliRunner()
    result = runner.invoke(run, args=kwargs)
    assert resutlts.output == ""

I get the following error:

Missing option --param 

Solution

  • CliRunner.invoke takes a list of command line parameters, not function parameters.

    Specifically you need to call it like this:

    runner.invoke(run, args=["--param", "5"])
    runner.invoke(run, "--param 5")
    

    for multiple arguments you can use either pattern:

    runner.invoke(run, args=["--param", "5", "6"])
    runner.invoke(run, args="--param 5 6")
    

    References

    https://click.palletsprojects.com/en/8.0.x/testing/