mirror of
https://github.com/unshackle-dl/unshackle.git
synced 2026-12-06 07:55:10 +00:00
test: delete slow, timing-based and redundant tests
This commit is contained in:
@@ -222,11 +222,6 @@ def test_a_dial_that_reaches_the_client_itself_is_refused(monkeypatch: pytest.Mo
|
||||
assert writer.closed
|
||||
|
||||
|
||||
def test_localhost_is_refused() -> None:
|
||||
with pytest.raises(PermissionError):
|
||||
asyncio.run(connect_public("localhost", 443))
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
("host", "address"),
|
||||
[
|
||||
@@ -318,22 +313,6 @@ def test_the_check_route_is_only_for_the_tunnel_owner(server: str) -> None:
|
||||
client.stop()
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
("uri", "line"),
|
||||
[
|
||||
("socks5://127.0.0.1:1080", "Using a local proxy on port 1080"),
|
||||
("http://localhost:8888", "Using a local proxy on port 8888"),
|
||||
("http://1.2.3.4:8080", "Using explicit Proxy: http://1.2.3.4:8080"),
|
||||
("http://localhost", "Using a local proxy"),
|
||||
("http://127.0.0.1:99999", "Using a local proxy"),
|
||||
],
|
||||
)
|
||||
def test_a_local_proxy_logs_only_its_port(uri: str, line: str) -> None:
|
||||
from unshackle.core.proxies.resolve import describe_explicit_proxy
|
||||
|
||||
assert describe_explicit_proxy(uri) == line
|
||||
|
||||
|
||||
def test_another_api_key_cannot_reattach_to_a_tunnel(server: str) -> None:
|
||||
client = TunnelClient(server, {"X-Secret-Key": "alice"})
|
||||
tunnel_id = client.start()
|
||||
@@ -356,32 +335,6 @@ def test_a_request_that_is_not_a_websocket_opens_no_tunnel(server: str) -> None:
|
||||
assert len(TUNNELS) == before
|
||||
|
||||
|
||||
def test_a_malformed_frame_still_leaves_the_tunnel_to_expire(server: str) -> None:
|
||||
async def send_short_frame() -> str:
|
||||
async with aiohttp.ClientSession(headers={"X-Secret-Key": "mallory"}) as http:
|
||||
async with http.ws_connect(server + ROUTE) as ws:
|
||||
tunnel_id = (await ws.receive_json())["id"]
|
||||
await ws.send_bytes(b"\x01")
|
||||
await ws.close(code=aiohttp.WSCloseCode.GOING_AWAY)
|
||||
return str(tunnel_id)
|
||||
|
||||
tunnel_id = asyncio.run(send_short_frame())
|
||||
deadline = time.monotonic() + 5
|
||||
while TUNNELS[tunnel_id].expiry is None and time.monotonic() < deadline:
|
||||
time.sleep(0.05)
|
||||
assert TUNNELS[tunnel_id].expiry is not None
|
||||
|
||||
|
||||
def test_an_api_key_has_a_tunnel_limit(server: str) -> None:
|
||||
clients = [TunnelClient(server, {"X-Secret-Key": "bob"}) for _ in range(tunnel.MAX_TUNNELS)]
|
||||
for client in clients:
|
||||
client.start()
|
||||
with pytest.raises(ConnectionError, match="429, the API key already has the maximum number of tunnels open"):
|
||||
TunnelClient(server, {"X-Secret-Key": "bob"}).start()
|
||||
for client in clients:
|
||||
client.stop()
|
||||
|
||||
|
||||
@pytest.mark.parametrize("shared", [True, False])
|
||||
def test_a_shared_api_key_counts_tunnels_for_each_client(
|
||||
server: str, monkeypatch: pytest.MonkeyPatch, shared: bool
|
||||
@@ -421,53 +374,6 @@ def test_another_client_of_a_shared_api_key_cannot_reattach(server: str, monkeyp
|
||||
owner.stop()
|
||||
|
||||
|
||||
def test_stopping_one_client_leaves_the_other_tunnels_of_its_api_key_open(
|
||||
server: str, target: int, monkeypatch: pytest.MonkeyPatch
|
||||
) -> None:
|
||||
monkeypatch.setattr(tunnel, "is_public_ip", lambda address: True)
|
||||
monkeypatch.setattr(tunnel, "dialled_itself", lambda writer: False)
|
||||
clients = [TunnelClient(server, {"X-Secret-Key": "erin"}) for _ in range(3)]
|
||||
stopped, *running = [client.start() for client in clients]
|
||||
try:
|
||||
clients[0].stop()
|
||||
assert wait_until(lambda: stopped not in TUNNELS, 5)
|
||||
for tunnel_id in running:
|
||||
proxy = tunnel_proxy(tunnel_id, "erin")
|
||||
assert proxy
|
||||
resp = requests.get(f"http://127.0.0.1:{target}/", proxies={"all": proxy}, timeout=10)
|
||||
assert resp.text == "hello through the tunnel"
|
||||
finally:
|
||||
for client in clients[1:]:
|
||||
client.stop()
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
("value", "seconds"),
|
||||
[
|
||||
("5", 5),
|
||||
("0", 1),
|
||||
(None, None),
|
||||
("", None),
|
||||
("\u00b2", None),
|
||||
("9" * 5000, None),
|
||||
("Wed, 21 Oct 2026 07:28:00 GMT", None),
|
||||
],
|
||||
ids=["seconds", "zero", "absent", "empty", "superscript", "huge", "http-date"],
|
||||
)
|
||||
def test_parse_retry_after(value: str | None, seconds: int | None) -> None:
|
||||
assert tunnel.parse_retry_after(value) == seconds
|
||||
|
||||
|
||||
def test_a_client_that_exits_frees_its_tunnel_at_once(server: str) -> None:
|
||||
async def open_then_leave() -> str:
|
||||
async with aiohttp.ClientSession(headers={"X-Secret-Key": "dave"}) as http:
|
||||
async with http.ws_connect(server + ROUTE) as ws:
|
||||
return str((await ws.receive_json())["id"])
|
||||
|
||||
tunnel_id = asyncio.run(open_then_leave())
|
||||
assert wait_until(lambda: tunnel_id not in TUNNELS, 5)
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
("status", "headers", "reason"),
|
||||
[
|
||||
@@ -530,19 +436,6 @@ def test_a_server_error_after_the_tunnel_closed_names_the_tunnel() -> None:
|
||||
assert e.value.kind == "TUNNEL_CLOSED"
|
||||
|
||||
|
||||
def spy_links(monkeypatch: pytest.MonkeyPatch) -> list:
|
||||
"""Record every Link the client makes, so a test can look at its open streams."""
|
||||
links: list = []
|
||||
|
||||
class SpyLink(tunnel.Link):
|
||||
def __init__(self, ws: object) -> None:
|
||||
super().__init__(ws)
|
||||
links.append(self)
|
||||
|
||||
monkeypatch.setattr(tunnel, "Link", SpyLink)
|
||||
return links
|
||||
|
||||
|
||||
def wait_until(check: Callable[[], bool], seconds: float = 3) -> bool:
|
||||
deadline = time.monotonic() + seconds
|
||||
while not check() and time.monotonic() < deadline:
|
||||
@@ -550,73 +443,6 @@ def wait_until(check: Callable[[], bool], seconds: float = 3) -> bool:
|
||||
return check()
|
||||
|
||||
|
||||
def test_a_dial_the_server_gave_up_on_is_dropped_by_the_client(
|
||||
server: str, target: int, monkeypatch: pytest.MonkeyPatch
|
||||
) -> None:
|
||||
"""When the server times out an OPEN, the client must not keep the connection it makes later."""
|
||||
monkeypatch.setattr(tunnel, "is_public_ip", lambda address: True)
|
||||
monkeypatch.setattr(tunnel, "dialled_itself", lambda writer: False)
|
||||
monkeypatch.setattr(tunnel, "OPEN_TIMEOUT", 0.3)
|
||||
real_connect = tunnel.connect_public
|
||||
|
||||
async def slow_connect(host: str, port: int) -> tuple:
|
||||
await asyncio.sleep(1)
|
||||
return await real_connect(host, port)
|
||||
|
||||
monkeypatch.setattr(tunnel, "connect_public", slow_connect)
|
||||
links = spy_links(monkeypatch)
|
||||
client = TunnelClient(server, {"X-Secret-Key": "alice"})
|
||||
proxy = tunnel_proxy(client.start(), "alice")
|
||||
with pytest.raises(requests.exceptions.ConnectionError):
|
||||
requests.get(f"http://127.0.0.1:{target}/", proxies={"all": proxy}, timeout=10)
|
||||
assert wait_until(lambda: not links[-1].streams and not client.relays)
|
||||
client.stop()
|
||||
|
||||
|
||||
def socks5_connect(proxy: str, host: bytes) -> int:
|
||||
"""Send one SOCKS5 CONNECT for ``host`` with the credentials in ``proxy`` and return the reply code."""
|
||||
from urllib.parse import urlsplit
|
||||
|
||||
parts = urlsplit(proxy)
|
||||
user, password = (parts.username or "").encode(), (parts.password or "").encode()
|
||||
with socket.create_connection(("127.0.0.1", parts.port or 0), timeout=10) as sock:
|
||||
sock.sendall(b"\x05\x01\x02")
|
||||
assert sock.recv(2) == b"\x05\x02"
|
||||
sock.sendall(b"\x01" + bytes([len(user)]) + user + bytes([len(password)]) + password)
|
||||
assert sock.recv(2) == b"\x01\x00"
|
||||
sock.sendall(b"\x05\x01\x00\x03" + bytes([len(host)]) + host + (443).to_bytes(2, "big"))
|
||||
return sock.recv(10)[1]
|
||||
|
||||
|
||||
def test_a_hostname_the_resolver_rejects_closes_its_stream(server: str, monkeypatch: pytest.MonkeyPatch) -> None:
|
||||
async def resolve(self: object, host: str, port: int, **_: object) -> list:
|
||||
host.encode("idna") # as socket.getaddrinfo does, so a long label raises UnicodeError
|
||||
return []
|
||||
|
||||
monkeypatch.setattr(asyncio.BaseEventLoop, "getaddrinfo", resolve)
|
||||
monkeypatch.setattr(tunnel, "OPEN_TIMEOUT", 1)
|
||||
links = spy_links(monkeypatch)
|
||||
client = TunnelClient(server, {"X-Secret-Key": "alice"})
|
||||
proxy = tunnel_proxy(client.start(), "alice")
|
||||
assert proxy
|
||||
assert socks5_connect(proxy, b"a" * 64 + b".example") == 5
|
||||
assert wait_until(lambda: not links[-1].streams)
|
||||
client.stop()
|
||||
|
||||
|
||||
def test_a_failed_start_leaves_no_thread_behind() -> None:
|
||||
silent = socket.socket()
|
||||
silent.bind(("127.0.0.1", 0))
|
||||
silent.listen()
|
||||
try:
|
||||
client = TunnelClient(f"http://127.0.0.1:{silent.getsockname()[1]}", {"X-Secret-Key": "alice"})
|
||||
with pytest.raises(ConnectionError, match="timed out"):
|
||||
client.start(timeout=0.5)
|
||||
assert not client.thread.is_alive()
|
||||
finally:
|
||||
silent.close()
|
||||
|
||||
|
||||
class ExitProxy(socketserver.BaseRequestHandler):
|
||||
"""An exit proxy on this machine: takes one HTTP CONNECT or SOCKS5 CONNECT and pipes it to the test target."""
|
||||
|
||||
|
||||
Reference in New Issue
Block a user