如何对需要有效Click上下文的功能进行单元测试

问题描述 投票:1回答:1

我正在研究a command-line shell,并且我正在尝试测试一些分析命令参数的函数。

parser.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)

这是我为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']]

运行此单元测试时,出现错误,提示没有活动的Click上下文。

python unit-testing click
1个回答
0
投票

点击库Context()对象可用作Python上下文。因此,要在测试中设置active上下文,只需执行以下操作:

Context()

要创建要测试的with ctx: .... ,可以实例化一个:

Context

测试代码:

ctx = click.Context(a_click_command, obj=my_context_object)

结果:

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()
© www.soinside.com 2019 - 2024. All rights reserved.