core: add all the required files
This commit is contained in:
Executable
+60
@@ -0,0 +1,60 @@
|
||||
#!/usr/bin/env bash
|
||||
# One-shot check for mini_serv:
|
||||
# [1/3] strict compile (-Wall -Wextra -Werror)
|
||||
# [2/3] behavioral tester (13 checks, offline)
|
||||
# [3/3] the real exam-style Grademe diff
|
||||
#
|
||||
# Usage: bash tester/check.sh [path/to/mini_serv.c]
|
||||
# Default source: sandbox/rendu/mini_serv/mini_serv.c
|
||||
#
|
||||
# Env: SKIP_GRADEME=1 -> stop after the behavioral tester
|
||||
set -u
|
||||
ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
|
||||
SRC="${1:-$ROOT/sandbox/rendu/mini_serv/mini_serv.c}"
|
||||
BIN="$ROOT/sandbox/mini_serv"
|
||||
|
||||
if [ ! -f "$SRC" ]; then
|
||||
echo "No source file at: $SRC"
|
||||
echo "Write your mini_serv.c there (exact filename matters), or pass a path."
|
||||
exit 2
|
||||
fi
|
||||
|
||||
echo "== [1/3] strict compile: cc -Wall -Wextra -Werror =="
|
||||
mkdir -p "$ROOT/sandbox"
|
||||
if ! cc -Wall -Wextra -Werror -g "$SRC" -o "$BIN"; then
|
||||
echo "COMPILE FAILED."
|
||||
exit 1
|
||||
fi
|
||||
echo "OK -> $BIN"
|
||||
|
||||
echo
|
||||
echo "== [2/3] behavioral tester =="
|
||||
if ! python3 "$ROOT/tester/mini_serv_tester.py" "$BIN"; then
|
||||
echo
|
||||
echo "Behavioral tests FAILED — fix and run again."
|
||||
exit 1
|
||||
fi
|
||||
|
||||
if [ "${SKIP_GRADEME:-0}" = "1" ]; then
|
||||
echo
|
||||
echo "SKIP_GRADEME=1 -> stopping here. All green so far."
|
||||
exit 0
|
||||
fi
|
||||
|
||||
echo
|
||||
echo "== [3/3] grademe final boss (exact exam-style diff, ~25s) =="
|
||||
cd "$ROOT/sandbox" || exit 1
|
||||
rm -f traceback .system/grading/passed
|
||||
bash .system/grading/tester.sh
|
||||
if [ -f .system/grading/passed ]; then
|
||||
echo "GRADEME: PASSED"
|
||||
echo
|
||||
echo "ALL GREEN. Now: close this, start from a blank file, and do it again."
|
||||
else
|
||||
echo "GRADEME: FAILED"
|
||||
echo "See sandbox/traceback (expected vs your output). First lines:"
|
||||
if [ -f traceback ]; then
|
||||
sed -n '1,40p' traceback
|
||||
fi
|
||||
exit 1
|
||||
fi
|
||||
@@ -0,0 +1,10 @@
|
||||
#!/bin/bash
|
||||
|
||||
# close fd before init
|
||||
exec 6<&-
|
||||
exec 6</dev/tcp/127.0.0.1/"$1"
|
||||
|
||||
while read -r <&6
|
||||
do
|
||||
echo "$REPLY"
|
||||
done
|
||||
@@ -0,0 +1,5 @@
|
||||
Ceci est un test de Ctrl+D dans ton programme ici:\04Si tu ne passes pas ce test, tu devrais verifier le fonctionnement du ctrl+d.
|
||||
voici
|
||||
un
|
||||
nouveau
|
||||
test
|
||||
@@ -0,0 +1,29 @@
|
||||
#!/bin/bash
|
||||
# Print the first free TCP port in [first_port, last_port]
|
||||
# (default: a random start in 8888-9887, so back-to-back runs use other ports).
|
||||
# Works with ss (Linux), lsof (macOS/Linux) or netstat, whichever is installed.
|
||||
|
||||
first_port=${1:-$((8888 + RANDOM % 1000))}
|
||||
last_port=${2:-$((first_port + 1000))}
|
||||
|
||||
port_in_use()
|
||||
{
|
||||
if command -v ss >/dev/null 2>&1; then
|
||||
ss -tuln 2>/dev/null | grep -q "[.:]$1 "
|
||||
elif command -v lsof >/dev/null 2>&1; then
|
||||
lsof -nP -iTCP:"$1" -sTCP:LISTEN >/dev/null 2>&1
|
||||
elif command -v netstat >/dev/null 2>&1; then
|
||||
netstat -an 2>/dev/null | grep -E "[.:]$1 " | grep -q LISTEN
|
||||
else
|
||||
# last resort: something accepts connections on this port
|
||||
(exec 3<>"/dev/tcp/127.0.0.1/$1") 2>/dev/null
|
||||
fi
|
||||
}
|
||||
|
||||
for ((port = first_port; port <= last_port; port++)); do
|
||||
if ! port_in_use "$port"; then
|
||||
echo "$port"
|
||||
exit 0
|
||||
fi
|
||||
done
|
||||
echo 0
|
||||
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
@@ -0,0 +1,17 @@
|
||||
#!/bin/bash
|
||||
# usage: bash test_eof.sh <port>
|
||||
# Sends eof_test one word at a time (with a literal ^D inside) on one connection.
|
||||
|
||||
PORT=$1
|
||||
|
||||
send_msg()
|
||||
{
|
||||
exec 3<>"/dev/tcp/127.0.0.1/$PORT" || return 1
|
||||
cat >&3
|
||||
exec 3>&-
|
||||
}
|
||||
|
||||
for x in $(cat eof_test); do
|
||||
printf "$x"
|
||||
sleep 0.1
|
||||
done | send_msg
|
||||
@@ -0,0 +1,125 @@
|
||||
#!/bin/bash
|
||||
# usage: bash test_miniserv.sh <port> (run from .system/grading)
|
||||
# Starts the student's server, connects a listener (catchmsg.sh) and several
|
||||
# short-lived clients, then stores everything the listener received in `bim`.
|
||||
# Only uses bash's /dev/tcp, so it does not depend on the installed nc flavor.
|
||||
|
||||
PORT=$1
|
||||
rm -f bim trace final
|
||||
|
||||
fail()
|
||||
{
|
||||
{
|
||||
echo "----------------8<-------------[ START TEST "
|
||||
printf "%b" "$1"
|
||||
echo "----------------8<------------- END TEST ]"
|
||||
} >> traceback
|
||||
}
|
||||
|
||||
send_msg()
|
||||
{
|
||||
exec 3<>"/dev/tcp/127.0.0.1/$PORT" || return 1
|
||||
cat >&3
|
||||
exec 3>&-
|
||||
}
|
||||
|
||||
# 0 = listening, 1 = not listening, 2 = no tool available to check
|
||||
port_listening()
|
||||
{
|
||||
if command -v ss >/dev/null 2>&1; then
|
||||
ss -tln 2>/dev/null | grep -q "[.:]$PORT "
|
||||
elif command -v lsof >/dev/null 2>&1; then
|
||||
lsof -nP -iTCP:"$PORT" -sTCP:LISTEN >/dev/null 2>&1
|
||||
elif command -v netstat >/dev/null 2>&1; then
|
||||
netstat -an 2>/dev/null | grep -E "[.:]$PORT " | grep -q LISTEN
|
||||
else
|
||||
return 2
|
||||
fi
|
||||
}
|
||||
|
||||
CC=$(command -v clang || command -v cc || command -v gcc)
|
||||
if ! "$CC" -o final ../../rendu/mini_serv/mini_serv.c > trace 2>&1 || [ ! -e final ]; then
|
||||
fail " 🔎 YOUR OUTPUT:\n$(cat trace)\n ❌ COMPILATION ERROR\n"
|
||||
exit 1
|
||||
fi
|
||||
|
||||
SERVER=""
|
||||
CATCH=""
|
||||
|
||||
cleanup()
|
||||
{
|
||||
# stop the server first: the listener then reads EOF and flushes `bim`
|
||||
[ -n "$SERVER" ] && kill "$SERVER" 2>/dev/null
|
||||
[ -n "$SERVER" ] && wait "$SERVER" 2>/dev/null
|
||||
if [ -n "$CATCH" ]; then
|
||||
for _ in $(seq 1 20); do
|
||||
kill -0 "$CATCH" 2>/dev/null || break
|
||||
sleep 0.1
|
||||
done
|
||||
kill "$CATCH" 2>/dev/null
|
||||
wait "$CATCH" 2>/dev/null
|
||||
fi
|
||||
}
|
||||
trap cleanup EXIT
|
||||
|
||||
# start the server and wait (max 3s) until it listens
|
||||
# 0 = listening, 1 = never listened, 2 = the process exited (e.g. bind failed)
|
||||
start_server()
|
||||
{
|
||||
./final "$PORT" > /dev/null 2>&1 &
|
||||
SERVER=$!
|
||||
for _ in $(seq 1 30); do
|
||||
port_listening
|
||||
case $? in
|
||||
0) return 0 ;;
|
||||
2) sleep 1; kill -0 "$SERVER" 2>/dev/null && return 0 || return 2 ;;
|
||||
esac
|
||||
kill -0 "$SERVER" 2>/dev/null || return 2
|
||||
sleep 0.1
|
||||
done
|
||||
return 1
|
||||
}
|
||||
|
||||
# A port can still be busy (TIME_WAIT) right after a previous run, which
|
||||
# makes bind() fail: if the server exits at startup, retry on other ports.
|
||||
attempt=1
|
||||
while true; do
|
||||
start_server
|
||||
status=$?
|
||||
[ $status -eq 0 ] && break
|
||||
kill "$SERVER" 2>/dev/null
|
||||
wait "$SERVER" 2>/dev/null
|
||||
SERVER=""
|
||||
if [ $status -eq 1 ] || [ $attempt -ge 5 ]; then
|
||||
fail " ❌ PORT IS NOT OPEN \n 💻 TEST\n./a.out $PORT\n Connecting after the server is started\n Cannot connect to port $PORT\n"
|
||||
exit 1
|
||||
fi
|
||||
attempt=$((attempt + 1))
|
||||
PORT=$(bash findport.sh $((PORT + 1)))
|
||||
done
|
||||
|
||||
bash catchmsg.sh "$PORT" >> bim &
|
||||
CATCH=$!
|
||||
sleep 1
|
||||
|
||||
echo "Si vous ne voyez QUE ce message, c'est mauvais signe." | send_msg
|
||||
sleep 0.2
|
||||
echo "Bienvenue sur le test de votre miniserv" | send_msg
|
||||
sleep 0.2
|
||||
echo "Ceci est un message" | send_msg
|
||||
sleep 0.2
|
||||
printf "Voici un texte sans retour a la ligne" | send_msg
|
||||
sleep 0.2
|
||||
echo -n "This is a text without backline at the end" | send_msg
|
||||
sleep 0.4
|
||||
printf "Et voici un texte avec plusieurs\nretours\na\nla\nligne\n" | send_msg
|
||||
sleep 0.2
|
||||
|
||||
bash test_eof.sh "$PORT"
|
||||
sleep 1
|
||||
|
||||
send_msg < very_long_msg.txt
|
||||
sleep 1
|
||||
|
||||
send_msg < other_long_msg.txt
|
||||
sleep 2
|
||||
@@ -0,0 +1,40 @@
|
||||
#!/bin/bash
|
||||
cd .system/grading/
|
||||
# if there is a traceback file then remove it
|
||||
if [ -e traceback ]; then
|
||||
rm traceback
|
||||
fi
|
||||
|
||||
echo "Test may be long, please wait..."
|
||||
|
||||
# for port in $(seq 4444 65000); do echo -ne "\035" | telnet 127.0.0.1 $port > /dev/null 2>&1; [ $? -eq 1 ] && break; done
|
||||
|
||||
PORT=$(bash findport.sh)
|
||||
|
||||
bash test_miniserv.sh $PORT &> /dev/null 2>&1
|
||||
|
||||
# if there is a final file and there is not a traceback file then the diff is check
|
||||
if [ -e final ] && [ ! -e traceback ]; then
|
||||
|
||||
DIFF=$(diff bim normal.output)
|
||||
if [ "$DIFF" != "" ]
|
||||
then
|
||||
|
||||
echo "----------------8<-------------[ START TEST " >> traceback
|
||||
printf " 💻 TEST\n./a.out $PORT\n" >> traceback
|
||||
printf " Then there is 3 connexion to the server\n" >> traceback
|
||||
printf " 🔎 YOUR OUTPUT:\n" >> traceback
|
||||
cat bim >> traceback
|
||||
printf " 🗝 EXPECTED OUTPUT:\n" >> traceback
|
||||
cat normal.output >> traceback
|
||||
echo "----------------8<------------- END TEST ]" >> traceback
|
||||
mv traceback ../../traceback
|
||||
cd ../../
|
||||
exit 1
|
||||
fi
|
||||
|
||||
touch passed
|
||||
else
|
||||
mv traceback ../../traceback
|
||||
fi
|
||||
cd ../../
|
||||
File diff suppressed because one or more lines are too long
Executable
+512
@@ -0,0 +1,512 @@
|
||||
#!/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())
|
||||
Reference in New Issue
Block a user