python - 如何在 python 中模拟.修补普通字典?

标签 python unit-testing mocking

如何模拟.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/

相关文章:

python - 从 Azure Databricks 读取时,已安装的 Azure 存储在文件夹内显示 mount.err

python - Python 中的夏令时

unit-testing - 模拟 Eureka Feign 客户端进行单元测试

javascript - AfterEach 需要 Jasmine 测试帮助

使用 DSharp 的 Delphi 模拟不会使用枚举值进行编译

Python 补丁装饰器溢出到其他方法中

python - 删除各个子目录中相同的文件名

python - 无法正确修补对象的属性

unit-testing - 如何自动化安装程序测试

go - 如何使用 testify/mock 在 golang 中模拟数据库层