【问题标题】:Asserting string matches regex in pytest断言字符串匹配 pytest 中的正则表达式
【发布时间】:2019-01-04 20:48:46
【问题描述】:

我正在使用 pytest 编写测试,以确保传入的时间戳字符串与适当的正则表达式格式匹配。我是通过以下方式完成的。

test_epoch():
    timestamp = "1541811598.802"
    epoch_regex = re.compile(r'^[0-9]+$')
    assert epoch_regex.match(epoch)

但是,当测试运行时,我收到以下错误:

AssertionError: assert None
+  where None = <built-in method match of re.Pattern object at 0x11ade6480>('1541840398.802')
+    where <built-in method match of re.Pattern object at 0x11ade6480> = re.compile('^[0-9]+$').match

有谁知道我哪里出错以及如何正确断言字符串匹配正则表达式?

【问题讨论】:

    标签: python regex pytest assert assertion


    【解决方案1】:

    timestamp 真的匹配正则表达式吗?如果你去掉timestamp 中的'.' 会发生什么?我感觉timestamp = "1541811598802" 会过去。

    还请记住,'.' 是正则表达式中的一个特殊字符,因此当您修改正则表达式时,请务必考虑到这一点(提示,使用 \ 转义特殊字符)!

    【讨论】:

      猜你喜欢
      • 2020-04-15
      • 2012-06-05
      • 2013-12-25
      • 1970-01-01
      相关资源
      最近更新 更多