blob: b3482e70d6f752cebeb60400786bc22d8eeb2f8e [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
from collections.abc import Sequence
import json
import os
import pathlib
import tempfile
import typing
import unittest
import unittest.mock as mock
import async_utils.command as command
from parameterized import parameterized
import args
import environment
import event
import execution
import test_list_file
import tests_json_file
def _make_exec_env(
fuchsia_dir: str, out_dir: str, gemini_api_key: typing.Optional[str] = None
) -> environment.ExecutionEnvironment:
"""Create an execution environment for test."""
return environment.ExecutionEnvironment(
fuchsia_dir=fuchsia_dir,
out_dir=out_dir,
test_json_file="",
disabled_ctf_tests_file="",
log_file=None,
test_list_file="",
gemini_api_key=gemini_api_key,
)
def _make_host_test(
rel_path: str,
*,
list_cases_argument: str | None = None,
execution_entry: test_list_file.TestListExecutionEntry | None = None,
is_e2e: bool = False,
) -> test_list_file.Test:
"""Create a path-based host or E2E Test entry for unit tests."""
environments = (
[
tests_json_file.EnvironmentEntry(
dimensions=tests_json_file.DimensionsEntry(device_type="AEMU")
)
]
if is_e2e
else []
)
return test_list_file.Test(
tests_json_file.TestEntry(
tests_json_file.TestSection(
rel_path,
f"//{rel_path}",
"linux",
path=rel_path,
list_cases_argument=list_cases_argument,
),
environments=environments,
),
test_list_file.TestListEntry(rel_path, [], execution=execution_entry),
)
class TestExecution(unittest.IsolatedAsyncioTestCase):
def setUp(self) -> None:
super().setUp()
patch = mock.patch.dict(os.environ, {}, clear=False)
patch.start()
os.environ.pop("FUCHSIA_NODENAME", None)
self.addCleanup(patch.stop)
def assertContainsSublist(
self, target: list[typing.Any], data: list[typing.Any]
) -> None:
"""Helper method to assert that one list is contained in the other, in order.
Args:
target (list[typing.Any]): The sublist to search for.
data (list[typing.Any]): The list to search in.
"""
self.assertNotEqual(len(target), 0, "Target list cannot be empty")
starts = [i for i, v in enumerate(data) if v == target[0]]
for start_index in starts:
if data[start_index : start_index + len(target)] == target:
return
self.assertTrue(False, f"List {target} is not a sublist of {data}")
async def test_run_command(self) -> None:
"""Test that run_command works with and without events"""
with tempfile.TemporaryDirectory() as tmp:
open(os.path.join(tmp, "temp-file.txt"), "w").close()
output = await execution.run_command(
"ls", "temp-file.txt", env={"CWD": tmp}
)
assert output is not None
self.assertEqual(output.return_code, 0)
recorder = event.EventRecorder()
recorder.emit_init()
output = await execution.run_command(
"ls", "temp-file.txt", env={"CWD": tmp}, recorder=recorder
)
assert output is not None
self.assertEqual(output.return_code, 0)
recorder.emit_end()
events = [e async for e in recorder.iter()]
# Ensure we got init, end, and at least one sub-event start/stop
self.assertGreater(len(events), 4)
async def test_run_command_failure(self) -> None:
"""Test that running an invalid command emits an error event"""
recorder = event.EventRecorder()
recorder.emit_init()
output = await execution.run_command(
"___invalid_command_name___", recorder=recorder
)
recorder.emit_end()
events = [e async for e in recorder.iter()]
# Ensure we get no output and that at least one event is an error.
self.assertIsNone(output)
self.assertTrue(any([e.error is not None for e in events]))
@parameterized.expand(
[
(
"with default log severity",
[],
[["--max-severity-logs", "INFO"]],
[],
),
(
"with default capture syslog",
[],
[["--capture-syslog"]],
[],
),
(
"without capture syslog",
["--no-capture-syslog"],
[],
["--capture-syslog"],
),
(
"with min log severity override",
["--min-severity-logs", "DEBUG"],
[["--min-severity-logs", "DEBUG"]],
[],
),
(
"without log restriction",
["--no-restrict-logs"],
[["--min-severity-logs", "TRACE"]],
["--max-severity-logs"],
),
(
"with default to not run disabled tests",
[],
[["--min-severity-logs", "TRACE"]],
["--run-disabled"],
),
(
"with disabled tests running",
["--also-run-disabled-tests"],
[["--run-disabled"], ["--min-severity-logs", "TRACE"]],
[],
),
(
"with full moniker in logs",
["--show-full-moniker-in-logs"],
[["--show-full-moniker-in-logs"]],
[],
),
(
"without full moniker in logs",
["--no-show-full-moniker-in-logs"],
[],
["--show-full-moniker-in-logs"],
),
(
"without ffx output directory",
[],
[],
["--output-directory"],
),
(
"with ffx output directory",
["--ffx-output-directory", "foo"],
[["--output-directory", "foo/0"]],
[],
),
(
"with extra args",
["--", "--foo"],
[["--", "--foo"]],
[],
),
]
)
async def test_test_execution_component(
self,
_unused_name: str,
flag_list: list[str],
expected_present_flag_lists: list[list[str]],
expected_not_present_flags: list[str],
) -> None:
"""Test the usage of the TestExecution wrapper on a component test"""
exec_env = _make_exec_env("/fuchsia", "/out/fuchsia")
test = execution.TestExecution(
test_list_file.Test(
tests_json_file.TestEntry(
tests_json_file.TestSection("foo", "//foo", "fuchsia")
),
test_list_file.TestListEntry(
"foo",
[],
test_list_file.TestListExecutionEntry(
"fuchsia-pkg://fuchsia.com/foo#meta/foo_test.cm",
realm="foo_tests",
max_severity_logs="INFO",
min_severity_logs="TRACE",
test_filters=["-foo", "-bar"],
),
),
),
exec_env,
args.parse_args(["--no-use-package-hash"] + flag_list),
)
command_line = test.command_line()
self.assertContainsSublist(
[
"fx",
"--dir",
"/out/fuchsia",
"ffx",
"test",
"run",
"--realm",
"foo_tests",
],
command_line,
)
self.assertContainsSublist(
[
"--test-filter",
"-foo",
"--test-filter",
"-bar",
],
command_line,
)
self.assertContainsSublist(
["fuchsia-pkg://fuchsia.com/foo#meta/foo_test.cm"], command_line
)
for expected_flag_list in expected_present_flag_lists:
self.assertContainsSublist(expected_flag_list, command_line)
for not_present_flag in expected_not_present_flags:
self.assertFalse(
not_present_flag in command_line,
f"Expected {not_present_flag} to not be in {command_line}",
)
self.assertFalse(test.is_hermetic())
self.assertFalse(test.is_host_test())
self.assertIsNone(test.environment())
self.assertTrue(test.should_symbolize())
@parameterized.expand(
[
(
"test execution does not pass a --parallel by default",
None,
None,
[],
),
(
"test execution respects parallel overrides in test specs",
1,
None,
["--parallel", "1"],
),
(
"test execution flag overrides test spec",
4,
2,
["--parallel", "2"],
),
]
)
async def test_test_execution_parallel_cases(
self,
_unused_name: str,
spec_parallel: int | None,
flag_parallel: int | None,
expected_args: list[str],
) -> None:
"""Test the usage of the TestExecution wrapper on a component test"""
exec_env = _make_exec_env("/fuchsia", "/out/fuchsia")
test = execution.TestExecution(
test_list_file.Test(
tests_json_file.TestEntry(
tests_json_file.TestSection(
"foo", "//foo", "fuchsia", parallel=spec_parallel
)
),
test_list_file.TestListEntry(
"foo",
[],
test_list_file.TestListExecutionEntry(
"fuchsia-pkg://fuchsia.com/foo#meta/foo_test.cm",
realm="foo_tests",
max_severity_logs="INFO",
min_severity_logs="TRACE",
),
),
),
exec_env,
args.parse_args(
["--no-use-package-hash"]
+ (
[]
if not flag_parallel
else ["--parallel-cases", str(flag_parallel)]
)
),
)
self.assertListEqual(
test.command_line(),
[
"fx",
"--dir",
"/out/fuchsia",
"ffx",
"test",
"run",
"--realm",
"foo_tests",
"--max-severity-logs",
"INFO",
"--min-severity-logs",
"TRACE",
]
+ expected_args
+ [
"--capture-syslog",
"--timeout",
"300",
"fuchsia-pkg://fuchsia.com/foo#meta/foo_test.cm",
],
)
self.assertFalse(test.is_hermetic())
self.assertFalse(test.is_host_test())
self.assertIsNone(test.environment())
self.assertTrue(test.should_symbolize())
@parameterized.expand(
[
(
"test execution does not pass a --no-exception-channel by default",
None,
[],
),
(
"test execution respects create_no_exception_channel in test specs",
True,
["--no-exception-channel"],
),
]
)
async def test_test_execution_create_no_exception_channel(
self,
_unused_name: str,
spec_create_no_exception_channel: bool | None,
expected_args: list[str],
) -> None:
"""Test the usage of the TestExecution wrapper on a component test"""
exec_env = _make_exec_env("/fuchsia", "/out/fuchsia")
test = execution.TestExecution(
test_list_file.Test(
tests_json_file.TestEntry(
tests_json_file.TestSection(
"foo",
"//foo",
"fuchsia",
create_no_exception_channel=spec_create_no_exception_channel,
)
),
test_list_file.TestListEntry(
"foo",
[],
test_list_file.TestListExecutionEntry(
"fuchsia-pkg://fuchsia.com/foo#meta/foo_test.cm",
realm="foo_tests",
max_severity_logs="INFO",
min_severity_logs="TRACE",
),
),
),
exec_env,
args.parse_args(["--no-use-package-hash"]),
)
self.assertListEqual(
test.command_line(),
[
"fx",
"--dir",
"/out/fuchsia",
"ffx",
"test",
"run",
"--realm",
"foo_tests",
"--max-severity-logs",
"INFO",
"--min-severity-logs",
"TRACE",
]
+ expected_args
+ [
"--capture-syslog",
"--timeout",
"300",
"fuchsia-pkg://fuchsia.com/foo#meta/foo_test.cm",
],
)
self.assertFalse(test.is_hermetic())
self.assertFalse(test.is_host_test())
self.assertIsNone(test.environment())
self.assertTrue(test.should_symbolize())
async def test_test_execution_pure_device_test_with_path(
self,
) -> None:
"""Test the usage of the TestExecution wrapper on a pure device test with path"""
exec_env = _make_exec_env("/fuchsia", "/out/fuchsia")
test = execution.TestExecution(
test_list_file.Test(
tests_json_file.TestEntry(
tests_json_file.TestSection(
"foo",
"//foo",
"linux",
package_url="fuchsia-pkg://fuchsia.com/foo#meta/foo_test.cm",
path="bin/test_component_wrapper.sh",
)
),
test_list_file.TestListEntry(
"foo",
[],
test_list_file.TestListExecutionEntry(
"fuchsia-pkg://fuchsia.com/foo#meta/foo_test.cm",
realm="foo_tests",
max_severity_logs="INFO",
min_severity_logs="TRACE",
),
),
),
exec_env,
args.parse_args(["--", "--some_extra_arg"]),
)
self.assertTrue(test._is_pure_device_test())
self.assertFalse(test.is_host_test())
self.assertTrue(test._test.is_pure_device_test())
self.assertFalse(test._test.is_e2e_test())
command_line = test.command_line()
self.assertEqual(
[
"/out/fuchsia/bin/test_component_wrapper.sh",
"--realm=foo_tests",
"--max-severity-logs=INFO",
"--min-severity-logs=TRACE",
"--target-test-args=--some_extra_arg",
"--timeout=300",
],
command_line,
)
env = test.environment()
assert env is not None
# TODO: Add environment checking when added.
expected_env_subset = {
"CWD": "/out/fuchsia",
"FUCHSIA_CUSTOM_TEST_ARGS": "--some_extra_arg",
}
self.assertTrue(expected_env_subset.items() <= env.items())
@parameterized.expand(
(
(
"pure_device_test_with_path",
tests_json_file.TestEntry(
tests_json_file.TestSection(
"foo",
"//foo",
"linux",
package_url="fuchsia-pkg://fuchsia.com/foo#meta/foo_test.cm",
path="foo_foo_test_test.sh",
),
environments=[
tests_json_file.EnvironmentEntry(
dimensions=tests_json_file.DimensionsEntry(
device_type="AEMU"
)
)
],
expects_ssh=True,
),
test_list_file.TestListExecutionEntry(
"fuchsia-pkg://fuchsia.com/foo#meta/foo_test.cm",
),
True,
True,
),
(
"pure_device_test_without_path",
tests_json_file.TestEntry(
tests_json_file.TestSection(
"foo",
"//foo",
"fuchsia",
package_url="fuchsia-pkg://fuchsia.com/foo#meta/foo_test.cm",
),
environments=[
tests_json_file.EnvironmentEntry(
dimensions=tests_json_file.DimensionsEntry(
device_type="AEMU"
)
)
],
),
test_list_file.TestListExecutionEntry(
"fuchsia-pkg://fuchsia.com/foo#meta/foo_test.cm",
),
True,
False,
),
(
"pure_device_test_with_empty_path",
tests_json_file.TestEntry(
tests_json_file.TestSection(
"foo",
"//foo",
"linux",
package_url="fuchsia-pkg://fuchsia.com/foo#meta/foo_test.cm",
path="",
),
),
test_list_file.TestListExecutionEntry(
"fuchsia-pkg://fuchsia.com/foo#meta/foo_test.cm",
),
True,
False,
),
(
"bootfs_component",
tests_json_file.TestEntry(
tests_json_file.TestSection(
"foo",
"//foo",
"fuchsia",
package_url="fuchsia-boot:///foo#meta/foo_test.cm",
),
expects_ssh=False,
),
test_list_file.TestListExecutionEntry(
"fuchsia-boot:///foo#meta/foo_test.cm",
),
True,
False,
),
(
"pure_host_test",
tests_json_file.TestEntry(
tests_json_file.TestSection(
"foo",
"//foo",
"linux",
path="host_x64/foo",
),
),
None,
False,
False,
),
(
"e2e_test",
tests_json_file.TestEntry(
tests_json_file.TestSection(
"foo",
"//foo",
"linux",
path="host_x64/foo_e2e",
),
environments=[
tests_json_file.EnvironmentEntry(
dimensions=tests_json_file.DimensionsEntry(
device_type="AEMU"
)
)
],
),
None,
False,
False,
),
(
"boot_test",
tests_json_file.TestEntry(
tests_json_file.TestSection(
"foo",
"//foo",
"linux",
path="boot_test.sh",
),
environments=[
tests_json_file.EnvironmentEntry(
dimensions=tests_json_file.DimensionsEntry(
device_type="AEMU"
)
)
],
is_boot_test=True,
),
None,
False,
False,
),
(
"bootfs_test",
tests_json_file.TestEntry(
tests_json_file.TestSection(
"foo",
"//foo",
"fuchsia",
path="/boot/test/foo",
),
expects_ssh=False,
),
None,
False,
False,
),
)
)
def test_pure_device_test_execution_classification(
self,
_name: str,
entry: tests_json_file.TestEntry,
execution_entry: test_list_file.TestListExecutionEntry | None,
expected_is_pure_device: bool,
expected_uses_pure_device_path: bool,
) -> None:
"""Test classification and path execution for pure device and other test types."""
exec_env = _make_exec_env("/fuchsia", "/out/fuchsia")
device_env = environment.DeviceEnvironment(
address="127.0.0.1",
port="39259",
name="fuchsia-target",
private_key_path="/path/to/fuchsia_ed25519",
)
test = execution.TestExecution(
test_list_file.Test(
entry,
test_list_file.TestListEntry(
"foo", [], execution=execution_entry
),
),
exec_env,
args.parse_args(["--no-use-package-hash"]),
device_env=device_env,
)
self.assertEqual(test._is_pure_device_test(), expected_is_pure_device)
env = test.environment()
cmd = test.command_line()
if expected_uses_pure_device_path:
assert entry.test.path is not None
self.assertEqual(
cmd[0], os.path.join("/out/fuchsia", entry.test.path)
)
assert env is not None
self.assertEqual(env.get("FUCHSIA_HOST_TOOLS"), "./host_x64")
self.assertEqual(env.get("FUCHSIA_DEVICE_ADDR"), "127.0.0.1:39259")
else:
if expected_is_pure_device:
self.assertEqual(
cmd[:5], ["fx", "--dir", "/out/fuchsia", "ffx", "test"]
)
self.assertIsNone(env)
else:
self.assertEqual(cmd, [entry.test.path])
assert env is not None
self.assertNotIn("FUCHSIA_HOST_TOOLS", env)
@parameterized.expand(
(
("ipv4_with_port", "127.0.0.1", "39259", "127.0.0.1:39259"),
("ipv4_without_port", "127.0.0.1", "", "127.0.0.1"),
(
"bracketed_ipv6_with_scope_and_port",
"[fe80::1%eth0]",
"8022",
"[fe80::1%eth0]:8022",
),
(
"bracketed_ipv6_without_port",
"[fe80::1%eth0]",
"",
"[fe80::1%eth0]",
),
(
"unbracketed_ipv6_with_port",
"fe80::1",
"8022",
"[fe80::1]:8022",
),
(
"unbracketed_ipv6_with_scope_and_port",
"fe80::1%eth0",
"8022",
"[fe80::1%eth0]:8022",
),
("unbracketed_ipv6_without_port", "fe80::1", "", "fe80::1"),
(
"unbracketed_ipv6_with_scope_without_port",
"fe80::1%eth0",
"",
"fe80::1%eth0",
),
("hostname_with_port", "localhost", "8022", "localhost:8022"),
("hostname_without_port", "localhost", "", "localhost"),
("usb_cid", "usb:cid", "3", "usb:cid:3"),
("usb_cid_22", "usb:cid", "22", "usb:cid:22"),
("vsock_cid", "vsock:cid", "4", "vsock:cid:4"),
)
)
def test_pure_device_test_environment_device_addr(
self,
_name: str,
address: str,
port: str,
expected_target_addr: str,
) -> None:
"""Test that pure device tests with path set FUCHSIA_DEVICE_ADDR to a complete TargetAddr."""
exec_env = _make_exec_env("/fuchsia", "/out/fuchsia")
device_env = environment.DeviceEnvironment(
address=address,
port=port,
name="fuchsia-target",
private_key_path="/path/to/fuchsia_ed25519",
)
test = execution.TestExecution(
test_list_file.Test(
tests_json_file.TestEntry(
tests_json_file.TestSection(
"foo",
"//foo",
"linux",
package_url="fuchsia-pkg://fuchsia.com/foo#meta/foo_test.cm",
path="bin/test_component_wrapper.sh",
)
),
test_list_file.TestListEntry(
"foo",
[],
test_list_file.TestListExecutionEntry(
"fuchsia-pkg://fuchsia.com/foo#meta/foo_test.cm",
),
),
),
exec_env,
args.parse_args([]),
device_env=device_env,
)
self.assertTrue(test._is_pure_device_test())
self.assertFalse(test.is_host_test())
env = test.environment()
assert env is not None
self.assertDictEqual(
env,
{
"CWD": "/out/fuchsia",
"FUCHSIA_DEVICE_ADDR": expected_target_addr,
"FUCHSIA_SSH_KEY": "/path/to/fuchsia_ed25519",
"FUCHSIA_HOST_TOOLS": "./host_x64",
},
)
def test_e2e_environment_preserves_split_addr_and_port(
self,
) -> None:
"""Test that E2E tests are not treated as pure device tests and preserve split address and port env vars."""
exec_env = _make_exec_env("/fuchsia", "/out/fuchsia")
device_env = environment.DeviceEnvironment(
address="127.0.0.1",
port="39259",
name="fuchsia-emulator",
private_key_path="/path/to/fuchsia_ed25519",
)
test = execution.TestExecution(
test_list_file.Test(
tests_json_file.TestEntry(
tests_json_file.TestSection(
"foo",
"//foo",
"linux",
path="host_x64/foo_e2e",
),
environments=[
tests_json_file.EnvironmentEntry(
dimensions=tests_json_file.DimensionsEntry(
device_type="AEMU"
)
)
],
),
test_list_file.TestListEntry("foo", [], execution=None),
),
exec_env,
args.parse_args([]),
device_env=device_env,
)
self.assertFalse(test._is_pure_device_test())
self.assertTrue(test._test.is_e2e_test())
self.assertFalse(test.is_host_test())
env = test.environment()
assert env is not None
self.assertDictEqual(
env,
{
"CWD": "/out/fuchsia",
"FUCHSIA_DEVICE_ADDR": "127.0.0.1",
"FUCHSIA_SSH_PORT": "39259",
"FUCHSIA_SSH_KEY": "/path/to/fuchsia_ed25519",
"FUCHSIA_NODENAME": "fuchsia-emulator",
},
)
# TODO(b/444203259): Failing on debian 12 Linux. Re-enable once a fix is implemented.
# async def test_test_execution_host(self) -> None:
# """Test the usage of the TestExecution wrapper on a host test, and actually run it"""
# with tempfile.TemporaryDirectory() as tmp:
# # We will run ls, but it needs to be relative to the output directory.
# # Find the actual path to the ls binary and symlink it into the
# # output directory.
# env_path = (
# subprocess.check_output(["which", "env"]).decode().strip()
# )
# self.assertTrue(os.path.isfile, f"{env_path} is not a file")
# os.symlink(env_path, os.path.join(tmp, "env"))
# exec_env = _make_exec_env("/fuchsia", tmp)
# flags = args.parse_args([])
# test = execution.TestExecution(
# test_list_file.Test(
# tests_json_file.TestEntry(
# tests_json_file.TestSection(
# "foo", "//foo", "linux", path="env"
# )
# ),
# test_list_file.TestListEntry("foo", [], execution=None),
# ),
# exec_env,
# flags,
# )
# self.assertFalse(test.is_hermetic())
# env = test.environment()
# assert env is not None
# self.assertDictEqual(env, {"CWD": tmp})
# self.assertFalse(test.should_symbolize())
# recorder = event.EventRecorder()
# recorder.emit_init()
# output = await test.run(recorder, flags, event.GLOBAL_RUN_ID)
# recorder.emit_end()
# assert output is not None
# lines = output.stdout.splitlines()
# outdir: None | str = None
# for line in lines:
# l = line.split("=")
# if len(l) > 1 and l[0] == "FUCHSIA_TEST_OUTDIR":
# outdir = l[1]
# assert outdir is not None
# self.assertEqual(
# outdir[:4],
# "/tmp",
# f"Expecting that the output directory is an absolute path into /tmp. Found {outdir}",
# )
# self.assertFalse(
# any([e.error is not None async for e in recorder.iter()])
# )
@parameterized.expand(
[
("without --e2e enabled", ["--no-e2e"], execution.TestSkipped),
("with --e2e enabled", ["--e2e"], execution.TestFailed),
]
)
@mock.patch("execution.run_command", return_value=None)
async def test_test_execution_e2e(
self,
_unused_name: str,
extra_flags: list[str],
expected_exception: type,
command_mock: mock.MagicMock,
) -> None:
"""Test that execution of e2e depends on the --e2e flag"""
exec_env = _make_exec_env("/fuchsia", "/out/fuchsia")
flags = args.parse_args(extra_flags)
test = execution.TestExecution(
test_list_file.Test(
tests_json_file.TestEntry(
tests_json_file.TestSection(
"foo", "//foo", "linux", path="ls"
),
environments=[
tests_json_file.EnvironmentEntry(
dimensions=tests_json_file.DimensionsEntry(
device_type="AEMU"
)
)
],
),
test_list_file.TestListEntry("foo", [], execution=None),
),
exec_env,
flags,
)
self.assertTrue(test._test.is_e2e_test())
self.assertFalse(test.is_hermetic())
self.assertFalse(test.is_host_test())
env = test.environment()
assert env is not None
self.assertDictEqual(env, {"CWD": "/out/fuchsia"})
self.assertFalse(test.should_symbolize())
recorder = event.EventRecorder()
recorder.emit_init()
try:
await test.run(recorder, flags, event.GLOBAL_RUN_ID)
self.assertTrue(False, "No exception was raised")
except Exception as e:
self.assertIsInstance(e, expected_exception)
recorder.emit_end()
@mock.patch("execution.run_command", return_value=None)
async def test_test_execution_skip_boot_tests(
self, command_mock: mock.MagicMock
) -> None:
"""Test that boot tests are skipped"""
exec_env = _make_exec_env("/fuchsia", "/out/fuchsia")
flags = args.parse_args([])
test = execution.TestExecution(
test_list_file.Test(
tests_json_file.TestEntry(
tests_json_file.TestSection(
"foo", "//foo", "linux", path="ls"
),
environments=[
tests_json_file.EnvironmentEntry(
dimensions=tests_json_file.DimensionsEntry(
device_type="AEMU"
)
)
],
is_boot_test=True,
),
test_list_file.TestListEntry("foo", [], execution=None),
),
exec_env,
flags,
)
self.assertFalse(test._test.is_e2e_test())
self.assertFalse(test.is_hermetic())
env = test.environment()
assert env is not None
self.assertDictEqual(env, {"CWD": "/out/fuchsia"})
self.assertFalse(test.should_symbolize())
recorder = event.EventRecorder()
recorder.emit_init()
try:
await test.run(recorder, flags, event.GLOBAL_RUN_ID)
self.assertTrue(False, "No exception was raised")
except Exception as e:
self.assertIsInstance(e, execution.TestSkipped)
self.assertEqual(
str(e),
"Boot tests are not supported by `fx test`. Use `fx run-boot-test` or `fx core-tests`.",
)
recorder.emit_end()
async def test_test_execution_with_package_hash(self) -> None:
"""Ensure that test execution respects --use-package-hash"""
with tempfile.TemporaryDirectory() as tmp:
with open(os.path.join(tmp, "package-repositories.json"), "w") as f:
json.dump(
[
{
"targets": "targets.json",
}
],
f,
)
with open(os.path.join(tmp, "targets.json"), "w") as f:
json.dump(
{
"signed": {
"targets": {
"foo_test/0": {
"custom": {
"merkle": "f00",
}
},
"bar_test/0": {},
}
}
},
f,
)
def make_test(name: str) -> test_list_file.Test:
name = f"fuchsia-pkg://fuchsia.com/{name}#meta/test.cm"
return test_list_file.Test(
tests_json_file.TestEntry(
tests_json_file.TestSection(name, "//foo", "linux")
),
test_list_file.TestListEntry(
name,
[],
execution=test_list_file.TestListExecutionEntry(name),
),
)
def assertTestExecutionFailsUsingMerkleHash(
error_regex: str,
test: test_list_file.Test,
exec_env: environment.ExecutionEnvironment,
) -> None:
self.assertRaisesRegex(
execution.TestCouldNotRun,
error_regex,
lambda: execution.TestExecution(
test, exec_env, args.parse_args([])
).command_line(),
)
self.assertIsNotNone(
execution.TestExecution(
test,
exec_env,
args.parse_args(["--no-use-package-hash"]),
).command_line()
)
# This environment is missing a package-repository.json file, so attempts
# to match a merkle root will fail.
missing_exec_env = environment.ExecutionEnvironment(
fuchsia_dir="/fuchsia",
out_dir="",
test_json_file="",
disabled_ctf_tests_file="",
)
assertTestExecutionFailsUsingMerkleHash(
r"(?s)Could not load a Merkle hash.*Try running fx build\.",
make_test("foo_test"),
missing_exec_env,
)
# This environment contains a package repository, so we need to
# ensure the merkle hash argument is respected.
exec_env = environment.ExecutionEnvironment(
fuchsia_dir="/fuchsia",
out_dir="",
test_json_file="",
disabled_ctf_tests_file="",
package_repositories_file=os.path.join(
tmp, "package-repositories.json"
),
)
# Hash is present only when use_merkle_hash is True, absent otherwise.
self.assertIn(
"fuchsia-pkg://fuchsia.com/foo_test?hash=f00#meta/test.cm",
execution.TestExecution(
make_test("foo_test"), exec_env, args.parse_args([])
).command_line(),
)
self.assertIn(
"fuchsia-pkg://fuchsia.com/foo_test#meta/test.cm",
execution.TestExecution(
make_test("foo_test"),
exec_env,
args.parse_args(["--no-use-package-hash"]),
).command_line(),
)
# Mangle the component URL such that a name cannot be extracted,
# and expect an error.
broken_test = make_test("foo_test")
assert broken_test.info is not None
assert broken_test.info.execution is not None
broken_test.info.execution.component_url = "foo_test"
assertTestExecutionFailsUsingMerkleHash(
r"(?s)Failed to parse package name for Merkle root matching.*foo_test.*",
broken_test,
exec_env,
)
# This test has an entry, but no merkle.
assertTestExecutionFailsUsingMerkleHash(
r"(?s)Could not find a Merkle hash for this test.*Try running fx build\.",
make_test("bar_test"),
exec_env,
)
# This test has no entry.
assertTestExecutionFailsUsingMerkleHash(
r"(?s)Could not find a Merkle hash for this test.*Try running fx build\.",
make_test("baz_test"),
exec_env,
)
def _make_command_output(
self, stdout: str, return_code: int = 0
) -> command.CommandOutput:
return command.CommandOutput(stdout, "", return_code, 0.2, None)
@mock.patch("execution.run_command")
async def test_gemini_analysis_not_called_on_success(
self, command_mock: mock.AsyncMock
) -> None:
"""test that gemini analysis is not called on a successful run."""
exec_env = _make_exec_env("/fuchsia", "/out/fuchsia")
flags = args.parse_args(["--gemini-analysis"])
test = execution.TestExecution(
test_list_file.Test(
tests_json_file.TestEntry(
tests_json_file.TestSection(
"foo", "//foo", "linux", path="ls"
)
),
test_list_file.TestListEntry("foo", [], execution=None),
),
exec_env,
flags,
)
# Simulate a successful command
command_mock.return_value = self._make_command_output(
"success", return_code=0
)
recorder = event.EventRecorder()
recorder.emit_init()
await test.run(recorder, flags, event.GLOBAL_RUN_ID)
# The command should only be called once for the test itself.
command_mock.assert_called_once()
@mock.patch("execution.run_command")
async def test_gemini_analysis_verbosity_level_passed(
self, command_mock: mock.AsyncMock
) -> None:
"""test that the verbosity level is correctly passed to the gemini analysis script."""
exec_env = _make_exec_env(
"/fuchsia", "/out_dir", gemini_api_key="fake_key"
)
flags = args.parse_args(
["--gemini-analysis=3", "--env", "GEMINI_API_KEY=fake_key"]
)
test = execution.TestExecution(
test_list_file.Test(
tests_json_file.TestEntry(
tests_json_file.TestSection(
"foo", "//foo", "linux", path="ls"
)
),
test_list_file.TestListEntry("foo", [], execution=None),
),
exec_env,
flags,
)
# Simulate a failing command
command_mock.return_value = self._make_command_output(
"some error", return_code=1
)
recorder = event.EventRecorder()
recorder.emit_init()
with self.assertRaises(execution.TestFailed):
await test.run(recorder, flags, event.GLOBAL_RUN_ID)
# The first call is to the test itself, the second is to gemini_analysis.py
self.assertEqual(command_mock.call_count, 2)
gemini_call = command_mock.call_args_list[1]
self.assertIn("gemini_analysis.py", gemini_call.args[0])
self.assertIn("--verbosity", gemini_call.args)
self.assertIn("3", gemini_call.args)
self.assertEqual(gemini_call.kwargs["input_bytes"], b"some error\n")
@mock.patch("execution.run_command")
async def test_gemini_analysis_with_no_api_key(
self, command_mock: mock.AsyncMock
) -> None:
"""test that gemini analysis prints an error if no api key is provided."""
exec_env = _make_exec_env("/fuchsia", "/out/fuchsia")
flags = args.parse_args(["--gemini-analysis"])
test = execution.TestExecution(
test_list_file.Test(
tests_json_file.TestEntry(
tests_json_file.TestSection(
"foo", "//foo", "linux", path="ls"
)
),
test_list_file.TestListEntry("foo", [], execution=None),
),
exec_env,
flags,
)
# Simulate a failing command
command_mock.return_value = self._make_command_output(
"some error", return_code=1
)
recorder = event.EventRecorder()
recorder.emit_init()
with self.assertRaises(execution.TestFailed):
await test.run(recorder, flags, event.GLOBAL_RUN_ID)
# The command should only be called once for the test itself, as gemini analysis should be skipped.
command_mock.assert_called_once()
@mock.patch("execution.run_command")
async def test_gemini_analysis_does_not_pass_api_key_in_command_line_args(
self, command_mock: mock.AsyncMock
) -> None:
"""Test that the Gemini API key is passed via environment variables,
not in CLI arguments or unredacted event logs."""
secret_key = "super_secret_gemini_key_12345"
exec_env = _make_exec_env(
"/fuchsia", "/out_dir", gemini_api_key=secret_key
)
flags = args.parse_args(
["--gemini-analysis=2", "--env", f"GEMINI_API_KEY={secret_key}"]
)
test = execution.TestExecution(
test_list_file.Test(
tests_json_file.TestEntry(
tests_json_file.TestSection(
"foo", "//foo", "linux", path="ls"
)
),
test_list_file.TestListEntry("foo", [], execution=None),
),
exec_env,
flags,
)
command_mock.return_value = self._make_command_output(
"some failure log", return_code=1
)
recorder = event.EventRecorder()
recorder.emit_init()
with self.assertRaises(execution.TestFailed):
await test.run(recorder, flags, event.GLOBAL_RUN_ID)
self.assertEqual(command_mock.call_count, 2)
gemini_call = command_mock.call_args_list[1]
self.assertNotIn(secret_key, gemini_call.args)
self.assertNotIn("--api-key", gemini_call.args)
self.assertEqual(
gemini_call.kwargs.get("env", {}).get("GEMINI_API_KEY"), secret_key
)
@parameterized.expand(
(
(
"stdout_reason",
77,
"SKIP: LEAN_BIN_DIR is not set\n",
"",
"SKIP: LEAN_BIN_DIR is not set",
),
(
"stderr_reason",
77,
"",
"missing verification toolchains\n",
"missing verification toolchains",
),
(
"stdout_and_stderr_reason",
77,
"skipping verification\n",
"set LEAN_BIN_DIR to enable\n",
"skipping verification\nset LEAN_BIN_DIR to enable",
),
(
"empty_output_fallback",
77,
" \n",
"",
"Test exited with skip status (exit code 77).",
),
(
"custom_exit_code_fallback",
42,
"",
"",
"Test exited with skip status (exit code 42).",
),
)
)
@mock.patch.object(execution, "run_command", autospec=True)
async def test_host_test_skipped_exit_code_raises_test_skipped(
self,
_name: str,
skipped_exit_code: int,
stdout: str,
stderr: str,
expected_message: str,
command_mock: mock.AsyncMock,
) -> None:
"""Test that a host test exiting with its configured skipped_test_exit_code maps to TestSkipped."""
exec_env = _make_exec_env(
"/fuchsia", "/out/fuchsia", gemini_api_key="fake_key"
)
flags = args.parse_args(["--gemini-analysis=2"])
test = execution.TestExecution(
test_list_file.Test(
tests_json_file.TestEntry(
tests_json_file.TestSection(
"foo",
"//foo",
"linux",
path="host_x64/foo",
skipped_test_exit_code=skipped_exit_code,
)
),
test_list_file.TestListEntry("foo", [], execution=None),
),
exec_env,
flags,
)
self.assertTrue(test.is_host_test())
skipped_output = command.CommandOutput(
stdout, stderr, skipped_exit_code, 0.2, None
)
command_mock.return_value = skipped_output
recorder = event.EventRecorder()
recorder.emit_init()
with self.assertRaises(execution.TestSkipped) as cm:
await test.run(recorder, flags, event.GLOBAL_RUN_ID)
self.assertEqual(str(cm.exception), expected_message)
self.assertIs(cm.exception.command_output, skipped_output)
# Skip must not trigger failure analysis.
command_mock.assert_called_once()
@mock.patch.object(execution, "run_command", autospec=True)
async def test_host_test_skipped_exit_code_with_output_flag_uses_concise_message(
self, command_mock: mock.AsyncMock
) -> None:
"""Test that -o/--output uses a concise skip reason instead of duplicating live output."""
exec_env = _make_exec_env("/fuchsia", "/out/fuchsia")
flags = args.parse_args(["--output"])
self.assertTrue(flags.output)
test = execution.TestExecution(
test_list_file.Test(
tests_json_file.TestEntry(
tests_json_file.TestSection(
"foo",
"//foo",
"linux",
path="host_x64/foo",
skipped_test_exit_code=77,
)
),
test_list_file.TestListEntry("foo", [], execution=None),
),
exec_env,
flags,
)
self.assertTrue(test.is_host_test())
skipped_output = command.CommandOutput(
"SKIP: LEAN_BIN_DIR is not set\n",
"missing verification toolchains\n",
77,
0.2,
None,
)
command_mock.return_value = skipped_output
recorder = event.EventRecorder()
recorder.emit_init()
with self.assertRaises(execution.TestSkipped) as cm:
await test.run(recorder, flags, event.GLOBAL_RUN_ID)
self.assertEqual(
str(cm.exception),
"Test exited with skip status (exit code 77).",
)
self.assertIs(cm.exception.command_output, skipped_output)
command_mock.assert_called_once()
@parameterized.expand(
(
("unset_exit_77", None, 77),
("zero_exit_77", 0, 77),
("mismatched_exit_code", 77, 1),
)
)
@mock.patch.object(execution, "run_command", autospec=True)
async def test_host_test_without_matching_skipped_exit_code_raises_test_failed(
self,
_name: str,
skipped_exit_code: int | None,
return_code: int,
command_mock: mock.AsyncMock,
) -> None:
"""Test that exit code 77 fails when skipped_test_exit_code is unset, 0, or different."""
exec_env = _make_exec_env("/fuchsia", "/out/fuchsia")
flags = args.parse_args([])
test = execution.TestExecution(
test_list_file.Test(
tests_json_file.TestEntry(
tests_json_file.TestSection(
"foo",
"//foo",
"linux",
path="host_x64/foo",
skipped_test_exit_code=skipped_exit_code,
)
),
test_list_file.TestListEntry("foo", [], execution=None),
),
exec_env,
flags,
)
self.assertTrue(test.is_host_test())
command_mock.return_value = command.CommandOutput(
"", "permission denied", return_code, 0.2, None
)
recorder = event.EventRecorder()
recorder.emit_init()
with self.assertRaises(execution.TestFailed):
await test.run(recorder, flags, event.GLOBAL_RUN_ID)
@mock.patch.object(execution, "run_command", autospec=True)
async def test_host_test_skipped_exit_code_with_timeout_raises_test_timeout(
self, command_mock: mock.AsyncMock
) -> None:
"""Test that a timed-out host test still raises TestTimeout even with matching skip code."""
exec_env = _make_exec_env("/fuchsia", "/out/fuchsia")
flags = args.parse_args([])
test = execution.TestExecution(
test_list_file.Test(
tests_json_file.TestEntry(
tests_json_file.TestSection(
"foo",
"//foo",
"linux",
path="host_x64/foo",
skipped_test_exit_code=77,
)
),
test_list_file.TestListEntry("foo", [], execution=None),
),
exec_env,
flags,
)
self.assertTrue(test.is_host_test())
command_mock.return_value = command.CommandOutput(
"", "", 77, 300.0, None, was_timeout=True
)
recorder = event.EventRecorder()
recorder.emit_init()
with self.assertRaises(execution.TestTimeout):
await test.run(recorder, flags, event.GLOBAL_RUN_ID)
@mock.patch.object(execution, "run_command", autospec=True)
async def test_non_host_test_skipped_exit_code_raises_test_failed(
self, command_mock: mock.AsyncMock
) -> None:
"""Test that skipped_test_exit_code is only mapped to TestSkipped for host tests."""
exec_env = _make_exec_env("/fuchsia", "/out/fuchsia")
flags = args.parse_args(["--no-use-package-hash"])
test = execution.TestExecution(
test_list_file.Test(
tests_json_file.TestEntry(
tests_json_file.TestSection(
"foo",
"//foo",
"fuchsia",
skipped_test_exit_code=77,
)
),
test_list_file.TestListEntry(
"foo",
[],
test_list_file.TestListExecutionEntry(
"fuchsia-pkg://fuchsia.com/foo#meta/foo_test.cm",
),
),
),
exec_env,
flags,
)
self.assertFalse(test.is_host_test())
command_mock.return_value = command.CommandOutput(
"component error", "", 77, 0.2, None
)
recorder = event.EventRecorder()
recorder.emit_init()
with self.assertRaises(execution.TestFailed):
await test.run(recorder, flags, event.GLOBAL_RUN_ID)
class TestExecutionUtils(unittest.IsolatedAsyncioTestCase):
def _make_command_output(
self, stdout: str, return_code: int = 0
) -> command.CommandOutput:
return command.CommandOutput(stdout, "", return_code, 0.2, None)
def setUp(self) -> None:
self._temp_dir = tempfile.TemporaryDirectory()
self._env = _make_exec_env(self._temp_dir.name, "")
self._ssh_key_file = os.path.join(
self._temp_dir.name, "fuchsia_ed25519"
)
with open(self._ssh_key_file, "w") as f:
f.write("placeholder key")
return super().setUp()
def tearDown(self) -> None:
self._temp_dir.cleanup()
return super().tearDown()
@mock.patch("execution.run_command")
async def test_get_device_environment_success(
self, command_patch: mock.AsyncMock
) -> None:
command_patch.side_effect = [
self._make_command_output(""), # target wait
self._make_command_output("foo-bar"), # target default get
self._make_command_output("127.0.0.1:6000"), # target list
# config get ssh.priv
self._make_command_output(self._ssh_key_file),
]
device_env = await execution.get_device_environment_from_exec_env(
self._env
)
expected_device_subset = {
"address": "127.0.0.1",
"port": "6000",
"name": "foo-bar",
"private_key_path": self._ssh_key_file,
}
self.assertTrue(
expected_device_subset.items() <= vars(device_env).items()
)
@mock.patch("execution.run_command")
async def test_get_device_environment_ipv6(
self, command_patch: mock.AsyncMock
) -> None:
command_patch.side_effect = [
self._make_command_output(""), # target wait
self._make_command_output("foo-bar"), # target default get
self._make_command_output("[::1]:6000"), # target list
# config get ssh.priv
self._make_command_output(self._ssh_key_file),
]
device_env = await execution.get_device_environment_from_exec_env(
self._env
)
expected_device_ipv6_subset = {
"address": "[::1]",
"port": "6000",
"name": "foo-bar",
"private_key_path": self._ssh_key_file,
}
self.assertTrue(
expected_device_ipv6_subset.items() <= vars(device_env).items()
)
@mock.patch("execution.run_command")
async def test_get_device_environment_ssh_error(
self, command_patch: mock.AsyncMock
) -> None:
command_patch.side_effect = [
self._make_command_output(""), # target wait
self._make_command_output("foo-bar"), # target default get
self._make_command_output("", return_code=1), # target list fails
]
with self.assertRaisesRegex(
execution.DeviceConfigError, "Failed to get the ssh address"
):
await execution.get_device_environment_from_exec_env(self._env)
@mock.patch("execution.run_command")
async def test_get_device_environment_wait_error(
self, command_patch: mock.AsyncMock
) -> None:
command_patch.side_effect = [
self._make_command_output("", return_code=1), # target wait fails
]
with self.assertRaisesRegex(
execution.DeviceConfigError,
"Failed to wait for target to become reachable",
):
await execution.get_device_environment_from_exec_env(self._env)
@mock.patch("execution.run_command")
async def test_get_device_environment_bad_ip_format(
self, command_patch: mock.AsyncMock
) -> None:
command_patch.side_effect = [
self._make_command_output(""), # target wait
self._make_command_output("foo-bar"), # target default get
self._make_command_output("foo"), # target list
]
with self.assertRaisesRegex(
execution.DeviceConfigError,
r"Could not parse target address: 'foo'\.\nExpected 'ip:port' format\.\nReturn code: 0,\nStderr: ''",
):
await execution.get_device_environment_from_exec_env(self._env)
@mock.patch("execution.run_command")
async def test_get_device_environment_no_target_name(
self, command_patch: mock.AsyncMock
) -> None:
command_patch.side_effect = [
self._make_command_output(""), # target wait
self._make_command_output(
"", return_code=1
), # target default get fails
]
with self.assertRaisesRegex(
execution.DeviceConfigError,
"Failed to get the target name. Please ensure you have set a default target using 'fx set-device'. See 'fx set-device --help' for more details on target resolution.",
):
await execution.get_device_environment_from_exec_env(self._env)
@mock.patch("execution.run_command")
async def test_get_device_environment_ssh_key_not_found(
self, command_patch: mock.AsyncMock
) -> None:
command_patch.side_effect = [
self._make_command_output(""), # target wait
self._make_command_output("foo-bar"), # target default get
self._make_command_output("127.0.0.1:6000"), # target list
self._make_command_output(
"/nonexistent/path"
), # config get ssh.priv
]
with self.assertRaisesRegex(
execution.DeviceConfigError,
"Path returned by 'ssh.priv' does not exist",
):
await execution.get_device_environment_from_exec_env(self._env)
async def test_test_execution_gets_env_from_flags(self) -> None:
"""Test TestExecution wrapper uses the environment provided by flags"""
with tempfile.TemporaryDirectory() as tmp:
exec_env = _make_exec_env("/fuchsia", tmp)
flags = args.parse_args(
["-e", "foo=bar", "--env", "my_setting=baz"]
)
test = execution.TestExecution(
test_list_file.Test(
tests_json_file.TestEntry(
tests_json_file.TestSection(
"foo", "//foo", "linux", path="wont_exist"
)
),
test_list_file.TestListEntry("foo", [], execution=None),
),
exec_env,
flags,
)
e = test.environment()
assert e is not None
self.assertDictEqual(
e,
{"CWD": tmp, "foo": "bar", "my_setting": "baz"},
)
@parameterized.expand(
[
(
None,
None,
300,
),
(
None,
1234,
1234,
),
(
1234,
None,
1234,
),
(
0,
None,
None,
),
(
0,
1234,
None,
),
]
)
def test_calculate_timeout(
self,
arg: float | None,
config: int | None,
result: float | None,
) -> None:
"""Test _calculate_timeout function works properly"""
exec_env = _make_exec_env("/fuchsia", "/out/fuchsia")
test = execution.TestExecution(
test_list_file.Test(
tests_json_file.TestEntry(
tests_json_file.TestSection(
"foo",
"//foo",
"fuchsia",
timeout_secs=config,
)
),
test_list_file.TestListEntry(
"foo",
[],
test_list_file.TestListExecutionEntry(
"fuchsia-pkg://fuchsia.com/foo#meta/foo_test.cm",
realm="foo_tests",
max_severity_logs="INFO",
min_severity_logs="TRACE",
),
),
),
exec_env,
args.parse_args(["--timeout", str(arg)] if arg is not None else []),
)
self.assertEqual(test._calculate_timeout(), result)
async def test_get_device_ssh_address_ipv6_brackets_and_multiline(
self,
) -> None:
"""Test that get_device_environment_from_exec_env parses IPv6 bracketed addresses and ignores earlier lines."""
exec_env = _make_exec_env("/fuchsia", "/out/fuchsia")
recorder = mock.MagicMock()
with tempfile.NamedTemporaryFile() as tf:
async def fake_run_command(
*args_list: str, **kwargs: typing.Any
) -> command.CommandOutput:
cmd = " ".join(args_list)
if "wait" in cmd:
return command.CommandOutput(
stdout="",
stderr="",
return_code=0,
runtime=0.1,
wrapper_return_code=0,
)
elif "default get" in cmd:
return command.CommandOutput(
stdout="my-target\n",
stderr="",
return_code=0,
runtime=0.1,
wrapper_return_code=0,
)
elif "target list" in cmd:
return command.CommandOutput(
stdout="Some warning notice\n[fe80::1%eth0]:8022\n",
stderr="",
return_code=0,
runtime=0.1,
wrapper_return_code=0,
)
elif "ssh.priv" in cmd:
return command.CommandOutput(
stdout=f"{tf.name}\n",
stderr="",
return_code=0,
runtime=0.1,
wrapper_return_code=0,
)
return command.CommandOutput(
stdout="",
stderr="",
return_code=1,
runtime=0.1,
wrapper_return_code=1,
)
with mock.patch(
"execution.run_command", side_effect=fake_run_command
):
dev_env = await execution.get_device_environment_from_exec_env(
exec_env, recorder
)
self.assertEqual(dev_env.address, "[fe80::1%eth0]")
self.assertEqual(dev_env.port, "8022")
self.assertEqual(dev_env.private_key_path, tf.name)
async def test_get_device_ssh_address_parses_unbracketed_ipv6_and_default_port(
self,
) -> None:
"""Test that get_device_environment_from_exec_env parses unbracketed IPv6 addresses without mangling the address."""
exec_env = _make_exec_env("/fuchsia", "/out/fuchsia")
recorder = mock.MagicMock()
with tempfile.NamedTemporaryFile() as tf:
async def fake_run_command(
*args_list: str, **kwargs: typing.Any
) -> command.CommandOutput:
cmd = " ".join(args_list)
if "wait" in cmd:
return command.CommandOutput(
stdout="",
stderr="",
return_code=0,
runtime=0.1,
wrapper_return_code=0,
)
elif "default get" in cmd:
return command.CommandOutput(
stdout="my-target\n",
stderr="",
return_code=0,
runtime=0.1,
wrapper_return_code=0,
)
elif "target list" in cmd:
return command.CommandOutput(
stdout="fe80::1\n",
stderr="",
return_code=0,
runtime=0.1,
wrapper_return_code=0,
)
elif "ssh.priv" in cmd:
return command.CommandOutput(
stdout=f"{tf.name}\n",
stderr="",
return_code=0,
runtime=0.1,
wrapper_return_code=0,
)
return command.CommandOutput(
stdout="",
stderr="",
return_code=1,
runtime=0.1,
wrapper_return_code=1,
)
with mock.patch(
"execution.run_command", side_effect=fake_run_command
):
dev_env = await execution.get_device_environment_from_exec_env(
exec_env, recorder
)
self.assertEqual(dev_env.address, "fe80::1")
self.assertEqual(dev_env.port, "22")
@parameterized.expand(
[
(
"bracketed_ipv6_with_port",
"[fe80::1%eth0]:8022",
"[fe80::1%eth0]",
"8022",
),
("bracketed_ipv6_default_port", "[fe80::1]", "[fe80::1]", "22"),
(
"bracketed_ipv6_explicit_standard_port",
"[fe80::1]:22",
"[fe80::1]",
"22",
),
("bracketed_loopback_with_port", "[::1]:8022", "[::1]", "8022"),
("bracketed_loopback_default_port", "[::1]", "[::1]", "22"),
(
"bracketed_global_unicast_with_port",
"[2001:db8::1]:53",
"[2001:db8::1]",
"53",
),
(
"bracketed_full_ipv6_with_port",
"[2001:0db8:85a3:0000:0000:8a2e:0370:7334]:8022",
"[2001:0db8:85a3:0000:0000:8a2e:0370:7334]",
"8022",
),
(
"bracketed_ipv4_mapped_ipv6",
"[::ffff:192.0.2.1]:8022",
"[::ffff:192.0.2.1]",
"8022",
),
("bracketed_unspecified_ipv6", "[::]:22", "[::]", "22"),
("unbracketed_link_local", "fe80::1", "fe80::1", "22"),
(
"unbracketed_link_local_with_scope",
"fe80::1%eth0",
"fe80::1%eth0",
"22",
),
("unbracketed_loopback", "::1", "::1", "22"),
("unbracketed_global_unicast", "2001:db8::1", "2001:db8::1", "22"),
(
"unbracketed_full_ipv6",
"2001:db8:85a3:8d3:1319:8a2e:370:7348",
"2001:db8:85a3:8d3:1319:8a2e:370:7348",
"22",
),
("ipv4_with_port", "192.168.1.1:8022", "192.168.1.1", "8022"),
("ipv4_loopback_with_port", "127.0.0.1:22", "127.0.0.1", "22"),
("hostname_with_port", "localhost:8022", "localhost", "8022"),
("usb_cid", "usb:cid:3", "usb:cid", "3"),
("vsock_cid", "vsock:cid:4", "vsock:cid", "4"),
]
)
def test_parse_device_address_valid(
self,
_name: str,
target_line: str,
expected_ip: str,
expected_port: str,
) -> None:
"""Test _parse_device_address parses various valid address formats correctly."""
ip, port = execution._parse_device_address(target_line)
self.assertEqual(ip, expected_ip)
self.assertEqual(port, expected_port)
@parameterized.expand(
(
("slirp_ipv4", "127.0.0.1:39259", "127.0.0.1:39259"),
(
"bracketed_ipv6_with_scope_and_port",
"[fe80::1%eth0]:8022",
"[fe80::1%eth0]:8022",
),
(
"unbracketed_ipv6_with_scope",
"fe80::1%eth0",
"[fe80::1%eth0]:22",
),
("unbracketed_ipv6", "fe80::1", "[fe80::1]:22"),
("hostname_with_port", "localhost:8022", "localhost:8022"),
("usb_cid", "usb:cid:3", "usb:cid:3"),
("vsock_cid", "vsock:cid:4", "vsock:cid:4"),
)
)
def test_parse_and_format_target_address_roundtrip(
self,
_name: str,
target_line: str,
expected_formatted: str,
) -> None:
"""Test parsed device addresses format back into valid ffx target addresses."""
ip, port = execution._parse_device_address(target_line)
self.assertEqual(
execution._format_target_address(ip, port), expected_formatted
)
@parameterized.expand(
[
("missing_closing_bracket", "[fe80::1"),
("empty_bracket", "[]:22"),
("empty_port_after_colon", "[fe80::1]:"),
("non_numeric_port", "[fe80::1]:abc"),
("port_zero", "[fe80::1]:0"),
("port_too_large", "[fe80::1]:65536"),
("negative_port", "[fe80::1]:-1"),
("junk_after_bracket", "[fe80::1]extra:22"),
("invalid_ipv6_triple_colon", "[fe80:::1]:22"),
("invalid_ipv6_hex_chars", "[fe80::xyz]:22"),
("empty_scope_id_in_bracket", "[fe80::1%]:22"),
("unbracketed_triple_colon", "fe80:::1"),
("unbracketed_invalid_hex", "fe80::xyz"),
("unbracketed_empty_scope_id", "fe80::1%"),
("missing_host_before_colon", ":8022"),
("no_colon_no_ipv6", "nohost"),
("usb_cid_non_numeric", "usb:cid:abc"),
("usb_cid_empty", "usb:cid:"),
]
)
def test_parse_device_address_invalid(
self,
_name: str,
target_line: str,
) -> None:
"""Test _parse_device_address rejects malformed addresses and invalid ports."""
with self.assertRaises(execution.DeviceConfigError):
execution._parse_device_address(target_line)
@mock.patch("async_utils.command.AsyncCommand.create")
async def test_command_abort_waits_for_process_exit_without_sleeping_full_timeout(
self, mock_create: mock.AsyncMock
) -> None:
"""Test that abort_signal waits on process runner task rather than sleeping 5s."""
mock_cmd = mock.MagicMock()
runner_future = asyncio.get_running_loop().create_future()
def terminate_side_effect() -> None:
if not runner_future.done():
runner_future.set_result(None)
mock_cmd.terminate.side_effect = terminate_side_effect
mock_cmd._runner_task = runner_future
mock_cmd.run_to_completion = mock.AsyncMock(
return_value=mock.MagicMock(return_code=-15)
)
mock_create.return_value = mock_cmd
recorder = mock.MagicMock()
abort_signal = asyncio.Event()
task = asyncio.create_task(
execution.run_command(
"my_cmd",
recorder=recorder,
abort_signal=abort_signal,
)
)
await asyncio.sleep(0.01)
abort_signal.set()
await task
mock_cmd.kill.assert_not_called()
for call in recorder.emit_warning_message.call_args_list:
self.assertNotIn("did not terminate in time", call[0][0])
def test_is_host_test(self) -> None:
"""Test that TestExecution.is_host_test returns True for a pure host test."""
exec_env = _make_exec_env("/fuchsia", "/out/fuchsia")
test = execution.TestExecution(
test_list_file.Test(
tests_json_file.TestEntry(
tests_json_file.TestSection(
"foo", "//foo", "linux", path="host_x64/foo"
)
),
test_list_file.TestListEntry("foo", [], execution=None),
),
exec_env,
args.parse_args([]),
)
self.assertTrue(test.is_host_test())
self.assertFalse(test.is_hermetic())
class TestHostTestFiltering(unittest.IsolatedAsyncioTestCase):
def _make_command_output(
self, stdout: str, return_code: int = 0
) -> command.CommandOutput:
return command.CommandOutput(stdout, "", return_code, 0.1, None)
def test_custom_python_main_callable_omits_enumerate_command(self) -> None:
with tempfile.TemporaryDirectory() as tmp:
out_dir = pathlib.Path(tmp)
(out_dir / "custom_main.py").write_text("def custom_main(): pass\n")
(out_dir / "custom_py.sh").write_text(
"#!/bin/bash\n"
'if [[ "$1" == "--list_host_python_unittests" ]]; then\n'
" exec python3 lister.pyz --list_tests 'custom_main.py'\n"
"fi\n"
"exec python3 'custom_main.py' \"$@\"\n"
)
self.assertIsNone(
execution.TestExecution(
_make_host_test(
"custom_py.sh",
list_cases_argument="list_host_python_unittests",
),
_make_exec_env("/fuchsia", tmp),
args.parse_args([]),
).enumerate_cases_command_line()
)
@mock.patch.object(execution, "run_command", autospec=True)
async def test_python_unittest_host_filter_and_custom_callable(
self, mock_run_command: mock.AsyncMock
) -> None:
exec_env = _make_exec_env("/fuchsia", "/out/fuchsia")
py_test = _make_host_test(
"host_x64/py_test.sh",
list_cases_argument="list_host_python_unittests",
)
# Matching filter runs only matching unittest cases before extra_args.
flags = args.parse_args(
["--test-filter", "*alpha*", "--", "--extra-flag"]
)
test_exec = execution.TestExecution(py_test, exec_env, flags)
mock_run_command.side_effect = [
self._make_command_output(
"MySuite.test_alpha\nMySuite.test_beta\n"
),
self._make_command_output("OK"),
]
recorder = event.EventRecorder()
recorder.emit_init()
await test_exec.run(recorder, flags, event.GLOBAL_RUN_ID)
self.assertEqual(mock_run_command.call_count, 2)
self.assertSequenceEqual(
mock_run_command.call_args_list[0].args,
(
"/out/fuchsia/host_x64/py_test.sh",
"--list_host_python_unittests",
),
)
self.assertSequenceEqual(
mock_run_command.call_args_list[1].args,
(
"host_x64/py_test.sh",
"MySuite.test_alpha",
"--extra-flag",
),
)
# Empty unittest case list raises TestFilterUnsupported.
mock_run_command.reset_mock()
mock_run_command.side_effect = [self._make_command_output("")]
empty_exec = execution.TestExecution(py_test, exec_env, flags)
with self.assertRaises(execution.TestFilterUnsupported):
await empty_exec.run(recorder, flags, event.GLOBAL_RUN_ID)
# On-disk custom main_callable wrapper raises TestFilterUnsupported without running.
mock_run_command.reset_mock()
with tempfile.TemporaryDirectory() as tmp:
out_dir = pathlib.Path(tmp)
(out_dir / "custom_main.py").write_text("def custom_main(): pass\n")
(out_dir / "custom_py.sh").write_text(
"#!/bin/bash\n"
'if [[ "$1" == "--list_host_python_unittests" ]]; then\n'
" exec python3 lister.pyz --list_tests 'custom_main.py'\n"
"fi\n"
"exec python3 'custom_main.py' \"$@\"\n"
)
custom_test = test_list_file.Test(
tests_json_file.TestEntry(
tests_json_file.TestSection(
"custom_py.sh",
"//foo:custom_py",
"linux",
path="custom_py.sh",
list_cases_argument="list_host_python_unittests",
)
),
test_list_file.TestListEntry(
"custom_py.sh", [], execution=None
),
)
custom_exec = execution.TestExecution(
custom_test, _make_exec_env("/fuchsia", tmp), flags
)
with self.assertRaises(execution.TestFilterUnsupported):
await custom_exec.run(recorder, flags, event.GLOBAL_RUN_ID)
mock_run_command.assert_not_called()
@mock.patch.object(execution, "run_command", autospec=True)
async def test_rust_go_and_gtest_host_filtering(
self, mock_run_command: mock.AsyncMock
) -> None:
with tempfile.TemporaryDirectory() as tmp:
out_dir = pathlib.Path(tmp)
(out_dir / "rust.sh").write_text(
"#!/bin/bash\nexec host_x64/rust_test_parser 'host_x64/rust_bin' \"$@\"\n"
)
(out_dir / "go.sh").write_text(
"#!/bin/bash\nexec host_x64/go_test_parser 'host_x64/go_bin' -test.v \"$@\"\n"
)
(out_dir / "gtest_bin").write_bytes(
b"\x7fELF\x02\x01\x01\x00--gtest_filter\x00"
)
(out_dir / "gunit_bin").write_bytes(
b"\x7fELF\x02\x01\x01\x00--gunit_filter\x00"
)
(out_dir / "opaque.sh").write_text(
'#!/bin/bash\nexec ./custom_tool "$@"\n'
)
exec_env = _make_exec_env("/fuchsia", tmp)
recorder = event.EventRecorder()
recorder.emit_init()
def make_exec(
rel_path: str, cli: list[str]
) -> tuple[execution.TestExecution, args.Flags]:
parsed_flags = args.parse_args(cli)
return (
execution.TestExecution(
_make_host_test(rel_path), exec_env, parsed_flags
),
parsed_flags,
)
# 1. Rust host test with --test-filter and --also-run-disabled-tests
rust_exec, rust_flags = make_exec(
"rust.sh",
[
"--test-filter",
"tests::*match*",
"--also-run-disabled-tests",
],
)
mock_run_command.side_effect = [
self._make_command_output(
"starting tool host_x64/rust_test_parser\n"
"Running host_x64/rust_bin\n"
"tests::test_matching: test\n"
"tests::test_other: test\n"
),
self._make_command_output("ok"),
]
await rust_exec.run(recorder, rust_flags, event.GLOBAL_RUN_ID)
self.assertSequenceEqual(
mock_run_command.call_args_list[1].args,
(
"rust.sh",
"--include-ignored",
"--exact",
"tests::test_matching",
),
)
# 2. Go host test with --test-filter
mock_run_command.reset_mock()
go_exec, go_flags = make_exec(
"go.sh", ["--test-filter", "TestQEMU*/sub_1"]
)
mock_run_command.side_effect = [
self._make_command_output(
"starting tool host_x64/go_test_parser\n"
"Running host_x64/go_bin\n"
"TestAEMU\n"
"TestQEMUBuilder\n"
),
self._make_command_output("PASS"),
]
await go_exec.run(recorder, go_flags, event.GLOBAL_RUN_ID)
self.assertSequenceEqual(
mock_run_command.call_args_list[1].args,
("go.sh", "-test.run", "^TestQEMU.*$/sub_1"),
)
# 3. C++ GTest/zxtest host test with --test-filter
mock_run_command.reset_mock()
cc_exec, cc_flags = make_exec(
"gtest_bin", ["--test-filter", "Opt*"]
)
mock_run_command.side_effect = [
self._make_command_output(
"ArgsParser\n .General\n .OptStruct\n"
),
self._make_command_output("[ PASSED ]"),
]
await cc_exec.run(recorder, cc_flags, event.GLOBAL_RUN_ID)
self.assertSequenceEqual(
mock_run_command.call_args_list[1].args,
("gtest_bin", "--gtest_filter=ArgsParser.OptStruct"),
)
# 3b. C++ gunit host test with --test-filter and --also-run-disabled-tests
mock_run_command.reset_mock()
gunit_exec, gunit_flags = make_exec(
"gunit_bin",
["--test-filter", "*Opt*", "--also-run-disabled-tests"],
)
mock_run_command.side_effect = [
self._make_command_output(
"ArgsParser.\n General\n DISABLED_OptStruct\n"
),
self._make_command_output("[ PASSED ]"),
]
await gunit_exec.run(recorder, gunit_flags, event.GLOBAL_RUN_ID)
self.assertSequenceEqual(
mock_run_command.call_args_list[0].args,
(
f"{tmp}/gunit_bin",
"--gunit_list_tests",
"--gunit_also_run_disabled_tests",
),
)
self.assertSequenceEqual(
mock_run_command.call_args_list[1].args,
(
"gunit_bin",
"--gunit_also_run_disabled_tests",
"--gunit_filter=ArgsParser.DISABLED_OptStruct",
),
)
# 4. Opaque custom host_test raises TestFilterUnsupported
mock_run_command.reset_mock()
opaque_exec, opaque_flags = make_exec(
"opaque.sh", ["--test-filter", "anything"]
)
with self.assertRaises(execution.TestFilterUnsupported):
await opaque_exec.run(
recorder, opaque_flags, event.GLOBAL_RUN_ID
)
mock_run_command.assert_not_called()
# 5. Missing host test binary (e.g. --no-build) raises TestCouldNotRun
missing_exec, missing_flags = make_exec(
"unbuilt_bin", ["--test-filter", "anything"]
)
with self.assertRaises(execution.TestCouldNotRun):
await missing_exec.run(
recorder, missing_flags, event.GLOBAL_RUN_ID
)
mock_run_command.assert_not_called()
@parameterized.expand(
(
(
"rust_strips_benchmarks_and_headers",
"rust.sh",
b'#!/bin/bash\nexec host_x64/rust_test_parser host_x64/bin "$@"\n',
None,
(),
(
"starting tool rust_test_parser\n"
"mod::case_a: test\n"
"mod::bench_b: benchmark\n"
"top_case: test\n\n"
"2 tests, 1 benchmark\n"
),
("--list", "--format=terse"),
"mod::case_a\ntop_case",
),
(
"go_strips_wrapper_and_pass_lines",
"go.sh",
b'#!/bin/bash\nexec host_x64/go_test_parser host_x64/bin -test.v "$@"\n',
None,
(),
(
"starting tool go_test_parser\n"
"Running host_x64/bin\n"
"TestAlpha\n"
"BenchmarkBeta\n"
"ExampleGamma\n"
"FuzzDelta\n"
"PASS\n"
"ok pkg 0.001s\n"
),
("-test.list", "."),
"TestAlpha\nBenchmarkBeta\nExampleGamma\nFuzzDelta",
),
(
"gtest_excludes_disabled_by_default",
"gtest_bin",
b"\x7fELF\x02\x01\x01\x00--gtest_filter\x00",
None,
(),
"Suite.\n ActiveCase\n DISABLED_SlowCase\n",
("--gtest_list_tests",),
"Suite.ActiveCase",
),
(
"gtest_includes_disabled_when_requested",
"gtest_bin",
b"\x7fELF\x02\x01\x01\x00--gtest_filter\x00",
None,
("--also-run-disabled-tests",),
"Suite.\n ActiveCase\n DISABLED_SlowCase\n",
("--gtest_list_tests", "--gtest_also_run_disabled_tests"),
"Suite.ActiveCase\nSuite.DISABLED_SlowCase",
),
(
"gunit_includes_disabled_when_requested",
"gunit_bin",
b"\x7fELF\x02\x01\x01\x00--gunit_filter\x00",
None,
("--also-run-disabled-tests",),
"Suite.\n ActiveCase\n DISABLED_SlowCase\n",
("--gunit_list_tests", "--gunit_also_run_disabled_tests"),
"Suite.ActiveCase\nSuite.DISABLED_SlowCase",
),
(
"mobly_zero_cases_banner_only",
"mobly.sh",
b'#!/bin/bash\nexec ./mobly_driver "$@"\n',
"list_mobly_tests",
(),
"Starting Mobly driver...\n==========> EmptyMoblySuite <==========\n",
("--list_mobly_tests",),
"",
),
)
)
@mock.patch.object(execution, "run_command", autospec=True)
async def test_enumerate_test_cases_host_runners(
self,
_name: str,
rel_path: str,
file_bytes: bytes,
list_arg: str | None,
cli_flags: Sequence[str],
raw_stdout: str,
expected_enum_flags: Sequence[str],
expected_stdout: str,
mock_run_command: mock.AsyncMock,
) -> None:
with tempfile.TemporaryDirectory() as tmp:
(pathlib.Path(tmp) / rel_path).write_bytes(file_bytes)
parsed_flags = args.parse_args(list(cli_flags))
test_exec = execution.TestExecution(
_make_host_test(rel_path, list_cases_argument=list_arg),
_make_exec_env("/fuchsia", tmp),
parsed_flags,
)
mock_run_command.return_value = self._make_command_output(
raw_stdout
)
recorder = event.EventRecorder()
recorder.emit_init()
enumeration_output = await test_exec.enumerate_test_cases(recorder)
assert enumeration_output is not None
self.assertEqual(mock_run_command.call_count, 1)
self.assertSequenceEqual(
mock_run_command.call_args.args,
(f"{tmp}/{rel_path}", *expected_enum_flags),
)
self.assertEqual(enumeration_output.stdout, expected_stdout)
@parameterized.expand(
(
(
"rust_include_ignored",
"rust.sh",
b'#!/bin/bash\nexec host_x64/rust_test_parser host_x64/bin "$@"\n',
("rust.sh", "--include-ignored"),
),
(
"gtest_also_run_disabled",
"gtest_bin",
b"\x7fELF\x02\x01\x01\x00--gtest_filter\x00",
("gtest_bin", "--gtest_also_run_disabled_tests"),
),
(
"gunit_also_run_disabled",
"gunit_bin",
b"\x7fELF\x02\x01\x01\x00--gunit_filter\x00",
("gunit_bin", "--gunit_also_run_disabled_tests"),
),
)
)
@mock.patch.object(execution, "run_command", autospec=True)
async def test_also_run_disabled_tests_without_filter(
self,
_name: str,
rel_path: str,
file_bytes: bytes,
expected_args: Sequence[str],
mock_run_command: mock.AsyncMock,
) -> None:
with tempfile.TemporaryDirectory() as tmp:
(pathlib.Path(tmp) / rel_path).write_bytes(file_bytes)
parsed_flags = args.parse_args(["--also-run-disabled-tests"])
test_exec = execution.TestExecution(
_make_host_test(rel_path),
_make_exec_env("/fuchsia", tmp),
parsed_flags,
)
mock_run_command.return_value = self._make_command_output("ok")
recorder = event.EventRecorder()
recorder.emit_init()
await test_exec.run(recorder, parsed_flags, event.GLOBAL_RUN_ID)
self.assertEqual(mock_run_command.call_count, 1)
self.assertSequenceEqual(
mock_run_command.call_args.args, expected_args
)
@parameterized.expand(
(
(
"enum_nonzero_exit",
command.CommandOutput("", "enumeration error", 2, 0.1, None),
"Suite.*",
execution.TestCouldNotRun,
),
(
"enum_none_output",
None,
"Suite.*",
execution.TestCouldNotRun,
),
(
"zero_matching_cases",
command.CommandOutput("Suite.\n CaseA\n", "", 0, 0.1, None),
"NoMatch*",
execution.TestSkipped,
),
)
)
@mock.patch.object(execution, "run_command", autospec=True)
async def test_run_host_filter_aborts_before_binary_on_enum_error_or_zero_match(
self,
_name: str,
enum_output: command.CommandOutput | None,
filter_pattern: str,
expected_exc: type[execution.TestExecutionError],
mock_run_command: mock.AsyncMock,
) -> None:
with tempfile.TemporaryDirectory() as tmp:
(pathlib.Path(tmp) / "gtest_bin").write_bytes(
b"\x7fELF\x02\x01\x01\x00--gtest_filter\x00"
)
parsed_flags = args.parse_args(["--test-filter", filter_pattern])
test_exec = execution.TestExecution(
_make_host_test("gtest_bin"),
_make_exec_env("/fuchsia", tmp),
parsed_flags,
)
mock_run_command.return_value = enum_output
recorder = event.EventRecorder()
recorder.emit_init()
with self.assertRaises(expected_exc):
await test_exec.run(recorder, parsed_flags, event.GLOBAL_RUN_ID)
# Only the enumeration command ran; the test binary was never invoked.
self.assertEqual(mock_run_command.call_count, 1)
@mock.patch.object(execution, "run_command", autospec=True)
async def test_mobly_e2e_glob_and_exclusion_filter_and_zero_match_skip(
self, mock_run_command: mock.AsyncMock
) -> None:
exec_env = _make_exec_env("/fuchsia", "/out/fuchsia")
device_env = environment.DeviceEnvironment(
address="127.0.0.1",
port="22",
name="fuchsia-dut",
private_key_path="/path/to/key",
)
mobly_test = _make_host_test(
"host_x64/mobly_e2e",
list_cases_argument="list_mobly_tests",
is_e2e=True,
)
raw_mobly_list = (
"==========> MyMoblySuite <==========\n"
"test_fast\n"
"test_slow\n"
"helper_case\n"
)
recorder = event.EventRecorder()
recorder.emit_init()
match_flags = args.parse_args(
[
"--e2e",
"--test-filter=test_*",
"--test-filter=-*_slow",
]
)
match_exec = execution.TestExecution(
mobly_test, exec_env, match_flags, device_env=device_env
)
mock_run_command.side_effect = [
self._make_command_output(raw_mobly_list),
self._make_command_output("PASS"),
]
await match_exec.run(recorder, match_flags, event.GLOBAL_RUN_ID)
self.assertEqual(mock_run_command.call_count, 2)
self.assertSequenceEqual(
mock_run_command.call_args_list[1].args,
(
"host_x64/mobly_e2e",
"--ssh-key",
"/path/to/key",
"--test_cases",
"test_fast",
),
)
mock_run_command.reset_mock()
skip_flags = args.parse_args(["--e2e", "--test-filter", "unmatched_*"])
skip_exec = execution.TestExecution(
mobly_test, exec_env, skip_flags, device_env=device_env
)
mock_run_command.side_effect = [
self._make_command_output(raw_mobly_list)
]
with self.assertRaises(execution.TestSkipped):
await skip_exec.run(recorder, skip_flags, event.GLOBAL_RUN_ID)
self.assertEqual(mock_run_command.call_count, 1)
# .hermetic Mobly wrapper without list_cases_argument still gets --list_mobly_tests and --ssh-key.
with tempfile.TemporaryDirectory() as tmp:
(pathlib.Path(tmp) / "hermetic_mobly.sh").write_text(
'#!/bin/bash\nexec host_x64/mobly_test_parser ./driver ./test "$@"\n'
)
hermetic_exec = execution.TestExecution(
_make_host_test("hermetic_mobly.sh", is_e2e=True),
_make_exec_env("/fuchsia", tmp),
args.parse_args(["--e2e"]),
device_env=device_env,
)
self.assertSequenceEqual(
hermetic_exec.enumerate_cases_command_line() or (),
(f"{tmp}/hermetic_mobly.sh", "--list_mobly_tests"),
)
self.assertSequenceEqual(
hermetic_exec.command_line(
extra_runner_args=("--test_cases", "test_fast")
),
(
"hermetic_mobly.sh",
"--ssh-key",
"/path/to/key",
"--test_cases",
"test_fast",
),
)
class TestPackagePreResolution(unittest.IsolatedAsyncioTestCase):
def setUp(self) -> None:
super().setUp()
patch = mock.patch.dict(os.environ, {}, clear=False)
patch.start()
os.environ.pop("FUCHSIA_NODENAME", None)
self.addCleanup(patch.stop)
def _make_command_output(
self,
stdout: str = "",
stderr: str = "",
return_code: int = 0,
was_timeout: bool = False,
) -> command.CommandOutput:
return command.CommandOutput(
stdout, stderr, return_code, 0.1, None, was_timeout=was_timeout
)
def _make_device_test(
self,
*,
package_url: str
| None = "fuchsia-pkg://fuchsia.com/foo#meta/foo_test.cm",
path: str | None = "bin/foo_test_wrapper.sh",
os_name: str = "linux",
timeout_secs: int | None = None,
package_resolution_timeout_secs: int | None = None,
component_url: str
| None = "fuchsia-pkg://fuchsia.com/foo#meta/foo_test.cm",
) -> test_list_file.Test:
execution_entry = (
test_list_file.TestListExecutionEntry(component_url)
if component_url is not None
else None
)
return test_list_file.Test(
tests_json_file.TestEntry(
tests_json_file.TestSection(
"foo",
"//foo",
os_name,
package_url=package_url,
path=path,
timeout_secs=timeout_secs,
package_resolution_timeout_secs=package_resolution_timeout_secs,
)
),
test_list_file.TestListEntry("foo", [], execution=execution_entry),
)
@parameterized.expand(
(
("none", None, None),
("empty", "", None),
("bootfs_url", "fuchsia-boot:///foo#meta/foo_test.cm", None),
(
"component_url",
"fuchsia-pkg://fuchsia.com/foo#meta/foo_test.cm",
"fuchsia-pkg://fuchsia.com/foo",
),
(
"bare_package_url",
"fuchsia-pkg://fuchsia.com/foo",
"fuchsia-pkg://fuchsia.com/foo",
),
(
"hashed_component_url",
"fuchsia-pkg://fuchsia.com/foo?hash=abc123#meta/foo_test.cm",
"fuchsia-pkg://fuchsia.com/foo?hash=abc123",
),
)
)
def test_extract_package_resolve_url(
self,
_name: str,
package_url: str | None,
expected: str | None,
) -> None:
self.assertEqual(
execution._extract_package_resolve_url(package_url), expected
)
@parameterized.expand(
(
(
"default",
None,
None,
execution.DEFAULT_PACKAGE_RESOLUTION_TIMEOUT,
),
(
"zero_configured_uses_default",
None,
0,
execution.DEFAULT_PACKAGE_RESOLUTION_TIMEOUT,
),
("explicit_configured", None, 660, 660),
(
"cli_timeout_does_not_override_default",
30,
None,
execution.DEFAULT_PACKAGE_RESOLUTION_TIMEOUT,
),
("cli_timeout_does_not_override_configured", 30, 660, 660),
("zero_cli_timeout_disables_default", 0, None, None),
("zero_cli_timeout_disables_configured", 0, 660, None),
)
)
def test_calculate_package_resolution_timeout(
self,
_name: str,
cli_timeout: float | None,
configured_timeout: int | None,
expected: float | None,
) -> None:
exec_env = _make_exec_env("/fuchsia", "/out/fuchsia")
flags = args.parse_args(
["--timeout", str(cli_timeout)] if cli_timeout is not None else []
)
test = execution.TestExecution(
self._make_device_test(
package_resolution_timeout_secs=configured_timeout
),
exec_env,
flags,
)
self.assertEqual(test._calculate_package_resolution_timeout(), expected)
@mock.patch.object(execution, "run_command", autospec=True)
async def test_pre_resolves_package_before_test_pilot_with_separate_timeout(
self, mock_run_command: mock.AsyncMock
) -> None:
exec_env = _make_exec_env("/fuchsia", "/out/fuchsia")
flags = args.parse_args(["--no-use-package-hash"])
test = execution.TestExecution(
self._make_device_test(
timeout_secs=30,
package_resolution_timeout_secs=660,
),
exec_env,
flags,
)
mock_run_command.side_effect = (
self._make_command_output("Successfully resolved"),
self._make_command_output("PASSED"),
)
recorder = event.EventRecorder()
recorder.emit_init()
output = await test.run(recorder, flags, event.GLOBAL_RUN_ID)
recorder.emit_end()
self.assertEqual(output.stdout, "PASSED")
self.assertEqual(mock_run_command.call_count, 2)
resolve_call = mock_run_command.call_args_list[0]
self.assertSequenceEqual(
resolve_call.args,
(
"fx",
"--dir",
"/out/fuchsia",
"ffx",
"target",
"package",
"resolve",
"fuchsia-pkg://fuchsia.com/foo",
),
)
self.assertEqual(resolve_call.kwargs["timeout"], 660)
self.assertFalse(resolve_call.kwargs["print_verbatim"])
self.assertEqual(resolve_call.kwargs["parent"], event.GLOBAL_RUN_ID)
test_call = mock_run_command.call_args_list[1]
self.assertSequenceEqual(
test_call.args,
("/out/fuchsia/bin/foo_test_wrapper.sh", "--timeout=30"),
)
self.assertEqual(
test_call.kwargs["timeout"], 30 + flags.timeout_grace_period
)
@mock.patch.object(execution, "run_command", autospec=True)
async def test_pre_resolves_package_with_default_timeout_for_legacy_ffx_test(
self, mock_run_command: mock.AsyncMock
) -> None:
exec_env = _make_exec_env("/fuchsia", "/out/fuchsia")
flags = args.parse_args(["--no-use-package-hash"])
test = execution.TestExecution(
self._make_device_test(
path=None,
os_name="fuchsia",
package_resolution_timeout_secs=None,
),
exec_env,
flags,
)
mock_run_command.side_effect = (
self._make_command_output("Successfully resolved"),
self._make_command_output("PASSED"),
)
recorder = event.EventRecorder()
recorder.emit_init()
output = await test.run(recorder, flags, event.GLOBAL_RUN_ID)
recorder.emit_end()
self.assertEqual(output.stdout, "PASSED")
self.assertEqual(mock_run_command.call_count, 2)
self.assertSequenceEqual(
mock_run_command.call_args_list[0].args,
(
"fx",
"--dir",
"/out/fuchsia",
"ffx",
"target",
"package",
"resolve",
"fuchsia-pkg://fuchsia.com/foo",
),
)
self.assertEqual(
mock_run_command.call_args_list[0].kwargs["timeout"],
execution.DEFAULT_PACKAGE_RESOLUTION_TIMEOUT,
)
self.assertSequenceEqual(
mock_run_command.call_args_list[1].args[:6],
("fx", "--dir", "/out/fuchsia", "ffx", "test", "run"),
)
self.assertEqual(
mock_run_command.call_args_list[1].kwargs["timeout"],
execution.DEFAULT_TIMEOUT + flags.timeout_grace_period,
)
@parameterized.expand(
(
(
"host_test",
tests_json_file.TestEntry(
tests_json_file.TestSection(
"foo", "//foo", "linux", path="host_x64/foo"
)
),
None,
(),
),
(
"e2e_test",
tests_json_file.TestEntry(
tests_json_file.TestSection(
"foo", "//foo", "linux", path="host_x64/foo_e2e"
),
environments=[
tests_json_file.EnvironmentEntry(
dimensions=tests_json_file.DimensionsEntry(
device_type="AEMU"
)
)
],
),
None,
("--e2e",),
),
(
"bootfs_component_test",
tests_json_file.TestEntry(
tests_json_file.TestSection(
"foo",
"//foo",
"fuchsia",
package_url="fuchsia-boot:///foo#meta/foo_test.cm",
)
),
test_list_file.TestListExecutionEntry(
"fuchsia-boot:///foo#meta/foo_test.cm"
),
("--no-use-package-hash",),
),
)
)
@mock.patch.object(execution, "run_command", autospec=True)
async def test_skips_pre_resolution_for_non_fuchsia_pkg_tests(
self,
_name: str,
entry: tests_json_file.TestEntry,
execution_entry: test_list_file.TestListExecutionEntry | None,
cli_flags: tuple[str, ...],
mock_run_command: mock.AsyncMock,
) -> None:
exec_env = _make_exec_env("/fuchsia", "/out/fuchsia")
flags = args.parse_args(list(cli_flags))
test = execution.TestExecution(
test_list_file.Test(
entry,
test_list_file.TestListEntry(
"foo", [], execution=execution_entry
),
),
exec_env,
flags,
)
mock_run_command.return_value = self._make_command_output("PASSED")
recorder = event.EventRecorder()
recorder.emit_init()
await test.run(recorder, flags, event.GLOBAL_RUN_ID)
recorder.emit_end()
mock_run_command.assert_called_once()
self.assertNotIn("resolve", mock_run_command.call_args.args)
@mock.patch.object(execution, "run_command", autospec=True)
async def test_resolution_timeout_warns_and_continues_to_run_test(
self, mock_run_command: mock.AsyncMock
) -> None:
exec_env = _make_exec_env("/fuchsia", "/out/fuchsia")
flags = args.parse_args(["--no-use-package-hash"])
test = execution.TestExecution(
self._make_device_test(timeout_secs=45),
exec_env,
flags,
)
mock_run_command.side_effect = (
self._make_command_output(return_code=-15, was_timeout=True),
self._make_command_output("PASSED"),
)
recorder = event.EventRecorder()
recorder.emit_init()
output = await test.run(recorder, flags, event.GLOBAL_RUN_ID)
recorder.emit_end()
self.assertEqual(output.stdout, "PASSED")
self.assertEqual(mock_run_command.call_count, 2)
warning_messages = tuple(
[
e.payload.user_message.value
async for e in recorder.iter()
if e.payload is not None
and e.payload.user_message is not None
and e.payload.user_message.level == event.MessageLevel.WARNING
]
)
self.assertTrue(
any(
"Timed out resolving package fuchsia-pkg://fuchsia.com/foo "
f"after {execution.DEFAULT_PACKAGE_RESOLUTION_TIMEOUT} seconds"
in msg
for msg in warning_messages
),
warning_messages,
)
@parameterized.expand(
(
(
"nonzero_with_stderr",
command.CommandOutput(
"", "PackageNotFound\n", 1, 0.1, None, was_timeout=False
),
"PackageNotFound",
"exit code 1",
),
(
"nonzero_empty_output",
command.CommandOutput("", "", 1, 0.1, None, was_timeout=False),
"exit code 1",
"exit code 1",
),
(
"launch_error_none",
None,
"failed to run command",
"failed to run command",
),
)
)
@mock.patch.object(execution, "run_command", autospec=True)
async def test_resolution_failure_raises_test_failed_without_running_test(
self,
_name: str,
resolve_output: command.CommandOutput | None,
expected_verbatim_substring: str,
expected_error_substring: str,
mock_run_command: mock.AsyncMock,
) -> None:
exec_env = _make_exec_env("/fuchsia", "/out/fuchsia")
flags = args.parse_args(["--no-use-package-hash"])
test = execution.TestExecution(
self._make_device_test(),
exec_env,
flags,
)
mock_run_command.return_value = resolve_output
recorder = event.EventRecorder()
recorder.emit_init()
with self.assertRaises(execution.TestPackageResolutionFailed) as cm:
await test.run(recorder, flags, event.GLOBAL_RUN_ID)
recorder.emit_end()
mock_run_command.assert_called_once()
self.assertIsInstance(cm.exception, execution.TestFailed)
self.assertIs(cm.exception.command_output, resolve_output)
self.assertIn(expected_error_substring, str(cm.exception))
verbatim_messages = tuple(
[
e.payload.user_message.value
async for e in recorder.iter()
if e.payload is not None
and e.payload.user_message is not None
and e.payload.user_message.level == event.MessageLevel.VERBATIM
]
)
self.assertTrue(
any(
expected_verbatim_substring in msg for msg in verbatim_messages
),
verbatim_messages,
)
@mock.patch.object(execution, "run_command", autospec=True)
async def test_resolution_respects_abort_signal_before_and_during_resolve(
self, mock_run_command: mock.AsyncMock
) -> None:
exec_env = _make_exec_env("/fuchsia", "/out/fuchsia")
flags = args.parse_args(["--no-use-package-hash"])
test = execution.TestExecution(
self._make_device_test(),
exec_env,
flags,
)
# Case 1: abort_signal already set before resolution begins.
pre_aborted = asyncio.Event()
pre_aborted.set()
recorder = event.EventRecorder()
recorder.emit_init()
with self.assertRaises(execution.TestAborted) as cm:
await test.run(
recorder, flags, event.GLOBAL_RUN_ID, abort_signal=pre_aborted
)
recorder.emit_end()
self.assertIsNone(cm.exception.command_output)
mock_run_command.assert_not_called()
# Case 2: abort_signal becomes set while resolve times out; must raise
# TestAborted with no command_output, not warn and continue.
abort_on_timeout = asyncio.Event()
async def timeout_with_abort(
*_args: str, **_kwargs: typing.Any
) -> command.CommandOutput:
abort_on_timeout.set()
return self._make_command_output(return_code=-15, was_timeout=True)
mock_run_command.side_effect = timeout_with_abort
recorder = event.EventRecorder()
recorder.emit_init()
with self.assertRaises(execution.TestAborted) as cm:
await test.run(
recorder,
flags,
event.GLOBAL_RUN_ID,
abort_signal=abort_on_timeout,
)
recorder.emit_end()
self.assertIsNone(cm.exception.command_output)
mock_run_command.assert_called_once()
# Case 3: abort_signal becomes set as resolve returns 0; must raise
# TestAborted (never returning resolve_output) without running the test.
mock_run_command.reset_mock()
abort_on_success = asyncio.Event()
ok_output = self._make_command_output("Successfully resolved")
async def success_with_abort(
*_args: str, **_kwargs: typing.Any
) -> command.CommandOutput:
abort_on_success.set()
return ok_output
mock_run_command.side_effect = success_with_abort
recorder = event.EventRecorder()
recorder.emit_init()
with self.assertRaises(execution.TestAborted) as cm:
await test.run(
recorder,
flags,
event.GLOBAL_RUN_ID,
abort_signal=abort_on_success,
)
recorder.emit_end()
self.assertIsNone(cm.exception.command_output)
mock_run_command.assert_called_once()
@mock.patch.object(execution, "run_command", autospec=True)
async def test_resolution_propagates_task_cancellation(
self, mock_run_command: mock.AsyncMock
) -> None:
exec_env = _make_exec_env("/fuchsia", "/out/fuchsia")
flags = args.parse_args(["--no-use-package-hash"])
test = execution.TestExecution(
self._make_device_test(),
exec_env,
flags,
)
mock_run_command.side_effect = asyncio.CancelledError()
recorder = event.EventRecorder()
recorder.emit_init()
with self.assertRaises(asyncio.CancelledError):
await test.run(recorder, flags, event.GLOBAL_RUN_ID)
recorder.emit_end()
mock_run_command.assert_called_once()
@mock.patch.object(execution, "run_command", autospec=True)
async def test_pre_resolves_pinned_package_hash_for_legacy_ffx_test(
self, mock_run_command: mock.AsyncMock
) -> None:
with tempfile.TemporaryDirectory() as tmp:
repos_file = os.path.join(tmp, "package-repositories.json")
with open(repos_file, "w") as f:
json.dump([{"targets": "targets.json"}], f)
with open(os.path.join(tmp, "targets.json"), "w") as f:
json.dump(
{
"signed": {
"targets": {
"foo/0": {"custom": {"merkle": "deadbeef"}},
}
}
},
f,
)
exec_env = environment.ExecutionEnvironment(
fuchsia_dir="/fuchsia",
out_dir="/out/fuchsia",
test_json_file="",
disabled_ctf_tests_file="",
log_file=None,
test_list_file="",
package_repositories_file=repos_file,
)
# 1. Legacy ffx test run with default --use-package-hash pins ?hash=.
pinned_flags = args.parse_args([])
legacy_test = execution.TestExecution(
self._make_device_test(path=None, os_name="fuchsia"),
exec_env,
pinned_flags,
)
mock_run_command.side_effect = (
self._make_command_output("Successfully resolved"),
self._make_command_output("PASSED"),
)
recorder = event.EventRecorder()
recorder.emit_init()
await legacy_test.run(recorder, pinned_flags, event.GLOBAL_RUN_ID)
recorder.emit_end()
self.assertEqual(mock_run_command.call_count, 2)
self.assertSequenceEqual(
mock_run_command.call_args_list[0].args,
(
"fx",
"--dir",
"/out/fuchsia",
"ffx",
"target",
"package",
"resolve",
"fuchsia-pkg://fuchsia.com/foo?hash=deadbeef",
),
)
self.assertIn(
"fuchsia-pkg://fuchsia.com/foo?hash=deadbeef#meta/foo_test.cm",
mock_run_command.call_args_list[1].args,
)
# 2. Test-pilot wrapper resolves the unpinned package URL matching test-pilot.
mock_run_command.reset_mock()
mock_run_command.side_effect = (
self._make_command_output("Successfully resolved"),
self._make_command_output("PASSED"),
)
pilot_test = execution.TestExecution(
self._make_device_test(
path="bin/foo_test_wrapper.sh", os_name="linux"
),
exec_env,
pinned_flags,
)
recorder = event.EventRecorder()
recorder.emit_init()
await pilot_test.run(recorder, pinned_flags, event.GLOBAL_RUN_ID)
recorder.emit_end()
self.assertEqual(mock_run_command.call_count, 2)
self.assertSequenceEqual(
mock_run_command.call_args_list[0].args,
(
"fx",
"--dir",
"/out/fuchsia",
"ffx",
"target",
"package",
"resolve",
"fuchsia-pkg://fuchsia.com/foo",
),
)
@mock.patch.object(execution, "run_command", autospec=True)
async def test_resolution_uses_minimal_environment_without_cwd_or_test_overrides(
self, mock_run_command: mock.AsyncMock
) -> None:
exec_env = environment.ExecutionEnvironment(
fuchsia_dir="/fuchsia",
out_dir="/outside/checkout/out",
test_json_file="",
disabled_ctf_tests_file="",
log_file=None,
test_list_file="",
usb_socket_path="/tmp/usb.sock",
)
device_env = environment.DeviceEnvironment(
address="127.0.0.1",
port="39259",
name="fuchsia-target",
private_key_path="/path/to/fuchsia_ed25519",
)
flags = args.parse_args(
[
"--no-use-package-hash",
"-e",
"PATH=/custom/path",
"-e",
"LD_PRELOAD=/custom/lib.so",
"-e",
"FUCHSIA_NODENAME=ignored-override",
"--",
"--test-arg",
]
)
test = execution.TestExecution(
self._make_device_test(),
exec_env,
flags,
device_env=device_env,
)
mock_run_command.side_effect = (
self._make_command_output("Successfully resolved"),
self._make_command_output("PASSED"),
)
recorder = event.EventRecorder()
recorder.emit_init()
await test.run(recorder, flags, event.GLOBAL_RUN_ID)
recorder.emit_end()
self.assertEqual(mock_run_command.call_count, 2)
resolve_env = mock_run_command.call_args_list[0].kwargs["env"]
self.assertEqual(
resolve_env,
{"FUCHSIA_DEVICE_ADDR": "127.0.0.1:39259"},
)
@mock.patch.object(execution, "run_command", autospec=True)
async def test_resolution_propagates_fuchsia_nodename_without_device_addr_shadow(
self, mock_run_command: mock.AsyncMock
) -> None:
exec_env = _make_exec_env("/fuchsia", "/out/fuchsia")
flags = args.parse_args(["--no-use-package-hash"])
device_env = environment.DeviceEnvironment(
address="127.0.0.1",
port="39259",
name="my-target",
private_key_path="/path/to/fuchsia_ed25519",
)
test = execution.TestExecution(
self._make_device_test(),
exec_env,
flags,
device_env=device_env,
)
mock_run_command.side_effect = (
self._make_command_output("Successfully resolved"),
self._make_command_output("PASSED"),
)
with mock.patch.dict(os.environ, {"FUCHSIA_NODENAME": "my-target"}):
recorder = event.EventRecorder()
recorder.emit_init()
await test.run(recorder, flags, event.GLOBAL_RUN_ID)
recorder.emit_end()
self.assertEqual(mock_run_command.call_count, 2)
resolve_call = mock_run_command.call_args_list[0]
self.assertSequenceEqual(
resolve_call.args,
(
"fx",
"--dir",
"/out/fuchsia",
"-t",
"my-target",
"ffx",
"target",
"package",
"resolve",
"fuchsia-pkg://fuchsia.com/foo",
),
)
# Do not inject FUCHSIA_DEVICE_ADDR when FUCHSIA_NODENAME is set in os.environ.
self.assertIsNone(resolve_call.kwargs["env"])
@mock.patch.object(execution, "run_command", autospec=True)
async def test_package_resolution_cache_reuses_resolved_package_across_components(
self, mock_run_command: mock.AsyncMock
) -> None:
exec_env = _make_exec_env("/fuchsia", "/out/fuchsia")
flags = args.parse_args(["--no-use-package-hash"])
cache = execution.PackageResolutionCache()
test_a = execution.TestExecution(
self._make_device_test(
package_url="fuchsia-pkg://fuchsia.com/shared-pkg#meta/comp_a.cm",
path="bin/comp_a.sh",
component_url="fuchsia-pkg://fuchsia.com/shared-pkg#meta/comp_a.cm",
),
exec_env,
flags,
package_resolution_cache=cache,
)
test_b = execution.TestExecution(
self._make_device_test(
package_url="fuchsia-pkg://fuchsia.com/shared-pkg#meta/comp_b.cm",
path="bin/comp_b.sh",
component_url="fuchsia-pkg://fuchsia.com/shared-pkg#meta/comp_b.cm",
),
exec_env,
flags,
package_resolution_cache=cache,
)
mock_run_command.side_effect = (
self._make_command_output("Successfully resolved"),
self._make_command_output("PASSED A"),
self._make_command_output("PASSED B"),
)
recorder = event.EventRecorder()
recorder.emit_init()
out_a = await test_a.run(recorder, flags, event.GLOBAL_RUN_ID)
out_b = await test_b.run(recorder, flags, event.GLOBAL_RUN_ID)
recorder.emit_end()
self.assertEqual(out_a.stdout, "PASSED A")
self.assertEqual(out_b.stdout, "PASSED B")
self.assertEqual(mock_run_command.call_count, 3)
resolve_calls = tuple(
c for c in mock_run_command.call_args_list if "resolve" in c.args
)
self.assertEqual(len(resolve_calls), 1)
@mock.patch.object(execution, "run_command", autospec=True)
async def test_package_resolution_cache_coalesces_concurrent_waiters(
self, mock_run_command: mock.AsyncMock
) -> None:
exec_env = _make_exec_env("/fuchsia", "/out/fuchsia")
flags = args.parse_args(["--no-use-package-hash"])
cache = execution.PackageResolutionCache()
resolve_started = asyncio.Event()
release_resolve = asyncio.Event()
resolve_count = 0
async def fake_run(
*cmd_args: str, **_kwargs: typing.Any
) -> command.CommandOutput:
nonlocal resolve_count
if "resolve" in cmd_args:
resolve_count += 1
resolve_started.set()
await release_resolve.wait()
return self._make_command_output("Successfully resolved")
return self._make_command_output(f"PASSED:{cmd_args[0]}")
mock_run_command.side_effect = fake_run
test_a = execution.TestExecution(
self._make_device_test(
package_url="fuchsia-pkg://fuchsia.com/shared-pkg#meta/comp_a.cm",
path="bin/comp_a.sh",
component_url="fuchsia-pkg://fuchsia.com/shared-pkg#meta/comp_a.cm",
),
exec_env,
flags,
package_resolution_cache=cache,
)
test_b = execution.TestExecution(
self._make_device_test(
package_url="fuchsia-pkg://fuchsia.com/shared-pkg#meta/comp_b.cm",
path="bin/comp_b.sh",
component_url="fuchsia-pkg://fuchsia.com/shared-pkg#meta/comp_b.cm",
),
exec_env,
flags,
package_resolution_cache=cache,
)
recorder = event.EventRecorder()
recorder.emit_init()
task_a = asyncio.create_task(
test_a.run(recorder, flags, event.GLOBAL_RUN_ID)
)
task_b = asyncio.create_task(
test_b.run(recorder, flags, event.GLOBAL_RUN_ID)
)
await resolve_started.wait()
await asyncio.sleep(0)
release_resolve.set()
out_a, out_b = await asyncio.gather(task_a, task_b)
recorder.emit_end()
self.assertEqual(resolve_count, 1)
self.assertIn("comp_a.sh", out_a.stdout)
self.assertIn("comp_b.sh", out_b.stdout)
@mock.patch.object(execution, "run_command", autospec=True)
async def test_package_resolution_cache_canceling_one_waiter_keeps_sibling_alive(
self, mock_run_command: mock.AsyncMock
) -> None:
exec_env = _make_exec_env("/fuchsia", "/out/fuchsia")
flags = args.parse_args(["--no-use-package-hash"])
cache = execution.PackageResolutionCache()
resolve_started = asyncio.Event()
release_resolve = asyncio.Event()
flight_abort_ref: asyncio.Event | None = None
async def fake_run(
*cmd_args: str, **kwargs: typing.Any
) -> command.CommandOutput:
nonlocal flight_abort_ref
if "resolve" in cmd_args:
flight_abort_ref = kwargs["abort_signal"]
resolve_started.set()
await release_resolve.wait()
return self._make_command_output("Successfully resolved")
return self._make_command_output("PASSED")
mock_run_command.side_effect = fake_run
test_a = execution.TestExecution(
self._make_device_test(path="bin/comp_a.sh"),
exec_env,
flags,
package_resolution_cache=cache,
)
test_b = execution.TestExecution(
self._make_device_test(path="bin/comp_b.sh"),
exec_env,
flags,
package_resolution_cache=cache,
)
recorder = event.EventRecorder()
recorder.emit_init()
task_a = asyncio.create_task(
test_a.run(recorder, flags, event.GLOBAL_RUN_ID)
)
task_b = asyncio.create_task(
test_b.run(recorder, flags, event.GLOBAL_RUN_ID)
)
await resolve_started.wait()
await asyncio.sleep(0)
task_a.cancel()
with self.assertRaises(asyncio.CancelledError):
await task_a
assert flight_abort_ref is not None
self.assertFalse(flight_abort_ref.is_set())
release_resolve.set()
out_b = await task_b
recorder.emit_end()
self.assertEqual(out_b.stdout, "PASSED")
@mock.patch.object(execution, "run_command", autospec=True)
async def test_package_resolution_cache_does_not_cache_aborted_resolution(
self, mock_run_command: mock.AsyncMock
) -> None:
exec_env = _make_exec_env("/fuchsia", "/out/fuchsia")
flags = args.parse_args(["--no-use-package-hash"])
cache = execution.PackageResolutionCache()
abort_event = asyncio.Event()
resolve_calls = 0
async def fake_run(
*cmd_args: str, **kwargs: typing.Any
) -> command.CommandOutput:
nonlocal resolve_calls
if "resolve" in cmd_args:
resolve_calls += 1
if resolve_calls == 1:
abort_event.set()
await kwargs["abort_signal"].wait()
return self._make_command_output(return_code=-15)
return self._make_command_output("Successfully resolved")
return self._make_command_output("PASSED")
mock_run_command.side_effect = fake_run
test = execution.TestExecution(
self._make_device_test(),
exec_env,
flags,
package_resolution_cache=cache,
)
recorder = event.EventRecorder()
recorder.emit_init()
with self.assertRaises(execution.TestAborted):
await test.run(
recorder, flags, event.GLOBAL_RUN_ID, abort_signal=abort_event
)
out = await test.run(recorder, flags, event.GLOBAL_RUN_ID)
recorder.emit_end()
self.assertEqual(resolve_calls, 2)
self.assertEqual(out.stdout, "PASSED")
@mock.patch.object(execution, "run_command", autospec=True)
async def test_package_resolution_cache_separates_different_targets(
self, mock_run_command: mock.AsyncMock
) -> None:
exec_env = _make_exec_env("/fuchsia", "/out/fuchsia")
flags = args.parse_args(["--no-use-package-hash"])
cache = execution.PackageResolutionCache()
test_target_1 = execution.TestExecution(
self._make_device_test(),
exec_env,
flags,
device_env=environment.DeviceEnvironment(
"127.0.0.1", "8022", "dev1", "/key"
),
package_resolution_cache=cache,
)
test_target_2 = execution.TestExecution(
self._make_device_test(),
exec_env,
flags,
device_env=environment.DeviceEnvironment(
"127.0.0.1", "8023", "dev2", "/key"
),
package_resolution_cache=cache,
)
mock_run_command.return_value = self._make_command_output("OK")
recorder = event.EventRecorder()
recorder.emit_init()
await test_target_1.run(recorder, flags, event.GLOBAL_RUN_ID)
await test_target_2.run(recorder, flags, event.GLOBAL_RUN_ID)
recorder.emit_end()
resolve_calls = tuple(
c for c in mock_run_command.call_args_list if "resolve" in c.args
)
self.assertEqual(len(resolve_calls), 2)
def _make_device_test(path: str | None = None) -> test_list_file.Test:
"""Create a component (device) test for profiler tests."""
return test_list_file.Test(
tests_json_file.TestEntry(
tests_json_file.TestSection(
"foo",
"//foo",
"fuchsia",
package_url="fuchsia-pkg://fuchsia.com/foo#meta/foo_test.cm",
path=path,
)
),
test_list_file.TestListEntry(
"foo",
[],
test_list_file.TestListExecutionEntry(
"fuchsia-pkg://fuchsia.com/foo#meta/foo_test.cm",
realm="foo_tests",
),
),
)
class TestProfiler(unittest.IsolatedAsyncioTestCase):
"""Tests for `fx test --profiler` in TestExecution.run."""
def setUp(self) -> None:
super().setUp()
patch = mock.patch.dict(os.environ, {}, clear=False)
patch.start()
os.environ.pop("FUCHSIA_NODENAME", None)
self.addCleanup(patch.stop)
self.exec_env = _make_exec_env("/fuchsia", "/out/fuchsia")
self.recorder = event.EventRecorder()
self.recorder.emit_init()
def tearDown(self) -> None:
self.recorder.emit_end()
super().tearDown()
def _mock_run_command(
self,
custom: typing.Callable[[list[str]], command.CommandOutput]
| None = None,
) -> list[list[str]]:
"""Mock run_command and record its calls, except package pre-resolution."""
calls: list[list[str]] = []
async def handler(
*cmd_args: str, **_kwargs: typing.Any
) -> command.CommandOutput:
argv = list(cmd_args)
if "resolve" in argv:
return command.CommandOutput("", "", 0, 0.0, None)
calls.append(argv)
if custom is not None:
return custom(argv)
return command.CommandOutput("", "", 0, 0.0, None)
patch = mock.patch("execution.run_command", side_effect=handler)
patch.start()
self.addCleanup(patch.stop)
return calls
@staticmethod
def _ffx_args(call_args: list[str]) -> list[str]:
return (
call_args[call_args.index("ffx") + 1 :]
if "ffx" in call_args
else call_args
)
async def test_profiler_wraps_device_and_e2e_tests(self) -> None:
"""--profiler wraps device tests by URL and e2e tests with --system-wide."""
with tempfile.TemporaryDirectory() as tmp:
output_path = os.path.join(tmp, "my_profile.pftrace")
config_path = os.path.join(tmp, "profiler.json")
with open(config_path, "w") as f:
json.dump(
{
"attach": ["--sample-period-us", "1000"],
"stop": [
"--output-format",
"perfetto",
"--output",
output_path,
],
},
f,
)
calls = self._mock_run_command()
flags = args.parse_args(
[
"--profiler",
"--no-use-package-hash",
"--profiler-config",
config_path,
]
)
flags.validate()
await execution.TestExecution(
_make_device_test(), self.exec_env, flags
).run(self.recorder, flags, event.GLOBAL_RUN_ID)
self.assertEqual(len(calls), 3)
self.assertIn("test", self._ffx_args(calls[1]))
self.assertEqual(
[self._ffx_args(c) for c in (calls[0], calls[2])],
[
[
"profiler",
"attach",
"--url",
"fuchsia-pkg://fuchsia.com/foo#meta/foo_test.cm",
"--background",
"--sample-period-us",
"1000",
],
[
"profiler",
"stop",
"--output-format",
"perfetto",
"--output",
output_path,
"--print-stats",
],
],
)
# test_pilot launches components without a merkle hash, so attach uses unhashed URL.
calls.clear()
pilot_flags = args.parse_args(["--profiler"])
await execution.TestExecution(
_make_device_test(path="host_x64/test_pilot"),
self.exec_env,
pilot_flags,
).run(self.recorder, pilot_flags, event.GLOBAL_RUN_ID)
self.assertEqual(len(calls), 3)
self.assertTrue(calls[1][0].endswith("test_pilot"))
self.assertEqual(
[self._ffx_args(c) for c in (calls[0], calls[2])],
[
[
"profiler",
"attach",
"--url",
"fuchsia-pkg://fuchsia.com/foo#meta/foo_test.cm",
"--background",
],
["profiler", "stop", "--print-stats"],
],
)
calls.clear()
e2e_flags = args.parse_args(["--profiler", "--e2e"])
await execution.TestExecution(
_make_host_test("ls", is_e2e=True), self.exec_env, e2e_flags
).run(self.recorder, e2e_flags, event.GLOBAL_RUN_ID)
self.assertEqual(len(calls), 3)
self.assertTrue(calls[1][0].endswith("ls"))
self.assertEqual(
[self._ffx_args(c) for c in (calls[0], calls[2])],
[
["profiler", "attach", "--system-wide", "--background"],
["profiler", "stop", "--print-stats"],
],
)
# Explicit target flag in attach args suppresses default --url / --system-wide.
calls.clear()
target_flags = args.parse_args(
["--profiler", "--no-use-package-hash"]
)
target_flags.profiler_attach_args = ["--moniker=/core/foo"]
await execution.TestExecution(
_make_device_test(), self.exec_env, target_flags
).run(self.recorder, target_flags, event.GLOBAL_RUN_ID)
self.assertEqual(len(calls), 3)
self.assertIn("test", self._ffx_args(calls[1]))
self.assertEqual(
[self._ffx_args(c) for c in (calls[0], calls[2])],
[
[
"profiler",
"attach",
"--background",
"--moniker=/core/foo",
],
["profiler", "stop", "--print-stats"],
],
)
async def test_profiler_aborts_on_abort_signal(self) -> None:
"""An aborted test run skips attach if pre-aborted or aborts the session mid-run."""
# An e2e test has no package to pre-resolve, so the profiler session is
# the first step to see the abort.
e2e_flags = args.parse_args(["--profiler", "--e2e"])
pre_aborted = asyncio.Event()
pre_aborted.set()
calls = self._mock_run_command()
with self.assertRaisesRegex(
execution.TestAborted, r"Aborted before starting profiler session"
):
await execution.TestExecution(
_make_host_test("ls", is_e2e=True), self.exec_env, e2e_flags
).run(
self.recorder,
e2e_flags,
event.GLOBAL_RUN_ID,
abort_signal=pre_aborted,
)
self.assertEqual(calls, [])
flags = args.parse_args(["--profiler", "--no-use-package-hash"])
attach_aborted = asyncio.Event()
def abort_on_attach(argv: list[str]) -> command.CommandOutput:
if "profiler" in argv and "attach" in argv:
attach_aborted.set()
return command.CommandOutput("", "", -15, 0.0, None)
return command.CommandOutput("", "", 0, 0.0, None)
calls = self._mock_run_command(abort_on_attach)
with self.assertRaisesRegex(
execution.TestAborted, r"Aborted while starting profiler session"
):
await execution.TestExecution(
_make_device_test(), self.exec_env, flags
).run(
self.recorder,
flags,
event.GLOBAL_RUN_ID,
abort_signal=attach_aborted,
)
self.assertEqual(
[self._ffx_args(c) for c in calls],
[
[
"profiler",
"attach",
"--url",
"fuchsia-pkg://fuchsia.com/foo#meta/foo_test.cm",
"--background",
],
["profiler", "stop", "--abort"],
],
)
mid_aborted = asyncio.Event()
def abort_on_test(argv: list[str]) -> command.CommandOutput:
if "test" in argv and "run" in argv:
mid_aborted.set()
return command.CommandOutput("", "", -15, 0.0, None)
return command.CommandOutput("", "", 0, 0.0, None)
calls = self._mock_run_command(abort_on_test)
with self.assertRaises(execution.TestFailed):
await execution.TestExecution(
_make_device_test(), self.exec_env, flags
).run(
self.recorder,
flags,
event.GLOBAL_RUN_ID,
abort_signal=mid_aborted,
)
self.assertEqual(
[self._ffx_args(c) for c in calls if "profiler" in c],
[
[
"profiler",
"attach",
"--url",
"fuchsia-pkg://fuchsia.com/foo#meta/foo_test.cm",
"--background",
],
["profiler", "stop", "--abort"],
],
)
async def test_profiler_session_recovery_and_error_precedence(self) -> None:
"""TooManySessions aborts + retries once; test failure precedes stop failure."""
attach_attempts = 0
def handler(argv: list[str]) -> command.CommandOutput:
nonlocal attach_attempts
if "profiler" in argv and "attach" in argv:
attach_attempts += 1
if attach_attempts == 1:
return command.CommandOutput(
"", "TooManySessions", 1, 0.0, None
)
return command.CommandOutput("", "", 0, 0.0, None)
if "test" in argv and "run" in argv:
return command.CommandOutput(
"", "assertion failed\n", 1, 0.0, None
)
if "profiler" in argv and "stop" in argv and "--abort" not in argv:
return command.CommandOutput("", "stop failed", 1, 0.0, None)
return command.CommandOutput("", "", 0, 0.0, None)
calls = self._mock_run_command(handler)
flags = args.parse_args(["--profiler", "--no-use-package-hash"])
with (
mock.patch.object(
self.recorder, "emit_warning_message", autospec=True
) as emit_warning,
self.assertRaises(execution.TestFailed) as ctx,
):
await execution.TestExecution(
_make_device_test(), self.exec_env, flags
).run(self.recorder, flags, event.GLOBAL_RUN_ID)
self.assertEqual(str(ctx.exception), "Test reported failure")
self.assertIsNotNone(ctx.exception.command_output)
self.assertEqual(
ctx.exception.command_output.stderr, "assertion failed\n"
)
# The stop failure is still reported when the test failure takes precedence.
emit_warning.assert_any_call(
"Failed to stop profiler session and write profile: stop failed"
)
self.assertEqual(
[self._ffx_args(c) for c in calls if "profiler" in c],
[
[
"profiler",
"attach",
"--url",
"fuchsia-pkg://fuchsia.com/foo#meta/foo_test.cm",
"--background",
],
["profiler", "stop", "--abort"],
[
"profiler",
"attach",
"--url",
"fuchsia-pkg://fuchsia.com/foo#meta/foo_test.cm",
"--background",
],
["profiler", "stop", "--print-stats"],
["profiler", "stop", "--abort"],
],
)
# Passing test + failing `ffx profiler stop` raises TestProfilerStopFailed with stop_error.
self._mock_run_command(
lambda argv: (
command.CommandOutput("stop failed", " \n", 1, 0.0, None)
if "profiler" in argv
and "stop" in argv
and "--abort" not in argv
else command.CommandOutput("", "", 0, 0.0, None)
)
)
with self.assertRaisesRegex(
execution.TestProfilerStopFailed, r"stop failed"
):
await execution.TestExecution(
_make_device_test(), self.exec_env, flags
).run(self.recorder, flags, event.GLOBAL_RUN_ID)
# Test timeout takes precedence over a subsequent `ffx profiler stop` failure.
self._mock_run_command(
lambda argv: (
command.CommandOutput("", "stop failed", 1, 0.0, None)
if "profiler" in argv
and "stop" in argv
and "--abort" not in argv
else command.CommandOutput(
"", "timed out", 1, 305.0, None, was_timeout=True
)
if "test" in argv and "run" in argv
else command.CommandOutput("", "", 0, 0.0, None)
)
)
with self.assertRaises(execution.TestTimeout):
await execution.TestExecution(
_make_device_test(), self.exec_env, flags
).run(self.recorder, flags, event.GLOBAL_RUN_ID)
# Unrecoverable `ffx profiler attach` failure raises TestCouldNotRun without running test.
calls = self._mock_run_command(
lambda argv: (
command.CommandOutput("attach failed", " \n", 1, 0.0, None)
if "profiler" in argv and "attach" in argv
else command.CommandOutput("", "", 0, 0.0, None)
)
)
with self.assertRaisesRegex(
execution.TestCouldNotRun, r"attach failed"
):
await execution.TestExecution(
_make_device_test(), self.exec_env, flags
).run(self.recorder, flags, event.GLOBAL_RUN_ID)
self.assertFalse(any("test" in c and "run" in c for c in calls))