Debian Codegraph @

tests/test_ipynb.py

raw
1 import contextlib
2 import pathlib
3 import re
4 from contextlib import AbstractContextManager
5 from contextlib import ExitStack as does_not_raise
6 from dataclasses import replace
7
8 import pytest
9 from click.testing import CliRunner
10 from pytest import MonkeyPatch
11
12 from black import (
13 Mode,
14 NothingChanged,
15 format_cell,
16 format_file_contents,
17 format_file_in_place,
18 main,
19 )
20 from black.handle_ipynb_magics import (
21 Replacement,
22 create_token,
23 jupyter_dependencies_are_installed,
24 unmask_cell,
25 )
26 from tests.util import DATA_DIR, get_case_path, read_jupyter_notebook
27
28 with contextlib.suppress(ModuleNotFoundError):
29 import IPython
30 pytestmark = pytest.mark.jupyter
31 pytest.importorskip("IPython", reason="IPython is an optional dependency")
32 pytest.importorskip("tokenize_rt", reason="tokenize-rt is an optional dependency")
33
34 JUPYTER_MODE = Mode(is_ipynb=True)
35
36 EMPTY_CONFIG = DATA_DIR / "empty_pyproject.toml"
37
38 runner = CliRunner()
39
40
41 def test_noop() -> None:
42 src = 'foo = "a"'
43 with pytest.raises(NothingChanged):
44 format_cell(src, fast=True, mode=JUPYTER_MODE)
45
46
47 @pytest.mark.parametrize("n_chars", [1, 2, 3, 4, 5, 17])
48 def test_create_token_uses_requested_length(n_chars: int) -> None:
49 assert len(create_token(n_chars)) == n_chars
50
51
52 def test_unmask_cell_raises_when_token_is_not_unique() -> None:
53 replacement = Replacement(mask='b"dead"', src="%time")
54 with pytest.raises(NothingChanged):
55 unmask_cell(f"{replacement.mask}\nvalue = {replacement.mask}", [replacement])
56
57
58 @pytest.mark.parametrize("fast", [True, False])
59 def test_trailing_semicolon(fast: bool) -> None:
60 src = 'foo = "a" ;'
61 result = format_cell(src, fast=fast, mode=JUPYTER_MODE)
62 expected = 'foo = "a";'
63 assert result == expected
64
65
66 def test_trailing_semicolon_with_comment() -> None:
67 src = 'foo = "a" ; # bar'
68 result = format_cell(src, fast=True, mode=JUPYTER_MODE)
69 expected = 'foo = "a"; # bar'
70 assert result == expected
71
72
73 def test_trailing_semicolon_with_comment_on_next_line() -> None:
74 src = "import black;\n\n# this is a comment"
75 with pytest.raises(NothingChanged):
76 format_cell(src, fast=True, mode=JUPYTER_MODE)
77
78
79 def test_trailing_semicolon_indented() -> None:
80 src = "with foo:\n plot_bar();"
81 with pytest.raises(NothingChanged):
82 format_cell(src, fast=True, mode=JUPYTER_MODE)
83
84
85 def test_trailing_semicolon_noop() -> None:
86 src = 'foo = "a";'
87 with pytest.raises(NothingChanged):
88 format_cell(src, fast=True, mode=JUPYTER_MODE)
89
90
91 @pytest.mark.parametrize(
92 "mode",
93 [
94 pytest.param(JUPYTER_MODE, id="default mode"),
95 pytest.param(
96 replace(JUPYTER_MODE, python_cell_magics={"cust1", "cust2"}),
97 id="custom cell magics mode",
98 ),
99 ],
100 )
101 def test_cell_magic(mode: Mode) -> None:
102 src = "%%time\nfoo =bar"
103 result = format_cell(src, fast=True, mode=mode)
104 expected = "%%time\nfoo = bar"
105 assert result == expected
106
107
108 def test_cell_magic_noop() -> None:
109 src = "%%time\n2 + 2"
110 with pytest.raises(NothingChanged):
111 format_cell(src, fast=True, mode=JUPYTER_MODE)
112
113
114 @pytest.mark.parametrize(
115 "mode",
116 [
117 pytest.param(JUPYTER_MODE, id="default mode"),
118 pytest.param(
119 replace(JUPYTER_MODE, python_cell_magics={"cust1", "cust2"}),
120 id="custom cell magics mode",
121 ),
122 ],
123 )
124 @pytest.mark.parametrize(
125 "src, expected",
126 (
127 pytest.param("ls =!ls", "ls = !ls", id="System assignment"),
128 pytest.param("!ls\n'foo'", '!ls\n"foo"', id="System call"),
129 pytest.param("!!ls\n'foo'", '!!ls\n"foo"', id="Other system call"),
130 pytest.param("?str\n'foo'", '?str\n"foo"', id="Help"),
131 pytest.param("??str\n'foo'", '??str\n"foo"', id="Other help"),
132 pytest.param(
133 "%matplotlib inline\n'foo'",
134 '%matplotlib inline\n"foo"',
135 id="Line magic with argument",
136 ),
137 pytest.param("%time\n'foo'", '%time\n"foo"', id="Line magic without argument"),
138 pytest.param(
139 "env = %env var", "env = %env var", id="Assignment to environment variable"
140 ),
141 pytest.param("env = %env", "env = %env", id="Assignment to magic"),
142 ),
143 )
144 def test_magic(src: str, expected: str, mode: Mode) -> None:
145 result = format_cell(src, fast=True, mode=mode)
146 assert result == expected
147
148
149 @pytest.mark.parametrize(
150 "src",
151 (
152 "%%bash\n2+2",
153 "%%html --isolated\n2+2",
154 "%%writefile e.txt\n meh\n meh",
155 ),
156 )
157 def test_non_python_magics(src: str) -> None:
158 with pytest.raises(NothingChanged):
159 format_cell(src, fast=True, mode=JUPYTER_MODE)
160
161
162 @pytest.mark.skipif(
163 IPython.version_info < (8, 3),
164 reason="Change in how TransformerManager transforms this input",
165 )
166 def test_set_input() -> None:
167 src = "a = b??"
168 expected = "??b"
169 result = format_cell(src, fast=True, mode=JUPYTER_MODE)
170 assert result == expected
171
172
173 def test_input_already_contains_transformed_magic() -> None:
174 src = '%time foo()\nget_ipython().run_cell_magic("time", "", "foo()\\n")'
175 with pytest.raises(NothingChanged):
176 format_cell(src, fast=True, mode=JUPYTER_MODE)
177
178
179 def test_magic_noop() -> None:
180 src = "ls = !ls"
181 with pytest.raises(NothingChanged):
182 format_cell(src, fast=True, mode=JUPYTER_MODE)
183
184
185 def test_cell_magic_with_magic() -> None:
186 src = "%%timeit -n1\nls =!ls"
187 result = format_cell(src, fast=True, mode=JUPYTER_MODE)
188 expected = "%%timeit -n1\nls = !ls"
189 assert result == expected
190
191
192 @pytest.mark.parametrize(
193 "src, expected",
194 (
195 ("\n\n\n%time \n\n", "%time"),
196 (" \n\t\n%%timeit -n4 \t \nx=2 \n\r\n", "%%timeit -n4\nx = 2"),
197 (
198 " \t\n\n%%capture \nx=2 \n%config \n\n%env\n\t \n \n\n",
199 "%%capture\nx = 2\n%config\n\n%env",
200 ),
201 ),
202 )
203 def test_cell_magic_with_empty_lines(src: str, expected: str) -> None:
204 result = format_cell(src, fast=True, mode=JUPYTER_MODE)
205 assert result == expected
206
207
208 @pytest.mark.parametrize(
209 "mode, expected_output, expectation",
210 [
211 pytest.param(
212 JUPYTER_MODE,
213 "%%custom_python_magic -n1 -n2\nx=2",
214 pytest.raises(NothingChanged),
215 id="No change when cell magic not registered",
216 ),
217 pytest.param(
218 replace(JUPYTER_MODE, python_cell_magics={"cust1", "cust2"}),
219 "%%custom_python_magic -n1 -n2\nx=2",
220 pytest.raises(NothingChanged),
221 id="No change when other cell magics registered",
222 ),
223 pytest.param(
224 replace(JUPYTER_MODE, python_cell_magics={"custom_python_magic", "cust1"}),
225 "%%custom_python_magic -n1 -n2\nx = 2",
226 does_not_raise(),
227 id="Correctly change when cell magic registered",
228 ),
229 ],
230 )
231 def test_cell_magic_with_custom_python_magic(
232 mode: Mode, expected_output: str, expectation: AbstractContextManager[object]
233 ) -> None:
234 with expectation:
235 result = format_cell(
236 "%%custom_python_magic -n1 -n2\nx=2",
237 fast=True,
238 mode=mode,
239 )
240 assert result == expected_output
241
242
243 @pytest.mark.parametrize(
244 "src",
245 (
246 " %%custom_magic \nx=2",
247 "\n\n%%custom_magic\nx=2",
248 "# comment\n%%custom_magic\nx=2",
249 "\n \n # comment with %%time\n\t\n %%custom_magic # comment \nx=2",
250 ),
251 )
252 def test_cell_magic_with_custom_python_magic_after_spaces_and_comments_noop(
253 src: str,
254 ) -> None:
255 with pytest.raises(NothingChanged):
256 format_cell(src, fast=True, mode=JUPYTER_MODE)
257
258
259 def test_cell_magic_nested() -> None:
260 src = "%%time\n%%time\n2+2"
261 result = format_cell(src, fast=True, mode=JUPYTER_MODE)
262 expected = "%%time\n%%time\n2 + 2"
263 assert result == expected
264
265
266 def test_cell_magic_with_magic_noop() -> None:
267 src = "%%t -n1\nls = !ls"
268 with pytest.raises(NothingChanged):
269 format_cell(src, fast=True, mode=JUPYTER_MODE)
270
271
272 def test_automagic() -> None:
273 src = "pip install black"
274 with pytest.raises(NothingChanged):
275 format_cell(src, fast=True, mode=JUPYTER_MODE)
276
277
278 def test_multiline_magic() -> None:
279 src = "%time 1 + \\\n2"
280 with pytest.raises(NothingChanged):
281 format_cell(src, fast=True, mode=JUPYTER_MODE)
282
283
284 def test_multiline_no_magic() -> None:
285 src = "1 + \\\n2"
286 result = format_cell(src, fast=True, mode=JUPYTER_MODE)
287 expected = "1 + 2"
288 assert result == expected
289
290
291 def test_cell_magic_with_invalid_body() -> None:
292 src = "%%time\nif True"
293 with pytest.raises(NothingChanged):
294 format_cell(src, fast=True, mode=JUPYTER_MODE)
295
296
297 def test_empty_cell() -> None:
298 src = ""
299 with pytest.raises(NothingChanged):
300 format_cell(src, fast=True, mode=JUPYTER_MODE)
301
302
303 def test_entire_notebook_empty_metadata() -> None:
304 content = read_jupyter_notebook("jupyter", "notebook_empty_metadata")
305 result = format_file_contents(content, fast=True, mode=JUPYTER_MODE)
306 expected = (
307 "{\n"
308 ' "cells": [\n'
309 " {\n"
310 ' "cell_type": "code",\n'
311 ' "execution_count": null,\n'
312 ' "metadata": {\n'
313 ' "tags": []\n'
314 " },\n"
315 ' "outputs": [],\n'
316 ' "source": [\n'
317 ' "%%time\\n",\n'
318 ' "\\n",\n'
319 ' "print(\\"foo\\")"\n'
320 " ]\n"
321 " },\n"
322 " {\n"
323 ' "cell_type": "code",\n'
324 ' "execution_count": null,\n'
325 ' "metadata": {},\n'
326 ' "outputs": [],\n'
327 ' "source": []\n'
328 " }\n"
329 " ],\n"
330 ' "metadata": {},\n'
331 ' "nbformat": 4,\n'
332 ' "nbformat_minor": 4\n'
333 "}\n"
334 )
335 assert result == expected
336
337
338 def test_entire_notebook_trailing_newline() -> None:
339 content = read_jupyter_notebook("jupyter", "notebook_trailing_newline")
340 result = format_file_contents(content, fast=True, mode=JUPYTER_MODE)
341 expected = (
342 "{\n"
343 ' "cells": [\n'
344 " {\n"
345 ' "cell_type": "code",\n'
346 ' "execution_count": null,\n'
347 ' "metadata": {\n'
348 ' "tags": []\n'
349 " },\n"
350 ' "outputs": [],\n'
351 ' "source": [\n'
352 ' "%%time\\n",\n'
353 ' "\\n",\n'
354 ' "print(\\"foo\\")"\n'
355 " ]\n"
356 " },\n"
357 " {\n"
358 ' "cell_type": "code",\n'
359 ' "execution_count": null,\n'
360 ' "metadata": {},\n'
361 ' "outputs": [],\n'
362 ' "source": []\n'
363 " }\n"
364 " ],\n"
365 ' "metadata": {\n'
366 ' "interpreter": {\n'
367 ' "hash": "e758f3098b5b55f4d87fe30bbdc1367f20f246b483f96267ee70e6c40cb185d8"\n' # noqa:B950
368 " },\n"
369 ' "kernelspec": {\n'
370 ' "display_name": "Python 3.8.10 64-bit (\'black\': venv)",\n'
371 ' "name": "python3"\n'
372 " },\n"
373 ' "language_info": {\n'
374 ' "name": "python",\n'
375 ' "version": ""\n'
376 " }\n"
377 " },\n"
378 ' "nbformat": 4,\n'
379 ' "nbformat_minor": 4\n'
380 "}\n"
381 )
382 assert result == expected
383
384
385 def test_entire_notebook_no_trailing_newline() -> None:
386 content = read_jupyter_notebook("jupyter", "notebook_no_trailing_newline")
387 result = format_file_contents(content, fast=True, mode=JUPYTER_MODE)
388 expected = (
389 "{\n"
390 ' "cells": [\n'
391 " {\n"
392 ' "cell_type": "code",\n'
393 ' "execution_count": null,\n'
394 ' "metadata": {\n'
395 ' "tags": []\n'
396 " },\n"
397 ' "outputs": [],\n'
398 ' "source": [\n'
399 ' "%%time\\n",\n'
400 ' "\\n",\n'
401 ' "print(\\"foo\\")"\n'
402 " ]\n"
403 " },\n"
404 " {\n"
405 ' "cell_type": "code",\n'
406 ' "execution_count": null,\n'
407 ' "metadata": {},\n'
408 ' "outputs": [],\n'
409 ' "source": []\n'
410 " }\n"
411 " ],\n"
412 ' "metadata": {\n'
413 ' "interpreter": {\n'
414 ' "hash": "e758f3098b5b55f4d87fe30bbdc1367f20f246b483f96267ee70e6c40cb185d8"\n' # noqa: B950
415 " },\n"
416 ' "kernelspec": {\n'
417 ' "display_name": "Python 3.8.10 64-bit (\'black\': venv)",\n'
418 ' "name": "python3"\n'
419 " },\n"
420 ' "language_info": {\n'
421 ' "name": "python",\n'
422 ' "version": ""\n'
423 " }\n"
424 " },\n"
425 ' "nbformat": 4,\n'
426 ' "nbformat_minor": 4\n'
427 "}"
428 )
429 assert result == expected
430
431
432 def test_entire_notebook_without_changes() -> None:
433 content = read_jupyter_notebook("jupyter", "notebook_without_changes")
434 with pytest.raises(NothingChanged):
435 format_file_contents(content, fast=True, mode=JUPYTER_MODE)
436
437
438 def test_non_python_notebook() -> None:
439 content = read_jupyter_notebook("jupyter", "non_python_notebook")
440
441 with pytest.raises(NothingChanged):
442 format_file_contents(content, fast=True, mode=JUPYTER_MODE)
443
444
445 def test_empty_string() -> None:
446 with pytest.raises(NothingChanged):
447 format_file_contents("", fast=True, mode=JUPYTER_MODE)
448
449
450 def test_unparseable_notebook() -> None:
451 path = get_case_path("jupyter", "notebook_which_cant_be_parsed.ipynb")
452 msg = rf"File '{re.escape(str(path))}' cannot be parsed as valid Jupyter notebook\."
453 with pytest.raises(ValueError, match=msg):
454 format_file_in_place(path, fast=True, mode=JUPYTER_MODE)
455
456
457 def test_ipynb_diff_with_change() -> None:
458 result = runner.invoke(
459 main,
460 [
461 str(get_case_path("jupyter", "notebook_trailing_newline.ipynb")),
462 "--diff",
463 f"--config={EMPTY_CONFIG}",
464 ],
465 )
466 expected = "@@ -1,3 +1,3 @@\n %%time\n \n-print('foo')\n+print(\"foo\")\n"
467 assert expected in result.output
468
469
470 def test_ipynb_diff_with_no_change() -> None:
471 result = runner.invoke(
472 main,
473 [
474 str(get_case_path("jupyter", "notebook_without_changes.ipynb")),
475 "--diff",
476 f"--config={EMPTY_CONFIG}",
477 ],
478 )
479 expected = "1 file would be left unchanged."
480 assert expected in result.output
481
482
483 def test_cache_isnt_written_if_no_jupyter_deps_single(
484 monkeypatch: MonkeyPatch, tmp_path: pathlib.Path
485 ) -> None:
486 # Check that the cache isn't written to if Jupyter dependencies aren't installed.
487 jupyter_dependencies_are_installed.cache_clear()
488 nb = get_case_path("jupyter", "notebook_trailing_newline.ipynb")
489 tmp_nb = tmp_path / "notebook.ipynb"
490 tmp_nb.write_bytes(nb.read_bytes())
491 monkeypatch.setattr("black.jupyter_dependencies_are_installed", lambda warn: False)
492 result = runner.invoke(
493 main, [str(tmp_path / "notebook.ipynb"), f"--config={EMPTY_CONFIG}"]
494 )
495 assert "No Python files are present to be formatted. Nothing to do" in result.output
496 jupyter_dependencies_are_installed.cache_clear()
497 monkeypatch.setattr("black.jupyter_dependencies_are_installed", lambda warn: True)
498 result = runner.invoke(
499 main, [str(tmp_path / "notebook.ipynb"), f"--config={EMPTY_CONFIG}"]
500 )
501 assert "reformatted" in result.output
502
503
504 def test_cache_isnt_written_if_no_jupyter_deps_dir(
505 monkeypatch: MonkeyPatch, tmp_path: pathlib.Path
506 ) -> None:
507 # Check that the cache isn't written to if Jupyter dependencies aren't installed.
508 jupyter_dependencies_are_installed.cache_clear()
509 nb = get_case_path("jupyter", "notebook_trailing_newline.ipynb")
510 tmp_nb = tmp_path / "notebook.ipynb"
511 tmp_nb.write_bytes(nb.read_bytes())
512 monkeypatch.setattr(
513 "black.files.jupyter_dependencies_are_installed", lambda warn: False
514 )
515 result = runner.invoke(main, [str(tmp_path), f"--config={EMPTY_CONFIG}"])
516 assert "No Python files are present to be formatted. Nothing to do" in result.output
517 jupyter_dependencies_are_installed.cache_clear()
518 monkeypatch.setattr(
519 "black.files.jupyter_dependencies_are_installed", lambda warn: True
520 )
521 result = runner.invoke(main, [str(tmp_path), f"--config={EMPTY_CONFIG}"])
522 assert "reformatted" in result.output
523
524
525 def test_ipynb_flag(tmp_path: pathlib.Path) -> None:
526 nb = get_case_path("jupyter", "notebook_trailing_newline.ipynb")
527 tmp_nb = tmp_path / "notebook.a_file_extension_which_is_definitely_not_ipynb"
528 tmp_nb.write_bytes(nb.read_bytes())
529 result = runner.invoke(
530 main,
531 [
532 str(tmp_nb),
533 "--diff",
534 "--ipynb",
535 f"--config={EMPTY_CONFIG}",
536 ],
537 )
538 expected = "@@ -1,3 +1,3 @@\n %%time\n \n-print('foo')\n+print(\"foo\")\n"
539 assert expected in result.output
540
541
542 def test_ipynb_and_pyi_flags() -> None:
543 nb = get_case_path("jupyter", "notebook_trailing_newline.ipynb")
544 result = runner.invoke(
545 main,
546 [
547 str(nb),
548 "--pyi",
549 "--ipynb",
550 "--diff",
551 f"--config={EMPTY_CONFIG}",
552 ],
553 )
554 assert isinstance(result.exception, SystemExit)
555 expected = "Cannot pass both `pyi` and `ipynb` flags!\n"
556 assert result.output == expected
557
558
559 def test_unable_to_replace_magics(monkeypatch: MonkeyPatch) -> None:
560 src = '%%time\na = b"foo"'
561 monkeypatch.setattr("secrets.token_hex", lambda _: "foo")
562 with pytest.raises(
563 AssertionError, match="Black was not able to replace IPython magic"
564 ):
565 format_cell(src, fast=True, mode=JUPYTER_MODE)