繁体   English   中英

当被测试的函数是 Click 命令时,pytest 失败

[英]pytest fails when tested function is Click command

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

查看相关文档页面以获取更多示例。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM