python - 当测试的函数是 Click 命令时 pytest 失败

标签 python python-3.x pytest

使用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/

相关文章:

python - 使用 imwrite opencv python 函数写入同一图像后更改像素值

python - pandas groupby 中非空值的移位和滚动平均值

python - 在 Python 中读取二进制字符串,zlib

python-3.x - Elasticsearch DSL或查询格式

python-3.x - 如何在不使用 for 循环的情况下检索包含在值列表字典中的目标值的目标值键?

python - OpenMDAO 的 SimpleGADriver 中自动计算的具有整数值的位

python-3.x - Python/Pandas 仅当值不为 0 时才进行减法

python - 在测试中检查 CLI 的退出代码

python - Assert_called_once_with 需要检查调用中的实例是否具有相同的信息

python - 使用pytest对学生代码进行测试和评分