如果我的库有一个contrib
额外的依赖项(比如requests
),我希望用户必须安装才能访问 CLI API,但是我在 CI 中的测试期间安装了额外的 contrib 如何使用pytest
'sMonkeyPatch
删除测试期间的依赖关系以确保我的检测是正确的?
例如,如果contrib
额外安装requests
,那么我希望用户必须这样做
$ python -m pip install mylib[contrib]
然后能够在命令行拥有一个看起来像的 CLI API
$ mylib contrib myfunction
wheremyfunction
使用requests
依赖
# mylib/src/mylib/cli/contrib.py
import click
try:
import requests
except ModuleNotFoundError:
pass # should probably warn though, but this is just an example
# ...
@click.group(name="contrib")
def cli():
"""
Contrib experimental operations.
"""
@cli.command()
@click.argument("example", default="-")
def myfunction(example):
requests.get(example)
# ...
我如何在我的测试中模拟或猴子补丁, 以便我可以确保用户会正确地收到警告以及如果他们只是这样做requests
pytest
ModuleNotFoundError
$ python -m pip install mylib
$ mylib contrib myfunction
? 在阅读了有关 pytest 标签的其他一些问题后,我仍然认为我不明白如何做到这一点,所以我在这里问。