测试Python Click命令异常 [英] Testing Python Click Command Exceptions

查看:83
本文介绍了测试Python Click命令异常的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试通过使用 Click程序包.

这是我的命令:

@click.option(
    '--bucket_name',
...)
@click.option(
    '--group_id',
...)
@click.option(
    '--artifact_id',
...)
@click.option(
    '--version',
...)
@click.option(
    '--artifact_dir',
    required=False,
    default='downloads/artifacts/',
...)
@click.command()
def download_artifacts(
    bucket_name,
    group_id, artifact_id, version,
    artifact_dir
):
    logger.info(
        f"bucket_name: {bucket_name}, "
        f"group_id: {group_id}, "
        f"artifact_id: {artifact_id}, "
        f"version: {version}, "
        f"artifact_dir: {artifact_dir}, "
        )

    if not artifact_dir.endswith('/'):
        raise ValueError(
            "Enter artifact_dir ending with '/' ! artifact_dir: "
            f"{artifact_dir}")
...

这是我的 assertRaises 测试代码无效:

This is my test code with assertRaises that doesn't work:

def test_download_artifacts_invalid_dir(
        self,
    ):
        runner = CliRunner()
        with self.assertRaises(ValueError):
            result = runner.invoke(
                download_artifacts,
                '--bucket_name my_bucket \
                --group_id gi \
                --artifact_id ai \
                --version 1.0.0 \
                --artifact_dir artifact_dir'.split(),
                input='5')

断言失败,并且给出 E AssertionError:未引发ValueError .

我已经找到了这种测试方式,通过,但是看起来并不优雅:

I have found this way of testing, which passes, but it doesn't seem very elegant:

def test_download_artifacts_invalid_dir(
        self,
    ):
        runner = CliRunner()
        result = runner.invoke(
            download_artifacts,
            '--bucket_name my_bucket \
            --group_id gi \
            --artifact_id ai \
            --version 1.0.0 \
            --artifact_dir artifact_dir'.split(),
            input='5')
        print(f"result.exception: {result.exception}")
        assert "Enter artifact_dir ending" in str(result.exception)

推荐答案

两种通过click.CliRunner()测试异常的方法

DOCS 中提示了第一种方法:

Two ways to test for exceptions with click.CliRunner()

The first method is hinted out in the DOCS:

基本测试

用于测试Click应用程序的基本功能是 CliRunner可以将命令作为命令行脚本来调用. CliRunner.invoke()方法单独运行命令行脚本,并以字节和二进制数据的形式捕获输出.

Basic Testing

The basic functionality for testing Click applications is the CliRunner which can invoke commands as command line scripts. The CliRunner.invoke() method runs the command line script in isolation and captures the output as both bytes and binary data.

返回值是[Result]对象,其中包含捕获的输出数据,退出代码和可选的异常.

The return value is a [Result] object, which has the captured output data, exit code, and optional exception attached.

result = runner.invoke(throw_value_error)
assert isinstance(result.exception, ValueError)

第二种方法是在catch_exceptions = False 参数.CliRunner.invoke"rel =" nofollow noreferrer> CliRunner.invoke()

The second method is to set the catch_exceptions=False parameter on CliRunner.invoke()

runner.invoke(..., catch_exceptions=False)

测试代码

import click.testing
import pytest

@click.command()
def throw_value_error():
    raise ValueError("This is My Message!")

def test_catch_value_error():
    """Read the CliRunner exception report"""
    runner = click.testing.CliRunner()
    result = runner.invoke(throw_value_error)
    assert isinstance(result.exception, ValueError)
    assert 'My Message' in str(result.exception)

def test_throw_value_error():
    """Have the CliRunner not catch my exception"""
    runner = click.testing.CliRunner()
    with pytest.raises(ValueError):
        runner.invoke(throw_value_error, catch_exceptions=False)

测试结果

============================= test session starts ==============================
platform linux -- Python 3.7.7, pytest-6.2.1 -- /usr/bin/python
collecting ... collected 2 item

tests/test_api_authz.py::test_catch_value_error PASSED                   [ 50%]
tests/test_api_authz.py::test_throw_value_error PASSED                   [100%]

============================== 2 passed in 0.05s ===============================

这篇关于测试Python Click命令异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆