Search code examples
testingcommand-line-interfacepytestpython-click

Click: Test click.group commands without running their code


I´m currently writing tests for my application and therefore, I have to test some click.group commands I defined:

Let´s say I defined them like:

@click.group(cls=MyGroup)
@click.pass_context
def myapp(ctx):
    init_stuff()    

@myapp.command()
@click.option('--myOption')
def foo(myOption: str) -> None:
    do_stuff() # change some files, print, create other files

I know that I could use the CliRunner from click.testing. However, I just want to make sure, that the command is called, but I DONT WANT it to execute any code (for example by applying the CliRunner.invoke()).

How could this be done? I couldn´t come up with a solution using mocking with foo for example. Or do I have to execute code lets say using the isolated_filesystem() which CliRunner provides?

So the question is: What would be the most efficient way to test my commands when defined like shown above?

Many thanks in advance


Solution

  • You could add a --dry-run flag to your group or some commands, and save it it inside the context, and if the flag is enabled, do not execute any code. Then you can use CliRunner.invoke() with the --dry-run flag enabled and just check your invocations have happened, without actually executing the code.