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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion cmake/Frontends.cmake
Original file line number Diff line number Diff line change
Expand Up @@ -435,7 +435,7 @@ function(webfront_add_browser_tests target frontend assets_directory lifecycle_t
if(WEBFRONT_FRONTEND_${frontend}_XVFB_LINUX AND CMAKE_SYSTEM_NAME STREQUAL "Linux")
set(lifecycle_command "${XVFB_RUN_EXECUTABLE}" -a ${lifecycle_command})
endif()
set(lifecycle_modes no-bridge early-close rejected-ready navigation-failure path-encoding content-policy navigation-allow-list view-association)
set(lifecycle_modes no-bridge early-close rejected-ready navigation-failure path-encoding content-policy navigation-allow-list view-association stage-report)
list(APPEND lifecycle_modes ui-executor native-window second-open)
foreach(mode ${lifecycle_modes})
set(lifecycle_name "${frontend}Lifecycle-${mode}")
Expand Down
10 changes: 10 additions & 0 deletions docs/TEST_TIERS.md
Original file line number Diff line number Diff line change
Expand Up @@ -83,3 +83,13 @@ protection rules of `master`; the workflow cannot set that itself.

The fast tier does not replace the others: the unit tests are also part of the standard run, so a pull request still
reports one complete result.

The shared frontend lifecycle runner has a 45-second watchdog which reports the last observed stage and exits with a failure
status when the interface thread cannot be unwound. Forced process exit does not itself terminate browser subprocesses; they
can remain orphaned until the surrounding CI runner or operating system cleans them up. Do not kill the process group from
the watchdog: a shared Xvfb display and other tests may belong to that group. The 45-second deadline can preempt the
more specific errors of scenarios that make multiple successive 30-second waits. Forced exit also loses the process's
unflushed gcov coverage data. Page stage reports are best effort and can be lost during navigation or disconnection.

The `FrontendLifecycleWatchdog` probe bypasses frontend initialization to test the deadline without a display. The ordinary
`CEFLifecycle-*` CTest cases exercise CEF subprocess dispatch and frontend initialization before the watchdog is started.
4 changes: 2 additions & 2 deletions test/cmake/CheckFrontendGenerators.cmake
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ foreach(generator Ninja "Ninja Multi-Config" Ninja)
endif()
webfront_read_frontend_tests("${directory}" tests)
string(JSON count LENGTH "${tests}" tests)
if(NOT count EQUAL 13)
message(FATAL_ERROR "${generator}: expected Jasmine, eleven shared lifecycle cases and the engine test, got ${count}")
if(NOT count EQUAL 14)
message(FATAL_ERROR "${generator}: expected Jasmine, twelve shared lifecycle cases and the engine test, got ${count}")
endif()
endforeach()
4 changes: 2 additions & 2 deletions test/cmake/CheckFrontendSelection.cmake
Original file line number Diff line number Diff line change
Expand Up @@ -437,9 +437,9 @@ foreach(case webkitgtk-display webkitgtk-linux cef-linux cef-macos cef-windows c
continue()
endif()
if(case STREQUAL "extension" OR case STREQUAL "webview2-windows")
set(expected_count 13)
set(expected_count 14)
else()
set(expected_count 12)
set(expected_count 13)
endif()
if(NOT count EQUAL expected_count)
list(APPEND failures "${case}: expected ${expected_count} tests, got ${count}")
Expand Down
26 changes: 26 additions & 0 deletions test/cmake/CheckLifecycleStageValues.cmake
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
file(READ "${SOURCE_DIR}/test/web/FrontendLifecycle.cpp" cpp)
foreach(page view-association.html content-policy.html policy-escaped.html lifecycle-stage-probe.html)
file(READ "${SOURCE_DIR}/test/web/${page}" html)
string(REGEX MATCH "const stage = \\{[^}]+\\}" declaration "${html}")
if(NOT declaration)
message(FATAL_ERROR "Missing stage declaration in ${page}")
endif()
string(REGEX MATCHALL "[A-Za-z][A-Za-z0-9]*: *[0-9]+" entries "${declaration}")
foreach(entry IN LISTS entries)
string(REGEX REPLACE "^([A-Za-z][A-Za-z0-9]*): *([0-9]+)$" "\\1" name "${entry}")
string(REGEX REPLACE "^([A-Za-z][A-Za-z0-9]*): *([0-9]+)$" "\\2" value "${entry}")
if(NOT cpp MATCHES "(^|[\n\r])[ \t]*${name}[ \t]*=[ \t]*${value}[ \t]*,")
message(FATAL_ERROR "${page}: ${entry} does not match LifecycleStage in FrontendLifecycle.cpp")
endif()
endforeach()
if(NOT entries)
message(FATAL_ERROR "No stage values found in ${page}")
endif()
string(REGEX MATCHALL "stage\\.[A-Za-z][A-Za-z0-9]*" references "${html}")
foreach(reference IN LISTS references)
string(REGEX REPLACE "^stage\\." "" name "${reference}")
if(NOT declaration MATCHES "(^|[{,])[ \t]*${name}[ \t]*:")
message(FATAL_ERROR "${page}: ${reference} has no declared value")
endif()
endforeach()
endforeach()
9 changes: 9 additions & 0 deletions test/cmake/CheckLifecycleWatchdog.cmake
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
execute_process(COMMAND "${PROBE}" watchdog-probe RESULT_VARIABLE result ERROR_VARIABLE error TIMEOUT 7)
if(NOT result STREQUAL "1" OR NOT error MATCHES "Lifecycle timeout at stage: association: waiting for second WebSocket")
message(FATAL_ERROR "Watchdog did not report the stalled stage and fail: result=${result}, stderr=${error}")
endif()

execute_process(COMMAND "${PROBE}" watchdog-uninstrumented-probe RESULT_VARIABLE result ERROR_VARIABLE error TIMEOUT 7)
if(NOT result STREQUAL "1" OR NOT error MATCHES "Lifecycle timeout at stage: uninstrumented mode or frontend initialization")
message(FATAL_ERROR "Watchdog did not report an uninstrumented mode: result=${result}, stderr=${error}")
endif()
4 changes: 2 additions & 2 deletions test/cmake/frontends/CMakeLists.txt
Original file line number Diff line number Diff line change
Expand Up @@ -88,7 +88,7 @@ elseif(CASE STREQUAL "webkitgtk-linux")
include("${ROOT}/test/cmake/WebKitGTKTestEnvironment.cmake")
function(webfront_add_webkitgtk_tests)
list(LENGTH ARGN shared_count)
if(NOT shared_count EQUAL 12 OR NOT "WebFrontWebKitGTKIntegration" IN_LIST ARGN)
if(NOT shared_count EQUAL 13 OR NOT "WebFrontWebKitGTKIntegration" IN_LIST ARGN)
message(FATAL_ERROR "WebKitGTK setup must receive every shared test, including Jasmine")
endif()
foreach(test IN LISTS ARGN)
Expand Down Expand Up @@ -176,7 +176,7 @@ if(CASE STREQUAL "extension" AND NOT TEST EngineLifecycle)
message(FATAL_ERROR "The new engine's lifecycle tests were not registered")
endif()

foreach(mode no-bridge early-close rejected-ready navigation-failure path-encoding view-association)
foreach(mode no-bridge early-close rejected-ready navigation-failure path-encoding view-association stage-report)
set(lifecycle_name "${frontend}Lifecycle-${mode}")
if(NOT TEST ${lifecycle_name})
message(FATAL_ERROR "Missing shared lifecycle case ${lifecycle_name}")
Expand Down
8 changes: 8 additions & 0 deletions test/web/CMakeLists.txt
Original file line number Diff line number Diff line change
Expand Up @@ -20,8 +20,16 @@ if(${WEBFRONT_FRONTEND_${WEBFRONT_WEBTEST_FRONTEND}_OPTION}
target_compile_definitions(frontend_lifecycle PRIVATE WEBFRONT_TEST_FRONTEND=${WEBFRONT_WEBTEST_FRONTEND_TYPE})
webfront_setup_frontends_for_target(frontend_lifecycle)
add_dependencies(webtest frontend_lifecycle)
add_test(NAME FrontendLifecycleWatchdog COMMAND "${CMAKE_COMMAND}"
"-DPROBE=$<TARGET_FILE:frontend_lifecycle>" -P "${PROJECT_SOURCE_DIR}/test/cmake/CheckLifecycleWatchdog.cmake")
set_tests_properties(FrontendLifecycleWatchdog PROPERTIES TIMEOUT 10 LABELS fast)
endif()

# Keep the stage values in the HTML probes synchronized with the C++ enum, including in CEF-off builds.
add_test(NAME FrontendLifecycleStageValues COMMAND "${CMAKE_COMMAND}" "-DSOURCE_DIR=${PROJECT_SOURCE_DIR}"
-P "${PROJECT_SOURCE_DIR}/test/cmake/CheckLifecycleStageValues.cmake")
set_tests_properties(FrontendLifecycleStageValues PROPERTIES TIMEOUT 10 LABELS fast)

# Manual validation of the interface-thread executor and the native window (#450) with a real browser, window and native
# dialog: never built or run by CTest/CI. See docs/validation/native-integration-450.md.
add_executable(native_integration_manual EXCLUDE_FROM_ALL NativeIntegrationManual.cpp)
Expand Down
113 changes: 112 additions & 1 deletion test/web/FrontendLifecycle.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,8 @@

#include <atomic>
#include <chrono>
#include <condition_variable>
#include <cstdlib>
#include <future>
#include <list>
#include <thread>
Expand All @@ -26,6 +28,72 @@ using TestFS = webfront::fs::Multi<webfront::fs::IndexFS, webfront::fs::Native
using App = webfront::BasicWFWithFrontend<webfront::NetProvider, TestFS, webfront::testdriver::QuietFrontend<Frontend>>;
static_assert(Frontend::action == webfront::frontend::Action::closeServerAfterOpen);

// Values reported by the lifecycle pages; keep their named constants in sync with this enum.
enum class LifecycleStage : std::int32_t {
uninstrumented = 0,
bridgeConnected = 1,
associationOrigins = 2,
associationSecondSocket = 3,
associationRegistration = 4,
policyPopup = 5,
policyNavigation = 6,
policyDestination = 7,
pageCompleted = 8,
windowClosed = 9,
startingInstrumented = 10,
};
std::atomic<LifecycleStage> lifecycleStage = LifecycleStage::uninstrumented;
constexpr const char* stageName(LifecycleStage stage) {
switch (stage) {
case LifecycleStage::uninstrumented: return "uninstrumented mode or frontend initialization";
case LifecycleStage::bridgeConnected: return "bridge connected";
case LifecycleStage::associationOrigins: return "association: checking origins";
case LifecycleStage::associationSecondSocket: return "association: waiting for second WebSocket";
case LifecycleStage::associationRegistration: return "association: waiting for second connection registration";
case LifecycleStage::policyPopup: return "policy: bridge ready, opening popup";
case LifecycleStage::policyNavigation: return "policy: waiting for navigation or cancellation";
case LifecycleStage::policyDestination: return "policy: destination bridge ready";
case LifecycleStage::pageCompleted: return "page reported completion, waiting for window close";
case LifecycleStage::windowClosed: return "window closed, checking results or shutting down";
case LifecycleStage::startingInstrumented: return "starting frontend or waiting for first bridge connection";
}
return "unknown stage";
}

// A stuck UI loop or a page which never settles must fail before CTest's outer timeout. The watchdog
// terminates the process because the owning thread cannot safely be unwound; EXIT_FAILURE makes CTest fail.
class LifecycleWatchdog {
std::mutex mutex;
std::condition_variable changed;
bool finished = false;
std::thread worker;
public:
explicit LifecycleWatchdog(std::chrono::seconds timeout) : worker([this, timeout] {
std::unique_lock lock{mutex};
if (!changed.wait_for(lock, timeout, [this] { return finished; })) {
std::cerr << "Lifecycle timeout at stage: " << stageName(lifecycleStage.load()) << std::endl;
std::_Exit(EXIT_FAILURE);
}
}) { }
~LifecycleWatchdog() {
{
std::lock_guard lock{mutex};
finished = true;
}
changed.notify_one();
worker.join();
}
};

template <class Application>
void registerLifecycleStage(Application& app) {
app.cppFunction("lifecycleStage", [](std::int32_t stage) {
if (stage >= static_cast<std::int32_t>(LifecycleStage::associationOrigins)
&& stage <= static_cast<std::int32_t>(LifecycleStage::pageCompleted))
lifecycleStage = static_cast<LifecycleStage>(stage);
});
}

int show(std::string_view page) {
App app(webfront::WebFrontConfig{.documentRoot = std::filesystem::current_path()});
std::atomic<bool> connected = false;
Expand All @@ -46,8 +114,12 @@ int checkViewAssociation() {
std::vector<bool> embedded;
std::vector<bool> local;
std::atomic<bool> originsChecked = false;
lifecycleStage = LifecycleStage::startingInstrumented;
registerLifecycleStage(app);
app.onUIStarted([&](App::UI ui) {
std::scoped_lock lock{mutex};
if (embedded.empty())
lifecycleStage = LifecycleStage::bridgeConnected;
embedded.push_back(ui.isEmbeddedView());
local.push_back(ui.isLocalClient());
});
Expand All @@ -60,6 +132,7 @@ int checkViewAssociation() {
});
app.cppFunction("originsChecked", [&] { originsChecked = true; });
app.show("view-association.html");
lifecycleStage = LifecycleStage::windowClosed;
if (!originsChecked)
throw std::runtime_error("The view association script did not match the browser's serialized IPv6 origins");
std::scoped_lock lock{mutex};
Expand All @@ -72,6 +145,20 @@ int checkViewAssociation() {
return 0;
}

// Exercise a page stage report through the real bridge without making the other scenarios depend on telemetry.
int checkStageReport() {
App app(webfront::WebFrontConfig{.documentRoot = std::filesystem::current_path()});
registerLifecycleStage(app);
std::atomic<bool> observed = false;
app.cppFunction("stageProbeFinished", [&] {
observed = lifecycleStage == LifecycleStage::associationOrigins;
});
app.show("lifecycle-stage-probe.html");
if (!observed)
throw std::runtime_error("The page stage report did not reach the lifecycle runner");
return 0;
}

// What the interface thread's executor reports for one operation.
enum class Outcome { ran, stopped, unavailable, failed };

Expand Down Expand Up @@ -442,19 +529,29 @@ int checkContentPolicy(bool allowNavigation) {
policy.navigationAllowedOrigins = {"http://localhost:9002"};
using PolicyApp = webfront::BasicWFWithFrontend<webfront::NetProvider, TestFS, PolicyLifecycleFrontend>;
PolicyApp app(webfront::WebFrontConfig{.documentRoot = std::filesystem::current_path(), .contentPolicy = policy});
lifecycleStage = LifecycleStage::startingInstrumented;
registerLifecycleStage(app);
app.onUIStarted([](PolicyApp::UI) {
auto initial = LifecycleStage::startingInstrumented;
lifecycleStage.compare_exchange_strong(initial, LifecycleStage::bridgeConnected);
});
std::atomic<bool> completed = false;
std::atomic<bool> escaped = false;
std::atomic<bool> navigated = false;
app.cppFunction("policyCompleted", [&] {
lifecycleStage = LifecycleStage::pageCompleted;
completed = true;
});
app.cppFunction("policyEscaped", [&] {
lifecycleStage = LifecycleStage::pageCompleted;
escaped = true;
});
app.cppFunction("policyNavigated", [&] {
lifecycleStage = LifecycleStage::pageCompleted;
navigated = true;
});
app.show("content-policy.html");
lifecycleStage = LifecycleStage::windowClosed;
if (escaped)
throw std::runtime_error("Frontend allowed an unmanaged popup");
if (completed == allowNavigation)
Expand Down Expand Up @@ -501,6 +598,7 @@ int run(std::string_view mode) {
cases.emplace("native-window", checkNativeWindow);
cases.emplace("second-open", checkSecondOpen);
cases.emplace("view-association", checkViewAssociation);
cases.emplace("stage-report", checkStageReport);
const auto selected = cases.find(mode);
if (selected == cases.end())
throw std::runtime_error("Unknown lifecycle scenario");
Expand All @@ -511,8 +609,21 @@ int run(std::string_view mode) {

int main(int argc, char** argv) {
try {
// CEF subprocesses have their own argument list and must dispatch before mode parsing.
if (argc == 2 && (std::string_view(argv[1]) == "watchdog-probe" || std::string_view(argv[1]) == "watchdog-uninstrumented-probe")) {
LifecycleWatchdog watchdog(std::chrono::seconds(1));
if (std::string_view(argv[1]) == "watchdog-probe")
lifecycleStage = LifecycleStage::associationSecondSocket;
std::this_thread::sleep_for(std::chrono::seconds(5));
return 0;
}
#ifdef WEBFRONT_EMBED_CEF
// CEF subprocesses must dispatch before starting any test threads.
webfront::detail::ensureFrontendInitialized<Frontend>();
#endif
LifecycleWatchdog watchdog(std::chrono::seconds(45));
#ifndef WEBFRONT_EMBED_CEF
webfront::detail::ensureFrontendInitialized<Frontend>();
#endif
return argc == 2 ? run(argv[1]) : 1;
} catch (const std::exception& error) {
std::cerr << error.what() << '\n';
Expand Down
7 changes: 7 additions & 0 deletions test/web/content-policy.html
Original file line number Diff line number Diff line change
@@ -1,7 +1,13 @@
<!doctype html>
<script src="/WebFront.js"></script>
<script type="module">
// Values match LifecycleStage in FrontendLifecycle.cpp. Diagnostics must not change the test outcome.
const stage = { policyPopup: 5, policyNavigation: 6 };
const reportStage = value => {
try { webFront.cppFunction("lifecycleStage")(value).catch(() => {}); } catch { /* best effort */ }
};
await webFront.ready;
reportStage(stage.policyPopup);
const popup = window.open('/policy-escaped.html?popup', '_blank');
if (popup !== null) {
await webFront.cppFunction('policyEscaped')();
Expand All @@ -17,6 +23,7 @@
const target = new URL('/policy-escaped.html?navigation', location.href);
target.hostname = 'localhost';
// Keep one history entry so WebView2 permits the destination's script closure.
reportStage(stage.policyNavigation);
location.replace(target.href);
}
</script>
14 changes: 14 additions & 0 deletions test/web/lifecycle-stage-probe.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
<!doctype html>
<script src="/WebFront.js"></script>
<script type="module">
// Values match LifecycleStage in FrontendLifecycle.cpp.
const stage = { associationOrigins: 2 };
try {
await webFront.ready;
// This dedicated probe waits for the report to exercise its delivery; ordinary scenarios do not.
await webFront.cppFunction('lifecycleStage')(stage.associationOrigins);
await webFront.cppFunction('stageProbeFinished')();
} finally {
window.close();
}
</script>
6 changes: 6 additions & 0 deletions test/web/policy-escaped.html
Original file line number Diff line number Diff line change
@@ -1,8 +1,14 @@
<!doctype html>
<script src="/WebFront.js"></script>
<script type="module">
// Values match LifecycleStage in FrontendLifecycle.cpp. Diagnostics must not change the test outcome.
const stage = { policyDestination: 7 };
const reportStage = value => {
try { webFront.cppFunction("lifecycleStage")(value).catch(() => {}); } catch { /* best effort */ }
};
try {
await webFront.ready;
reportStage(stage.policyDestination);
await webFront.cppFunction(location.search === '?popup' ? 'policyEscaped' : 'policyNavigated')();
} catch (error) {
console.error('Policy destination could not report its result', error);
Expand Down
9 changes: 9 additions & 0 deletions test/web/view-association.html
Original file line number Diff line number Diff line change
Expand Up @@ -3,11 +3,17 @@
<title>View association</title>
<script src="WebFront.js"></script>
<script>
// Values match LifecycleStage in FrontendLifecycle.cpp. Diagnostics must not change the test outcome.
const stage = { associationOrigins: 2, associationSecondSocket: 3, associationRegistration: 4, pageCompleted: 8 };
const reportStage = value => {
try { webFront.cppFunction("lifecycleStage")(value).catch(() => {}); } catch { /* best effort */ }
};
// The page of the embedded view connects with the secret of the launch; the secret is gone once presented.
// A second connection of the same page, from the same loopback address, presents none: it is not the view.
(async () => {
try {
await webFront.ready;
reportStage(stage.associationOrigins);
if ("__webfrontView" in window) throw new Error("the launch secret is still readable by the page");
// Run the C++-generated injection against origins serialized by the real engine. A synthetic window
// keeps the fixed test secret separate from the real view's launch secret and needs no IPv6 listener.
Expand All @@ -24,6 +30,7 @@
if ("__webfrontView" in foreign) throw new Error("a foreign origin received the secret");
}
await webFront.cppFunction("originsChecked")();
reportStage(stage.associationSecondSocket);
await new Promise((resolve, reject) => {
const socket = new WebSocket(`ws://${location.host}`, "WebFront_0.1");
socket.binaryType = "arraybuffer";
Expand All @@ -32,10 +39,12 @@
socket.onerror = () => reject(new Error("the second connection failed"));
socket.onclose = () => reject(new Error("the second connection closed before answering"));
});
reportStage(stage.associationRegistration);
for (let attempt = 0; attempt < 100; ++attempt) {
if (await webFront.cppFunction("startedConnections")() >= 2) break;
await new Promise(resolve => setTimeout(resolve, 50));
}
reportStage(stage.pageCompleted);
} finally {
window.close();
}
Expand Down
Loading