2

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 
1
  • with your edit away from --int your test code has got out of sync (should use param not int). And there's a typo resultlts -> results Commented Sep 21, 2021 at 14:03

1 Answer 1

2

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/

Sign up to request clarification or add additional context in comments.

6 Comments

thanks for your answer, what if my param is a list something like this @click.option("--param", required=True, type=(iint, float)) how can I pass the parameter. I trieed ['--param', "5 2"] and ["--param", (5, 3)] but i did not work it shows : param options requires 2 arguments
how would you pass it on the command line?
see latest update
Thanks yes it works
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.