【问题标题】:Check if the string conforms to a certain format检查字符串是否符合某种格式
【发布时间】:2013-02-05 16:04:08
【问题描述】:

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

我的源代码如下

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

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

【问题讨论】:

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


    【解决方案1】:

    看起来您必须为此使用正则表达式:

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

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

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

    (在这个简单的例子中,你可以只使用startswithendswith。)

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

    【讨论】:

    • 对,但我不想在我的测试中出现“输入 .* 无效”。我可以访问 MY_CODE 常量,我想要类似 assertTrue(do_something(MY_CODE).match(m))
    • +1,虽然我不确定我是否同意“不要测试这个”部分。针对某种格式测试字符串输出和错误消息是非常明智的。
    • @larsmans 好吧,也许是显示代码的简单性让我这么想。也许测试格式是明智的,但如果有一行代码总是生成输出并且它是return MY_CODE % some_var,那么我可能不会测试它。
    • 对不起,我简化了它,但实际上代码非常复杂,我想测试 a)是否打印了错误消息,b)如果是,则确认格式
    猜你喜欢
    • 2016-06-07
    • 2022-10-23
    • 2012-08-31
    • 2021-03-19
    • 1970-01-01
    • 2015-12-28
    • 2016-08-09
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多