513 lines
15 KiB
Python
Executable File
513 lines
15 KiB
Python
Executable File
#!/usr/bin/env python3
|
|
"""mini_serv behavioral tester.
|
|
|
|
Usage:
|
|
python3 mini_serv_tester.py <compiled-mini_serv> [--quick]
|
|
|
|
Mirrors what the exam-style grading script checks, plus edge cases:
|
|
bad args, bind failure, arrival broadcast rules, per-line relay, split lines,
|
|
no-flush-on-disconnect, id monotonicity, 0x04-as-data, a 400 KB single line,
|
|
a no-newline payload, 25 clients, a lazy client that never reads, fd leaks.
|
|
|
|
Exit code 0 = all tests passed.
|
|
|
|
NOTE: client disconnects are serialized (small sleeps) on purpose — the real
|
|
test does the same. RST/SIGPIPE storms are not part of the exam, so we don't
|
|
weaponize them here.
|
|
"""
|
|
import argparse
|
|
import os
|
|
import socket
|
|
import subprocess
|
|
import sys
|
|
import threading
|
|
import time
|
|
|
|
HOST = "127.0.0.1"
|
|
PASS = "\033[32mPASS\033[0m"
|
|
FAIL = "\033[31mFAIL\033[0m"
|
|
|
|
|
|
# ---------------------------------------------------------------- helpers ---
|
|
|
|
def free_port():
|
|
s = socket.socket()
|
|
s.bind((HOST, 0))
|
|
port = s.getsockname()[1]
|
|
s.close()
|
|
return port
|
|
|
|
|
|
def port_taken(port):
|
|
"""Passive check: can we bind it? (No connection is made.)"""
|
|
s = socket.socket()
|
|
try:
|
|
s.bind((HOST, port))
|
|
return False
|
|
except OSError:
|
|
return True
|
|
finally:
|
|
s.close()
|
|
|
|
|
|
class Server:
|
|
def __init__(self, binary):
|
|
self.binary = binary
|
|
self.proc = None
|
|
self.port = 0
|
|
|
|
def start(self):
|
|
for _ in range(10):
|
|
port = free_port()
|
|
proc = subprocess.Popen(
|
|
[self.binary, str(port)],
|
|
stdout=subprocess.DEVNULL,
|
|
stderr=subprocess.DEVNULL,
|
|
)
|
|
for _ in range(60):
|
|
if port_taken(port):
|
|
self.proc, self.port = proc, port
|
|
return port
|
|
if proc.poll() is not None:
|
|
break
|
|
time.sleep(0.05)
|
|
proc.kill()
|
|
proc.wait()
|
|
raise RuntimeError("server never became reachable")
|
|
|
|
def stop(self):
|
|
if self.proc and self.proc.poll() is None:
|
|
self.proc.terminate()
|
|
try:
|
|
self.proc.wait(timeout=2)
|
|
except subprocess.TimeoutExpired:
|
|
self.proc.kill()
|
|
self.proc.wait()
|
|
|
|
|
|
def connect(port):
|
|
s = socket.create_connection((HOST, port), timeout=5.0)
|
|
s.settimeout(0.2)
|
|
return s
|
|
|
|
|
|
def drain(s, wait=0.4):
|
|
data = b""
|
|
deadline = time.time() + wait
|
|
while time.time() < deadline:
|
|
try:
|
|
chunk = s.recv(1 << 20)
|
|
if not chunk:
|
|
break
|
|
data += chunk
|
|
deadline = time.time() + 0.15
|
|
except socket.timeout:
|
|
continue
|
|
except OSError:
|
|
break
|
|
return data
|
|
|
|
|
|
def close_all(*socks):
|
|
for s in socks:
|
|
if s is None:
|
|
continue
|
|
try:
|
|
s.close()
|
|
except OSError:
|
|
pass
|
|
|
|
|
|
class Collector(threading.Thread):
|
|
"""Background reader for scenarios where the client must drain while
|
|
another client is still sending (otherwise kernel buffers can deadlock
|
|
the test, not the server)."""
|
|
|
|
def __init__(self, sock):
|
|
super().__init__(daemon=True)
|
|
self.sock = sock
|
|
self.data = b""
|
|
self._stop = False
|
|
|
|
def run(self):
|
|
self.sock.settimeout(0.2)
|
|
while not self._stop:
|
|
try:
|
|
chunk = self.sock.recv(1 << 20)
|
|
if not chunk:
|
|
break
|
|
self.data += chunk
|
|
except socket.timeout:
|
|
continue
|
|
except OSError:
|
|
break
|
|
|
|
def stop(self):
|
|
self._stop = True
|
|
self.join(timeout=2)
|
|
|
|
|
|
# ------------------------------------------------------------------ tests ---
|
|
|
|
def t_bad_args(binary):
|
|
r = subprocess.run([binary], capture_output=True, timeout=10)
|
|
if r.returncode != 1:
|
|
return False, f"exit code {r.returncode}, want 1"
|
|
if r.stderr != b"Wrong number of arguments\n":
|
|
return False, f"stderr {r.stderr!r}, want b'Wrong number of arguments\\n'"
|
|
return True, "exit 1 + exact stderr"
|
|
|
|
|
|
def t_bind_failure(binary):
|
|
port = free_port()
|
|
blocker = socket.socket()
|
|
blocker.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
|
|
blocker.bind((HOST, port))
|
|
blocker.listen(1)
|
|
try:
|
|
r = subprocess.run([binary, str(port)], capture_output=True, timeout=10)
|
|
finally:
|
|
blocker.close()
|
|
if r.returncode != 1:
|
|
return False, f"exit code {r.returncode}, want 1"
|
|
if r.stderr != b"Fatal error\n":
|
|
return False, f"stderr {r.stderr!r}, want b'Fatal error\\n'"
|
|
return True, "exit 1 + exact stderr"
|
|
|
|
|
|
def t_arrivals(binary):
|
|
srv = Server(binary)
|
|
port = srv.start()
|
|
c0 = c1 = None
|
|
try:
|
|
c0 = connect(port)
|
|
got = drain(c0, 0.5)
|
|
if got:
|
|
return False, f"client 0 received {got!r} on its own connect, want silence"
|
|
c1 = connect(port)
|
|
got0, got1 = drain(c0), drain(c1, 0.3)
|
|
want = b"server: client 1 just arrived\n"
|
|
if got0 != want:
|
|
return False, f"client 0 got {got0!r}, want {want!r}"
|
|
if got1:
|
|
return False, f"newcomer got {got1!r}, want silence (arrival is for OTHERS only)"
|
|
return True, "arrival broadcast to others only; first id is 0"
|
|
finally:
|
|
close_all(c0, c1)
|
|
srv.stop()
|
|
|
|
|
|
def t_chat(binary):
|
|
srv = Server(binary)
|
|
port = srv.start()
|
|
c0 = c1 = c2 = None
|
|
try:
|
|
c0, c1, c2 = connect(port), connect(port), connect(port)
|
|
drain(c0, 0.5)
|
|
drain(c1, 0.3)
|
|
c1.sendall(b"hello\n")
|
|
g0, g2, g1 = drain(c0), drain(c2), drain(c1, 0.3)
|
|
want = b"client 1: hello\n"
|
|
if g0 != want or g2 != want:
|
|
return False, f"c0={g0!r} c2={g2!r}, want {want!r} each"
|
|
if g1:
|
|
return False, f"sender received its own message: {g1!r}"
|
|
c0.sendall(b"a\nb\n")
|
|
want2 = b"client 0: a\nclient 0: b\n"
|
|
g1, g2 = drain(c1), drain(c2)
|
|
if g1 != want2 or g2 != want2:
|
|
return False, f"multi-line c1={g1!r} c2={g2!r}, want {want2!r}"
|
|
return True, "relay to others; one 'client N: ' prefix per line"
|
|
finally:
|
|
close_all(c0, c1, c2)
|
|
srv.stop()
|
|
|
|
|
|
def t_split_line(binary):
|
|
srv = Server(binary)
|
|
port = srv.start()
|
|
c0 = c1 = None
|
|
try:
|
|
c0, c1 = connect(port), connect(port)
|
|
drain(c0, 0.5)
|
|
c1.sendall(b"par")
|
|
if drain(c0, 0.35):
|
|
return False, "server emitted something for an incomplete line"
|
|
c1.sendall(b"tial\n")
|
|
got = drain(c0)
|
|
want = b"client 1: partial\n"
|
|
if got != want:
|
|
return False, f"got {got!r}, want {want!r}"
|
|
return True, "partial line held, completed by the next packet"
|
|
finally:
|
|
close_all(c0, c1)
|
|
srv.stop()
|
|
|
|
|
|
def t_no_flush_on_eof(binary):
|
|
srv = Server(binary)
|
|
port = srv.start()
|
|
c0 = c1 = None
|
|
try:
|
|
c0, c1 = connect(port), connect(port)
|
|
drain(c0, 0.5)
|
|
c1.sendall(b"never terminated")
|
|
time.sleep(0.3)
|
|
c1.close()
|
|
c1 = None
|
|
got = drain(c0, 1.0)
|
|
want = b"server: client 1 just left\n"
|
|
if got != want:
|
|
return False, f"got {got!r}, want {want!r} (leftover partial must be dropped)"
|
|
return True, "partial line dropped on disconnect; 'left' broadcast sent"
|
|
finally:
|
|
close_all(c0, c1)
|
|
srv.stop()
|
|
|
|
|
|
def t_ids_increment(binary):
|
|
srv = Server(binary)
|
|
port = srv.start()
|
|
c0 = c1 = c2 = None
|
|
try:
|
|
c0 = connect(port)
|
|
c1 = connect(port)
|
|
drain(c0, 0.5)
|
|
c1.close()
|
|
c1 = None
|
|
drain(c0, 0.4)
|
|
c2 = connect(port)
|
|
got = drain(c0)
|
|
want = b"server: client 2 just arrived\n"
|
|
if got != want:
|
|
return False, f"got {got!r}, want {want!r} (id must not be reused)"
|
|
return True, "ids increment forever, never reused"
|
|
finally:
|
|
close_all(c0, c1, c2)
|
|
srv.stop()
|
|
|
|
|
|
def t_ctrl_d_is_data(binary):
|
|
srv = Server(binary)
|
|
port = srv.start()
|
|
c0 = c1 = None
|
|
try:
|
|
c0, c1 = connect(port), connect(port)
|
|
drain(c0, 0.5)
|
|
c1.sendall(b"a\x04b\n")
|
|
got = drain(c0)
|
|
want = b"client 1: a\x04b\n"
|
|
if got != want:
|
|
return False, f"got {got!r}, want {want!r}"
|
|
return True, "0x04 relayed as plain data"
|
|
finally:
|
|
close_all(c0, c1)
|
|
srv.stop()
|
|
|
|
|
|
def t_big_line(binary):
|
|
srv = Server(binary)
|
|
port = srv.start()
|
|
c0 = c1 = None
|
|
col = None
|
|
try:
|
|
c0, c1 = connect(port), connect(port)
|
|
drain(c0, 0.5)
|
|
payload = b"y" * 400000 + b"\n"
|
|
want = b"client 1: " + payload
|
|
col = Collector(c0)
|
|
col.start()
|
|
c1.sendall(payload)
|
|
deadline = time.time() + 10
|
|
while time.time() < deadline and col.data != want:
|
|
time.sleep(0.05)
|
|
col.stop()
|
|
if col.data != want:
|
|
return False, f"got {len(col.data)} bytes, want {len(want)}"
|
|
return True, "400 KB single line relayed intact"
|
|
finally:
|
|
if col:
|
|
col.stop()
|
|
close_all(c0, c1)
|
|
srv.stop()
|
|
|
|
|
|
def t_no_newline_dropped(binary):
|
|
srv = Server(binary)
|
|
port = srv.start()
|
|
c0 = c1 = None
|
|
try:
|
|
c0, c1 = connect(port), connect(port)
|
|
drain(c0, 0.5)
|
|
c1.sendall(b"z" * 10000)
|
|
time.sleep(0.4)
|
|
c1.close()
|
|
c1 = None
|
|
got = drain(c0, 1.0)
|
|
want = b"server: client 1 just left\n"
|
|
if got != want:
|
|
return False, f"got {got[:120]!r}..., want {want!r}"
|
|
return True, "10 KB no-newline payload buffered then dropped"
|
|
finally:
|
|
close_all(c0, c1)
|
|
srv.stop()
|
|
|
|
|
|
def t_many_clients(binary):
|
|
srv = Server(binary)
|
|
port = srv.start()
|
|
clients = []
|
|
try:
|
|
clients.append(connect(port))
|
|
for _ in range(24):
|
|
clients.append(connect(port))
|
|
time.sleep(0.02)
|
|
want_arr = b"".join(b"server: client %d just arrived\n" % i
|
|
for i in range(1, 25))
|
|
got = drain(clients[0], 1.5)
|
|
if got != want_arr:
|
|
return False, f"arrivals mismatch: {len(got)} bytes vs {len(want_arr)} expected"
|
|
for c in clients[1:]:
|
|
c.close()
|
|
time.sleep(0.12)
|
|
want_left = b"".join(b"server: client %d just left\n" % i
|
|
for i in range(1, 25))
|
|
got = drain(clients[0], 2.0)
|
|
if got != want_left:
|
|
return False, f"departures mismatch: {len(got)} bytes vs {len(want_left)} expected"
|
|
return True, "25 clients: arrivals and departures in order"
|
|
finally:
|
|
close_all(*clients)
|
|
srv.stop()
|
|
|
|
|
|
def t_lazy_client(binary):
|
|
"""c0 never reads while others chat. The server must not drop c0, must not
|
|
lose data for it, and must stay responsive."""
|
|
srv = Server(binary)
|
|
port = srv.start()
|
|
c0 = c1 = c2 = None
|
|
try:
|
|
n = 500
|
|
chunk1 = (b"client 1: " + b"a" * 40 + b"\n") * n
|
|
chunk2 = (b"client 2: " + b"b" * 40 + b"\n") * n
|
|
c0 = connect(port) # lazy: never reads until the end
|
|
c1 = connect(port)
|
|
time.sleep(0.25) # server sends arrival to c0
|
|
c1.sendall((b"a" * 40 + b"\n") * n)
|
|
time.sleep(0.4)
|
|
c2 = connect(port)
|
|
time.sleep(0.25)
|
|
c2.sendall((b"b" * 40 + b"\n") * n + b"final\n")
|
|
time.sleep(0.4)
|
|
c0.sendall(b"ping\n")
|
|
time.sleep(0.25)
|
|
exp_c0 = (b"server: client 1 just arrived\n"
|
|
+ chunk1
|
|
+ b"server: client 2 just arrived\n"
|
|
+ chunk2
|
|
+ b"client 2: final\n")
|
|
exp_c1 = (b"server: client 2 just arrived\n"
|
|
+ chunk2
|
|
+ b"client 2: final\n"
|
|
+ b"client 0: ping\n")
|
|
exp_c2 = b"client 0: ping\n"
|
|
got0, got1, got2 = drain(c0, 3.0), drain(c1, 1.0), drain(c2, 0.5)
|
|
if got0 != exp_c0:
|
|
return False, f"lazy client c0: {len(got0)} bytes, want {len(exp_c0)}"
|
|
if got1 != exp_c1:
|
|
return False, f"c1: {len(got1)} bytes, want {len(exp_c1)}"
|
|
if got2 != exp_c2:
|
|
return False, f"c2: {got2!r}, want {exp_c2!r}"
|
|
if srv.proc.poll() is not None:
|
|
return False, "server died during the scenario"
|
|
return True, "lazy client kept, no data lost, server alive"
|
|
finally:
|
|
close_all(c0, c1, c2)
|
|
srv.stop()
|
|
|
|
|
|
def t_fd_leaks(binary):
|
|
srv = Server(binary)
|
|
port = srv.start()
|
|
socks = []
|
|
try:
|
|
fd_dir = f"/proc/{srv.proc.pid}/fd"
|
|
base = len(os.listdir(fd_dir))
|
|
for _ in range(10):
|
|
socks.append(connect(port))
|
|
time.sleep(0.05)
|
|
time.sleep(0.3)
|
|
for s in socks:
|
|
s.close()
|
|
time.sleep(0.25)
|
|
socks = []
|
|
time.sleep(0.5)
|
|
now = len(os.listdir(fd_dir))
|
|
if now > base + 2:
|
|
return False, f"fds before={base}, after={now} — looks like a leak"
|
|
return True, f"fds stable ({base} -> {now})"
|
|
finally:
|
|
close_all(*socks)
|
|
srv.stop()
|
|
|
|
|
|
TESTS = [
|
|
("args: no argument -> exit 1 + 'Wrong number of arguments\\n'", t_bad_args),
|
|
("bind failure -> exit 1 + 'Fatal error\\n'", t_bind_failure),
|
|
("connect: arrival broadcast goes to others only", t_arrivals),
|
|
("chat: relay to others, one prefix per line", t_chat),
|
|
("chat: line split across packets is reassembled", t_split_line),
|
|
("disconnect: partial line is dropped, not flushed", t_no_flush_on_eof),
|
|
("ids increment, never reused", t_ids_increment),
|
|
("0x04 byte is data, not EOF", t_ctrl_d_is_data),
|
|
("400 KB single line relayed intact", t_big_line),
|
|
("10 KB line without newline: dropped on disconnect", t_no_newline_dropped),
|
|
("25 clients: arrivals and departures in order", t_many_clients),
|
|
("lazy client: kept connected, no data loss", t_lazy_client),
|
|
("fd leak check after connect/disconnect churn", t_fd_leaks),
|
|
]
|
|
|
|
QUICK_SKIP = {"400 KB single line relayed intact",
|
|
"25 clients: arrivals and departures in order",
|
|
"lazy client: kept connected, no data loss"}
|
|
|
|
|
|
def main():
|
|
ap = argparse.ArgumentParser(description="mini_serv behavioral tester")
|
|
ap.add_argument("binary", help="compiled mini_serv executable")
|
|
ap.add_argument("--quick", action="store_true",
|
|
help="skip the heavy 400 KB / 25-client / lazy-client tests")
|
|
args = ap.parse_args()
|
|
|
|
if not os.path.exists(args.binary):
|
|
print(f"binary not found: {args.binary}")
|
|
return 2
|
|
|
|
failures = 0
|
|
for name, fn in TESTS:
|
|
if args.quick and name in QUICK_SKIP:
|
|
print(f"[SKIP] {name}")
|
|
continue
|
|
t0 = time.time()
|
|
try:
|
|
ok, msg = fn(args.binary)
|
|
except Exception as exc: # noqa: BLE001
|
|
ok, msg = False, f"tester exception: {exc!r}"
|
|
dt = time.time() - t0
|
|
print(f"[{PASS if ok else FAIL}] {name} ({dt:.1f}s)")
|
|
print(f" {msg}")
|
|
if not ok:
|
|
failures += 1
|
|
|
|
print()
|
|
if failures:
|
|
print(f"{failures} test(s) failed.")
|
|
else:
|
|
print("all tests passed.")
|
|
return 1 if failures else 0
|
|
|
|
|
|
if __name__ == "__main__":
|
|
sys.exit(main())
|