如何模拟.patch 普通字典 {} ?
我想检查 header 是否设置为 {'Content-Type': 'application/json'}。
def get(self):
result = Spider.get_news_urls()
for k, v in result.iteritems():
response = requests.get(v)
xml = response.text()
headers = {'Content-Type': 'application/json'}
data = ''
taskqueue.Task(url='/v1/worker', headers=headers, payload=json.dumps(data)).add(queue_name='itagnewstasks')
return 'success', 200
以下单元测试似乎成功修补了字典。但我有一个 {},我需要修补它。
@mock.patch('__builtin__.dict')
@mock.patch('requests.get')
def test_header_is_set_to_json(self, req_get, x):
gen = Generator()
gen.get()
x.assert_called_with()
我想另一种方法是模拟补丁 taskqueue.Task()
并比较是否使用 headers= {'Content-Type': 'application/json'} 调用它
作为参数。
最佳答案
您想要模拟的 header 是在您正在测试的方法中构造的,因此模拟 taskqueue.Task
调用会容易得多。如果您将 header 字典传递到方法中,那么您只需保留一个副本并检查它是否已按预期更新。
您可以使用patch.dict模拟字典:
>>> foo = {}
>>> with patch.dict(foo, {'newkey': 'newvalue'}):
... assert foo == {'newkey': 'newvalue'}
...
>>> assert foo == {}
关于python - 如何在 python 中模拟.修补普通字典?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28191464/