Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions newsfragments/3493.bugfix.rst
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
Allow importing Trio on Android API levels where ``socket.if_indextoname`` and ``socket.if_nametoindex`` are unavailable.
28 changes: 28 additions & 0 deletions src/trio/_tests/test_socket.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
import inspect
import os
import socket as stdlib_socket
import subprocess
import sys
import tempfile
from pathlib import Path
Expand Down Expand Up @@ -167,6 +168,33 @@ def test_socket_has_some_reexports() -> None:
assert tsocket.ntohs == stdlib_socket.ntohs


def test_imports_without_android_interface_helpers() -> None:
script = """
import socket as real_socket
import sys
import types

fake_socket = types.ModuleType("socket")
fake_socket.__dict__.update(real_socket.__dict__)
del fake_socket.if_indextoname
del fake_socket.if_nametoindex
sys.modules["socket"] = fake_socket

import trio.socket
"""
environment = os.environ.copy()
source_path = str(Path(__file__).parents[2])
environment["PYTHONPATH"] = os.pathsep.join(
[source_path, environment.get("PYTHONPATH", "")]
)
subprocess.run(
[sys.executable, "-c", script],
cwd=Path(__file__).parents[3],
env=environment,
check=True,
)


################################################################
# name resolution
################################################################
Expand Down
10 changes: 6 additions & 4 deletions src/trio/socket.py
Original file line number Diff line number Diff line change
Expand Up @@ -69,10 +69,12 @@
)

if sys.implementation.name == "cpython":
from socket import (
if_indextoname as if_indextoname,
if_nametoindex as if_nametoindex,
)
# These functions are not available on all Android API levels.
with _suppress(ImportError):
from socket import (
if_indextoname as if_indextoname,
if_nametoindex as if_nametoindex,
)

# For android devices, if_nameindex support was introduced in API 24,
# so it doesn't exist for any version prior.
Expand Down