【问题标题】:assertion dict with regex带有正则表达式的断言字典
【发布时间】:2016-04-28 14:06:55
【问题描述】:

它可能用正则表达式断言字典?

例子:字典

{
    "mimetype": "application/json",
    "status_code": 200,
    "data": {
      "id": 1,
      "username": "foo",
      "access_token": "5151818748748"
  }
}

with: 正则表达式在键 access_token

{
    "mimetype": "application/json",
    "status_code": 200,
    "data": {
      "id": 1,
      "username": "foo",
      "access_token": "(.+)"
  }
}

【问题讨论】:

  • 你在说什么?这是 Web 框架的一部分还是什么?正则表达式断言应该在哪里发生?你需要在这里给我们一些背景信息。假设我们现在不是坐在你旁边......
  • @tdelaney 我在单元测试中使用它

标签: python regex dictionary


【解决方案1】:

假设我理解正确:

import re

def assert_dict(template, thing):
    if len(template) != len(thing):
        raise AssertionError("Assertion failed")
    for key in template:
        if isinstance(template[key], dict):
            assert_dict(template[key], thing[key])
        else:
            if template[key] == thing[key]:
                continue
            elif re.fullmatch(template[key], thing[key]):
                continue
            else:
                raise AssertionError("Assertion failed")

这会检查它们是否具有相同的键值对,如果是,则首先测试它们是否相同,如果不是,则第二个是否与第一个匹配。

只要字典中没有花哨的东西,这将起作用。列表可以工作,但列表中的字典不行,尽管实现它也相当简单。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-02-05
    • 2015-10-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多