我正在编写一个CLI来使用elasticsearch-py库与elasticsearch交互。我试图模拟elasticsearch-py函数,以便在不调用真正集群的情况下测试我的函数。
main.py
Escli继承了克里夫的App 班级
class Escli(App):
_es = elasticsearch5.Elasticsearch()settings.py
from escli.main import Escli
class Settings:
def get(self, sections):
raise NotImplementedError()
class ClusterSettings(Settings):
def get(self, setting, persistency='transient'):
settings = Escli._es.cluster\
.get_settings(include_defaults=True, flat_settings=True)\
.get(persistency)\
.get(setting)
return settingssettings_test.py
import escli.settings
class TestClusterSettings(TestCase):
def setUp(self):
self.patcher = patch('elasticsearch5.Elasticsearch')
self.MockClass = self.patcher.start()
def test_get(self):
# Note this is an empty dict to show my point
# it will contain childs dict to allow my .get(persistency).get(setting)
self.MockClass.return_value.cluster.get_settings.return_value = {}
cluster_settings = escli.settings.ClusterSettings()
ret = cluster_settings.get('cluster.routing.allocation.node_concurrent_recoveries', persistency='transient')
# ret should contain a subset of my dict defined above我希望让Escli._es.cluster.get_settings()返回我想要的东西( dict对象),以便不进行真正的HTTP调用,但它一直在这样做。
我所知道的:
MagicMockObject.return_value.InstanceMethodName.return_value = ...的操作Escli._es.cluster.get_settings,因为Escli试图将Escli作为模块导入,而模块无法工作。所以我在修补整张图解。我拼命地想把一些return_value放在任何地方,但我不明白为什么我不能正确地嘲弄那个东西。
发布于 2018-05-25 13:25:26
您应该嘲笑您正在测试的位置。根据提供的示例,这意味着您在settings.py模块中使用的settings.py类需要针对settings.py进行模拟。因此,更实际地说,您的patch调用在setUp中应该是这样的:
self.patcher = patch('escli.settings.Escli')现在,根据测试的运行方式,您可以在正确的位置上模拟您想要的内容。
此外,要为测试添加更多的健壮性,您可能需要考虑对您正在创建的Elasticsearch实例进行指定,以验证您实际上正在调用与Elasticsearch相关的有效方法。考虑到这一点,您可以这样做:
self.patcher = patch('escli.settings.Escli', Mock(Elasticsearch))要更多地了解spec的确切含义,请查看文档中的补丁部分。
最后,如果您对探索吡喃的伟大世界感兴趣,那么可以创建一个pytest-弹性搜索插件来帮助您实现这一目标。
https://stackoverflow.com/questions/50506310
复制相似问题