正则表达式对我来说仍然是一门黑暗艺术,但我认为这是需要练习的事情之一。因此,我更关心能够生成 py.test 函数来显示我的正则表达式失败的地方。我当前的代码是这样的:
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
是这样的
0: "an easy..."
1: "a few things..."
2: "a really pathological..."
其中最后一个是第一个(唯一?)一个未通过测试的。
我想我可以做类似的事情
assertSequenceEqual(test_matches, [not None]*len(test_matches))
但这看起来很恶心,我的印象是<object> is not None
是检查对象是否存在的首选方法None
而不是<object> != None
.
另一种方法是使用参数化 https://pytest.org/latest/example/parametrize.html.
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
个人失败而不影响其他人。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)