Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

add test to cover when unable to replace magics #2471

Merged
merged 1 commit into from Sep 25, 2021
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
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)