检查字符串是否符合某种格式

时间:2013-02-20 15:23:07

标签: python string unit-testing python-2.7 string-formatting

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

我的源代码包含以下内容

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 个答案:

答案 0 :(得分:3)

看起来你必须使用正则表达式:

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

您可以尝试将格式字符串转换为正则表达式,方法是将%s翻译为.*,将%d翻译为\d,依此类推:

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

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

虽然实际上我认为你根本不应该测试它。