Skip to content

Documented mechanism for calling black from Python code #425

@simonw

Description

@simonw

I tried to write a unit test that uses "black --check" to confirm that the other code in the repository is black-approved.

I couldn't see an easy way to do this by importing black directly, so instead I used the click.CliRunner class to programatically execute it using CLI arguments. Here's my implementation of that:

import black
from click.testing import CliRunner
from pathlib import Path

code_root = Path(__file__).parent.parent


def test_black():
    runner = CliRunner()
    result = runner.invoke(
        black.main,
        [str(code_root / "tests"), str(code_root / "sqlite_utils"), "--check"],
    )
    assert result.exit_code == 0, result.output

This works! Or rather, it works under Python 3.6. Python 3.7 in Travis is giving me this surprising result:

__________________________________ test_black __________________________________
    def test_black():
        runner = CliRunner()
        result = runner.invoke(
            black.main,
            [str(code_root / "tests"), str(code_root / "sqlite_utils"), "--check"],
        )
>       assert result.exit_code == 0, result.output
E       AssertionError: 
E       assert -1 == 0
E        +  where -1 = <Result KeyError(<Task finished coro=<BaseEventLoop.run_in_executor() done, defined at /opt/python/3.7-dev/lib/python3.7/asyncio/base_events.py:653> result=False>)>.exit_code

I'm still trying to figure out what went wrong there.

At any rate though: it would be really useful if there was an easy, documented mechanism for programatically invoking black.

Metadata

Metadata

Assignees

No one assigned

    Labels

    T: bugSomething isn't workingT: documentationImprovements to the docs (e.g. new topic, correction, etc)T: user supportOP looking for assistance or answers to a question

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions