我有一个 Python 包,其中包含 pyproject.toml 中定义的可选依赖项。我想运行 pytest,同时确保仅在安装了相关可选依赖项时才执行特定测试。否则,应该跳过这些测试。
例如,在 pyproject.toml 中给出这样的可选依赖项:
[project.optional-dependencies]
extra_name = ["package_name>=1.0"]
我想使用这样的装饰器:
@skip_if_optionals_are_not_installed("extra_name")
def test_something():
# Test logic here
pass
我目前的实现思路是这样的:
import toml
from pathlib import Path
from functools import wraps
def __get_optional_requirements(module: str):
with Path("pyproject.toml").open() as file:
data = toml.load(file)
optional_requirements = data.get("project", {}).get("optional-dependencies", {})
return optional_requirements.get(module, [])
def requires_pip_optional_or_skip_test(optional_module_name):
def decorator(func):
@wraps(func)
def wrapper(*args, **kwargs):
requirements = __get_optional_requirements(optional_module_name)
for requirement in requirements:
compare_versions(requirement) # Some function to check if the dependency is installed
return func(*args, **kwargs)
return wrapper
return decorator
感觉很麻烦,有待改进。
@pytest.importorskip("extra_name")
def test_something():
# Test logic here
pass
extra_name = pytest.importorskip("extra_name")