madduck's git repository

Every one of the projects in this repository is available at the canonical URL git://git.madduck.net/madduck/pub/<projectpath> — see each project's metadata for the exact URL.

All patches and comments are welcome. Please squash your changes to logical commits before using git-format-patch and git-send-email to patches@git.madduck.net. If you'd read over the Git project's submission guidelines and adhered to them, I'd be especially grateful.

SSH access, as well as push access can be individually arranged.

If you use my repositories frequently, consider adding the following snippet to ~/.gitconfig and using the third clone URL listed for each project:

[url "git://git.madduck.net/madduck/"]
  insteadOf = madduck:

Add test to cover when unable to replace magics (#2471)
authorMarco Edward Gorelli <marcogorelli@protonmail.com>
Sat, 25 Sep 2021 19:46:36 +0000 (20:46 +0100)
committerGitHub <noreply@github.com>
Sat, 25 Sep 2021 19:46:36 +0000 (15:46 -0400)
Another follow-up from #2357, adding a test for uncovered code.

src/black/handle_ipynb_magics.py
tests/test_ipynb.py

index b18f8629136e2af1713a7f2fa72c4be50ea53935..63c8aafe35b70e4d16b7d59f349feeb6f392601a 100644 (file)
@@ -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(
index 038155e9270e25ec98d3cf35b25329bea3c93eb6..12f176c9341f5b91a7b85d57da905401ab96abcb 100644 (file)
@@ -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)