正则表达式对我来说仍然是一门黑暗的艺术,但我认为这是需要练习的事情之一。因此,我更关心的是能够生成 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
.
最佳答案
另一种方法是使用 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
单独失败而不影响其他案例的优势。
关于python - 使用 py.test 在 Python 中测试正则表达式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22818948/