diff options
| author | Mohamed Hegazy <mhegazy@anthropic.com> | 2026-10-20 17:19:54 +0000 |
|---|---|---|
| committer | Claude <noreply@anthropic.com> | 2026-10-20 17:19:54 +0000 |
| commit | 0f6be178f21e3966272328322e6291b2f47c4727 (patch) | |
| tree | 355d693a59ba39f5fdde016e3541edf2b011b5f9 /plugins/security-guidance/tests | |
| parent | 6d375ed2062b0c34e8a18885439cd992ad2d834a (diff) | |
| parent | e68e375d22866ba36c1eb0b4cc46db96c65f6a4e (diff) | |
Merge main into mhegazy/sg-stop-diff-memorymhegazy/sg-stop-diff-memory
Conflict in get_git_diff: main added IGNORE_SUBMODULES to the diff command on the line where this branch resets its read counters. Both are kept.
Diffstat (limited to 'plugins/security-guidance/tests')
4 files changed, 585 insertions, 0 deletions
diff --git a/plugins/security-guidance/tests/test_launcher_newer_python.py b/plugins/security-guidance/tests/test_launcher_newer_python.py new file mode 100644 index 00000000..fc152b73 --- /dev/null +++ b/plugins/security-guidance/tests/test_launcher_newer_python.py @@ -0,0 +1,55 @@ +"""sg-python.sh finds Python releases newer than its versioned list. + +The versioned names it prefers stop at python3.13. A machine whose `python3` +is below 3.10 (stock macOS: 3.9) and whose only newer interpreter is +python3.14 used to end up on 3.9, which cannot load the agent SDK, so the +commit reviewer was off without a word. See #4907, #5024. + +Interpreters are emulated with shell scripts, so these tests need a POSIX +shell. +""" +import sys + +import pytest + +from test_launcher_process_count import PYTHON, _add, _run, _starts, box # noqa: F401 + +pytestmark = pytest.mark.skipif(sys.platform == "win32", reason="POSIX shell wrappers") + + +def test_newer_release_beats_a_python3_below_3_10(box): + _add(box, "python3", PYTHON, version="3.9") + _add(box, "python3.14", PYTHON, version="3.14") + r = _run(box, "hook.py") + assert "ran:python3.14" in r.stdout, r.stdout + r.stderr + assert _starts(box) == ["python3 probe", "python3.14 probe", "python3.14 hook.py"] + + +def test_newer_release_is_found_when_it_is_the_only_python(box): + _add(box, "python3.15", PYTHON, version="3.15") + r = _run(box, "hook.py") + assert "ran:python3.15" in r.stdout, r.stdout + r.stderr + assert _starts(box) == ["python3.15 probe", "python3.15 hook.py"] + + +@pytest.mark.parametrize("working", ["python3.12", "python3", "python"]) +def test_an_interpreter_that_already_works_is_kept(box, working): + _add(box, working, PYTHON, version="3.12") + _add(box, "python3.14", PYTHON, version="3.14") + r = _run(box, "hook.py") + assert f"ran:{working}" in r.stdout, r.stdout + r.stderr + assert "python3.14 probe" not in _starts(box) + + +def test_oldest_of_the_newer_releases_is_tried_first(box): + _add(box, "python3.16", PYTHON, version="3.16") + _add(box, "python3.14", PYTHON, version="3.14") + r = _run(box, "hook.py") + assert "ran:python3.14" in r.stdout, r.stdout + r.stderr + + +def test_no_python_at_all_still_starts_nothing(box): + r = _run(box, "hook.py") + assert r.returncode == 1 + assert "python3.14" in r.stderr + assert _starts(box) == [] diff --git a/plugins/security-guidance/tests/test_nested_repos.py b/plugins/security-guidance/tests/test_nested_repos.py new file mode 100644 index 00000000..cb010018 --- /dev/null +++ b/plugins/security-guidance/tests/test_nested_repos.py @@ -0,0 +1,162 @@ +import os +import subprocess +import tempfile + +import pytest + +from conftest import ( + GIT_ENV, STUB_VULN, VULN_PY, git, make_repo, metrics_of, run_hook, + stop_payload, ups_payload, +) + +import gitutil + + +def _add_nested_repo(parent, rel, marker): + """A directory with its own `.git` whose config names a filter command, + the way an unpacked archive or a vendored checkout can. The command leaves + a line in `marker` each time git runs it.""" + nested = make_repo(parent / rel, { + "lib.py": "print('one')\n", + ".gitattributes": "* filter=probe\n", + }) + git(nested, "config", "filter.probe.clean", + f"sh -c 'echo ran >> \"{marker.as_posix()}\"; cat'") + # Same size, so git has to read the file to tell whether it changed. + (nested / "lib.py").write_text("print('two')\n") + old = os.stat(nested / ".git" / "index").st_mtime - 3600 + os.utime(nested / ".git" / "index", (old, old)) + return nested + + +@pytest.fixture +def outer(tmp_path): + return make_repo(tmp_path / "outer", {"app.py": "print('hi')\n"}) + + +@pytest.fixture +def marker(tmp_path): + return tmp_path / "filter-ran" + + +def _turn(repo, hook_env, stub_api, during): + stub_api.vulns = [STUB_VULN] + assert run_hook(ups_payload(repo), hook_env)[0] == 0 + during() + return run_hook(stop_payload(repo), hook_env) + + +def test_untracked_nested_repo_filter_not_run(outer, marker, hook_env, stub_api): + def during(): + _add_nested_repo(outer, "vendor/pkg", marker) + (outer / "app.py").write_text(VULN_PY) + + rc, out, err = _turn(outer, hook_env, stub_api, during) + + assert not marker.exists(), marker.read_text() + # The turn's own edit is still reviewed. + assert stub_api.calls, (rc, out, err) + assert "app.py" in out + err + + +def test_untracked_nested_repo_alone_is_not_reviewed(outer, marker, hook_env, stub_api): + rc, out, err = _turn( + outer, hook_env, stub_api, + lambda: _add_nested_repo(outer, "vendor/pkg", marker)) + + assert not marker.exists(), marker.read_text() + assert not stub_api.calls + assert (metrics_of(out) or {}).get("skipped") is True + + +@pytest.fixture +def git_env(tmp_path, monkeypatch): + """For calling gitutil in this process: a temp dir of our own, and the + environment restored afterwards.""" + d = tmp_path / "tmproot" + d.mkdir() + monkeypatch.setattr(tempfile, "tempdir", str(d)) + saved = dict(os.environ) + os.environ.update(GIT_ENV) + yield + os.environ.clear() + os.environ.update(saved) + + +def _record_nested_repo(outer, marker, gitmodules=None): + nested = _add_nested_repo(outer, "vendor/pkg", marker) + if gitmodules: + (outer / ".gitmodules").write_text(gitmodules) + git(outer, "add", "-A") + git(outer, "commit", "-q", "-m", "add vendor/pkg") + if marker.exists(): + marker.unlink() + return nested + + +def test_untracked_nested_repo_is_not_a_changed_file(outer, marker, git_env): + _add_nested_repo(outer, "vendor/pkg", marker) + (outer / "new.py").write_text("x = 1\n") + + tracked, untracked = gitutil._git_status_porcelain(str(outer)) + + assert (tracked, untracked) == (set(), {"new.py"}) + + +def test_intent_to_add_skips_nested_repos(outer, marker, git_env): + _add_nested_repo(outer, "vendor/pkg", marker) + (outer / "new.py").write_text("x = 1\n") + + with gitutil._temp_index(str(outer), ["new.py", "vendor/pkg/"]) as env: + assert env is not None + listed = subprocess.run( + ["git", "ls-files", "-s"], cwd=outer, capture_output=True, + text=True, env=env, + ).stdout + + assert "new.py" in listed + assert "160000" not in listed + assert not marker.exists() + + +# A repository can ask for one submodule to be checked whatever the default. +GITMODULES_IGNORE_NONE = ( + '[submodule "pkg"]\n\tpath = vendor/pkg\n\turl = ./vendor/pkg\n\tignore = none\n' +) + + +@pytest.mark.parametrize("gitmodules", [None, GITMODULES_IGNORE_NONE]) +def test_status_and_diff_leave_out_recorded_nested_repo(outer, marker, git_env, gitmodules): + nested = _record_nested_repo(outer, marker, gitmodules) + (nested / "lib.py").write_text("print('abc')\n") + (outer / "app.py").write_text(VULN_PY) + + tracked, untracked = gitutil._git_status_porcelain(str(outer)) + diff = gitutil.get_git_diff(str(outer), "HEAD", untracked_paths=[]) + names = gitutil._git_name_only(str(outer), "HEAD") + + assert tracked == {"app.py"} + assert names == {"app.py"} + assert "app.py" in diff and "vendor/pkg" not in diff + assert not marker.exists() + + +def test_commit_range_diff_does_not_enter_nested_repo(outer, marker, git_env, tmp_path): + nested = _record_nested_repo(outer, marker, GITMODULES_IGNORE_NONE) + ext_marker = tmp_path / "ext-diff-ran" + git(nested, "config", "diff.external", + f"sh -c 'echo ran >> \"{ext_marker.as_posix()}\"'") + base = git(outer, "rev-parse", "HEAD").strip() + git(nested, "commit", "-q", "-am", "two") + git(outer, "commit", "-q", "-am", "move vendor/pkg") + for m in (marker, ext_marker): + if m.exists(): + m.unlink() + # The user's own setting asks for a submodule's changes inline. + os.environ.update({"GIT_CONFIG_COUNT": "1", "GIT_CONFIG_KEY_0": "diff.submodule", + "GIT_CONFIG_VALUE_0": "diff"}) + + out = gitutil._git_diff_range(str(outer), base, "HEAD") + + assert not ext_marker.exists() and not marker.exists() + assert "lib.py" not in (out or "") diff --git a/plugins/security-guidance/tests/test_no_credentials_notice.py b/plugins/security-guidance/tests/test_no_credentials_notice.py new file mode 100644 index 00000000..1995397e --- /dev/null +++ b/plugins/security-guidance/tests/test_no_credentials_notice.py @@ -0,0 +1,175 @@ +"""Without credentials the LLM reviews are skipped; the user is told.""" +import json +import os +import time + +import pytest + +from conftest import ( + bash_payload, commit_file, edit_payload, git, metrics_of, run_hook, + stop_payload, ups_payload, VULN_PY, +) + +# Anything in the developer's shell that changes whether a review would run. +_AMBIENT = ( + "ANTHROPIC_API_KEY", "ANTHROPIC_AUTH_TOKEN", + "CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC", "DISABLE_TELEMETRY", "DO_NOT_TRACK", + "CLAUDE_CODE_USE_BEDROCK", "CLAUDE_CODE_USE_VERTEX", "CLAUDE_CODE_USE_FOUNDRY", + "CLAUDE_CODE_USE_MANTLE", "CLAUDE_CODE_USE_ANTHROPIC_AWS", + "SECURITY_GUIDANCE_DISABLE", "ENABLE_SECURITY_REMINDER", + "ENABLE_CODE_SECURITY_REVIEW", "ENABLE_STOP_REVIEW", "ENABLE_COMMIT_REVIEW", + "ENABLE_PATTERN_RULES", +) + + +def _env(hook_env, creds=False, **extra): + env = {k: v for k, v in hook_env.items() if k not in _AMBIENT} + if creds: + env["ANTHROPIC_API_KEY"] = "test-key" + env.update(extra) + return env + + +def _edit_output(repo, env, name="app.py", content=VULN_PY, session_id="s1"): + (repo / name).write_text(content) + rc, out, _ = run_hook( + edit_payload(repo, repo / name, new_string=content, session_id=session_id), env) + assert rc == 0 + lines = [l for l in out.splitlines() if l.startswith("{")] + assert len(lines) <= 1 + return json.loads(lines[0]) if lines else {} + + +def _notice(repo, env, **kw): + return _edit_output(repo, env, **kw).get("systemMessage") + + +def _marker(env): + return os.path.join(env["SECURITY_WARNINGS_STATE_DIR"], ".no_credentials_notice") + + +def test_edit_without_credentials_tells_the_user_once(workspace, hook_env): + _, repo = workspace + env = _env(hook_env) + notice = _notice(repo, env) + assert "is not running" in notice + assert "No Anthropic credentials were passed" in notice + assert "only the pattern warnings on edits are active" in notice + assert "ENABLE_CODE_SECURITY_REVIEW=0" in notice + assert _notice(repo, env) is None + assert _notice(repo, env, session_id="s2") is None + + +def test_notice_comes_back_after_a_week(workspace, hook_env): + _, repo = workspace + env = _env(hook_env) + assert _notice(repo, env) + six_days, eight_days = time.time() - 6 * 86400, time.time() - 8 * 86400 + os.utime(_marker(env), (six_days, six_days)) + assert _notice(repo, env) is None + os.utime(_marker(env), (eight_days, eight_days)) + assert _notice(repo, env) + assert _notice(repo, env) is None + + +def test_notice_names_every_setting_that_withholds_credentials(workspace, hook_env): + _, repo = workspace + notice = _notice(repo, _env(hook_env, DISABLE_TELEMETRY="1", DO_NOT_TRACK="true")) + assert "while DISABLE_TELEMETRY or DO_NOT_TRACK is set" in notice + + +@pytest.mark.parametrize("var", ["CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC", "DO_NOT_TRACK"]) +def test_notice_names_the_setting(workspace, hook_env, var): + _, repo = workspace + assert f"while {var} is set" in _notice(repo, _env(hook_env, **{var: "1"})) + + +def test_do_not_track_off_is_not_blamed(workspace, hook_env): + _, repo = workspace + notice = _notice(repo, _env(hook_env, DO_NOT_TRACK="0")) + assert "DO_NOT_TRACK" not in notice and "No Anthropic credentials" in notice + + +def test_notice_does_not_promise_pattern_warnings_that_are_off(workspace, hook_env): + _, repo = workspace + notice = _notice(repo, _env(hook_env, ENABLE_PATTERN_RULES="0")) + assert "is not running" in notice and "pattern warnings" not in notice + + +def test_notice_rides_along_with_a_pattern_warning(workspace, hook_env): + _, repo = workspace + risky = "import os\nos.system('ls ' + name)\n" + with_creds = _edit_output( + repo, _env(hook_env, creds=True), name="a.py", content=risky) + assert with_creds["metrics"]["pattern_hits"] == 1 + assert "systemMessage" not in with_creds + out = _edit_output(repo, _env(hook_env), name="b.py", content=risky) + assert "is not running" in out["systemMessage"] + assert out["metrics"] == with_creds["metrics"] + assert (out["hookSpecificOutput"]["additionalContext"] + == with_creds["hookSpecificOutput"]["additionalContext"]) + + +def test_no_notice_with_credentials(workspace, hook_env): + _, repo = workspace + assert _notice(repo, _env(hook_env, creds=True)) is None + assert _notice(repo, _env(hook_env, ANTHROPIC_AUTH_TOKEN="t")) is None + assert _notice(repo, _env(hook_env, CLAUDE_CODE_USE_BEDROCK="1")) is None + assert not os.path.exists(_marker(hook_env)) + + +def test_no_notice_when_the_reviews_are_turned_off(workspace, hook_env): + _, repo = workspace + assert _notice(repo, _env(hook_env, ENABLE_CODE_SECURITY_REVIEW="0")) is None + assert _notice(repo, _env(hook_env, SECURITY_GUIDANCE_DISABLE="1")) is None + assert _notice(repo, _env( + hook_env, ENABLE_STOP_REVIEW="0", SECURITY_GUIDANCE_COMMIT_REVIEW="off", + SG_PUSH_SWEEP="off")) is None + assert not os.path.exists(_marker(hook_env)) + assert _notice(repo, _env(hook_env, ENABLE_STOP_REVIEW="0")) + + +def test_no_notice_outside_a_git_repo(workspace, hook_env, tmp_path): + _, repo = workspace + plain = tmp_path / "plain" + plain.mkdir() + env = _env(hook_env) + assert _notice(plain, env, name="notes.py") is None + assert not os.path.exists(_marker(env)) + assert _notice(repo, env) + + +def test_no_notice_when_the_state_dir_is_unwritable(workspace, hook_env, tmp_path): + _, repo = workspace + blocker = tmp_path / "not-a-dir" + blocker.write_text("") + env = _env(hook_env, SECURITY_WARNINGS_STATE_DIR=str(blocker / "state")) + assert _notice(repo, env) is None + assert _notice(repo, env) is None + + +def test_skipped_reviews_report_the_missing_credentials(workspace, hook_env, stub_api): + _, repo = workspace + env = _env(hook_env) + run_hook(ups_payload(repo), env) + _edit_output(repo, env) + rc, out, _ = run_hook(stop_payload(repo), env) + m = metrics_of(out) + assert rc == 0 and m["skip_reason"] == 3 and m["no_creds"] is True + + _, commit_out = commit_file(repo, "app.py", VULN_PY + "# again\n") + rc, out, _ = run_hook( + bash_payload(repo, "git commit -m change", stdout=commit_out), env) + m = metrics_of(out) + assert rc == 0 and m["skip_reason"] == 22 and m["no_creds"] is True + + rc, out, _ = run_hook(bash_payload(repo, "git push origin main"), env) + m = metrics_of(out) + assert rc == 0 and m["push_sweep"] and m["skip_reason"] == 22 and m["no_creds"] is True + assert stub_api.calls == [] + + off = _env(hook_env, ENABLE_CODE_SECURITY_REVIEW="0") + for payload in (stop_payload(repo, session_id="s3"), + bash_payload(repo, "git push origin main", session_id="s3")): + rc, out, _ = run_hook(payload, off) + assert "no_creds" not in metrics_of(out) diff --git a/plugins/security-guidance/tests/test_notebook_edit_patterns.py b/plugins/security-guidance/tests/test_notebook_edit_patterns.py new file mode 100644 index 00000000..df4d37a9 --- /dev/null +++ b/plugins/security-guidance/tests/test_notebook_edit_patterns.py @@ -0,0 +1,193 @@ +"""NotebookEdit cell sources go through the same pattern checks as file edits.""" +import json +import subprocess +import sys + +import pytest + +import extensibility +import security_reminder_hook as hook + +from conftest import HOOKS_DIR, metrics_of, run_hook + +CELL = ( + "import pickle, os\n" + "data = pickle.loads(open('model.pkl', 'rb').read())\n" + "os.system(f'convert {user_input}')\n" +) +CELL_RULES = ["os_system_injection", "pickle_deserialization"] + + +@pytest.fixture +def env(hook_env, tmp_path): + # Keep the developer's own security-patterns files out of the counts. + home = tmp_path / "home" + home.mkdir() + hook_env.update(HOME=str(home), USERPROFILE=str(home)) + hook_env.pop("CLAUDE_CONFIG_DIR", None) + return hook_env + + +def notebook_payload(cwd, notebook, new_source=CELL, tool_response=None, **tool_input): + return { + "session_id": "s1", + "hook_event_name": "PostToolUse", + "tool_name": "NotebookEdit", + "tool_input": {"notebook_path": str(notebook), "new_source": new_source, **tool_input}, + "tool_response": tool_response if tool_response is not None else {}, + "cwd": str(cwd), + } + + +def warning_of(stdout): + for line in stdout.splitlines(): + if line.strip().startswith("{"): + out = json.loads(line).get("hookSpecificOutput") + if out: + return out["additionalContext"] + return "" + + +@pytest.mark.parametrize("tool_input", [ + {"cell_id": "c1"}, + {"cell_id": "c1", "edit_mode": "replace", "cell_type": "code"}, + {"cell_id": "c1", "edit_mode": "insert", "cell_type": "code"}, + {"edit_mode": "insert", "cell_type": "code"}, + {"cell_id": "c1", "cell_type": "markdown"}, +]) +def test_cell_source_is_checked(tmp_path, env, tool_input): + rc, out, _ = run_hook( + notebook_payload(tmp_path, tmp_path / "analysis.ipynb", **tool_input), env) + assert rc == 0 + warning = warning_of(out) + assert "pickle" in warning + assert "os.system" in warning + assert metrics_of(out)["pattern_hits"] == 2 + + +def test_same_cell_matches_a_python_file_edit(tmp_path, env): + _, nb_out, _ = run_hook( + notebook_payload(tmp_path, tmp_path / "analysis.ipynb", cell_id="c1"), env) + py = notebook_payload(tmp_path, tmp_path / "analysis.py") + py.update(tool_name="Edit", tool_input={ + "file_path": str(tmp_path / "analysis.py"), "old_string": "", "new_string": CELL}) + _, py_out, _ = run_hook(py, env) + assert metrics_of(nb_out)["rule_mask"] == metrics_of(py_out)["rule_mask"] + + +@pytest.mark.parametrize("tool_input, tool_response", [ + ({"cell_id": "c1", "edit_mode": "delete"}, {}), + ({"cell_id": "c1", "edit_mode": "delete", "cell_type": "code"}, {"error": ""}), + ({"cell_id": "c1"}, {"error": "File has been modified since read"}), + ({"cell_id": "c1"}, {"new_source": CELL, "error": "Edit rejected"}), +]) +def test_deleted_cell_and_failed_edit_are_not_checked(tmp_path, env, tool_input, tool_response): + rc, out, _ = run_hook( + notebook_payload(tmp_path, tmp_path / "analysis.ipynb", + tool_response=tool_response, **tool_input), env) + assert rc == 0 + assert metrics_of(out) is None + assert warning_of(out) == "" + + +def test_successful_edit_with_an_empty_error_is_checked(tmp_path, env): + # What Claude Code sends for an edit that worked. + _, out, _ = run_hook( + notebook_payload(tmp_path, tmp_path / "analysis.ipynb", cell_id="c1", + tool_response={"error": "", "cell_type": "code", "old_source": CELL}), + env) + assert metrics_of(out)["pattern_hits"] == 2 + + +@pytest.mark.parametrize("tool_input, tool_response", [ + ({"cell_id": "c1", "new_source": None}, {}), + ({"cell_id": "c1", "new_source": ["import pickle"]}, {}), + ({"cell_id": None}, {}), + ({"cell_id": "c1"}, "Updated cell c1"), + ({"cell_id": "c1"}, None), +]) +def test_unexpected_shapes_do_not_break_the_hook(tmp_path, env, tool_input, tool_response): + payload = notebook_payload(tmp_path, tmp_path / "analysis.ipynb", **tool_input) + payload["tool_response"] = tool_response + rc, _, err = run_hook(payload, env) + assert rc == 0 + assert "Traceback" not in err + + +def test_clean_cell_is_quiet(tmp_path, env): + rc, out, _ = run_hook( + notebook_payload(tmp_path, tmp_path / "analysis.ipynb", + new_source="import json\ndata = json.load(open('m.json'))\n", + cell_id="c1"), env) + assert rc == 0 + assert metrics_of(out) is None + + +def saved_notebook(code, bom=""): + # NotebookEdit saves a cell's source as one string; Jupyter saves a list of lines. + return bom + json.dumps({ + "cells": [ + {"cell_type": "markdown", "id": "m", "metadata": {}, "source": "# Notes\n"}, + {"cell_type": "code", "id": "c", "metadata": {}, "source": code, "outputs": []}, + ], + "metadata": {}, "nbformat": 4, "nbformat_minor": 5, + }, indent=1) + + +@pytest.fixture +def rules(monkeypatch): + monkeypatch.setattr(extensibility, "_user_patterns", []) + return lambda path, content: sorted(r for r, _ in hook.check_patterns(str(path), content)) + + +@pytest.mark.parametrize("bom", ["", ""]) +def test_saved_notebook_is_checked_by_its_cells_as_written(rules, bom): + saved = saved_notebook(CELL, bom) + assert "\\nos.system(" in saved + assert rules("analysis.ipynb", saved) == CELL_RULES + assert rules("analysis.ipynb", saved_notebook(CELL.splitlines(True), bom)) == CELL_RULES + assert rules("analysis.ipynb", saved_notebook("x = 1\n", bom)) == [] + + +def test_saved_notebook_outputs_are_not_checked(rules): + saved = json.loads(saved_notebook("x = 1\n")) + saved["cells"][1]["outputs"] = [{"output_type": "stream", "name": "stdout", "text": [CELL]}] + assert rules("analysis.ipynb", json.dumps(saved)) == [] + saved["cells"][0]["source"] = CELL.splitlines(True) + assert rules("analysis.ipynb", json.dumps(saved)) == CELL_RULES + + +@pytest.mark.parametrize("content", [ + "{not json", "{}", '{"cells": 5}', '{"cells": [5]}', '{"cells": [{"source": 5}]}', "[]", +]) +def test_content_that_is_not_a_saved_notebook_is_checked_as_is(rules, content): + assert rules("analysis.ipynb", content) == [] + assert rules("analysis.ipynb", content + "\nimport os\nos.system(cmd)\n") == ["os_system_injection"] + + +def test_other_files_are_not_read_as_notebooks(rules): + assert rules("analysis.py", saved_notebook("import os\nos.system(cmd)\n")) == [] + + +SWEEP = ( + "import sys, json; sys.path.insert(0, sys.argv[1]);" + "import security_reminder_hook as h;" + "print(json.dumps(h.sweep_pending_warnings('s1')[:2]))" +) + + +def sweep(env): + r = subprocess.run([sys.executable, "-c", SWEEP, str(HOOKS_DIR)], + capture_output=True, text=True, env=env) + return json.loads(r.stdout.strip().splitlines()[-1]) + + +def test_notebook_warning_is_tallied_from_the_saved_cells(tmp_path, env): + nb = tmp_path / "analysis.ipynb" + nb.write_text(saved_notebook(CELL)) + run_hook(notebook_payload(tmp_path, nb, cell_id="c"), env) + assert sweep(env) == [0, 2] + + run_hook(notebook_payload(tmp_path, nb, cell_id="c"), env) + nb.write_text(saved_notebook("x = 1\n")) + assert sweep(env) == [2, 0] |
