In the __init__.py
-file of my project I have the following code, for retrieving the current version of the program from the pyproject.toml
-file:
from typing import Any
from importlib import metadata
try:
import tomllib
with open("pyproject.toml", "rb") as project_file:
pyproject: dict[str, Any] = tomllib.load(project_file)
__version__ = pyproject["tool"]["poetry"]["version"]
except Exception as _:
__version__: str = metadata.version(__package__ or __name__)
This code works fine on Python 3.11 and newer. On older versions, however, tomllib
does not exist, and therefore the exception should be raised (and the version will be determined by using metadata
)
When testing on Python 3.11 with pytest
, is there any way of designing a test to check if that approach of determining the version works both with and without tomllib
, without having to create a second venv without tomllib
? I.e. how can I artificially generate the exception, such that I can test both branches without having to switch to different versions?
You can monkeypatch sys.modules
, so tomllib
is not there (see Python testing: Simulate ImportError)
Here is a curated example:
import sys
def func():
try:
import tomllib
return 1
except ImportError:
return 0
def test_with_tomllib():
assert func() == 1
def test_without_tomllib(monkeypatch):
monkeypatch.setitem(sys.modules, 'tomllib', None)
assert func() == 0