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.

Easy Python 3.9+ Aug 9, 2026 Modern tooling 14 views 0 copies

Python code

16 lines
Python 3.9+
```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

stdout
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

  1. Use `pytest-mock`'s `mocker.patch` for a simpler API in pytest tests.
  2. 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

Run this sample

Open the browser IDE to tweak the example and see results without installing anything.

Open editor

More from Modern tooling

Related tutorials and quizzes for this topic.