def test_pylint_works(capsys: "CaptureFixture") -> None: """ Check pylint works. Check all the warnings raised by pylint on the notebook. Parameters ---------- capsys Pytest fixture to capture stdout and stderr. """ # Pass one file with absolute path and the other one with relative path notebook1 = os.path.abspath( os.path.join("tests", "data", "notebook_for_testing.ipynb")) notebook2 = os.path.join("tests", "data", "notebook_with_indented_magics.ipynb") with pytest.raises(SystemExit): main(["pylint", notebook1, notebook2, "--disable=C0114"]) notebook1_expected_warnings = [ f"{str(notebook1)}:cell_2:19:8: C0303: Trailing whitespace (trailing-whitespace)", f"{str(notebook1)}:cell_1:1:0: W0611: Unused import os (unused-import)", f"{str(notebook1)}:cell_1:3:0: W0611: Unused import glob (unused-import)", f"{str(notebook1)}:cell_1:5:0: W0611: Unused import nbqa (unused-import)", f'{str(notebook1)}:cell_4:1:0: C0413: Import "from random import randint"' + " should be placed at the top of the module (wrong-import-position)", f'{str(notebook1)}:cell_5:1:0: C0413: Import "import pprint"' + " should be placed at the top of the module (wrong-import-position)", f'{str(notebook1)}:cell_5:2:0: C0413: Import "import sys"' + " should be placed at the top of the module (wrong-import-position)", f"{str(notebook1)}:cell_4:1:0: C0411: standard import" + ' "from random import randint"' + ' should be placed before "import nbqa" (wrong-import-order)', f"{str(notebook1)}:cell_5:1:0: C0411: standard import" + ' "import pprint"' + ' should be placed before "import nbqa" (wrong-import-order)', f"{str(notebook1)}:cell_5:2:0: C0411: standard import" + ' "import sys"' + ' should be placed before "import nbqa" (wrong-import-order)', ] notebook2_expected_warnings = [ f'{str(notebook2)}:cell_2:1:0: C0413: Import "from random import randint"' + " should be placed at the top of the module (wrong-import-position)" ] # check out and err out, err = capsys.readouterr() # This is to ensure no additional warnings get generated apart # from the expected ones. This will also help to update the test when the # notebooks used for testing are modified later. assert out.count(rf"{str(notebook1)}:cell_") == len( notebook1_expected_warnings) assert out.count(rf"{str(notebook2)}:cell_") == len( notebook2_expected_warnings) assert all(warning in out for warning in notebook1_expected_warnings) assert all(warning in out for warning in notebook2_expected_warnings) assert err == ""
def test_black_works_with_trailing_semicolons( tmp_notebook_with_trailing_semicolon: Path, capsys: "CaptureFixture") -> None: """ Check black works. Should only reformat code cells. Parameters ---------- tmp_notebook_with_trailing_semicolon Temporary copy of :code:`notebook_with_trailing_semicolon.ipynb`. capsys Pytest fixture to capture stdout and stderr. """ # check diff with open(tmp_notebook_with_trailing_semicolon) as handle: before = handle.readlines() path = os.path.join("tests", "data", "notebook_with_trailing_semicolon.ipynb") Path("setup.cfg").write_text( dedent("""\ [nbqa.mutate] black=1 """)) main(["black", os.path.abspath(path), "--line-length=10"]) Path("setup.cfg").unlink() with open(tmp_notebook_with_trailing_semicolon) as handle: after = handle.readlines() diff = difflib.unified_diff(before, after) result = "".join( [i for i in diff if any([i.startswith("+ "), i.startswith("- ")])]) expected = dedent("""\ - "import glob;\\n", + "import glob\\n", - "def func(a, b):\\n", - " pass;\\n", - " " + "def func(\\n", + " a, b\\n", + "):\\n", + " pass;" """) assert result == expected # check out and err out, err = capsys.readouterr() expected_out = "" # replace \u with \\u for both expected_err and err expected_err = (dedent(f"""\ reformatted {path} All done! {SPARKLES} {SHORTCAKE} {SPARKLES} 1 file reformatted. """).encode("ascii", "backslashreplace").decode()) # This is required because linux supports emojis # so both should have \\ for comparison err = err.encode("ascii", "backslashreplace").decode() assert out == expected_out assert expected_err == err
def test_configs_work(capsys: "CaptureFixture") -> None: """ Check a flake8 cfg file is picked up by nbqa. Parameters ---------- capsys Pytest fixture to capture stdout and stderr. """ Path(".flake8").write_text( dedent("""\ [flake8] ignore=F401 select=E303 quiet=1 """)) main(["flake8", "tests", "--ignore", "E302"]) Path(".flake8").unlink() # check out and err out, _ = capsys.readouterr() expected_out = "" assert out == expected_out
def test_missing_root_dir(capsys) -> None: """Check useful error message is raised if :code:`nbqa` is called without root_dir.""" msg = dedent("""\ usage: nbqa <code quality tool> <notebook or directory> <nbqa options> <code quality tool arguments> \x1b[1mPlease specify:\x1b[0m - 1) a code quality tool (e.g. `black`, `pyupgrade`, `flake`, ...) - 2) some notebooks (or, if supported by the tool, directories) - 3) (optional) flags for nbqa (e.g. `--nbqa-mutate`) - 4) (optional) flags for code quality tool (e.g. `--line-length` for `black`) \x1b[1mExamples:\x1b[0m nbqa flake8 notebook.ipynb nbqa black notebook.ipynb --line-length=96 nbqa pyupgrade notebook_1.ipynb notebook_2.ipynb \x1b[1mMutation:\x1b[0m to let `nbqa` modify your notebook(s), also pass `--nbqa-mutate`, e.g.: nbqa black notebook.ipynb --nbqa-mutate See https://nbqa.readthedocs.io/en/latest/index.html for more details on how to run `nbqa`. __main__.py: error: the following arguments are required: root_dirs """) with pytest.raises(SystemExit): main(["flake8", "--ignore=E203"]) _, err = capsys.readouterr() assert msg == err
def test_black_works_with_leading_comment(capsys: "CaptureFixture") -> None: """ Check black works with notebooks with commented-out magics. Parameters ---------- capsys Pytest fixture to capture stdout and stderr. """ path = os.path.join("tests", "data", "starting_with_comment.ipynb") main(["black", os.path.abspath(path), "--nbqa-diff"]) out, err = capsys.readouterr() err = err.encode("ascii", "backslashreplace").decode() expected_out = f"""\ \x1b[1mCell 3\x1b[0m ------ --- {os.path.abspath(path)} +++ {os.path.abspath(path)} @@ -1,3 +1,3 @@ # export \x1b[31m-def example_func(hi = "yo"): \x1b[0m\x1b[32m+def example_func(hi="yo"): \x1b[0m pass To apply these changes use `--nbqa-mutate` instead of `--nbqa-diff` """ expected_err = (dedent(f"""\ reformatted {path} All done! {SPARKLES} {SHORTCAKE} {SPARKLES} 1 file reformatted. """).encode("ascii", "backslashreplace").decode()) assert expected_out == out assert expected_err == err
def test_running_in_different_dir_works(arg: Path, cwd: Path, capsys: "CaptureFixture") -> None: """ Check .nbqa.ini config is picked up when running from non-root directory. Parameters ---------- arg Directory or notebook to run command on. cwd Directory from which to run command. """ config_path = Path(".nbqa.ini") config_path.write_text( dedent("""\ [flake8] addopts = --ignore=F401 \ """)) original_cwd = os.getcwd() try: os.chdir(str(cwd)) main(["flake8", str(arg)]) out, _ = capsys.readouterr() assert "W291" in out assert "F401" not in out finally: os.chdir(original_cwd) Path(".nbqa.ini").unlink()
def test_pyupgrade_works_with_weird_databricks_file( capsys: "CaptureFixture") -> None: """ Check pyupgrade works with unusual databricks notebooks. Parameters ---------- capsys Pytest fixture to capture stdout and stderr. """ path = os.path.join("tests", "data", "databricks_notebook.ipynb") main(["pyupgrade", path, "--nbqa-diff"]) out, err = capsys.readouterr() expected_out = ( f"\x1b[1mCell 2\x1b[0m\n------\n--- {path}\n" f"+++ {path}\n" "@@ -1 +1 @@\n" "\x1b[31m-set(())\n" "\x1b[0m\x1b[32m+set()\n" "\x1b[0m\n" "To apply these changes use `--nbqa-mutate` instead of `--nbqa-diff`\n" ) expected_err = f"Rewriting {path}\n" assert out == expected_out assert err == expected_err
def test_pyproject_toml_works( tmp_pyprojecttoml: Path, capsys: "CaptureFixture" ) -> None: """ Check if config is picked up from pyproject.toml works. Parameters ---------- tmp_pyprojecttoml Temporary pyproject.toml file. capsys Pytest fixture to capture stdout and stderr. """ tmp_pyprojecttoml.write_text( dedent( """ [tool.nbqa.addopts] flake8 = [ "--ignore=F401", "--select=E303", "--quiet" ] """ ) ) with pytest.raises(SystemExit): main(["flake8", "tests", "--ignore", "E302"]) tmp_pyprojecttoml.unlink() # check out and err out, _ = capsys.readouterr() expected_out = "" assert out == expected_out
def test_diff_present(capsys: "CaptureFixture") -> None: """Test the results on --nbqa-diff on a dirty notebook.""" main(["black", str(DIRTY_NOTEBOOK), "--nbqa-diff"]) out, err = capsys.readouterr() err = err.encode("ascii", "backslashreplace").decode() expected_out = ( "\x1b[1mCell 2\x1b[0m\n" "------\n" f"--- {str(DIRTY_NOTEBOOK)}\n" f"+++ {str(DIRTY_NOTEBOOK)}\n" "@@ -12,8 +12,8 @@\n" " 'hello goodbye'\n" ' """\n' " \n" "\x1b[31m- return 'hello {}'.format(name)\n" '\x1b[0m\x1b[32m+ return "hello {}".format(name)\n' "\x1b[0m \n" " \n" " !ls\n" "\x1b[31m-hello(3) \n" "\x1b[0m\x1b[32m+hello(3)\n" "\x1b[0m\n" "To apply these changes use `--nbqa-mutate` instead of `--nbqa-diff`\n" ) assert out == expected_out expected_err = (dedent(f"""\ reformatted {str(DIRTY_NOTEBOOK)} All done! {SPARKLES} {SHORTCAKE} {SPARKLES} 1 file reformatted. """).encode("ascii", "backslashreplace").decode()) assert err == expected_err
def test_black_works_with_literal_assignment(capsys: "CaptureFixture") -> None: """ Check black works with notebooks with invalid syntax (e.g. assignment to literal). Parameters ---------- capsys Pytest fixture to capture stdout and stderr. """ path = os.path.abspath( os.path.join("tests", "invalid_data", "assignment_to_literal.ipynb")) with pytest.raises(SystemExit): main(["black", path]) out, err = capsys.readouterr() expected_out = "" expected_err = (( f"error: cannot format {path}: " "cannot use --safe with this file; failed to parse source file. AST error message: " "can't assign to literal (<unknown>, cell_1:1)\nOh no! " f"{COLLISION} {BROKEN_HEART} {COLLISION}\n1 file failed to reformat.\n" ).encode("ascii", "backslashreplace").decode()) # This is required because linux supports emojis # so both should have \\ for comparison err = err.encode("ascii", "backslashreplace").decode() assert expected_out == out assert expected_err == err
def test_process_cells_magic(capsys: "CaptureFixture") -> None: """ Notebook contains non-allowlist magic, but it's in process_cells. """ path = os.path.abspath( os.path.join("tests", "data", "non_default_magic.ipynb")) with pytest.raises(SystemExit): main([ "black", path, "--nbqa-diff", "--nbqa-process-cells", "javascript" ]) out, _ = capsys.readouterr() expected = ( "\x1b[1mCell 1\x1b[0m\n" "------\n" f"--- {path}\n" f"+++ {path}\n" "@@ -1,3 +1,3 @@\n" " %%javascript\n" " \n" "\x1b[31m-a = 2 \n" "\x1b[0m\x1b[32m+a = 2\n" "\x1b[0m\n" "To apply these changes use `--nbqa-mutate` instead of `--nbqa-diff`\n" ) assert out == expected
def test_file_not_found() -> None: """Check useful error message is raised if file or directory doesn't exist.""" msg = "No such file or directory: I don't exist" with pytest.raises(FileNotFoundError) as exc: main(["isort", "I don't exist", "--profile=black", "--nbqa-mutate"]) assert msg in str(exc.value)
def test_flake8_works(capsys: "CaptureFixture") -> None: """ Check flake8 works. Shouldn't alter the notebook content. Parameters ---------- capsys Pytest fixture to capture stdout and stderr. """ # check passing both absolute and relative paths path_0 = os.path.join("tests", "data", "notebook_for_testing.ipynb") path_1 = os.path.join("tests", "data", "notebook_for_testing_copy.ipynb") path_2 = os.path.abspath( os.path.join("tests", "data", "notebook_starting_with_md.ipynb")) with pytest.raises(SystemExit): main(["flake8", path_0, path_1, path_2]) out, err = capsys.readouterr() expected_out = dedent(f"""\ {path_0}:cell_1:1:1: F401 'os' imported but unused {path_0}:cell_1:3:1: F401 'glob' imported but unused {path_0}:cell_1:5:1: F401 'nbqa' imported but unused {path_0}:cell_2:19:9: W291 trailing whitespace {path_1}:cell_1:1:1: F401 'os' imported but unused {path_1}:cell_1:3:1: F401 'glob' imported but unused {path_1}:cell_1:5:1: F401 'nbqa' imported but unused {path_2}:cell_1:1:1: F401 'os' imported but unused {path_2}:cell_1:3:1: F401 'glob' imported but unused {path_2}:cell_1:5:1: F401 'nbqa' imported but unused {path_2}:cell_3:2:1: E302 expected 2 blank lines, found 0 """) expected_err = "" assert sorted(out.splitlines()) == sorted(expected_out.splitlines()) assert sorted(err.splitlines()) == sorted(expected_err.splitlines())
def test_file_not_found(capsys: "CaptureFixture") -> None: """Check useful error message is raised if file or directory doesn't exist.""" msg = "No such file or directory: I don't exist" main(["isort", "I don't exist", "--profile=black", "--nbqa-mutate"]) _, err = capsys.readouterr() assert msg in err
def test_isort_trailing_semicolon( tmp_notebook_with_trailing_semicolon: Path) -> None: """ Check isort works when a notebook starts with a markdown cell. Parameters ---------- tmp_notebook_with_trailing_semicolon Temporary copy of :code:`notebook_with_trailing_semicolon.ipynb`. """ # check diff with open(tmp_notebook_with_trailing_semicolon) as handle: before = handle.readlines() path = os.path.abspath( os.path.join("tests", "data", "notebook_with_trailing_semicolon.ipynb")) with pytest.raises(SystemExit): main(["isort", path, "--nbqa-mutate"]) with open(tmp_notebook_with_trailing_semicolon) as handle: after = handle.readlines() diff = difflib.unified_diff(before, after) result = "".join( [i for i in diff if any([i.startswith("+ "), i.startswith("- ")])]) expected = dedent("""\ - "import glob;\\n", + "import glob\\n", - " pass;\\n", - " " + " pass;" """) assert result == expected
def _run_nbqa(command: str, notebook: str, *args: str) -> Tuple[List[str], List[str]]: """ Run nbQA on the given notebook using the input command. Parameters ---------- command : str Third party tool to run notebook : str Notebook given to nbQA Returns ------- Tuple[List[str], List[str]] Content of the notebook before and after running nbQA """ with open(notebook) as handle: before = handle.readlines() with pytest.raises(SystemExit): main([command, notebook, *args]) with open(notebook) as handle: after = handle.readlines() return (before, after)
def test_pyproject_toml_works(temporarily_delete_pyprojecttoml: Path, capsys: "CaptureFixture") -> None: """ Check if config is picked up from pyproject.toml works. Parameters ---------- capsys Pytest fixture to capture stdout and stderr. """ filename: str = str(temporarily_delete_pyprojecttoml) with open(filename, "w") as handle: handle.write( dedent(""" [tool.nbqa.addopts] flake8 = [ "--ignore=F401", "--select=E303", "--quiet" ] """)) with pytest.raises(SystemExit): main(["flake8", "tests", "--ignore", "E302"]) Path(filename).unlink() # check out and err out, _ = capsys.readouterr() expected_out = "" assert out == expected_out
def test_comment_after_trailing_semicolons(capsys: "CaptureFixture") -> None: """Check isort works normally when there's a comment after trailing semicolon.""" # check diff path = os.path.abspath( os.path.join("tests", "data", "comment_after_trailing_semicolon.ipynb")) main(["isort", path, "--nbqa-diff"]) out, _ = capsys.readouterr() expected_out = ( "\x1b[1mCell 1\x1b[0m\n" "------\n" f"--- {path}\n" f"+++ {path}\n" "@@ -1,4 +1,5 @@\n" "\x1b[31m-import glob;\n" "\x1b[0m\x1b[32m+import glob\n" "\x1b[0m \n" " import nbqa;\n" "\x1b[32m+\n" "\x1b[0m # this is a comment\n" "\n" f"Fixing {path}\n" "To apply these changes use `--nbqa-mutate` instead of `--nbqa-diff`\n" ) assert out == expected_out
def test_missing_root_dir(capsys: "CaptureFixture") -> None: """Check useful error message is raised if :code:`nbqa` is called without root_dir.""" prefix = "\x1b[1m" suffix = "\x1b[0m" pattern = re.escape(f"""\ usage: nbqa <code quality tool> <notebook or directory> <nbqa options> \ <code quality tool arguments> {prefix}Please specify:{suffix} - 1) a code quality tool (e.g. `black`, `pyupgrade`, `flake`, ...) - 2) some notebooks (or, if supported by the tool, directories) - 3) (optional) flags for nbqa (e.g. `--nbqa-mutate`) - 4) (optional) flags for code quality tool (e.g. `--line-length` for `black`) {prefix}Examples:{suffix} nbqa flake8 notebook.ipynb nbqa black notebook.ipynb --line-length=96 nbqa pyupgrade notebook_1.ipynb notebook_2.ipynb {prefix}Mutation:{suffix} to let `nbqa` modify your notebook(s), \ also pass `--nbqa-mutate`, e.g.: nbqa black notebook.ipynb --nbqa-mutate See https://nbqa.readthedocs.io/en/latest/index.html for more details on \ how to run `nbqa`.\ """) pattern = pattern + ".*: error: the following arguments are required: root_dirs\n" with pytest.raises(SystemExit): main(["flake8", "--ignore=E203"]) _, err = capsys.readouterr() assert re.fullmatch(pattern, err, re.DOTALL)
def test_unable_to_reconstruct_message(capsys: "CaptureFixture") -> None: """Check error message shows if we're unable to reconstruct notebook.""" path = os.path.abspath(os.path.join("tests", "data", "notebook_for_testing.ipynb")) message = f"Error reconstructing {path}" main(["remove_comments", path, "--nbqa-mutate"]) _, err = capsys.readouterr() assert message in err
def test_unable_to_parse_output(capsys: "CaptureFixture") -> None: """ Check user is encouraged to report bug if we're unable to parse tool's output. Parameters ---------- capsys Pytest fixture to capture stdout and stderr. """ path = Path("tests") / "data/notebook_for_testing.ipynb" # pylint: disable=C0301 expected_err = dedent(r"""\ \x1b\[1mKeyError(.*) while parsing output from applying print_6174 to tests.data.notebook_for_testing\.ipynb Please report a bug at https://github\.com/nbQA\-dev/nbQA/issues \x1b\[0m """ # noqa: E501 ) # pylint: enable=C0301 expected_out = f"{str(path)}:6174:0 some silly warning\n" with pytest.raises(SystemExit): main(["print_6174", str(path), "--nbqa-mutate"]) out, err = capsys.readouterr() re.match(expected_err, err) assert expected_out == out
def test_configs_work_in_nbqaini(capsys: "CaptureFixture") -> None: """ Check a .nbqa.ini file is picked up by nbqa. No longer "officially" supported but keeping this here for backwards compatibility. Parameters ---------- capsys Pytest fixture to capture stdout and stderr. """ Path(".flake8").write_text( dedent("""\ [flake8] ignore=F401 select=E303 quiet=1 """)) Path(".nbqa.ini").write_text( dedent("""\ [flake8] config=.flake8 """)) with pytest.raises(SystemExit): main(["flake8", "tests", "--ignore", "E302"]) Path(".flake8").unlink() Path(".nbqa.ini").unlink() # check out and err out, _ = capsys.readouterr() assert out == ""
def test_black_multiple_files(tmp_test_data: Path) -> None: """ Check black works when running on a directory. Should reformat notebooks. Parameters ---------- tmp_test_data Temporary copy of test data. """ # check diff with open(str(tmp_test_data / "notebook_for_testing.ipynb")) as handle: before = handle.readlines() path = os.path.abspath(os.path.join("tests", "data")) Path("setup.cfg").write_text( dedent("""\ [nbqa.mutate] black=1 """)) main(["black", path]) Path("setup.cfg").unlink() with open(str(tmp_test_data / "notebook_for_testing.ipynb")) as handle: after = handle.readlines() diff = difflib.unified_diff(before, after) assert "".join(diff) != ""
def test_isort_initial_md( tmp_notebook_starting_with_md: "Path", capsys: "CaptureFixture" ) -> None: """ Check isort works when a notebook starts with a markdown cell. Parameters ---------- tmp_notebook_starting_with_md Temporary copy of :code:`notebook_for_testing.ipynb`. capsys Pytest fixture to capture stdout and stderr. """ # check diff with open(tmp_notebook_starting_with_md) as handle: before = handle.readlines() path = os.path.join("tests", "data", "notebook_starting_with_md.ipynb") with pytest.raises(SystemExit): main(["isort", path, "--nbqa-mutate"]) with open(tmp_notebook_starting_with_md) as handle: after = handle.readlines() diff = difflib.unified_diff(before, after) result = "".join([i for i in diff if any([i.startswith("+ "), i.startswith("- ")])]) expected = '+ "import glob\\n",\n- "\\n",\n- "import glob\\n",\n' assert result == expected # check out and err out, err = capsys.readouterr() expected_out = f"Fixing {path}{os.linesep}" expected_err = "" assert out == expected_out assert err == expected_err
def test_invalid_syntax_with_nbqa_diff(capsys: "CaptureFixture") -> None: """ Check that using nbqa-diff when there's invalid syntax doesn't have empty output. Parameters ---------- capsys Pytest fixture to capture stdout and stderr. """ path = os.path.join("tests", "invalid_data", "assignment_to_literal.ipynb") main(["black", os.path.abspath(path), "--nbqa-diff"]) out, err = capsys.readouterr() expected_out = "" expected_err = (( f"error: cannot format {path}: " "cannot use --safe with this file; failed to parse source file. AST error message: " "can't assign to literal (<unknown>, cell_1:1)\nOh no! " f"{COLLISION} {BROKEN_HEART} {COLLISION}\n1 file failed to reformat.\n" ).encode("ascii", "backslashreplace").decode()) # This is required because linux supports emojis # so both should have \\ for comparison err = err.encode("ascii", "backslashreplace").decode() assert expected_out == out assert expected_err == err
def test_isort_separated_imports(notebook: str, capsys: "CaptureFixture") -> None: """ Check isort works when a notebook has imports in different cells. We will pass --treat-comment-as-code '# %%'. Parameters ---------- tmp_notebook_starting_with_md Temporary copy of :code:`notebook_for_testing.ipynb`. capsys Pytest fixture to capture stdout and stderr. """ with open("setup.cfg", "w") as handle: handle.write( dedent( """\ [nbqa.isort] addopts = --treat-comment-as-code "# %%%%" """ ) ) path = os.path.abspath(os.path.join("tests", "data", notebook)) with pytest.raises(SystemExit): main(["isort", path, "--nbqa-mutate"]) Path("setup.cfg").unlink() # check out and err out, err = capsys.readouterr() expected_out = "" expected_err = "" assert out == expected_out assert err == expected_err
def test_mypy_works(capsys: "CaptureFixture") -> None: """ Check mypy works. Shouldn't alter the notebook content. Parameters ---------- capsys Pytest fixture to capture stdout and stderr. """ main([ "mypy", "--ignore-missing-imports", "--allow-untyped-defs", str(Path("tests") / "data"), ]) # check out and err out, err = capsys.readouterr() path_0 = os.path.join("tests", "data", "notebook_for_testing.ipynb") path_1 = os.path.join("tests", "data", "notebook_for_testing_copy.ipynb") path_2 = os.path.join("tests", "data", "notebook_starting_with_md.ipynb") expected_out = dedent(f"""\ {path_2}:cell_3:18: error: Argument 1 to "hello" has incompatible type "int"; expected "str" {path_1}:cell_2:18: error: Argument 1 to "hello" has incompatible type "int"; expected "str" {path_0}:cell_2:19: error: Argument 1 to "hello" has incompatible type "int"; expected "str" Found 3 errors in 3 files (checked 24 source files) """ # noqa ) expected_err = "" assert sorted(out.splitlines()) == sorted(expected_out.splitlines()) assert sorted(err.splitlines()) == sorted(expected_err.splitlines())
def test_isort_separated_imports(notebook: str, capsys: "CaptureFixture") -> None: """ Check isort works when a notebook has imports in different cells. We will pass --treat-comment-as-code '# %%NBQA-CELL-SEP'. Parameters ---------- notebook Notebook to run ``nbqa isort`` on. capsys Pytest fixture to capture stdout and stderr. """ Path("setup.cfg").write_text( dedent("""\ [nbqa.isort] addopts = --treat-comment-as-code "# %%%%NBQA-CELL-SEP" """)) path = os.path.abspath(os.path.join("tests", "data", notebook)) with pytest.raises(SystemExit): main(["isort", path, "--nbqa-mutate"]) Path("setup.cfg").unlink() # check out and err out, err = capsys.readouterr() expected_out = "" expected_err = "" assert out == expected_out assert err == expected_err
def test_nbqa_ini_works(capsys: "CaptureFixture") -> None: """ Check setup.cfg config is picked up works. Parameters ---------- capsys Pytest fixture to capture stdout and stderr. """ Path("setup.cfg").write_text( dedent("""\ [nbqa.addopts] flake8 = --ignore=F401 \ --select=E303 \ --quiet """)) with pytest.raises(SystemExit): main(["flake8", "tests", "--ignore", "E302"]) Path("setup.cfg").unlink() # check out and err out, _ = capsys.readouterr() expected_out = "" assert out == expected_out
def test_configs_work(capsys: "CaptureFixture") -> None: """ Check a flake8 cfg file is picked up by nbqa. Parameters ---------- tmp_notebook_for_testing Temporary copy of :code:`notebook_for_testing.ipynb`. capsys Pytest fixture to capture stdout and stderr. """ with open(".flake8", "w") as handle: handle.write("[flake8]\nignore=F401\nselect=E303\nquiet=1\n") with pytest.raises(SystemExit): main([ "flake8", "tests", "--ignore", "E302", "--nbqa-config", ".flake8" ]) Path(".flake8").unlink() # check out and err out, _ = capsys.readouterr() expected_out = "" assert out == expected_out