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.

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

Requires third-party packages — install first
pip install isort

Python code

21 lines
Python 3.9+
import 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

stdout
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

  1. Use pytest's monkeypatch fixture to replace isort.api.output in a test
  2. 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

Run locally

This sample needs third-party packages, so it cannot run in the browser IDE. Copy the code above, install the packages shown at the top, then run it in your own Python environment.

More from Modern tooling

Related tutorials and quizzes for this topic.