blob: 214242e641e1f790bd018ead17ad954016b74145 [file]
# Copyright 2023 The Fuchsia Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
import asyncio
import collections.abc
import json
import os
import os.path
import struct
import subprocess
import sys
import tempfile
import typing
import unittest
import fidl_fuchsia_controller_test as fc_test
import fidl_fuchsia_developer_ffx as ffx_fidl
from fuchsia_controller_py import (
Channel,
Context,
FcTransportStatus,
IsolateDir,
)
from fidl import AsyncChannel, DomainError
# Default `python_host_test` runner timeout is 300s for the entire test binary;
# keep the per-subprocess timeout at 80s (3 * 80s = 240s) so all three detect
# tests can time out and report partial output within the 300s budget.
_SUBPROCESS_TIMEOUT_SECS = 80
_EXCLUDED_SUBPROCESS_ENV_VARS: frozenset[str] = frozenset(
{
"FFX_LOG_DIR",
"FFX_LOG_ENABLED",
"FUCHSIA_DEVICE_ADDR",
"FUCHSIA_NODENAME",
"FUCHSIA_TEST_OUTDIR",
"PWD",
# Child inline scripts rely on `assert` statements; stripping them via
# `PYTHONOPTIMIZE` would silently turn checks into no-ops.
"PYTHONOPTIMIZE",
}
)
def _format_subprocess_stream(data: bytes | str | None) -> str:
if data is None:
return ""
if isinstance(data, bytes):
return data.decode("utf-8", errors="replace")
return data
def _write_user_config(
tmp_root: str, config: collections.abc.Mapping[str, typing.Any]
) -> None:
if sys.platform == "darwin":
cfg_dir = os.path.join(
tmp_root,
"Library",
"Preferences",
"Fuchsia",
"ffx",
"config",
)
else:
cfg_dir = os.path.join(tmp_root, "config", "Fuchsia", "ffx", "config")
os.makedirs(cfg_dir, exist_ok=True)
with open(
os.path.join(cfg_dir, ".ffx_user_config.json"),
"w",
encoding="utf-8",
) as f:
json.dump(dict(config), f)
def _make_subprocess_env(tmp_root: str) -> dict[str, str]:
python_paths = [os.path.abspath(p) if p else os.getcwd() for p in sys.path]
fc_internal_mod = sys.modules.get("fuchsia_controller_internal")
fc_internal_file = getattr(fc_internal_mod, "__file__", None)
if fc_internal_file:
python_paths.append(os.path.dirname(os.path.abspath(fc_internal_file)))
runtime_dir = os.path.join(tmp_root, "runtime")
return {
k: v
for k, v in os.environ.items()
if k not in _EXCLUDED_SUBPROCESS_ENV_VARS
} | {
"PYTHONPATH": os.pathsep.join(dict.fromkeys(python_paths)),
"HOME": tmp_root,
"XDG_CONFIG_HOME": os.path.join(tmp_root, "config"),
"XDG_CACHE_HOME": os.path.join(tmp_root, "cache"),
"XDG_DATA_HOME": os.path.join(tmp_root, "data"),
"XDG_STATE_HOME": os.path.join(tmp_root, "state"),
# `ffx_config` intentionally reads `XDG_RUNTIME_HOME` (not the standard
# `XDG_RUNTIME_DIR`) in `src/developer/ffx/config/src/paths.rs`.
"XDG_RUNTIME_HOME": runtime_dir,
# Isolate `XDG_RUNTIME_DIR` as well for defaults in `config.json`
# (e.g. `connectivity.usb_socket_path` and `ssh.controlmaster.dir`).
"XDG_RUNTIME_DIR": runtime_dir,
}
class TestSocketServer(fc_test.TestingServer):
def __init__(self, ctx: Context, ch: Channel):
client, server = ctx.socket_create()
self.client = client
self.server = server
super().__init__(ch)
def return_socket_or_error(
self,
) -> fc_test.TestingServer.ReturnSocketOrErrorResponse:
if self.server.as_int() == 0:
return DomainError(FcTransportStatus.FC_ERR_NOT_SUPPORTED)
return fc_test.TestingReturnSocketOrErrorResponse(
reader_thing=self.server.take()
)
def return_union(self) -> fc_test.TestingServer.ReturnUnionResponse:
res = fc_test.TestingReturnUnionResponse(x=10)
return res
def return_union_with_table(
self,
) -> fc_test.TestingServer.ReturnUnionWithTableResponse:
x = fc_test.NoopUnion(union_str="foobar")
res = fc_test.TestingReturnUnionWithTableResponse(x=x)
return res
def return_other_composed_protocol(
self,
) -> fc_test.TestingServer.ReturnOtherComposedProtocolResponse:
return fc_test.TestingReturnOtherComposedProtocolResponse(
client_thing=0
)
def return_possible_error(
self,
) -> fc_test.TestingServer.ReturnPossibleErrorResponse:
return DomainError("not implemented")
def return_possible_error2(
self,
) -> fc_test.TestingServer.ReturnPossibleError2Response:
return DomainError("not implemented")
class EndToEnd(unittest.IsolatedAsyncioTestCase):
def _get_default_config(self) -> typing.Dict[str, str]:
return {}
def _get_isolate_dir(self) -> IsolateDir:
isolation_path = None
tmp_path = os.getenv("TEST_UNDECLARED_OUTPUTS_DIR")
if tmp_path:
isolation_path = os.path.join(tmp_path, "isolate")
return IsolateDir(dir=isolation_path)
def test_config_get_nonexistent(self) -> None:
ctx = Context()
self.addCleanup(ctx.close)
self.assertEqual(ctx.config_get_string("foobarzzzzzzo==?"), None)
def test_config_get_exists(self) -> None:
config = self._get_default_config()
key = "foobar"
expect = "bazmumble"
config[key] = expect
ctx = Context(config=config)
self.addCleanup(ctx.close)
self.assertEqual(ctx.config_get_string(key), expect)
def test_config_get_too_long(self) -> None:
config = self._get_default_config()
key = "foobarzington"
expect = "b" * 50000
config[key] = expect
ctx = Context(config=config)
self.addCleanup(ctx.close)
with self.assertRaises(BufferError):
ctx.config_get_string(key)
async def test_client_sends_message_before_coro_await(self) -> None:
ctx = Context()
(ch0, ch1) = ctx.channel_create()
async_ch1 = AsyncChannel(ch1)
echo_proxy = ffx_fidl.EchoClient(ch0)
coro = echo_proxy.echo_string(value="foo")
buf, _ = await async_ch1.read()
txid = int.from_bytes(buf[0:4], sys.byteorder)
ordinal = next(
ord
for ord, info in ffx_fidl.EchoServer.method_map.items()
if info.name == "echo_string"
)
def encode_message(obj: typing.Any) -> tuple[bytes, list[typing.Any]]:
if obj is not None:
payload, handles = obj.encode()
else:
payload, handles = b"", []
header = struct.pack("<IHBBQ", txid, 0x02, 0x00, 0x01, ordinal)
return header + payload, handles
encoded_bytes, _ = encode_message(
ffx_fidl.EchoEchoStringRequest(value="foo")
)
self.assertEqual(buf, encoded_bytes)
msg = encode_message(
ffx_fidl.EchoEchoStringResponse(response="otherthing")
)
async_ch1.write(msg)
result = await coro
self.assertEqual(result.response, "otherthing")
def test_context_creation_duplicate_target_raises_exception(self) -> None:
configs: list[dict[str, typing.Any]] = [
{"target.default": "bar"},
{"target": {"default": "bar"}},
{"target": "bar"},
{"target.default": None, "target": {"default": "bar"}},
{"target.default": None, "target": "bar"},
]
for cfg in configs:
for factory in (Context, Context.isolated, Context.detect):
with self.assertRaisesRegex(
RuntimeError, "You must only specify one"
):
factory(config=cfg, target="foo")
def test_context_creation_invalid_config_type(self) -> None:
with self.assertRaisesRegex(
TypeError, "`config` must be a dict or None"
):
Context(config="not a dict") # type: ignore
with self.assertRaisesRegex(
TypeError, "`config` must be a dict or None"
):
Context(config=[]) # type: ignore
with self.assertRaisesRegex(
TypeError, "`config` must be a dict or None"
):
Context(config=[], target="foo") # type: ignore
with self.assertRaisesRegex(
TypeError, "`config` must be a dict or None"
):
Context(config="not a dict", target="foo") # type: ignore
with self.assertRaisesRegex(
ValueError, "Out of range float values are not JSON compliant"
):
Context(config={"x": float("nan")})
with self.assertRaisesRegex(
TypeError, "`target` must be a str or None"
):
Context(target=123) # type: ignore
with self.assertRaisesRegex(TypeError, "positional argument"):
Context({}, self._get_isolate_dir()) # type: ignore
with self.assertRaisesRegex(
TypeError, "`config` must be a dict or None"
):
Context.isolated(config="not a dict") # type: ignore
with self.assertRaisesRegex(
TypeError, "`isolate_dir` must be an IsolateDir or None"
):
Context.isolated(isolate_dir="not an isolate dir") # type: ignore
with self.assertRaisesRegex(
TypeError, "`target` must be a str or None"
):
Context.isolated(target=123) # type: ignore
with self.assertRaisesRegex(TypeError, "positional argument"):
Context.isolated({}, self._get_isolate_dir()) # type: ignore
with self.assertRaisesRegex(
TypeError, "`config` must be a dict or None"
):
Context.detect(config="not a dict") # type: ignore
with self.assertRaisesRegex(
TypeError, "`target` must be a str or None"
):
Context.detect(target=123) # type: ignore
with self.assertRaisesRegex(TypeError, "positional argument"):
Context.detect({}, "foo") # type: ignore
def test_strict_context_creation_and_config_get(self) -> None:
with tempfile.TemporaryDirectory() as shared_data:
ctx = Context(
config={
"shared_data": shared_data,
"ssh.priv": ["/keys/fuchsia_ed25519"],
"some": {"nested": {"key": "strict_val"}},
},
target="id:SERIAL-A",
)
self.addCleanup(ctx.close)
self.assertEqual(
ctx.config_get_string("some.nested.key"), "strict_val"
)
self.assertEqual(
ctx.config_get_string("target.default"), "id:SERIAL-A"
)
self.assertEqual(
ctx.config_get_string("ssh.controlmaster.mode"), "none"
)
self.assertIsNone(ctx.config_get_string("nonexistent.strict.key"))
# Nested None `target.default` must not overwrite explicit `target`
# even when `"target.default": None` appeared before `"target"`.
ctx_none_override = Context(
config={
"shared_data": shared_data,
"target.default": None,
"target": {"default": None},
},
target="id:SERIAL-B",
)
self.addCleanup(ctx_none_override.close)
self.assertEqual(
ctx_none_override.config_get_string("target.default"),
"id:SERIAL-B",
)
def test_strict_context_ssh_controlmaster_mode(self) -> None:
ctx_default = Context()
self.addCleanup(ctx_default.close)
self.assertEqual(
ctx_default.config_get_string("ssh.controlmaster.mode"), "none"
)
ctx_null = Context(config={"ssh.controlmaster.mode": None})
self.addCleanup(ctx_null.close)
self.assertEqual(
ctx_null.config_get_string("ssh.controlmaster.mode"), "none"
)
ctx_managed = Context(config={"ssh.controlmaster.mode": "managed"})
self.addCleanup(ctx_managed.close)
self.assertEqual(
ctx_managed.config_get_string("ssh.controlmaster.mode"), "managed"
)
ctx_explicit = Context(
config={
"ssh": {
"controlmaster": {
"mode": "explicit",
"path": "/tmp/cm.sock",
}
}
}
)
self.addCleanup(ctx_explicit.close)
self.assertEqual(
ctx_explicit.config_get_string("ssh.controlmaster.mode"),
"explicit",
)
self.assertEqual(
ctx_explicit.config_get_string("ssh.controlmaster.path"),
"/tmp/cm.sock",
)
ctx_isolated = Context.isolated(target="")
self.addCleanup(ctx_isolated.close)
self.assertIsNone(
ctx_isolated.config_get_string("ssh.controlmaster.mode")
)
def test_strict_context_rejects_invalid_config(self) -> None:
with self.assertRaisesRegex(RuntimeError, "shared_data"):
Context(config={}, target="id:SERIAL-A")
with self.assertRaisesRegex(RuntimeError, "shared_data"):
Context(target="id:SERIAL-A")
with self.assertRaisesRegex(RuntimeError, "ssh.priv"):
Context(target="127.0.0.1:8022")
with self.assertRaisesRegex(RuntimeError, "HOME"):
Context(config={"ssh.priv": ["$HOME/.ssh/key"]})
with self.assertRaisesRegex(RuntimeError, "ssh"):
Context(config={"ssh": 123})
with self.assertRaisesRegex(RuntimeError, "ssh.controlmaster"):
Context(config={"ssh.controlmaster": "managed"})
with self.assertRaisesRegex(RuntimeError, "ssh.controlmaster.mode"):
Context(config={"ssh.controlmaster.mode": ""})
with self.assertRaisesRegex(RuntimeError, "ssh.controlmaster.mode"):
Context(config={"ssh.controlmaster.mode": 123})
def test_isolated_context_creation_and_config_get(self) -> None:
config = self._get_default_config()
config["some.isolated.key"] = "isolated_val"
ctx = Context.isolated(
config=config,
isolate_dir=self._get_isolate_dir(),
target="fuchsia-emulator",
)
self.addCleanup(ctx.close)
self.assertEqual(
ctx.config_get_string("some.isolated.key"), "isolated_val"
)
self.assertEqual(
ctx.config_get_string("target.default"), "fuchsia-emulator"
)
# Passing `target=""` forces a local/testing context even if ambient
# target env vars are set, and isolated mode accepts non-strict `$HOME`.
default_ctx = Context.isolated(
config={"ssh.priv": ["$HOME/.ssh/key"]}, target=""
)
assert default_ctx._directory is not None
temp_isolate_path = default_ctx._directory.directory()
self.assertTrue(os.path.exists(temp_isolate_path))
default_ctx.channel_create()
# `close()` must drop the `IsolateDir` reference promptly so owned
# temporary isolate directories are removed without waiting for GC.
default_ctx.close()
self.assertFalse(os.path.exists(temp_isolate_path))
def _skip_if_ancestor_marker(
self, tmp_root: str, *, include_fx_root: bool
) -> None:
"""Skips the test if an ancestor directory has a shadowing ffx marker.
Both `EnvironmentContext::detect` and `EnvironmentContext::isolated`
resolve the working directory via `std::env::current_dir()` (`getcwd(3)`
physical path) and walk upward for `fuchsia_env.{toml,json5}`
(`ConfigDomain::find_root`, which uses `Path::exists()`).
`EnvironmentContext::detect` also walks upward for `.fx-root`
(`EnvironmentContext::find_fx_root`, which checks `Path::is_file()`).
Staying under `tempfile.TemporaryDirectory()` avoids writing outside the
task's isolated `$TMPDIR`.
"""
cursor = os.path.realpath(tmp_root)
while True:
for marker in ("fuchsia_env.toml", "fuchsia_env.json5"):
marker_path = os.path.join(cursor, marker)
if os.path.exists(marker_path):
self.skipTest(
f"temp dir {tmp_root} has ancestor marker {marker_path}"
)
if include_fx_root:
fx_root_path = os.path.join(cursor, ".fx-root")
if os.path.isfile(fx_root_path):
self.skipTest(
f"temp dir {tmp_root} has ancestor marker {fx_root_path}"
)
parent = os.path.dirname(cursor)
if parent == cursor:
break
cursor = parent
def _run_context_script(
self,
label: str,
script: str,
cwd: str,
env: collections.abc.Mapping[str, str],
) -> None:
# Run in a child process to avoid mutating `os.environ` or `cwd` while
# the parent process's Rust LibContext background threads are live.
try:
completed_process = subprocess.run(
[sys.executable, "-c", script],
cwd=cwd,
env=env,
stdin=subprocess.DEVNULL,
capture_output=True,
text=True,
timeout=_SUBPROCESS_TIMEOUT_SECS,
)
except subprocess.TimeoutExpired as err:
stdout = _format_subprocess_stream(err.stdout)
stderr = _format_subprocess_stream(err.stderr)
self.fail(
f"{label} subprocess timed out after "
f"{_SUBPROCESS_TIMEOUT_SECS}s:\nstdout={stdout}\nstderr={stderr}"
)
self.assertEqual(
completed_process.returncode,
0,
f"{label} subprocess failed:\n"
f"stdout={completed_process.stdout}\n"
f"stderr={completed_process.stderr}",
)
def test_detect_context_no_context_isolation(self) -> None:
"""Verifies NoContext mode reads user config and ignores stateful target.default."""
with tempfile.TemporaryDirectory() as tmp_root:
self._skip_if_ancestor_marker(tmp_root, include_fx_root=True)
_write_user_config(
tmp_root,
{
"detect_test_user_key": "from_user_config",
# Stateful user `target.default` must NOT be selected as
# the target specifier by `get_target_specifier`.
"target": {"default": "stale-user-target"},
},
)
no_ctx_dir = os.path.join(tmp_root, "no_ctx")
os.makedirs(no_ctx_dir)
base_env = _make_subprocess_env(tmp_root)
script = """
from fuchsia_controller_py import Context
ctx_detect = Context.detect(config={"detect_test_runtime_key": "from_runtime"})
assert ctx_detect.config_get_string("detect_test_runtime_key") == "from_runtime"
assert ctx_detect.config_get_string("detect_test_user_key") == "from_user_config"
assert ctx_detect.config_get_string("ssh.controlmaster.mode") is None
# Raw config query still sees the user-level value, while target resolution
# ignores stateful config and treats the context as local/unspecified.
assert ctx_detect.config_get_string("target.default") == "stale-user-target"
ch0, ch1 = ctx_detect.channel_create()
ch0.close()
ch1.close()
try:
ctx_detect.connect_remote_control_proxy()
raise AssertionError("expected RuntimeError for unspecified target")
except RuntimeError as err:
assert "no device has been specified" in str(err), str(err)
ctx_detect.close()
ctx_strict = Context()
assert ctx_strict.config_get_string("detect_test_user_key") is None
assert ctx_strict.config_get_string("ssh.controlmaster.mode") == "none"
ctx_strict.close()
ctx_isolated = Context.isolated()
assert ctx_isolated.config_get_string("detect_test_user_key") is None
assert ctx_isolated.config_get_string("ssh.controlmaster.mode") is None
ctx_isolated.close()
"""
self._run_context_script("NoContext", script, no_ctx_dir, base_env)
def test_detect_context_in_tree_isolation(self) -> None:
"""Verifies InTree mode detects `.fx-root` / `.fx-build-dir` and `FUCHSIA_NODENAME`."""
with tempfile.TemporaryDirectory() as tmp_root:
# `tree_root` creates its own `.fx-root`, which stops
# `EnvironmentContext::find_fx_root` locally, so only an ancestor
# `fuchsia_env.{toml,json5}` can shadow `InTree` detection.
self._skip_if_ancestor_marker(tmp_root, include_fx_root=False)
_write_user_config(
tmp_root, {"detect_test_user_key": "from_user_config"}
)
tree_root = os.path.join(tmp_root, "fake_tree")
build_dir = os.path.join(tree_root, "out", "test")
os.makedirs(build_dir)
with open(
os.path.join(tree_root, ".fx-root"), "w", encoding="utf-8"
):
pass
with open(
os.path.join(tree_root, ".fx-build-dir"), "w", encoding="utf-8"
) as f:
f.write("out/test\n")
with open(
os.path.join(build_dir, "ffx-config.json"),
"w",
encoding="utf-8",
) as f:
json.dump({"detect_test_build_key": "from_build_config"}, f)
tree_env = _make_subprocess_env(tmp_root) | {
"FUCHSIA_NODENAME": "ambient-node"
}
script = """
from fuchsia_controller_py import Context
ctx_detect = Context.detect()
assert ctx_detect.config_get_string("detect_test_build_key") == "from_build_config"
assert ctx_detect.config_get_string("detect_test_user_key") == "from_user_config"
assert ctx_detect.config_get_string("target.default") == "ambient-node"
ctx_detect.close()
ctx_detect_override = Context.detect(target="explicit-node")
assert ctx_detect_override.config_get_string("target.default") == "explicit-node"
ctx_detect_override.close()
# `target=""` forces a local/testing context even while FUCHSIA_NODENAME is set.
for factory in (Context, Context.detect, Context.isolated):
ctx_local = factory(target="")
ch0, ch1 = ctx_local.channel_create()
ch0.close()
ch1.close()
try:
ctx_local.connect_remote_control_proxy()
raise AssertionError("expected RuntimeError for target=''")
except RuntimeError as err:
assert "no device has been specified" in str(err), str(err)
ctx_local.close()
ctx_isolated = Context.isolated()
assert ctx_isolated.config_get_string("detect_test_build_key") is None
assert ctx_isolated.config_get_string("target.default") == "ambient-node"
ctx_isolated.close()
ctx_strict = Context()
assert ctx_strict.config_get_string("detect_test_build_key") is None
assert ctx_strict.config_get_string("target.default") is None
ctx_strict.close()
"""
self._run_context_script("InTree", script, tree_root, tree_env)
def test_detect_context_config_domain_isolation(self) -> None:
"""Verifies ConfigDomain mode detects `fuchsia_env.toml` defaults and build config."""
with tempfile.TemporaryDirectory() as tmp_root:
# `domain_root` creates its own `fuchsia_env.toml`, stopping
# `ConfigDomain::find_root` regardless of any ancestor markers.
_write_user_config(
tmp_root, {"detect_test_user_key": "from_user_config"}
)
domain_root = os.path.join(tmp_root, "fake_domain")
os.makedirs(domain_root)
with open(
os.path.join(domain_root, "fuchsia_env.toml"),
"w",
encoding="utf-8",
) as f:
f.write(
"[fuchsia.project]\n"
'build_config_path = "domain-build-config.json"\n'
"[fuchsia.project.default_config]\n"
'detect_test_domain_default = "from_domain_default"\n'
)
with open(
os.path.join(domain_root, "domain-build-config.json"),
"w",
encoding="utf-8",
) as f:
json.dump({"detect_test_domain_build": "from_domain_build"}, f)
base_env = _make_subprocess_env(tmp_root)
script = """
from fuchsia_controller_py import Context
ctx_detect = Context.detect(target="")
assert ctx_detect.config_get_string("detect_test_domain_default") == "from_domain_default"
assert ctx_detect.config_get_string("detect_test_domain_build") == "from_domain_build"
assert ctx_detect.config_get_string("detect_test_user_key") == "from_user_config"
ctx_detect.close()
ctx_isolated = Context.isolated(target="")
assert ctx_isolated.config_get_string("detect_test_domain_default") == "from_domain_default"
assert ctx_isolated.config_get_string("detect_test_domain_build") == "from_domain_build"
assert ctx_isolated.config_get_string("detect_test_user_key") is None
ctx_isolated.close()
ctx_strict = Context()
assert ctx_strict.config_get_string("detect_test_domain_default") is None
assert ctx_strict.config_get_string("detect_test_domain_build") is None
assert ctx_strict.config_get_string("detect_test_user_key") is None
ctx_strict.close()
"""
self._run_context_script(
"ConfigDomain", script, domain_root, base_env
)
def test_context_creation_conflicting_config_raises_error(
self,
) -> None:
with self.assertRaises(RuntimeError):
Context(config={"foo": 1, "foo.bar": 2})
with self.assertRaises(RuntimeError):
Context(config={"foo.bar": 2, "foo": 1})
with self.assertRaises(RuntimeError):
Context(config={"foo": {"bar": 1}, "foo.bar": {"baz": 2}})
def test_config_get_nested(self) -> None:
config = self._get_default_config()
config["some.nested.key"] = "nested_val"
ctx = Context(config=config)
self.addCleanup(ctx.close)
self.assertEqual(ctx.config_get_string("some.nested.key"), "nested_val")
def test_config_get_dict_nested(self) -> None:
config: typing.Dict[str, typing.Any] = self._get_default_config()
config["some"] = {"dict": {"nested": "dict_val"}}
ctx = Context(config=config)
self.addCleanup(ctx.close)
self.assertEqual(ctx.config_get_string("some.dict.nested"), "dict_val")
def test_context_creation_no_args(self) -> None:
ctx = Context()
self.addCleanup(ctx.close)
ctx.channel_create()
ctx_none = Context(config=None)
self.addCleanup(ctx_none.close)
ctx_none.channel_create()
async def test_sending_fidl_protocol(self) -> None:
ctx = Context()
tc_server, tc_client = ctx.channel_create()
list_server, list_client = ctx.channel_create()
tc_proxy = ffx_fidl.TargetCollectionClient(tc_client)
query = ffx_fidl.TargetQuery(string_matcher="foobar")
tc_proxy.list_targets(query=query, reader=list_client.take())
async_tc_server = AsyncChannel(tc_server)
buf, hdls = await async_tc_server.read()
self.assertEqual(len(hdls), 1)
new_list_client = Channel(hdls[0])
new_list_client.write((bytearray([5, 6, 7]), []))
async_list_server = AsyncChannel(list_server)
list_buf, list_hdls = await async_list_server.read()
self.assertEqual(len(list_hdls), 0)
self.assertEqual(list_buf, bytearray([5, 6, 7]))
async def test_sending_socket_as_result(self) -> None:
ctx = Context()
t_server, t_client = ctx.channel_create()
server = TestSocketServer(ctx, t_server)
client = fc_test.TestingClient(t_client)
server_task = asyncio.get_running_loop().create_task(server.serve())
res1 = await client.return_union()
self.assertEqual(res1.x, 10)
res2 = await client.return_union_with_table()
# This is to placate mypy
assert res2.x is not None
self.assertEqual(res2.x.union_str, "foobar")
res3 = await client.return_socket_or_error()
# TODO(b/415379365): Given this is intended to be a socket, it should return
# the appropriate type here.
assert res3.response is not None
self.assertNotEqual(res3.response.reader_thing, 0)
res4 = await client.return_socket_or_error()
self.assertEqual(res4.err, FcTransportStatus.FC_ERR_NOT_SUPPORTED)
server_task.cancel()