Taichi
Taichi

Reputation: 2597

pytest fails when tested function is Click command

Using Python 3.6.4, Click==7.0, and pytest==4.4.0. I got into a trouble when using Click & pytest at the same time.

test_foo.py

import unittest

import click
import pytest

@click.command()
def foo():
    print(1)


class TestFoo(unittest.TestCase):
    def test_foo(self):
        foo()

And when execute pytest test_foo.py::TestFoo::test_foo , it says

Usage: pytest [OPTIONS]
Try "pytest --help" for help.

Error: Got unexpected extra argument 
(tests/test_foo.py::TestFoo::test_foo)

All of the pytest options (such as -k or -m) does not work when Click command is enabled to the tested method.

It works fine when I comment out the line of @click.command(), of course.

How does everyone solve this when using both of them at the same time?

Upvotes: 2

Views: 700

Answers (1)

hoefling
hoefling

Reputation: 66541

You should use the ClickRunner to isolate the execution of click commands in tests. Your example, reworked:

import unittest
import click
import click.testing


@click.command()
def foo():
    print(1)


class TestFoo(unittest.TestCase):
    def test_foo(self):
        runner = click.testing.CliRunner()
        result = runner.invoke(foo)
        assert result.exit_code == 0
        assert result.output == '1\n'

Check out the relevant doc page for more examples.

Upvotes: 3

Related Questions