Home > Blockchain >  testing cli command with click options python
testing cli command with click options python

Time:09-22

Hi 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

CodePudding user response:

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/

  • Related