我正在尝试在单元测试中进行一些模式匹配。
我的源代码包含以下内容
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
我想断言上述的最好方法?
答案 0 :(得分:3)
看起来你必须使用正则表达式:
assertTrue(re.match("The input .* is invalid", m))
您可以尝试将格式字符串转换为正则表达式,方法是将%s
翻译为.*
,将%d
翻译为\d
,依此类推:
pattern = MY_CODE.replace('%s', '.*').replace(...)
(在这种简单的情况下,您只能使用startswith
和endswith
。)
虽然实际上我认为你根本不应该测试它。