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

我的源代码如下

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


我想要断言以上的最佳方法吗?

最佳答案

看起来您必须为此使用正则表达式:

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


您可以尝试通过将%s转换为.*%d转换为\d等将格式字符串转换为正则表达式:

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


(不过,在这种简单情况下,您只能使用startswithendswith。)

尽管实际上我不认为您应该对此进行测试。

关于python - 检查字符串是否符合特定格式,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/14983498/

10-15 02:13
查看更多