0

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?

3
  • If in the module click/testing.py is present from cli.utils import fn try with @patch('click.testing.fn'). Otherwise edit your question and add the content of the module click/testing.py wich contains the definition of the class CliRunner Commented Oct 5, 2023 at 12:07
  • click.testing is a standard click module: click.palletsprojects.com/en/8.1.x/testing Commented Oct 6, 2023 at 22:05
  • Sorry. Try with @patch('cli.main.fn'). Commented Oct 7, 2023 at 13:10

0

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.