diff --git a/src/black/handle_ipynb_magics.py b/src/black/handle_ipynb_magics.py index b18f8629136..63c8aafe35b 100644 --- a/src/black/handle_ipynb_magics.py +++ b/src/black/handle_ipynb_magics.py @@ -53,6 +53,7 @@ "%%writefile", ) ) +TOKEN_HEX = secrets.token_hex @dataclasses.dataclass(frozen=True) @@ -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( diff --git a/tests/test_ipynb.py b/tests/test_ipynb.py index 038155e9270..12f176c9341 100644 --- a/tests/test_ipynb.py +++ b/tests/test_ipynb.py @@ -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)