使用Python 3.6.4,Click==7.0,pytest==4.4.0。 我在同时使用 Click 和 pytest 时遇到了麻烦。
test_foo.py
import unittest
import click
import pytest
@click.command()
def foo():
print(1)
class TestFoo(unittest.TestCase):
def test_foo(self):
foo()
当执行 pytest test_foo.py::TestFoo::test_foo
时,它说
Usage: pytest [OPTIONS]
Try "pytest --help" for help.
Error: Got unexpected extra argument
(tests/test_foo.py::TestFoo::test_foo)
当对测试方法启用 Click 命令时,所有 pytest 选项(例如 -k
或 -m
)都不起作用。
当然,当我注释掉 @click.command()
行时,效果很好。
同时使用两者时大家都是如何解决这个问题的?
最佳答案
您应该使用ClickRunner
隔离测试中单击命令的执行。您的示例已重新设计:
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'
查看相关doc page了解更多示例。
关于python - 当测试的函数是 Click 命令时 pytest 失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55489636/