使用py.test在Python中测试正则表达式
正则表达式对我来说仍然是一门黑暗的艺术,但我认为这是需要练习的东西之一。因此,我更关心的是是否能够生成py.test函数来显示正则表达式失败的地方。我当前的代码是这样的:使用py.test在Python中测试正则表达式,python,unit-testing,python-3.x,pytest,Python,Unit Testing,Python 3.x,Pytest,正则表达式对我来说仍然是一门黑暗的艺术,但我认为这是需要练习的东西之一。因此,我更关心的是是否能够生成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",
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
其中最后一个是第一个(唯一?)未通过测试的
我想我可以做一些像
assertSequenceEqual(test_matches, [not None]*len(test_matches))
但这似乎很糟糕,我的印象是
不是None
是检查对象不是None
而不是!=无
您可以使用全部
:
assert all([my_regex.match(test) for test in goodinputs])
您可能还希望测试不应该匹配的输入,并使用否定的any
测试这些输入
assert not any([my_regex.match(test) for test in badinputs])
如果要查看哪些匹配失败,可以稍微重新组织现有代码,如:
for test in tests:
assert my_regex.match(test), test
如果断言失败,则应打印出test
的值
但是,这只会打印出第一次故障的详细信息
如果要查看所有故障,可以执行以下操作:
failures = [test for test in tests if not my_regex.match(test)]
assert len(failures) == 0, failures
另一种方法是使用
my_regex=re.compile(“这很有帮助,但我希望py.test打印出哪些匹配失败,但它似乎还没有这样做。我遇到了另外两个问题:1.在另一段代码中,我添加了一个带有end=”的Python3 print语句。”",这导致Py.test抱怨这是一个错误,没有运行进一步的测试。2.以前,测试需要约30秒,这似乎很长。现在它已经运行了约10分钟,但仍然没有完成,即使这是在2010年的MacBook Pro上。这可能是一个单独的问题?如果是,我建议你开始一个新的问题你是对的,但我不想因为没有回应而显得粗鲁和忘恩负义。
failures = [test for test in tests if not my_regex.match(test)]
assert len(failures) == 0, failures
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