使用 py.test 在 Python 中测试正则表达式 [英] Testing regexes in Python using py.test

查看:78
本文介绍了使用 py.test 在 Python 中测试正则表达式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

正则表达式对我来说仍然是一种黑暗艺术,但我认为这是需要练习的东西之一.因此,我更关心的是能够生成 py.test 函数来显示我的正则表达式失败的地方.我目前的代码是这样的:

Regexes are still something of a dark art to me, but I think that's one of those things that just takes practice. As such, I'm more concerned with being able to produce py.test functions that show me where my regexes are failing. My current code is something like this:

my_regex = re.compile("<this is where the magic (doesn't)? happen(s)?>")

def test_my_regex():
    tests = ["an easy test that I'm sure will pass",
             "a few things that may trip me up",
             "a really pathological, contrived example",
             "something from the real world?"]

    test_matches = [my_regex.match(test) for test in tests]

    for i in range(len(tests)):
        print("{}: {!r}".format(i, tests[i]))
        assert test_matches[i] is not None

当我运行 py.test myfile.py 时的输出类似于

for which the output when I run py.test myfile.py is something like

0: "an easy..."
1: "a few things..."
2: "a really pathological..."

最后一个是第一个(唯一?)没有通过测试的.

where the last one is the first (only?) one to have not passed the test.

我想我可以做类似的事情

I suppose I could do something like an

assertSequenceEqual(test_matches, [not None]*len(test_matches))

但这看起来很恶心,我的印象是 is not None 是检查对象不是 None 而不是 的首选方法.!= 无.

but that seems gross, and I was under the impression that <object> is not None is the preferred way of checking that an object isn't None rather than <object> != None.

推荐答案

另一种方法是使用 parametrize.

my_regex = re.compile("<this is where the magic (doesn't)? happen(s)?>")

@pytest.mark.parametrize('test_str', [
    "an easy test that I'm sure will pass",
    "a few things that may trip me up",
    "a really pathological, contrived example",
    "something from the real world?",
])
def test_my_regex(test_str):
     assert my_regex.match(test_str) is not None

这将为每个测试字符串生成一个独立的测试用例.这个 IMO 更干净,更容易添加新案例,并且还具有允许每个 test_str 单独失败而不影响其他人的优势.

This will produce an independent test case for each test string. This IMO is cleaner, easier to add new cases and also has the advantage of allowing each test_str to fail individually without affecting the others.

这篇关于使用 py.test 在 Python 中测试正则表达式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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