gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-01 08:07:03 25 4
gpt4 key购买 nike

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

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com