2016-01-22 85 views
1

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

例如:字典

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

有:正则表达式中的关键access_token

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

你在说什么?这是Web框架的一部分吗?正则表达式断言应该在哪里发生?你需要在这里给我们一些背景。假设我们现在不坐在你身边...... – tdelaney

+0

@tdelaney我在单元测试中使用它 –

回答

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") 

此检查,如果他们有相同的键值如果是,则首先测试它们是否相同,如果不是,则测试第二个垫子是否相同第一。

只要词典里没有什么特别的东西,就会工作。列表可以工作,但不能用列表中的字符串,尽管实现它也是相当简单的。