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

Python 检查字符串是否符合特定格式,python,string,unit-testing,python-2.7,string-formatting,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?

我试图在单元测试中进行一些模式匹配

我的源代码有以下内容

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(...)
(在这个简单的例子中,您可以只使用
startswith
endswith


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

是的,但我不想在测试中出现“输入。*无效”的情况。我有权访问MY_CODE常量,我想要assertTrue(do_something(MY_CODE).match(m))+1,尽管我不确定我是否同意“不要测试此”部分。根据某种格式测试字符串输出和错误消息是非常明智的。@larsmans好吧,也许是所示代码的简单性让我想到了这一点。也许测试格式是明智的,但如果只有一行代码总是生成输出,并且返回MY_code%some_var,则,然后我可能不会测试它。抱歉,我简化了它,但事实上代码非常复杂,我想测试a)是否打印了错误消息,b)如果是,它确认为一种格式