我有一个客户,他的期望是编写一个接受字典的函数convert()
,然后返回与输入字典相同的结果。现在,从我的角度来看,我应该在convert()
内进行检查,以使其与输入具有相同的键值,以便返回相同的值以通过assert
。但是,他说那不是他所期望的,他取消了合同。他希望convert()
函数返回没有模板进行检查的值(例如,不应该使用if record_id == 412029665_201012
),这是什么魔术?
from typing import Dict
def convert(json_in: Dict) -> Dict:
if json_in:
if 'record_id' and 'irs_object_id' in json_in:
record_id = json_in.get('record_id')
irs_object_id = json_in.get('irs_object_id')
if record_id == '412029665_201012' and irs_object_id == '201113199349201766':
return json_in
return dict() # empty dictionary
def test_no_change_case():
original: Dict = {
"record_id": "412029665_201012",
"irs_object_id": "201113199349201766",
}
expected: Dict = {
"record_id": "412029665_201012",
"irs_object_id": "201113199349201766",
}
actual: Dict = convert(original)
assert actual == expected
test_no_change_case()
答案 0 :(得分:0)
您始终可以执行assert original == expected
,这将检查是否所有键和对应的值都匹配,如下所示,如果我更改了expected
的键之一的值,或者添加了新的键值对,则断言失败
In [10]: from typing import Dict
In [11]: original: Dict = {
...: "record_id": "412029665_201012",
...: "irs_object_id": "201113199349201766",
...: }
In [12]: expected: Dict = {
...: "record_id": "412029665_201012",
...: "irs_object_id": "201113199349201766",
...: }
In [13]: assert original == expected
In [14]: expected: Dict = {
...: "record_id": "412029665_201012",
...: "irs_object_id": "2011",
...: }
In [15]: assert original == expected
---------------------------------------------------------------------------
AssertionError Traceback (most recent call last)
<ipython-input-15-573681974ca8> in <module>
----> 1 assert original == expected
AssertionError:
In [16]: expected: Dict = {
...: "record_id": "412029665_201012",
...: "irs_object_id": "201113199349201766",
...: "key": "value"
...: }
In [17]: assert original == expected
---------------------------------------------------------------------------
AssertionError Traceback (most recent call last)
<ipython-input-17-573681974ca8> in <module>
----> 1 assert original == expected
AssertionError
在原始代码中,实际上也不需要额外的if 'record_id' and 'irs_object_id' in json_in:
检查,因为您使用的是dict.get
方法,如果字典中不存在键,则该方法将返回None。
from typing import Dict
def convert(json_in: Dict) -> Dict:
if json_in:
#Removed the if test
record_id = json_in.get('record_id')
irs_object_id = json_in.get('irs_object_id')
if record_id == '412029665_201012' and irs_object_id == '201113199349201766':
return json_in
return dict() # empty dictionary
def test_no_change_case():
original: Dict = {
"record_id": "412029665_201012",
"irs_object_id": "201113199349201766",
}
expected: Dict = {
"record_id": "412029665_201012",
"irs_object_id": "201113199349201766",
}
actual: Dict = convert(original)
assert actual == expected
test_no_change_case()