# 教學課程:使用 zxdb 偵錯測試
本教學課程會逐步說明如何使用 fx test
指令和 Fuchsia 偵錯工具 (zxdb
) 執行偵錯工作流程。
如要進一步瞭解如何使用 zxdb 偵錯測試,請參閱「使用 zxdb 偵錯測試」一文。
瞭解測試案例
荒漠油廠
Rust 測試是由 Rust 測試執行工具執行。與 C++ 測試的 gTest 或 gUnit 執行器不同,Rust 測試執行元件預設會平行執行測試案例。這會導致使用 --break-on-failure
功能時的體驗不同。如要進一步瞭解偵錯並行測試程序時的預期行為,請參閱「並行執行測試案例」。支援平行測試程序。
以下是根據部分範例 Rust 測試程式碼的範例:
#[fuchsia::test]
async fn add_test() {
let (proxy, stream) = create_proxy_and_stream::<CalculatorMarker>();
// Run two tasks: The calculator_fake & the calculator_line method we're interested
// in testing.
let fake_task = calculator_fake(stream).fuse();
let calculator_line_task = calculator_line("1 + 2", &proxy).fuse();
futures::pin_mut!(fake_task, calculator_line_task);
futures::select! {
actual = calculator_line_task => {
let actual = actual.expect("Calculator didn't return value");
assert_eq!(actual, 5.0);
},
_ = fake_task => {
panic!("Fake should never complete.")
}
};
}
您可以使用 fx set
將這個測試目標新增至建構圖:
fx set workbench_eng.x64 --with-test //examples/fidl/calculator/rust/client:hermetic_tests
C++
根據預設,gTest 測試執行元件會依序執行測試案例,因此一次只能偵錯一個測試失敗。如要平行執行測試案例,請在 fx test
指令中加入 --parallel-cases
旗標。
以下是根據部分範例 C++ 測試程式碼的範例:
// Inject 1 process.
auto process1 = std::make_unique<MockProcess>(nullptr, kProcessKoid1, kProcessName1);
process1->AddThread(kProcess1ThreadKoid1);
harness.debug_agent()->InjectProcessForTest(std::move(process1));
// And another, with 2 threads.
auto process2 = std::make_unique<MockProcess>(nullptr, kProcessKoid2, kProcessName2);
process2->AddThread(kProcess2ThreadKoid1);
process2->AddThread(kProcess2ThreadKoid2);
harness.debug_agent()->InjectProcessForTest(std::move(process2));
reply = {};
remote_api->OnStatus(request, &reply);
ASSERT_EQ(reply.processes.size(), 3u); // <-- This will fail, since reply.processes.size() == 2
EXPECT_EQ(reply.processes[0].process_koid, kProcessKoid1);
EXPECT_EQ(reply.processes[0].process_name, kProcessName1);
...
您可以使用 fx set
將這個測試目標新增至建構圖:
fx set workbench_eng.x64 --with-test //src/developer/debug:tests
執行測試
荒漠油廠
使用 fx test --break-on-failure
指令執行測試,例如:
fx test -o --break-on-failure calculator-client-rust-unittests
輸出內容如下所示:
<...fx test startup...>
...
[RUNNING] tests::add_test
[RUNNING] tests::divide_test
[RUNNING] tests::multiply_test
[PASSED] parse::tests::parse_expression
[RUNNING] tests::pow_test
[PASSED] parse::tests::parse_expression_with_negative_numbers
[RUNNING] tests::subtract_test
[PASSED] parse::tests::parse_expression_with_multiplication
[PASSED] parse::tests::parse_expression_with_subtraction
[PASSED] parse::tests::parse_expression_with_pow
[PASSED] parse::tests::parse_operators
[01234.052188][218417][218422][<root>][add_test] ERROR: [examples/fidl/calculator/rust/client/src/main.rs(110)] PANIC info=panicked at ../../examples/fidl/calculato
r/rust/client/src/main.rs:110:17:
assertion `left == right` failed
left: 3.0
right: 5.0
[PASSED] parse::tests::parse_expression_with_division
[PASSED] tests::multiply_test
[PASSED] tests::divide_test
...
👋 zxdb is loading symbols to debug test failure in calculator-client-rust-unittest, please wait.
⚠ test failure in calculator-client-rust-unittest, type `frame` or `help` to get started.
108 actual = calculator_line_task => {
109 let actual = actual.expect("Calculator didn't return value");
▶ 110 assert_eq!(actual, 5.0);
111 },
112 _ = fake_task => {
🛑 process 8 calculator_client_bin_test::tests::add_test::test_entry_point::λ(core::task::wake::Context*) • main.rs:110
[zxdb]
請注意,測試的輸出內容會混雜在一起,這是因為 Rust 測試執行元件預設會平行執行測試案例。如要避免這種情況,請搭配使用 --parallel-cases
選項和 fx test
,例如:fx test --parallel-cases 1 --break-on-failure
calculator-client-rust-unittests
。工具運作不需要這個旗標,但可避免多項測試的輸出交錯,方便您閱讀,因此有助於偵錯。
使用該選項時,輸出內容如下所示:
fx test --parallel-cases 1 -o --break-on-failure calculator-client-rust-unittests
...
[RUNNING] parse::tests::parse_operators
[PASSED] parse::tests::parse_operators
[RUNNING] tests::add_test
[01391.909144][249125][249127][<root>][add_test] ERROR: [examples/fidl/calculator/rust/client/src/main.rs(110)] PANIC info=panicked at ../../examples/fidl/calculato
r/rust/client/src/main.rs:110:17:
assertion `left == right` failed
left: 3.0
right: 5.0
Status: [duration: 5.0s]
Running 1 tests [ ] 0.0%
fuchsia-pkg://fuchsia.com/calculator-client-rust-unittests#meta/calculator-client-rust-unittests.cm [0.5s]
👋 zxdb is loading symbols to debug test failure in calculator-client-rust-unittest, please wait.
⚠ test failure in calculator-client-rust-unittest, type `frame` or `help` to get started.
108 actual = calculator_line_task => {
109 let actual = actual.expect("Calculator didn't return value");
▶ 110 assert_eq!(actual, 5.0);
111 },
112 _ = fake_task => {
🛑 process 2 calculator_client_bin_test::tests::add_test::test_entry_point::λ(core::task::wake::Context*) • main.rs:110
[zxdb]
C++
使用 fx test --break-on-failure
指令執行測試,例如:
fx test -o --break-on-failure debug_agent_unit_tests
輸出內容如下所示:
<...fx test startup...>
Starting: fuchsia-pkg://fuchsia.com/debug_agent_unit_tests#meta/debug_agent_unit_tests.cm (NOT HERMETIC)
Command: fx ffx test run --realm /core/testing/system-tests --max-severity-logs WARN --break-on-failure fuchsia-pkg://fuchsia.com/debug_agent_unit_tests?hash=3f6d97801bb147034a344e3fe1bb69291a7b690b9d3d075246ddcba59397ac12#meta/debug_agent_unit_tests.cm
Status: [duration: 30.9s] [tasks: 3 running, 15/19 complete]
Running 2 tests [ ] 0.0%
👋 zxdb is loading symbols to debug test failure in debug_agent_unit_tests.cm, please wait.
⚠️ test failure in debug_agent_unit_tests.cm, type `frame` or `help` to get started.
103 remote_api->OnStatus(request, &reply);
104
▶ 105 ASSERT_EQ(reply.processes.size(), 3u);
106 EXPECT_EQ(reply.processes[0].process_koid, kProcessKoid1);
107 EXPECT_EQ(reply.processes[0].process_name, kProcessName1);
🛑 thread 1 debug_agent::DebugAgentTests_OnGlobalStatus_Test::TestBody(debug_agent::DebugAgentTests_OnGlobalStatus_Test*) • debug_agent_unittest.cc:105
[zxdb]
檢查失敗情形
荒漠油廠
這個範例包含測試失敗,因此 Rust 測試會在失敗時發出 abort
,zxdb
會注意到並回報這項失敗。zxdb
也會分析中止的呼叫堆疊,並直接將我們帶到失敗的原始碼。您可以使用 list
查看目前影格的其他程式碼行,例如:
list
105 let calculator_line_task = calculator_line("1 + 2", &proxy).fuse();
106 futures::pin_mut!(fake_task, calculator_line_task);
107 futures::select! {
108 actual = calculator_line_task => {
109 let actual = actual.expect("Calculator didn't return value");
▶ 110 assert_eq!(actual, 5.0);
111 },
112 _ = fake_task => {
113 panic!("Fake should never complete.")
114 }
115 };
116 }
117
118 #[fuchsia::test]
119 async fn subtract_test() {
120 let (proxy, stream) = create_proxy_and_stream::<CalculatorMarker>()
您也可以使用 frame
檢查整個呼叫堆疊,例如:
frame
0…12 «Rust library» (-r expands)
13 std::panicking::begin_panic_handler(…) • library/std/src/panicking.rs:697
14 core::panicking::panic_fmt(…) • library/core/src/panicking.rs:75
15 core::panicking::assert_failed_inner(…) • library/core/src/panicking.rs:448
16 core::panicking::assert_failed<…>(…) • fuchsia-third_party-rust/library/core/src/panicking.rs:403
▶ 17 calculator_client_bin_test::tests::add_test::test_entry_point::λ(…) • main.rs:110
18 core::future::future::«impl»::poll<…>(…) • future/future.rs:133
19…44 «Polled event in fuchsia::test_singlethreaded» (-r expands)
45 calculator_client_bin_test::tests::add_test() • main.rs:98
46 calculator_client_bin_test::tests::add_test::λ(…) • main.rs:99
47 core::ops::function::FnOnce::call_once<…>(…) • fuchsia-third_party-rust/library/core/src/ops/function.rs:253
48 core::ops::function::FnOnce::call_once<…>(…) • library/core/src/ops/function.rs:253 (inline)
49…70 «Rust test startup» (-r expands)
或者,在非同步環境中,您可以使用 async-backtrace
,例如:
async-backtrace
Task(id = 0)
└─ calculator_client_bin_test::tests::divide_test::test_entry_point • select_mod.rs:321
└─ select!
└─ (terminated)
└─ calculator_client_bin_test::tests::calculator_fake • main.rs:93
└─ futures_util::stream::try_stream::try_for_each::TryForEach
Task(id = 1)
└─ diagnostics_log::fuchsia::filter::«impl»::listen_to_interest_changes • fuchsia/filter.rs:63
└─ fidl::client::QueryResponseFut
您執行的所有指令都位於第 17 個影格的環境中,如 ▶
所示。
您可以再次列出原始碼,並提供一些額外背景資訊:
list -c 10
100 let (proxy, stream) = create_proxy_and_stream::<CalculatorMarker>();
101
102 // Run two tasks: The calculator_fake & the calculator_line method we're interested
103 // in testing.
104 let fake_task = calculator_fake(stream).fuse();
105 let calculator_line_task = calculator_line("1 + 2", &proxy).fuse();
106 futures::pin_mut!(fake_task, calculator_line_task);
107 futures::select! {
108 actual = calculator_line_task => {
109 let actual = actual.expect("Calculator didn't return value");
▶ 110 assert_eq!(actual, 5.0);
111 },
112 _ = fake_task => {
113 panic!("Fake should never complete.")
114 }
115 };
116 }
117
118 #[fuchsia::test]
119 async fn subtract_test() {
120 let (proxy, stream) = create_proxy_and_stream::<CalculatorMarker>();
如要找出測試失敗的原因,請列印一些變數,瞭解發生了什麼情況。actual
影格包含本機變數,其中應有一些字串,這些字串是透過呼叫 log_helper
和 log_helper2
執行個體上的 write_log
,並透過 mpsc 管道 recv_logs
接收而新增:
print actual
3
測試的期望值似乎略有錯誤。計算機應該會傳回「1 + 2」等於 3,但測試預期結果是 5!計算機傳回的答案正確,但測試期望值不正確。您現在可以從失敗的測試案例中分離,並修正測試期望。
detach
<...fx test output continues...>
Failed tests: tests::add_test
11 out of 12 tests passed...
Test fuchsia-pkg://fuchsia.com/calculator-client-rust-unittests?hash=b105775fa7c39eb67195a09d63be6c4314eeef8e93eb542616c0b5dbda73b8e2#meta/calculator-client-rust-unittests.cm produced unex
pected high-severity logs:
----------------xxxxx----------------
[09353.731026][1225676][1225678][<root>][add_test] ERROR: [examples/fidl/calculator/rust/client/src/main.rs(110)] PANIC info=panicked at ../../examples/fidl/calculator/rust/client/src/main
.rs:110:17:
assertion `left == right` failed
left: 3.0
right: 5.0
----------------xxxxx----------------
Failing this test. See: https://fuchsia.dev/fuchsia-src/development/diagnostics/test_and_logs#restricting_log_severity
fuchsia-pkg://fuchsia.com/calculator-client-rust-unittests?hash=b105775fa7c39eb67195a09d63be6c4314eeef8e93eb542616c0b5dbda73b8e2#meta/calculator-client-rust-unittests.cm completed with res
ult: FAILED
The test was executed in the hermetic realm. If your test depends on system capabilities, pass in correct realm. See https://fuchsia.dev/go/components/non-hermetic-tests
Tests failed.
現在,您可以對程式碼進行下列變更,修正測試:
- assert_eq!(actual, 5.0);
+ assert_eq!(actual, 3.0);
現在可以再次執行測試:
fx test --break-on-failure calculator-client-rust-unittests
輸出內容應如下所示:
<...fx test startup...>
Running 1 tests
Status: [duration: 13.5s]
Running 1 tests
Starting: fuchsia-pkg://fuchsia.com/calculator-client-rust-unittests#meta/calculator-client-rust-unittests.cm
Command: fx --dir /usr/local/google/home/jruthe/upstream/fuchsia/out/default ffx test run --max-severity-logs WARN --parallel 1 --no-exception-channel --break-on-failure fuchsia-pkg://fuchsia.com/calculator-client-rust-unittests?hash=abc77325b830d25e47d1de85b764f2b7a0d8975269dfc654f3a7f9a6859b851a#meta/calculator-client-rust-unittests.cm
Running test 'fuchsia-pkg://fuchsia.com/calculator-client-rust-unittests?hash=abc77325b830d25e47d1de85b764f2b7a0d8975269dfc654f3a7f9a6859b851a#meta/calculator-client-rust-unittests.cm'
[RUNNING] parse::tests::parse_expression
[PASSED] parse::tests::parse_expression
[RUNNING] parse::tests::parse_expression_with_division
[PASSED] parse::tests::parse_expression_with_division
[RUNNING] parse::tests::parse_expression_with_multiplication
[PASSED] parse::tests::parse_expression_with_multiplication
[RUNNING] parse::tests::parse_expression_with_negative_numbers
[PASSED] parse::tests::parse_expression_with_negative_numbers
[RUNNING] parse::tests::parse_expression_with_pow
[PASSED] parse::tests::parse_expression_with_pow
[RUNNING] parse::tests::parse_expression_with_subtraction
[PASSED] parse::tests::parse_expression_with_subtraction
[RUNNING] parse::tests::parse_operators
[PASSED] parse::tests::parse_operators
[RUNNING] tests::add_test
[PASSED] tests::add_test
[RUNNING] tests::divide_test
[PASSED] tests::divide_test
[RUNNING] tests::multiply_test
[PASSED] tests::multiply_test
[RUNNING] tests::pow_test
[PASSED] tests::pow_test
[RUNNING] tests::subtract_test
[PASSED] tests::subtract_test
12 out of 12 tests passed...
fuchsia-pkg://fuchsia.com/calculator-client-rust-unittests?hash=abc77325b830d25e47d1de85b764f2b7a0d8975269dfc654f3a7f9a6859b851a#meta/calculator-client-rust-unittests.cm completed with res
ult: PASSED
Deleting 1 files at /tmp/tmprwdcy73n: ffx_logs/ffx.log
To keep these files, set --ffx-output-directory.
Status: [duration: 14.8s] [tests: PASSED: 1 FAILED: 0 SKIPPED: 0]
C++
這個範例包含測試失敗,gTest 有一個選項可在測試失敗路徑中插入軟體中斷點,而 zxdb
擷取了這個選項。zxdb
也根據這項資訊判斷測試程式碼的位置,並直接跳至測試中的影格。您可以使用 list
查看目前影格的其他程式碼行,例如:
list
100 harness.debug_agent()->InjectProcessForTest(std::move(process2));
101
102 reply = {};
103 remote_api->OnStatus(request, &reply);
104
▶ 105 ASSERT_EQ(reply.processes.size(), 3u);
106 EXPECT_EQ(reply.processes[0].process_koid, kProcessKoid1);
107 EXPECT_EQ(reply.processes[0].process_name, kProcessName1);
108 ASSERT_EQ(reply.processes[0].threads.size(), 1u);
您可以使用 list
的 -c
標記,查看更多原始碼行:
list -c 10
95 constexpr uint64_t kProcess2ThreadKoid2 = 0x2;
96
97 auto process2 = std::make_unique<MockProcess>(nullptr, kProcessKoid2, kProcessName2);
98 process2->AddThread(kProcess2ThreadKoid1);
99 process2->AddThread(kProcess2ThreadKoid2);
100 harness.debug_agent()->InjectProcessForTest(std::move(process2));
101
102 reply = {};
103 remote_api->OnStatus(request, &reply);
104
▶ 105 ASSERT_EQ(reply.processes.size(), 3u);
106 EXPECT_EQ(reply.processes[0].process_koid, kProcessKoid1);
107 EXPECT_EQ(reply.processes[0].process_name, kProcessName1);
108 ASSERT_EQ(reply.processes[0].threads.size(), 1u);
109 EXPECT_EQ(reply.processes[0].threads[0].id.process, kProcessKoid1);
110 EXPECT_EQ(reply.processes[0].threads[0].id.thread, kProcess1ThreadKoid1);
111
112 EXPECT_EQ(reply.processes[1].process_koid, kProcessKoid2);
113 EXPECT_EQ(reply.processes[1].process_name, kProcessName2);
114 ASSERT_EQ(reply.processes[1].threads.size(), 2u);
115 EXPECT_EQ(reply.processes[1].threads[0].id.process, kProcessKoid2);
[zxdb]
您也可以使用 frame
指令檢查完整堆疊追蹤記錄:
frame
0 testing::UnitTest::AddTestPartResult(…) • gtest.cc:5383
1 testing::internal::AssertHelper::operator=(…) • gtest.cc:476
▶ 2 debug_agent::DebugAgentTests_OnGlobalStatus_Test::TestBody(…) • debug_agent_unittest.cc:105
3 testing::internal::HandleSehExceptionsInMethodIfSupported<…>(…) • gtest.cc:2635
4 testing::internal::HandleExceptionsInMethodIfSupported<…>(…) • gtest.cc:2690
5 testing::Test::Run(…) • gtest.cc:2710
6 testing::TestInfo::Run(…) • gtest.cc:2859
7 testing::TestSuite::Run(…) • gtest.cc:3038
8 testing::internal::UnitTestImpl::RunAllTests(…) • gtest.cc:5942
9 testing::internal::HandleSehExceptionsInMethodIfSupported<…>(…) • gtest.cc:2635
10 testing::internal::HandleExceptionsInMethodIfSupported<…>(…) • gtest.cc:2690
11 testing::UnitTest::Run(…) • gtest.cc:5506
12 RUN_ALL_TESTS() • gtest.h:2318
13 main(…) • run_all_unittests.cc:20
14…17 «libc startup» (-r expands)
[zxdb]
請注意,▶
指向測試的原始碼架構,表示所有指令都會在這個環境中執行。您可以使用 frame
指令,搭配堆疊追蹤中的相關數字,選取其他影格。
如要找出測試失敗的原因,請列印一些變數,瞭解發生了什麼情況。reply
框架包含區域變數,該變數應已由 remote_api->OnStatus
的函式呼叫填入:
print reply
{
processes = {
[0] = {
process_koid = 4660
process_name = "process-1"
components = {}
threads = {
[0] = {
id = {process = 4660, thread = 1}
name = "test thread"
state = kRunning
blocked_reason = kNotBlocked
stack_amount = kNone
frames = {}
}
}
}
[1] = {
process_koid = 22136
process_name = "process-2"
components = {}
threads = {
[0] = {
id = {process = 22136, thread = 1}
name = "test thread"
state = kRunning
blocked_reason = kNotBlocked
stack_amount = kNone
frames = {}
}
[1] = {
id = {process = 22136, thread = 2}
name = "test thread"
state = kRunning
blocked_reason = kNotBlocked
stack_amount = kNone
frames = {}
}
}
}
}
limbo = {}
breakpoints = {}
filters = {}
}
從輸出內容中,您可以看到 reply
變數已填入一些資訊,預期 processes
向量的大小應等於 3。列印 reply
的成員變數,即可查看更多資訊。
您也可以列印該向量的大小方法 (一般函式呼叫支援尚未實作):
print reply.processes
{
[0] = {
process_koid = 4660
process_name = "process-1"
components = {}
threads = {
[0] = {
id = {process = 4660, thread = 1}
name = "test thread"
state = kRunning
blocked_reason = kNotBlocked
stack_amount = kNone
frames = {}
}
}
}
[1] = {
process_koid = 22136
process_name = "process-2"
components = {}
threads = {
[0] = {
id = {process = 22136, thread = 1}
name = "test thread"
state = kRunning
blocked_reason = kNotBlocked
stack_amount = kNone
frames = {}
}
[1] = {
id = {process = 22136, thread = 2}
name = "test thread"
state = kRunning
blocked_reason = kNotBlocked
stack_amount = kNone
frames = {}
}
}
}
}
[zxdb] print reply.processes.size()
2
測試的期望值似乎略有錯誤。您只注入了 2 個模擬程序,但測試預期會有 3 個。您只需更新測試,將 reply.processes
向量的大小預期值從 3 改為 2 即可。現在可以透過 quit
關閉 zxdb,然後更新及修正測試:
quit
<...fx test output continues...>
Failed tests: DebugAgentTests.OnGlobalStatus <-- Failed test case that we debugged.
175 out of 176 attempted tests passed, 2 tests skipped...
fuchsia-pkg://fuchsia.com/debug_agent_unit_tests?hash=3f6d97801bb147034a344e3fe1bb69291a7b690b9d3d075246ddcba59397ac12#meta/debug_agent_unit_tests.cm completed with result: FAILED
Tests failed.
FAILED: fuchsia-pkg://fuchsia.com/debug_agent_unit_tests#meta/debug_agent_unit_tests.cm
找出測試失敗的原因後,即可修正測試:
-ASSERT_EQ(reply.processes.size(), 3u)
+ASSERT_EQ(reply.processes.size(), 2u)
接著執行 fx test
:
fx test --break-on-failure debug_agent_unit_tests
輸出內容應如下所示:
You are using the new fx test, which is currently ready for general use ✅
See details here: https://fuchsia.googlesource.com/fuchsia/+/refs/heads/main/scripts/fxtest/rewrite
To go back to the old fx test, use `fx --enable=legacy_fxtest test`, and please file a bug under b/293917801.
Default flags loaded from /usr/local/google/home/jruthe/.fxtestrc:
[]
Logging all output to: /usr/local/google/home/jruthe/upstream/fuchsia/out/workbench_eng.x64/fxtest-2024-03-25T15:56:31.874893.log.json.gz
Use the `--logpath` argument to specify a log location or `--no-log` to disable
To show all output, specify the `-o/--output` flag.
Found 913 total tests in //out/workbench_eng.x64/tests.json
Plan to run 1 test
Refreshing 1 target
> fx build src/developer/debug/debug_agent:debug_agent_unit_tests host_x64/debug_agent_unit_tests
Use --no-build to skip building
Executing build. Status output suspended.
ninja: Entering directory `/usr/local/google/home/jruthe/upstream/fuchsia/out/workbench_eng.x64'
[22/22](0) STAMP obj/src/developer/debug/debug_agent/debug_agent_unit_tests.stamp
Running 1 test
Starting: fuchsia-pkg://fuchsia.com/debug_agent_unit_tests#meta/debug_agent_unit_tests.cm (NOT HERMETIC)
Command: fx ffx test run --realm /core/testing/system-tests --max-severity-logs WARN --break-on-failure fuchsia-pkg://fuchsia.com/debug_agent_unit_tests?hash=399ff8d9871a6f0d53557c3d7c233cad645061016d44a7855dcea2c7b8af8101#meta/debug_agent_unit_tests.cm
Deleting 1 files at /tmp/tmp8m56ht95: ffx_logs/ffx.log
To keep these files, set --ffx-output-directory.
PASSED: fuchsia-pkg://fuchsia.com/debug_agent_unit_tests#meta/debug_agent_unit_tests.cm
Status: [duration: 16.9s] [tests: PASS: 1 FAIL: 0 SKIP: 0]
Running 1 tests [=====================================================================================================] 100.0%
zxdb 不再顯示,因為您已成功修正所有測試失敗問題!