Skip to content

Commit

Permalink
Add test to cover when unable to replace magics (#2471)
Browse files Browse the repository at this point in the history
Another follow-up from #2357, adding a test for uncovered code.
  • Loading branch information
MarcoGorelli committed Sep 25, 2021
1 parent 1af5331 commit 39b55f7
Show file tree
Hide file tree
Showing 2 changed files with 13 additions and 3 deletions.
7 changes: 4 additions & 3 deletions src/black/handle_ipynb_magics.py
Expand Up @@ -53,6 +53,7 @@
"%%writefile",
)
)
TOKEN_HEX = secrets.token_hex


@dataclasses.dataclass(frozen=True)
Expand Down Expand Up @@ -188,10 +189,10 @@ def get_token(src: str, magic: str) -> str:
"""
assert magic
nbytes = max(len(magic) // 2 - 1, 1)
token = secrets.token_hex(nbytes)
token = TOKEN_HEX(nbytes)
counter = 0
while token in src: # pragma: nocover
token = secrets.token_hex(nbytes)
while token in src:
token = TOKEN_HEX(nbytes)
counter += 1
if counter > 100:
raise AssertionError(
Expand Down
9 changes: 9 additions & 0 deletions tests/test_ipynb.py
Expand Up @@ -453,3 +453,12 @@ def test_ipynb_and_pyi_flags() -> None:
assert isinstance(result.exception, SystemExit)
expected = "Cannot pass both `pyi` and `ipynb` flags!\n"
assert result.output == expected


def test_unable_to_replace_magics(monkeypatch: MonkeyPatch) -> None:
src = "%%time\na = 'foo'"
monkeypatch.setattr("black.handle_ipynb_magics.TOKEN_HEX", lambda _: "foo")
with pytest.raises(
AssertionError, match="Black was not able to replace IPython magic"
):
format_cell(src, fast=True, mode=JUPYTER_MODE)

0 comments on commit 39b55f7

Please sign in to comment.