pytest-black Plugin
pytest-black is a pytest plugin that enables code format checking using the 'black' formatter directly within the pytest test suite. It integrates `black` as a linter, failing tests if code is not formatted according to `black`'s standards. The current version is 0.6.0, with releases typically occurring on an annual to bi-annual cadence.
Common errors
-
pytest: error: unrecognized arguments: --black
cause The pytest-black plugin is not installed or not correctly recognized by pytest.fixEnsure `pytest-black` is installed in the active Python environment: `pip install pytest-black`. -
ModuleNotFoundError: No module named 'black'
cause The 'black' formatter package, which pytest-black relies on, is not installed.fixInstall the 'black' formatter: `pip install black`. -
blackd cannot be used as an executable. Please install blackd to use it.
cause pytest-black's default behavior tries to use `blackd` (the black daemon) for faster checks if available, but it's not installed, and the fallback to `black` isn't working as expected.fixInstall `blackd` (`pip install blackd`) or explicitly configure pytest-black to use the `black` executable by setting `--black-executable black`.
Warnings
- gotcha pytest-black checks formatting but does NOT automatically reformat code. It merely reports formatting violations.
- gotcha The plugin is only active when the `--black` flag is explicitly passed to pytest. Running `pytest` without this flag will not perform any black checks.
- gotcha Ensure that the `black` package itself is installed in the same environment where `pytest` and `pytest-black` are running. `pytest-black` depends on `black` being available.
Install
-
pip install pytest-black
Imports
- pytest_black plugin activation
Install 'pytest-black' and run 'pytest --black'
Quickstart
import pytest # Create a test file (e.g., test_example.py) # with some unformatted code: # def test_hello(): # print( 'Hello, World!') # assert True # To run: # 1. Save the above unformatted code in test_example.py # 2. Run in terminal: pip install pytest-black black pytest # 3. Run in terminal: pytest --black # Expected output for unformatted code would include black errors. # If code is formatted, it would pass without black errors.