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

标签 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

我想要断言上述内容的最佳方式?

最佳答案

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

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/

相关文章:

php - AngularJS 应该测试什么

unit-testing - Rx-Kotlin awaitTerminalEvent 永远不会 onComplete

python - 列表索引超出范围

python - 从 TFRecords 读取时丢失数据

python - 如何在 Python 中将彩色输出打印到终端?

Python2 json : load using strings instead of unicode

php - PHP 中单引号和双引号字符串有什么区别?

python - 在特定位置更新文本文件中的字符串

ios - segues的自动化测试

python - Hello world Pyamf 小错误信息