How to Mock setuptools_scm get_version in Python
This code demonstrates how to mock setuptools_scm.get_version in Python using unittest.mock.patch to test version retrieval logic without installing or relying on the actual package.
Python code
16 lines```python
from unittest.mock import patch
def get_version_from_scm():
try:
import setuptools_scm
return setuptools_scm.get_version()
except (ImportError, LookupError):
return None
if __name__ == "__main__":
with patch("setuptools_scm.get_version", return_value="1.2.3"):
print(get_version_from_scm())
with patch("importlib.import_module", side_effect=ImportError("no setuptools_scm")):
print(get_version_from_scm())
Output
1.2.3
None
How it works
The patch context manager replaces the target attribute with a mock object for the duration of the with block. In the first case, setuptools_scm.get_version is mocked to return a fixed version string, so get_version_from_scm returns "1.2.3". In the second case, patching importlib.import_module with a side effect that raises ImportError simulates the absence of the setuptools_scm package, causing the function to catch the exception and return None. This pattern isolates code from external dependencies during testing, ensuring reliable unit tests.
Common mistakes
- Patching the function after importing the module instead of patching the target reference.
- Forgetting to include the `side_effect` argument to simulate an exception, leading to unexpected behavior.
- Mocking `setuptools_scm.get_version` but not accounting for the `LookupError` path when the package is present but fails to determine a version.
Variations
- Use `pytest-mock`'s `mocker.patch` for a simpler API in pytest tests.
- Patch the module-level name `sys.modules` to prevent import entirely instead of mocking `import_module`.
Real-world use cases
- Unit testing a command-line tool that retrieves its version via setuptools_scm, ensuring it works without a real repository.
- Validating fallback logic in a package installer that handles missing version metadata gracefully.
- Simulating an environment where setuptools_scm is not installed to test error handling in a CI pipeline.
Sponsored
More from Modern tooling
- Build a Recipe Runner Mock in Python easy
- Build a Textual TUI App Skeleton in Python easy
- Configure ruff linter rules in pyproject.toml with Python easy
- Data Conversion Helper Functions in Python easy
- How to Bind and Mock structlog Context in Python medium
- How to Build a Chainable Filter Helper in Python easy
Keep learning
Related tutorials and quizzes for this topic.