Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save tuantranf/56a7c83d0e45a76e242b62eccd30b7ad to your computer and use it in GitHub Desktop.
Save tuantranf/56a7c83d0e45a76e242b62eccd30b7ad to your computer and use it in GitHub Desktop.
Pytest - Click - Enable CliRunner to echo output to stdout/stderr

Enable CliRunner to echo output to stdout/stderr

Workaround

Referrence pallets/click#737

import functools
import pytest

@pytest.fixture
def cli():
    """Yield a click.testing.CliRunner to invoke the CLI."""
    class_ = CliRunner

    def invoke_wrapper(f):
        """Augment CliRunner.invoke to emit its output to stdout.

        This enables pytest to show the output in its logs on test
        failures.

        """
        @functools.wraps(f)
        def wrapper(*args, **kwargs):
            echo = kwargs.pop('echo', False)
            result = f(*args, **kwargs)

            if echo is True:
                sys.stdout.write(result.output)
            return result

        return wrapper

    class_.invoke = invoke_wrapper(class_.invoke)
    cli_runner = class_()

    yield cli_runner

Test case

 def test_methods(self, cli):
   # enable echo=True
   result = cli.invoke('test-click-command', echo=True)
   assert 'OK in result.output

Alternative solution

Using subprocess instead of CliRunner

def test_methods(self, cli):
   commands = ['test-click-command']
   return_code = sys.exit(subprocess.call(commands))
   assert return_code == self.SUCCESS_CODE

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment