Skip to content

Commit

Permalink
map blacken-docs (#676)
Browse files Browse the repository at this point in the history
* map blacken-docs

* add test

* add tests
  • Loading branch information
MarcoGorelli committed Nov 21, 2021
1 parent 5bef009 commit 0fc3679
Show file tree
Hide file tree
Showing 6 changed files with 126 additions and 10 deletions.
8 changes: 4 additions & 4 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@
</h1>

<h3 align="center">
Run isort, pyupgrade, mypy, pylint, flake8, mdformat, and more on Jupyter Notebooks
Run isort, pyupgrade, mypy, pylint, flake8, mdformat, black, blacken-docs, and more on Jupyter Notebooks
</h3>

<p align="center">
Expand Down Expand Up @@ -100,11 +100,11 @@ Rewriting my_notebook.ipynb
Format your markdown cells with [mdformat](https://mdformat.readthedocs.io/en/stable/index.html):

```console
$ nbqa mdformat tests/data/notebook_for_testing.ipynb --nbqa-md --nbqa-diff
$ nbqa mdformat my_notebook.ipynb --nbqa-md --nbqa-diff
Cell 2
------
--- tests/data/notebook_for_testing.ipynb
+++ tests/data/notebook_for_testing.ipynb
--- my_notebook.ipynb
+++ my_notebook.ipynb
@@ -1,2 +1 @@
-First level heading
-===
Expand Down
14 changes: 8 additions & 6 deletions nbqa/__main__.py
Original file line number Diff line number Diff line change
Expand Up @@ -54,6 +54,7 @@
False: replace_source.mutate,
}
SUFFIX = {False: ".py", True: ".md"}
COMMAND_TO_PYTHON_MODULE = {"blacken-docs": "blacken_docs"}


class TemporaryFile(NamedTuple):
Expand Down Expand Up @@ -258,8 +259,9 @@ def _run_command(
if command == "mypy" and "MYPY_FORCE_COLOR" not in my_env:
my_env["MYPY_FORCE_COLOR"] = "1"

python_module = COMMAND_TO_PYTHON_MODULE.get(command, command)
output = subprocess.run(
[sys.executable, "-m", command, *args, *cmd_args],
[sys.executable, "-m", python_module, *args, *cmd_args],
stderr=subprocess.PIPE,
stdout=subprocess.PIPE,
universal_newlines=True, # from Python3.7 this can be replaced with `text`
Expand Down Expand Up @@ -349,7 +351,6 @@ def _get_configs(cli_args: CLIArgs, project_root: Path) -> Configs:

# add default options
if cli_args.command == "isort":
# TypedDict key must be a string literal
config["addopts"] = (
*config["addopts"],
"--treat-comment-as-code",
Expand Down Expand Up @@ -663,14 +664,15 @@ def _check_command_is_installed(command: str) -> None:
UnsupportedPackageVersionError
If third-party tool is of an unsupported version.
"""
python_module = COMMAND_TO_PYTHON_MODULE.get(command, command)
try:
command_version = metadata.version(command) # type: ignore
command_version = metadata.version(python_module) # type: ignore
except metadata.PackageNotFoundError: # type: ignore
try:
import_module(command)
import_module(python_module)
except ImportError as exc:
if not os.path.isdir(command) and not os.path.isfile(
f"{os.path.join(*command.split('.'))}.py"
if not os.path.isdir(python_module) and not os.path.isfile(
f"{os.path.join(*python_module.split('.'))}.py"
): # pragma: nocover(py<37)
# I presume the lack of coverage in Python3.6 here is a bug, as all
# these branches are actually covered.
Expand Down
1 change: 1 addition & 0 deletions requirements-dev.txt
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
autoflake
autopep8
black
blacken-docs
coverage[toml]
flake8
isort>=5.4.2
Expand Down
9 changes: 9 additions & 0 deletions tests/data/notebook_for_testing.ipynb
Original file line number Diff line number Diff line change
Expand Up @@ -67,6 +67,15 @@
"hello(3) "
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"```python\n",
"2 +2\n",
"```"
]
},
{
"cell_type": "code",
"execution_count": null,
Expand Down
48 changes: 48 additions & 0 deletions tests/tools/test_blacken_docs.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
"""Check blacken-docs runs."""
import os
from typing import TYPE_CHECKING

from nbqa.__main__ import main

if TYPE_CHECKING:
from _pytest.capture import CaptureFixture


def test_blacken_docs(capsys: "CaptureFixture") -> None:
"""
Check blacken-docs.
Parameters
----------
capsys
Pytest fixture to capture stdout and stderr.
"""
path = os.path.join("tests", "data", "notebook_for_testing.ipynb")
main(["blacken-docs", path, "--nbqa-diff", "--nbqa-md"])
out, err = capsys.readouterr()
expected_out = (
"\x1b[1mCell 2\x1b[0m\n"
"------\n"
f"\x1b[1;37m--- {path}\n"
f"\x1b[0m\x1b[1;37m+++ {path}\n"
"\x1b[0m\x1b[36m@@ -1 +1 @@\n"
"\x1b[0m\x1b[31m-set(())\n"
"\x1b[0m\x1b[32m+set()\n"
"\x1b[0m\n"
"To apply these changes, remove the `--nbqa-diff` flag\n"
)
expected_out = (
"\x1b[1mCell 3\x1b[0m\n"
"------\n"
f"\x1b[1;37m--- {path}\n"
f"\x1b[0m\x1b[1;37m+++ {path}\n"
"\x1b[0m\x1b[36m@@ -1,3 +1,3 @@\n"
"\x1b[0m\x1b[31m-2 +2\n"
"\x1b[0m\x1b[32m+2 + 2\n"
"\x1b[0m\n"
f"{path}: Rewriting...\n"
"To apply these changes, remove the `--nbqa-diff` flag\n"
)
expected_err = ""
assert out == expected_out
assert err == expected_err
56 changes: 56 additions & 0 deletions tests/tools/test_mdformat.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,56 @@
"""Check mdformat works."""

import difflib
import os
from pathlib import Path
from typing import TYPE_CHECKING

from nbqa.__main__ import main

if TYPE_CHECKING:

from _pytest.capture import CaptureFixture


def test_mdformat(tmp_notebook_for_testing: Path) -> None:
"""
Check pyupgrade works. Should only reformat code cells.
Parameters
----------
tmp_notebook_for_testing
Temporary copy of :code:`tmp_notebook_for_testing.ipynb`.
"""
# check diff
with open(tmp_notebook_for_testing, encoding="utf-8") as handle:
before = handle.readlines()
path = os.path.join("tests", "data", "notebook_for_testing.ipynb")

main(["mdformat", os.path.abspath(path), "--nbqa-md"])
with open(tmp_notebook_for_testing, encoding="utf-8") as handle:
after = handle.readlines()

diff = difflib.unified_diff(before, after)
result = "".join(i for i in diff if any([i.startswith("+ "), i.startswith("- ")]))
expected = (
'- "First level heading\\n",\n- "==="\n+ "# First level heading"\n'
)
assert result == expected


def test_mdformat_works_with_empty_file(capsys: "CaptureFixture") -> None:
"""
Check mdformat works with empty notebook.
Parameters
----------
capsys
Pytest fixture to capture stdout and stderr.
"""
path = os.path.abspath(os.path.join("tests", "data", "footer.ipynb"))

main(["mdformat", path, "--nbqa-diff", "--nbqa-md"])

out, err = capsys.readouterr()
assert out == ""
assert err == ""

0 comments on commit 0fc3679

Please sign in to comment.