python - 使用 py.test 在 Python 中测试正则表达式

标签 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",
             "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/

相关文章:

python - 是否可以在不改变位置的情况下重命名字典中的键?

Django 添加一个变量值到 {%static 'path' %}

python-3.x - 尴尬的数组 : How to get numpy array after storing as Parquet (not BitMasked)?

python - 将子域名保存为字符串

python - 为什么我的 Flask 应用返回空白页面

python - ValueError : The truth value of array with more than one element is ambiguous. 使用 a.any() 或 a.all()

c# - 为 EF dbcontext 设置模拟对象以测试存储库方法

python - 如何使 easy_install 将包扩展到目录而不是单个 egg 文件中?

unit-testing - 开 Jest 找不到文件导入

c# - 如何对 Refit ApiResponse<T> 进行单元测试?