pytest-isort
pytest-isort is a pytest plugin that integrates isort's import ordering and formatting checks directly into the pytest test suite. It ensures that all Python files discoverable by pytest adhere to isort's configured rules, failing the test run if any incorrectly sorted imports are found. The current version is 4.0.0, released in February 2024, with active maintenance and updates to support newer Python and pytest versions.
Common errors
-
_pytest.runner.Skipped: pytest-isort requires pytest >= 7.
cause Your installed `pytest` version is too old for `pytest-isort` v4.0.0.fixUpgrade `pytest` to version 7 or newer: `pip install -U pytest` -
ModuleNotFoundError: No module named 'isort'
cause The `isort` library, a core dependency, is not installed or not available in your Python environment.fixInstall `isort`: `pip install isort` -
Imports are incorrectly sorted and/or formatted. Please run `isort` to fix this.
cause One or more Python files being checked by `pytest-isort` have imports that do not conform to your project's `isort` configuration.fixManually sort the imports or run `isort .` (or `isort --profile black .` if using black) in your project root to automatically fix all files. -
TypeError: argument of type 'NoneType' is not iterable
cause This can sometimes occur if `isort` is installed but an older, incompatible version (e.g., < 5.0) is present, leading to internal errors when `pytest-isort` tries to use it.fixEnsure `isort` is upgraded to version 5.x or newer: `pip install -U isort`
Warnings
- breaking Version 4.0.0 drops support for older Python and pytest versions. Python 3.8+ and pytest 7+ are now required. It also explicitly requires isort 5.x or newer.
- gotcha `pytest-isort` respects your project's `isort` configuration (e.g., `pyproject.toml`, `.isort.cfg`, `.editorconfig`). If your `isort` configuration differs from default expectations, `pytest-isort` will follow your configuration, potentially leading to unexpected pass/fail results.
- gotcha `pytest-isort` only checks files that are discovered and collected by `pytest` as part of its test run. It does not automatically check all Python files in your project (e.g., application code not under a `test_` prefix or configured for collection).
Install
-
pip install pytest-isort
Quickstart
import os
# test_imports.py
import os
import sys
from collections import defaultdict
def test_correct_imports():
# This test will pass isort checks if imports are sorted correctly
assert True
def test_bad_imports():
# This test (or file content) will cause pytest-isort to fail
# if imports are not sorted.
x = 1 # Added to avoid 'Empty file' issue with isort check itself
assert True
# To run this, save it as `test_imports.py` and run `pytest` in the same directory.
# If the imports within the file are not sorted according to isort rules,
# pytest-isort will report a failure.