If my library has a contrib
extra that has dependencies in it (say requests
) that I want users to have to install to have access to a CLI API, but I install the contrib extra during my tests in CI how do I use pytest
's MonkeyPatch
to remove the dependencies during tests to ensure my detection is correct?
For example, if the contrib
extra will additionally install requests
and so I want users to have to do
$ python -m pip install mylib[contrib]
to then be able to at the command line have a CLI API that would look like
$ mylib contrib myfunction
where myfunction
uses the requests
dependency
# 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)
# ...
How do I mock or monkeypatch out requests
in my pytest
tests so that I can make sure that a user would properly get a warning along with the ModuleNotFoundError
if they just do
$ python -m pip install mylib
$ mylib contrib myfunction
? After reading some other questions on the pytest tag I still don't think I understand how to do this, so I'm asking here.