gpt4 book ai didi

python - 使用日志记录或返回值而不是打印来测试点击

转载 作者:行者123 更新时间:2023-12-05 02:01:46 24 4
gpt4 key购买 nike

当我测试点击时,我了解到基本设置如下所示:

import click

@click.command()
@click.argument('name')
def hello(name):
click.echo('Hello %s!' % name)

测试文件

from click.testing import CliRunner
from hello import hello

def test_hello_world():
runner = CliRunner()
result = runner.invoke(hello, ['Peter'])
assert result.exit_code == 0
assert result.output == 'Hello Peter!\n'

但是,如果我使用日志记录而不是打印,我将无法捕获输出或检查命令的返回值。例如:

import click
import logging as log

@click.command()
@click.argument('name')
def hello(name):
log.info('Hello %s!' % name)
return name

如果不打印或click.echo,我无法检查返回值是否正确。

有没有一种方法可以检查返回值或检查使用点击记录的输出?

最佳答案

您可以使用 caplog fixture在 pytest 中捕获这样的日志输出:

def test_hello_world(caplog):
runner = CliRunner()
result = runner.invoke(hello, ['Peter'])
assert result.exit_code == 0
assert result.output == ''
assert caplog.messages == ['Hello Peter!']

至于要检查命令处理程序的“返回”值,Click 装饰命令不会返回常规意义上的任何内容。命令本身使用系统返回值,它正在 result.exit_code 上进行测试。

如果你真的认为你需要使用命令处理程序的返回值,你可以设置stand_alone flag .

关于python - 使用日志记录或返回值而不是打印来测试点击,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66303909/

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