2016-01-22 90 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") 

此檢查,如果他們有相同的鍵值如果是,則首先測試它們是否相同,如果不是,則測試第二個墊子是否相同第一。

只要詞典裏沒有什麼特別的東西,就會工作。列表可以工作,但不能用列表中的字符串,儘管實現它也是相當簡單的。