如何在python中mock.patch普通字典?
如何模拟.patch普通字典{} 我想检查标题是否设置为{'Content-Type':'application/json'}如何在python中mock.patch普通字典?,python,unit-testing,mocking,Python,Unit Testing,Mocking,如何模拟.patch普通字典{} 我想检查标题是否设置为{'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':
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
下面的单元测试似乎成功地修补了dict。但是我有一个{},我需要修补它
@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()
我想另一种方法是模拟patch
taskqueue.Task()
,并比较是否以headers={'Content-Type':'application/json'}
作为参数调用它,因此,模拟taskqueue.Task
调用会容易得多。如果您将头dict传递到方法中,那么您只需保留一个副本并检查它是否已按预期更新
您可以使用来模拟字典:
>>> foo = {}
>>> with patch.dict(foo, {'newkey': 'newvalue'}):
... assert foo == {'newkey': 'newvalue'}
...
>>> assert foo == {}
今天遇到了一个关于补丁.dict的问题
patch.dict
在退出时回滚整个dict
。。。不仅仅是修补过的值。如果这不是您想要的行为,您可能希望使用更具选择性的修补程序
这与patch.dict的工作原理相同,但它只恢复您修补的密钥
class DictPatch:
def __init__(self, obj, patch):
self.obj = obj
self.patch = patch
self.save = {}
self.pop = []
def start(self):
self.save = {k: v for k, v in self.obj.items() if k in self.patch}
self.pop = [k for k in self.patch if k not in self.obj]
self.obj.update(self.patch)
# this allows you to do self.addCleanup(DictPatch(...)), which is nice
return self.stop
def stop(self):
self.obj.update(self.save)
for k in self.pop:
self.obj.pop(k)
def __enter__(self):
self.start()
def __exit__(self, exc_type, exc_val, exc_tb):
self.stop()
注意:它会将所有键的dict重置为原始值,而不仅仅是您修补的键!