forked from longtao.wu/droboticflow
80 lines
2.0 KiB
Python
80 lines
2.0 KiB
Python
import os
|
|
import pathlib
|
|
import stat
|
|
import subprocess
|
|
|
|
|
|
ROOT = pathlib.Path(__file__).resolve().parents[2]
|
|
SCRIPT = ROOT / "scripts" / "npm-audit-retry.sh"
|
|
|
|
|
|
def run_audit_retry(tmp_path: pathlib.Path, extra_env: dict[str, str]) -> subprocess.CompletedProcess:
|
|
bin_dir = tmp_path / "bin"
|
|
bin_dir.mkdir()
|
|
counter_file = tmp_path / "npm-calls"
|
|
fake_npm = bin_dir / "npm"
|
|
fake_npm.write_text(
|
|
f"""#!/usr/bin/env bash
|
|
set -euo pipefail
|
|
if [[ "${{1:-}}" != "audit" ]]; then
|
|
echo "unexpected npm command: $*" >&2
|
|
exit 2
|
|
fi
|
|
count=0
|
|
if [[ -f "{counter_file}" ]]; then
|
|
count="$(cat "{counter_file}")"
|
|
fi
|
|
count=$((count + 1))
|
|
printf '%s' "$count" > "{counter_file}"
|
|
if (( count < 3 )); then
|
|
exit 42
|
|
fi
|
|
exit 0
|
|
""",
|
|
encoding="utf-8",
|
|
)
|
|
fake_npm.chmod(fake_npm.stat().st_mode | stat.S_IXUSR)
|
|
|
|
env = os.environ.copy()
|
|
env["PATH"] = f"{bin_dir}{os.pathsep}{env['PATH']}"
|
|
for key in ("NPM_AUDIT_ATTEMPTS", "NPM_AUDIT_RETRY_DELAY_SECONDS"):
|
|
env.pop(key, None)
|
|
env.update(extra_env)
|
|
return subprocess.run(
|
|
["bash", str(SCRIPT), "--audit-level=moderate"],
|
|
cwd=ROOT,
|
|
env=env,
|
|
text=True,
|
|
capture_output=True,
|
|
check=False,
|
|
)
|
|
|
|
|
|
def test_npm_audit_retry_retries_transient_failures(tmp_path):
|
|
result = run_audit_retry(
|
|
tmp_path,
|
|
{
|
|
"NPM_AUDIT_ATTEMPTS": "3",
|
|
"NPM_AUDIT_RETRY_DELAY_SECONDS": "0",
|
|
},
|
|
)
|
|
|
|
assert result.returncode == 0
|
|
assert "npm audit failed on attempt 1/3" in result.stderr
|
|
assert "npm audit failed on attempt 2/3" in result.stderr
|
|
assert (tmp_path / "npm-calls").read_text(encoding="utf-8") == "3"
|
|
|
|
|
|
def test_npm_audit_retry_rejects_invalid_attempts(tmp_path):
|
|
result = run_audit_retry(
|
|
tmp_path,
|
|
{
|
|
"NPM_AUDIT_ATTEMPTS": "0",
|
|
"NPM_AUDIT_RETRY_DELAY_SECONDS": "0",
|
|
},
|
|
)
|
|
|
|
assert result.returncode == 1
|
|
assert "NPM_AUDIT_ATTEMPTS must be a positive integer" in result.stderr
|
|
assert not (tmp_path / "npm-calls").exists()
|