okami.mom/strata

git clone https://git.nkp.pet/okami.mom/strata

Niko1221Merge main 6c642df75 into f-own-int (round 16: network waits, robustness, Windows kill-on-close job start, GitHub and transfer fixes)cd9745050

main
6.7 KiB131 linesraw
1"""Lane NET item 3: packaging/install.sh's fetch() under the network rule, against local servers: a TLS server that never answers its handshake
2(given up after the 15 s connect limit and one retry, about 32 s, not 10 minutes), a refused port (at once), a working server, and a slow link that
3keeps sending (never cut; real-time, STRATA_SLOW_NET_TESTS=1). curl and POSIX sh are needed; the Windows script is item 6."""
4
5import os
6import re
7import shutil
8import subprocess
9import tempfile
10import time
11import unittest
12from pathlib import Path
13
14from tests.terminal.test_netpolicy import BlackHole, Server, ok_body, refused_port, trickle
15
16ROOT = Path(__file__).resolve().parents[2]
17SH = ROOT / "packaging" / "install.sh"
18
19
20def curl_fetch_line() -> str:
21    m = re.search(r"^\s*fetch\(\) \{ curl [^\n]*\}", SH.read_text(encoding="utf-8"), re.M)
22    assert m, "install.sh has no curl fetch()"
23    return m.group(0).strip()
24
25
26@unittest.skipIf(os.name == "nt" or not (shutil.which("sh") and shutil.which("curl")), "needs POSIX sh and curl")
27class InstallFetch(unittest.TestCase):
28    def fetch(self, url, timeout=120):
29        with tempfile.TemporaryDirectory() as d:
30            out = Path(d) / "got"
31            t0 = time.monotonic()
32            env = {k: v for k, v in os.environ.items() if k.lower() not in ("http_proxy", "https_proxy", "all_proxy")}
33            r = subprocess.run(["sh", "-c", curl_fetch_line() + '\nfetch "$1" "$2"', "sh", url, str(out)], capture_output=True, text=True,
34                               timeout=timeout, env=env)
35            return r.returncode, (out.read_bytes() if out.exists() else b""), time.monotonic() - t0, r.stderr
36
37    def test_the_limits_are_in_the_script(self):
38        line = curl_fetch_line()
39        for flag in ("--connect-timeout 15", "--speed-limit 1", "--speed-time 60", "--retry 1"):
40            self.assertIn(flag, line)
41        self.assertNotIn("--max-time", line)                 # no total cap: a slow download that works is not cut
42        self.assertNotIn("--retry-connrefused", line)        # a refused connection fails at once
43
44    def test_a_handshake_that_never_answers_is_given_up_in_about_half_a_minute(self):
45        hole = BlackHole()
46        self.addCleanup(hole.close)
47        code, _got, took, err = self.fetch(f"https://127.0.0.1:{hole.port}/install-manifest.txt")
48        self.assertNotEqual(code, 0)
49        self.assertGreater(took, 25)
50        self.assertLess(took, 45, err)                       # 15 + 2 + 15 s, not 10 minutes
51        self.assertEqual(len(hole.held), 2)
52
53    def test_a_refused_port_fails_at_once(self):
54        code, _got, took, _err = self.fetch(f"http://127.0.0.1:{refused_port()}/install-manifest.txt")
55        self.assertNotEqual(code, 0)
56        self.assertLess(took, 3)
57
58    def test_a_working_server(self):
59        srv = Server(ok_body(b"linux-x86_64 0.1 a b 1\n"))
60        self.addCleanup(srv.close)
61        code, got, _took, err = self.fetch(srv.url("/install-manifest.txt"))
62        self.assertEqual((code, got), (0, b"linux-x86_64 0.1 a b 1\n"), err)
63
64    @unittest.skipUnless(os.environ.get("STRATA_SLOW_NET_TESTS") == "1", "real-time: STRATA_SLOW_NET_TESTS=1")
65    def test_a_slow_link_that_keeps_sending_is_not_cut(self):
66        srv = Server(trickle(150, 0.5))                      # 2 bytes a second for 75 s: past the 60 s window, above 1 byte/s
67        self.addCleanup(srv.close)
68        code, got, took, err = self.fetch(srv.url("/terminal.tar.gz"), timeout=200)
69        self.assertEqual((code, len(got)), (0, 150), err)
70        self.assertGreater(took, 70)
71
72
73class DocumentedLines(unittest.TestCase):
74    """W12 and the Windows line (owner 11-10): the documented install lines carry their limits; no copy of the old lines is left (old release notes
75    are history and keep theirs)."""
76    OLD = ("curl -fsSL https://github.com/Niko1221/Strata/releases/latest/download/install.sh -o install.sh",
77           "curl -fsSLO https://github.com/Niko1221/Strata/releases/latest/download/install.sh",
78           "irm https://github.com/Niko1221/Strata/releases/latest/download/install.ps1 | iex")
79
80    def files(self):
81        for p in ROOT.rglob("*"):
82            rel = p.relative_to(ROOT).as_posix()
83            if p.suffix.lower() not in (".md", ".ps1", ".sh", ".txt", ".json", ".ts", ".tsx", ".mjs", ".py", ".html") or not p.is_file():
84                continue
85            if rel.startswith(("node_modules/", ".git/", "history/")) or "/node_modules/" in rel or "release-notes-" in p.name:
86                continue
87            if p.resolve() == Path(__file__).resolve():
88                continue
89            yield rel, p
90
91    def test_no_old_line_is_left(self):
92        left = []
93        for rel, p in self.files():
94            try:
95                text = p.read_text(encoding="utf-8")
96            except (OSError, UnicodeDecodeError):
97                continue
98            left += [rel for old in self.OLD if old in text]
99        self.assertEqual(left, [])
100
101    def test_the_readme_lines(self):
102        text = (ROOT / "README.md").read_text(encoding="utf-8")
103        self.assertIn("curl -fsSL --connect-timeout 15 --max-time 120 https://github.com/Niko1221/Strata/releases/latest/download/install.sh "
104                      "-o install.sh && sh install.sh", text)
105        self.assertIn("irm -TimeoutSec 120 https://github.com/Niko1221/Strata/releases/latest/download/install.ps1 | iex", text)
106
107
108class InstallPs1Text(unittest.TestCase):
109    """Item 6: packaging/install.ps1 under the same rule (its real run is on Windows, through the coordinator)."""
110
111    def setUp(self):
112        self.ps1 = (ROOT / "packaging" / "install.ps1").read_text(encoding="utf-8")
113
114    def test_every_download_goes_through_fetch_with_the_limits(self):
115        self.assertNotIn("Invoke-WebRequest", self.ps1)
116        self.assertNotIn("Invoke-RestMethod", self.ps1)
117        self.assertEqual(len(re.findall(r"\bFetch \"\$feed/", self.ps1)), 3)
118        for text in ("$req.Timeout = 15000", "$req.ReadWriteTimeout = 60000", "Start-Sleep -Seconds 2", "$try -lt 2 -and $timedOut",
119                     "[Net.WebExceptionStatus]::Timeout", "$ProgressPreference = 'SilentlyContinue'", "DefaultNetworkCredentials"):
120            self.assertIn(text, self.ps1)
121        self.assertNotIn("TimeoutSec", self.ps1.split("& {", 1)[1])     # no total cap inside the script (PowerShell 7 would cut a slow download)
122
123    def test_the_messages(self):
124        self.assertIn("did not answer (or this computer is offline), so the installer could not start. Check that this computer can open "
125                      "https://$feedHost, then run the same line again. Nothing was installed.", self.ps1)
126        self.assertIn("the download stopped: $feedHost did not answer, or no data came for 60 seconds. Run the same line again; nothing was installed.",
127                      self.ps1)
128
129
130if __name__ == "__main__":
131    unittest.main()