【发布时间】:2021-04-02 16:51:31
【问题描述】:
我有一个使用 pytest 的 Python 应用程序。对于我的几个测试,有对 Elasticsearch 的 API 调用(使用 elasticsearch-dsl-py)会减慢我想要的测试:
- 除非使用 Pytest 标记,否则应避免。
- 如果使用标记,我希望该标记在测试运行之前执行一些代码。就像使用
yield时夹具的工作方式一样。
这主要是受到 pytest-django 的启发,您必须使用 django_db 标记才能连接到数据库(但如果您尝试连接到数据库,它们会抛出错误,而我只是不这样做'一开始就不想打电话,仅此而已)。
例如:
def test_unintentionally_using_es():
"""I don't want a call going to Elasticsearch. But they just happen. Is there a way to "mock" the call? Or even just prevent the call from happening?"""
@pytest.mark.elastic
def test_intentionally_using_es():
"""I would like for this marker to perform some tasks beforehand (i.e. clear the indices)"""
# To replicate that second test, I currently use a fixture:
@pytest.fixture
def elastic():
# Pre-test tasks
yield something
我认为这是标记的用例,对吧?主要受 pytest-django 启发。
【问题讨论】:
-
@pytest.mark.usefixtures("elastic")? -
对于模拟弹性搜索,请查看例如
elasticmock -
感谢@hoefling 啊,我认为
usefixtures装饰器非常适合第二种情况,而不是标记。但是我如何在默认情况下阻止对 ES 的调用(如没有应用标记/夹具时)? -
我想我现在明白你的意思了,很快就会添加答案。