How to Mock isort Output to Test Import Sorting in Python
Uses isort with check mode and a unittest mock to verify whether a Python source string has correctly sorted imports.
pip install isort
Python code
21 linesimport isort
from unittest.mock import patch
code = """
import os
import sys
import json
import pathlib
"""
def check_imports_sorted(code_str):
with patch("isort.api.output") as mock_output:
isort.code(code_str, check=True, show_diff=True)
return mock_output.called
if __name__ == "__main__":
sorted_code = "import json\nimport os\nimport pathlib\nimport sys\n"
unsorted_code = "import os\nimport sys\nimport json\nimport pathlib\n"
print(f"Sorted code detected correctly: {check_imports_sorted(sorted_code)}")
print(f"Unsorted code detected correctly: {check_imports_sorted(unsorted_code)}")
Output
Sorted code detected correctly: False
Unsorted code detected correctly: True
How it works
The isort.code function with check=True returns a boolean indicating whether the imports are already sorted; it does not raise an error. When show_diff=True, isort prints the diff to stdout, which we mock with patch("isort.api.output") to capture that output call. The mock's called attribute becomes True when isort tries to write a diff, meaning the imports are unsorted. This pattern lets you assert the sorting status without actually printing the diff.
Common mistakes
- Mocking the wrong path (e.g., 'isort.output' instead of 'isort.api.output')
- Forgetting that check=True returns a boolean and does not raise exceptions
- Not using show_diff=True, which is required for the output call to happen
Variations
- Use pytest's monkeypatch fixture to replace isort.api.output in a test
- Directly check the boolean return of isort.code without mocking output
Real-world use cases
- Unit testing your own linting wrapper that calls isort.check_code
- Validating import order in CI scripts without polluting logs with diffs
- Building a pre-commit hook that silently verifies sorted imports
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.