import asyncio import struct from hbd.client import gateway PROC_V4 = ( "Iface\tDestination\tGateway \tFlags\tRefCnt\tUse\tMetric\tMask\t\tMTU\tWindow\tIRTT\n" "wlan0\t00000000\t0100A8C0\t0003\t0\t0\t600\t00000000\t0\t0\t0\n" "eth0\t00000000\t0101A8C0\t0003\t0\t0\t100\t00000000\t0\t0\t0\n" "wlan0\t0000A8C0\t00000000\t0001\t0\t0\t600\t00FFFFFF\t0\t0\t0\n" ) PROC_V6 = ( "00000000000000000000000000000000 00 00000000000000000000000000000000 00 " "fe800000000000000000000000000001 00000400 00000001 00000000 00000003 wlan0\n" "00000000000000000000000000000000 00 00000000000000000000000000000000 00 " "00000000000000000000000000000000 ffffffff 00000001 00000000 00200200 lo\n" "fe800000000000000000000000000000 40 00000000000000000000000000000000 00 " "00000000000000000000000000000000 00000100 00000001 00000000 00000001 wlan0\n" ) MACOS = """ route to: default destination: default mask: default gateway: 192.168.1.1 interface: en0 """ WIN_V4 = """IPv4 Route Table Active Routes: Network Destination Netmask Gateway Interface Metric 0.0.0.0 0.0.0.0 192.168.1.1 192.168.1.50 25 0.0.0.0 0.0.0.0 10.0.0.1 10.0.0.9 50 127.0.0.0 255.0.0.0 On-link 127.0.0.1 331 """ WIN_V6 = """IPv6 Route Table Active Routes: If Metric Network Destination Gateway 12 281 ::/0 fe80::1 1 331 ::1/128 On-link """ def test_proc_v4_picks_lowest_metric_gateway(): assert gateway.parse_proc_route_v4(PROC_V4) == "192.168.1.1" # eth0, metric 100 def test_proc_v4_none_without_default_route(): assert gateway.parse_proc_route_v4(PROC_V4.splitlines()[0] + "\n") is None def test_proc_v6_skips_reject_and_non_default(): assert gateway.parse_proc_route_v6(PROC_V6) == "fe80::1" def test_macos(): assert gateway.parse_macos_route(MACOS) == "192.168.1.1" assert gateway.parse_macos_route("route: writing to routing socket: not in table") is None def test_windows_v4_lowest_metric(): assert gateway.parse_windows_route(WIN_V4, "ipv4") == "192.168.1.1" def test_windows_v6(): assert gateway.parse_windows_route(WIN_V6, "ipv6") == "fe80::1" def test_default_gateway_never_raises_on_parser_error(monkeypatch): """default_gateway catches all exceptions; never raises even if parser fails.""" monkeypatch.setattr("sys.platform", "linux") monkeypatch.setattr(gateway, "parse_proc_route_v4", lambda _: (_ for _ in ()).throw(struct.error)) result = asyncio.run(gateway.default_gateway("ipv4")) assert result is None