我正在尝试在单元测试中进行一些模式匹配。
我的源代码有以下内容
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
。)
尽管实际上我认为你根本不应该测试它。
关于python - 检查字符串是否符合某种格式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14983498/