From 39b55f787cff41ef9726b256cfdbedefe6d5c716 Mon Sep 17 00:00:00 2001 From: Marco Edward Gorelli Date: Sat, 25 Sep 2021 20:46:36 +0100 Subject: [PATCH] Add test to cover when unable to replace magics (#2471) Another follow-up from #2357, adding a test for uncovered code. --- src/black/handle_ipynb_magics.py | 7 ++++--- tests/test_ipynb.py | 9 +++++++++ 2 files changed, 13 insertions(+), 3 deletions(-) diff --git a/src/black/handle_ipynb_magics.py b/src/black/handle_ipynb_magics.py index b18f862..63c8aaf 100644 --- a/src/black/handle_ipynb_magics.py +++ b/src/black/handle_ipynb_magics.py @@ -53,6 +53,7 @@ NON_PYTHON_CELL_MAGICS = frozenset( "%%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 038155e..12f176c 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) -- 2.39.5