检查字符串是否符合特定格式

2 投票
1 回答
926 浏览
提问于 2025-04-17 16:30

我正在我的单元测试中尝试做一些模式匹配。

我的源代码是这样的

MY_CODE = "The input %s is invalid"

def my_func():
    check_something()
    return MY_CODE % some_var

在我的测试中,我有这样的内容

def test_checking(self):
    m = app.my_func()
    # How do I assert that m is of the format MY_CODE???
    # assertTrue(MY_CODE in m) wont work because the error code has been formatted

我想知道最好的方式来验证上面的内容?

1 个回答

3

看起来你需要用正则表达式来解决这个问题:

assertTrue(re.match("The input .* is invalid", m))

你可以尝试把格式字符串转换成正则表达式,把 %s 转换成 .*,把 %d 转换成 \d,依此类推:

pattern = MY_CODE.replace('%s', '.*').replace(...)

(在这个简单的情况下,你其实可以直接用 startswithendswith 来处理。)

不过实际上,我觉得你根本不需要测试这个。

撰写回答