[Python] How to patch a click cli app for unit testing

Discussão em 'Python' iniciado por Stack, Junho 18, 2025.

  1. Stack

    Stack Membro Participativo

    I have a cli tool written in Python using Click:

    cli/main.py

    import click
    from datetime import *
    from .utils import fn

    @click.group(invoke_without_command=True, context_settings = { 'ignore_unknown_options': True, 'allow_extra_args': True })
    @click.argument('args', nargs=-1)
    def cli(args):
    print(fn())

    if __name__ == "__main__":
    cli([])


    cli/utils.py

    def fn():
    return("Example")


    tests/test.py

    from click.testing import CliRunner
    from mock import *

    from cli.main import cli

    @patch('cli.utils.fn')
    class Test:
    def test_patch_fn(self, mock_fn: Mock):

    mock_fn.return_value = "Mocked return"

    runner = CliRunner()
    result = runner.invoke(cli, [])

    assert result.exit_code == 0
    assert result.stdout == "Mocked return"


    Running the test gives:

    FAILED tests/test.py::Test::test_patch_fn - AssertionError: assert 'Example\n' == 'Mocked return'


    ok, so the patching failed. I tried the following with varying results:

    patch string error
    cli.main.cli.utils.fn ModuleNotFoundError: No module named 'cli.main.cli'; 'cli.main' is not a package
    tests.test.cli.fn AttributeError: <Group cli> does not have the attribute 'fn'
    cli.fn AttributeError: <module 'cli' from '/home/user/code/click-example/cli/__init__.py'> does not have the attribute 'fn'
    cli.main.cli.fn AttributeError: <Group cli> does not have the attribute 'fn'

    What is the magic string I need to make this work?

    Continue reading...

Compartilhe esta Página