在Python行为测试框架中处理异常 [英] Handling Exceptions in Python Behave Testing framework

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

问题描述

我一直在考虑从鼻子转向行为测试(摩卡/柴等已经宠坏了我).到目前为止,一切都很好,但是除了:

I've been thinking about switching from nose to behave for testing (mocha/chai etc have spoiled me). So far so good, but I can't seem to figure out any way of testing for exceptions besides:

@then("It throws a KeyError exception")
def step_impl(context):
try:
    konfigure.load_env_mapping("baz", context.configs)
except KeyError, e:
    assert (e.message == "No baz configuration found") 

我可以用鼻子注释

@raises(KeyError)

我在行为中找不到类似的东西(不在源代码中,不在示例中,不在此处).能够指定方案概述中可能抛出的异常肯定很盛行.

I can't find anything like this in behave (not in the source, not in the examples, not here). It sure would be grand to be able to specify exceptions that might be thrown in the scenario outlines.

有人走这条路吗?

推荐答案

我本人对BDD还是很陌生,但总的来说,想法是测试记录了客户端可以期望的行为,而不是步骤实现.因此,我希望测试的规范方法如下:

I'm pretty new to BDD myself, but generally, the idea would be that the tests document what behaves the client can expect - not the step implementations. So I'd expect the canonical way to test this would be something like:

When I try to load config baz
Then it throws a KeyError with message "No baz configuration found"

步骤定义如下:

@when('...')
def step(context):
    try:
        # do some loading here
        context.exc = None
    except Exception, e:
        context.exc = e

@then('it throws a {type} with message "{msg}"')
def step(context, type, msg):
    assert isinstance(context.exc, eval(type)), "Invalid exception - expected " + type
    assert context.exc.message == msg, "Invalid message - expected " + msg

如果这是常见的模式,则可以编写自己的装饰器:

If that's a common pattern, you could just write your own decorator:

def catch_all(func):
    def wrapper(context, *args, **kwargs):
        try:
            func(context, *args, **kwargs)
            context.exc = None
        except Exception, e:
            context.exc = e

    return wrapper

@when('... ...')
@catch_all
def step(context):
    # do some loading here - same as before

这篇关于在Python行为测试框架中处理异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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