如何在 Python 中对需要活动 Click 上下文的函数进行单元测试

Dul*_*nas 7 python unit-testing pytest python-click

我正在使用命令行 shell,并且正在尝试测试一些解析命令参数的函数。

解析器.py:

import shlex
import click


def process_cmd(args, called_self=False):
    result = args

    # Replace aliases
    if not called_self:
        aliases = click.get_current_context().obj.config['ALIASES']
        if result[0] in aliases:
            substitution = process_cmd(split_args(aliases[result[0]]), True)
            if len(result) == 1:
                result = substitution
            else:
                result = substitution + result[1:]

    return result


def split_pipeline(args):
    cmd = []
    for arg in args:
        if arg == '|':
            yield process_cmd(cmd)
            cmd = []
        else:
            cmd.append(arg)
    # yield the last part of the pipeline
    yield process_cmd(cmd)
Run Code Online (Sandbox Code Playgroud)

这是我编写的单元测试split_pipeline

import parser

def test_pipeline():
    args = ['1', '2', '|', '3', '|', '4']
    result = [i for i in parser.split_pipeline(args)]
    assert result == [['1', '2'], ['3'], ['4']]
Run Code Online (Sandbox Code Playgroud)

运行此单元测试时,我收到一条错误消息,指出没有活动的 Click 上下文。

Ste*_*uch 7

单击库Context()对象可以用作 Python 上下文。因此,要在测试中设置活动上下文,您可以简单地执行以下操作:

with ctx:
    ....
Run Code Online (Sandbox Code Playgroud)

要创建一个Context测试对象,您可以实例化一个,如下所示:

ctx = click.Context(a_click_command, obj=my_context_object)
Run Code Online (Sandbox Code Playgroud)

测试代码:

import click


def process_cmd():
    click.echo(click.get_current_context().obj['prop'])


def test_with_context():
    ctx = click.Context(click.Command('cmd'), obj={'prop': 'A Context'})
    with ctx:
        process_cmd()

test_with_context()
Run Code Online (Sandbox Code Playgroud)

结果:

A Context
Run Code Online (Sandbox Code Playgroud)