Compare commits

...
Author SHA1 Message Date
feder-cr e7d4c79a70 test(fakeweb): a failure of the journey's request log is never the client's 2026-11-22 11:55:29 +01:00
feder-cr 6d24ec31d5 test(popup): the server-side recorder passes every call through unchanged and a recording error never reaches the server 2026-11-22 11:55:28 +01:00
feder-cr d43204be6c Merge origin/tests/characterization-69 into tests/intermittent-68 2026-11-22 11:55:27 +01:00
feder-cr b3eb30e4e4 tests: the goto-stopped test says in one line why a page is not reused 2026-11-22 11:24:15 +01:00
feder-cr b53d9899b3 tests: the two-connections loopback test keeps what the lab heard on the mDNS group, packet by packet, when it fails
A passive listener (tests/_mdns_listener.py) joins 224.0.0.251:5353 on 127.0.0.1, the interface the engine's responder joins, before each launch and records every packet with its time, source, query or response, names and addresses. It never sends or answers, shares the port with the engine's socket and never raises. No assertion, wait or deadline changes.
2026-11-22 10:52:12 +01:00
feder-cr f020c67fc7 ci: the unit rows hold the two new unit files (the model of a moving page's goto, a read whose probe ran out), 24 tests more 2026-11-22 10:04:24 +01:00
feder-cr 2659330e28 tests: the two-connections loopback test keeps the mDNS and mtransport logs and the page's ICE timeline when it fails
On failure the test saves the engine's own log of the failing launch (mdns_service and mtransport, MOZ_LOG_FILE in the evidence folder), the timings and the page's timeline of every launch up to it: each icecandidate of both connections, every ice and connection state change, when each addIceCandidate was called and settled. No assertion, wait or deadline changes.
2026-11-22 10:02:45 +01:00
feder-cr d9c7312229 tests: the no-proxy HTTP/3 test keeps the engine's HTTP log, the lab server's record and the visit timings when it fails
On failure the test saves the engine's own log of the launch (nsHttp and the neqo_glue, neqo_http3 and neqo_transport modules, MOZ_LOG_FILE in the evidence folder), the lab server's record of every TCP and QUIC connection (start, handshake, each request with its path, close and reason) and the url, protocol, goto time and read time of each visit. No assertion, wait or deadline changes.
2026-11-22 10:02:45 +01:00
feder-cr 9bd0a0c838 Merge branches 'tests/moving-page-goto-model', 'fix/read-timeout-is-the-deadline', 'tests/goto-meta-setup-on-a-fresh-page' and 'tests/evidence-intermittent-68' into tests/intermittent-68 2026-11-22 10:02:14 +01:00
feder-cr ccf1cacab5 test(popup): the 25 s popup saves, when it fails, the engine's wire and trace, what the server sent to the client and did with the target, what the client heard and the destination's record 2026-11-22 09:51:14 +01:00
feder-cr 45a6d0741a test(fakeweb): the journey saves, when it fails, the site's record of each request, the client's log of every request event per step and each step's in-flight list 2026-11-22 09:47:35 +01:00
feder-cr e682add14e tests: after a goto of a moving page raises the frame may go with either page; each test of the moving pages has its own page 2026-11-22 09:37:51 +01:00
feder-cr a4763a6e15 tests: the model of where the frame goes after a goto of a moving page raises, on a fake page (red on the model that picks one page) 2026-11-22 09:36:44 +01:00
feder-cr 55f9c5c4b3 tests: each iteration of the goto-and-every-way-it-is-stopped test runs on its own page, so a refresh the engine replays late cannot fall on the next iteration's setup goto 2026-11-22 09:36:24 +01:00
feder-cr 55aa929667 A read's probe running out of time is the read's timeout, not a second look at the clock 2026-11-22 09:35:00 +01:00
feder-cr 23e685d98f tests: a read whose probe ran out of time is the caller's timeout, whatever the clock says 2026-11-22 09:34:42 +01:00
16 changed files with 1281 additions and 182 deletions

No files matched your search

+2 -2
View File
@@ -14,8 +14,8 @@
{"id": "wrapper.e2e.fakeweb", "giro": "G2", "os": ["linux", "windows"], "min_tests": 4, "exact": true, "tests": ["tests/test_fakeweb_p2_e2e.py", "tests/test_fakeweb_p4_e2e.py"], "marker": "e2e", "needs_root": false, "note": "The fake web, offline: our browser on the hard pages (profile P2: a reused routed page reaches networkidle every time, also under a load of three other browsers; the other site is another process) and on the 17-step journey of a person (profile P4), each judged against what stock Firefox does, as tests/fakeweb/pages.json declares it. 4 = 3 + 1. Stock itself is held to that declaration, and compared with ours step by step, by scripts/run_fakeweb.py in .github/workflows/fakeweb.yml. Needs the candidate binary (STEALTHFOX_E2E_BINARY)."},
{"id": "wrapper.e2e.fontconfig", "giro": "G2", "os": ["linux"], "min_tests": 2, "exact": true, "tests": ["tests/test_the_parent_reads_the_bundle_from_fontconfig_s_cache_linux_e2e.py"], "marker": "e2e", "needs_root": false, "linux_only": "Fontconfig exists only on Linux: the parent of the engine shows <GRE>/fonts to it (FcConfigAppFontAddDir) to rebuild a font from a path and a face index. On Windows DirectWrite opens the file from its path, with no folder to scan and no cache to read, so this test has no Windows counterpart.", "note": "2 = (1) the stand-in that runs the engine under strace stays in the engine's place, as the core launches it (the leader of a process group of its own): a fake engine with a child, no browser; the process the launcher holds lives as long as the fake engine, and the group killed holds strace and the child (the stand-in that exec'd setsid forked and exited 0 at once: candidate 44161687675); (2) the warm launch of the parent reads the bundle from fontconfig's cache and does not scan it again (from firefox-66, engine_at_least). Two launches under strace with the same XDG_CACHE_HOME of the test, the first cold and the second warm: the cold parent opens every font file of <GRE>/fonts (the folder as the disk lists it) before any page and fontconfig writes its cache; the warm parent does not open every one of them, and it opens a *.cache-* file of fontconfig (a few files are opened to be used, so the verdict asks about the whole folder, as a scan does). Scan and drawing are told apart by position: only what the parent opens before the first page counts (the opens that draw are written as after_startup). Evidence in RUNNER_TEMP/invpw-evidence/fontconfig-cache: the interval and the number of opens of the bundle, the names of the files of the bundle each launch opened before the first page, the size of the cache file, the VmRSS of the parent after about:blank and after a page with every family, and a third launch with gfx.bundled-fonts.activate=0 (the behaviour before), which is evidence only. Needs strace on the runner: without it both are red, not skipped. No threshold."},
{"id": "wrapper.unit.compositing", "giro": "G1", "os": ["linux", "windows"], "min_tests": 30, "exact": true, "tests": ["tests/test_the_page_bytes_reference_compares_decoded_pixels.py"], "marker": "unit", "needs_root": false, "note": "The helpers of wrapper.e2e.compositing on known inputs, no browser: the PNG compared on decoded pixels (another deBG chunk and compression are the same, one pixel is not, every scanline filter), the comparison with a reference (changed, missing and extra keys named, the entry to record), the type of an engine process, an engine process known by its executable and not by the name it gives itself (Linux), and the CPU of a window, and the shape of the committed Windows reference, and the box cut out of a screenshot (its pixels, a box outside the picture refused, written as a PNG and read back, two boxes told apart by a pixel that is named, the pixels that are not grey)."},
{"id": "wrapper.unit.all.linux", "giro": "G1", "os": ["linux"], "min_tests": 2260, "exact": true, "tests": ["tests/test_a_162_message_is_read_like_a_161_one.py", "tests/test_a_click_makes_one_mousemove_at_its_point.py", "tests/test_a_closed_context_leaves_nothing_in_the_registry.py", "tests/test_a_closed_page_says_nothing.py", "tests/test_a_closed_pipe_is_a_closed_target.py", "tests/test_a_commit_at_any_point_of_the_hand_over_reaches_the_client_once.py", "tests/test_a_context_proxy_carries_its_measured_udp_exit.py", "tests/test_a_context_route_disables_the_cache.py", "tests/test_a_detached_frame_answers_detached.py", "tests/test_a_dialog_is_a_protocol_object.py", "tests/test_a_dialog_is_answered_after_a_pause.py", "tests/test_a_download_finished_before_it_was_announced_is_finished.py", "tests/test_a_failed_expect_carries_its_call_log.py", "tests/test_a_failed_launch_stops_the_display.py", "tests/test_a_field_is_typed_after_a_pause.py", "tests/test_a_launch_asks_nobody_on_the_internet_where_it_leaves_from.py", "tests/test_a_launch_gives_the_core_its_engine_for_the_security_state.py", "tests/test_a_launch_has_one_deadline.py", "tests/test_a_launch_without_a_session_gets_one.py", "tests/test_a_live_event_does_not_overtake_the_replay_of_a_new_page.py", "tests/test_a_module_that_leaves_a_browser_open_fails.py", "tests/test_a_new_page_waits_for_the_engine.py", "tests/test_a_non_finite_number_crosses_the_wire_as_a_tag.py", "tests/test_a_page_closed_before_its_announcement_is_not_announced.py", "tests/test_a_page_is_handed_over_only_when_the_engine_says_it_is_ready.py", "tests/test_a_path_leaves_as_one_stroke.py", "tests/test_a_port_number_is_held_until_it_is_used.py", "tests/test_a_request_and_a_response_are_light.py", "tests/test_a_request_says_what_it_is.py", "tests/test_a_session_ends_before_the_next_test_starts.py", "tests/test_a_stroke_is_judged_by_its_shape_not_its_length.py", "tests/test_a_unit_test_does_not_read_the_seal_of_the_job.py", "tests/test_actions_without_a_point.py", "tests/test_add_script_tag.py", "tests/test_an_expect_reads_its_value_once.py", "tests/test_async_api.py", "tests/test_browser_output_is_drained.py", "tests/test_ci_downloads_are_authenticated.py", "tests/test_ci_drive_gate_goes_through_the_core.py", "tests/test_ci_host_gate.py", "tests/test_ci_lab_geoip.py", "tests/test_ci_lab_geoip_verify.py", "tests/test_ci_lab_intermediates.py", "tests/test_ci_lab_security_state.py", "tests/test_ci_real_geoip_check.py", "tests/test_ci_real_geoip_exit_code.py", "tests/test_ci_runs_once_per_commit.py", "tests/test_ci_suite_run.py", "tests/test_ci_verdict.py", "tests/test_ci_workflows_build_the_geoip_database.py", "tests/test_ci_workflows_set_the_intermediates_list.py", "tests/test_ci_workflows_set_the_security_state.py", "tests/test_cli.py", "tests/test_click_rhythm.py", "tests/test_connect_does_not_start_threads_on_the_loop.py", "tests/test_context_locale_is_a_list.py", "tests/test_core_pin.py", "tests/test_cpu_by_type_window.py", "tests/test_cross_origin_iframe.py", "tests/test_cursor_dispatch.py", "tests/test_cursor_wiring.py", "tests/test_docs_name_the_mcp_repo_as_it_is.py", "tests/test_doh_session_prefs_unit.py", "tests/test_drag_motion.py", "tests/test_e2e_hermetic.py", "tests/test_element_handle_actions.py", "tests/test_every_order_of_the_events_of_a_popup_gives_one_page_event.py", "tests/test_every_page_draws_its_own_acts.py", "tests/test_every_refusal_is_declared.py", "tests/test_every_route_command_is_answered_may_fail.py", "tests/test_every_suite_runs_on_linux_and_windows.py", "tests/test_expose_binding_refusal.py", "tests/test_fakeweb_p4_report.py", "tests/test_fission_identity_parity_e2e.py", "tests/test_fixtures_name_why_the_package_is_missing.py", "tests/test_fork.py", "tests/test_frame_dispatch.py", "tests/test_geoip_used.py", "tests/test_goto_follows_the_base_url.py", "tests/test_hook_wiring.py", "tests/test_imports.py", "tests/test_integration.py", "tests/test_juggler_event_buffer.py", "tests/test_juggler_event_listeners.py", "tests/test_juggler_injected.py", "tests/test_juggler_lives_in_the_core.py", "tests/test_juggler_posix_pipe.py", "tests/test_juggler_transport.py", "tests/test_key_delay_reaches_the_keyboard.py", "tests/test_keyboard_rhythm.py", "tests/test_launch_counters_run_on_github.py", "tests/test_launcher_config.py", "tests/test_launcher_helpers.py", "tests/test_motion_never_hides_a_programming_error.py", "tests/test_navigation_response.py", "tests/test_new_page_defaults.py", "tests/test_no_event_of_any_family_is_lost_by_the_hand_over.py", "tests/test_no_legacy_in_the_wrapper.py", "tests/test_no_override_leaves_the_persona_scheme.py", "tests/test_no_thread_is_started_on_the_reader.py", "tests/test_page_number_follows_the_call.py", "tests/test_persistent_profile_keeps_state.py", "tests/test_pin.py", "tests/test_pin_dicts_are_valid.py", "tests/test_pinning_doc.py", "tests/test_pointer_server.py", "tests/test_popup_adoption_unit.py", "tests/test_prefs_composition_arm.pLine truncated
{"id": "wrapper.unit.all.windows", "giro": "G1", "os": ["windows"], "min_tests": 2261, "exact": true, "tests": ["tests/test_a_162_message_is_read_like_a_161_one.py", "tests/test_a_click_makes_one_mousemove_at_its_point.py", "tests/test_a_closed_context_leaves_nothing_in_the_registry.py", "tests/test_a_closed_page_says_nothing.py", "tests/test_a_closed_pipe_is_a_closed_target.py", "tests/test_a_commit_at_any_point_of_the_hand_over_reaches_the_client_once.py", "tests/test_a_context_proxy_carries_its_measured_udp_exit.py", "tests/test_a_context_route_disables_the_cache.py", "tests/test_a_detached_frame_answers_detached.py", "tests/test_a_dialog_is_a_protocol_object.py", "tests/test_a_dialog_is_answered_after_a_pause.py", "tests/test_a_download_finished_before_it_was_announced_is_finished.py", "tests/test_a_failed_expect_carries_its_call_log.py", "tests/test_a_failed_launch_stops_the_display.py", "tests/test_a_field_is_typed_after_a_pause.py", "tests/test_a_launch_asks_nobody_on_the_internet_where_it_leaves_from.py", "tests/test_a_launch_gives_the_core_its_engine_for_the_security_state.py", "tests/test_a_launch_has_one_deadline.py", "tests/test_a_launch_without_a_session_gets_one.py", "tests/test_a_live_event_does_not_overtake_the_replay_of_a_new_page.py", "tests/test_a_module_that_leaves_a_browser_open_fails.py", "tests/test_a_new_page_waits_for_the_engine.py", "tests/test_a_non_finite_number_crosses_the_wire_as_a_tag.py", "tests/test_a_page_closed_before_its_announcement_is_not_announced.py", "tests/test_a_page_is_handed_over_only_when_the_engine_says_it_is_ready.py", "tests/test_a_path_leaves_as_one_stroke.py", "tests/test_a_port_number_is_held_until_it_is_used.py", "tests/test_a_request_and_a_response_are_light.py", "tests/test_a_request_says_what_it_is.py", "tests/test_a_session_ends_before_the_next_test_starts.py", "tests/test_a_stroke_is_judged_by_its_shape_not_its_length.py", "tests/test_a_unit_test_does_not_read_the_seal_of_the_job.py", "tests/test_actions_without_a_point.py", "tests/test_add_script_tag.py", "tests/test_an_expect_reads_its_value_once.py", "tests/test_async_api.py", "tests/test_browser_output_is_drained.py", "tests/test_ci_downloads_are_authenticated.py", "tests/test_ci_drive_gate_goes_through_the_core.py", "tests/test_ci_host_gate.py", "tests/test_ci_lab_geoip.py", "tests/test_ci_lab_geoip_verify.py", "tests/test_ci_lab_intermediates.py", "tests/test_ci_lab_security_state.py", "tests/test_ci_real_geoip_check.py", "tests/test_ci_real_geoip_exit_code.py", "tests/test_ci_runs_once_per_commit.py", "tests/test_ci_suite_run.py", "tests/test_ci_verdict.py", "tests/test_ci_workflows_build_the_geoip_database.py", "tests/test_ci_workflows_set_the_intermediates_list.py", "tests/test_ci_workflows_set_the_security_state.py", "tests/test_cli.py", "tests/test_click_rhythm.py", "tests/test_connect_does_not_start_threads_on_the_loop.py", "tests/test_context_locale_is_a_list.py", "tests/test_core_pin.py", "tests/test_cpu_by_type_window.py", "tests/test_cross_origin_iframe.py", "tests/test_cursor_dispatch.py", "tests/test_cursor_wiring.py", "tests/test_docs_name_the_mcp_repo_as_it_is.py", "tests/test_doh_session_prefs_unit.py", "tests/test_drag_motion.py", "tests/test_e2e_hermetic.py", "tests/test_element_handle_actions.py", "tests/test_every_order_of_the_events_of_a_popup_gives_one_page_event.py", "tests/test_every_page_draws_its_own_acts.py", "tests/test_every_refusal_is_declared.py", "tests/test_every_route_command_is_answered_may_fail.py", "tests/test_every_suite_runs_on_linux_and_windows.py", "tests/test_expose_binding_refusal.py", "tests/test_fakeweb_p4_report.py", "tests/test_fission_identity_parity_e2e.py", "tests/test_fixtures_name_why_the_package_is_missing.py", "tests/test_fork.py", "tests/test_frame_dispatch.py", "tests/test_geoip_used.py", "tests/test_goto_follows_the_base_url.py", "tests/test_hook_wiring.py", "tests/test_imports.py", "tests/test_integration.py", "tests/test_juggler_event_buffer.py", "tests/test_juggler_event_listeners.py", "tests/test_juggler_injected.py", "tests/test_juggler_lives_in_the_core.py", "tests/test_juggler_transport.py", "tests/test_key_delay_reaches_the_keyboard.py", "tests/test_keyboard_rhythm.py", "tests/test_launch_counters_run_on_github.py", "tests/test_launcher_config.py", "tests/test_launcher_helpers.py", "tests/test_motion_never_hides_a_programming_error.py", "tests/test_navigation_response.py", "tests/test_new_page_defaults.py", "tests/test_no_event_of_any_family_is_lost_by_the_hand_over.py", "tests/test_no_legacy_in_the_wrapper.py", "tests/test_no_override_leaves_the_persona_scheme.py", "tests/test_no_thread_is_started_on_the_reader.py", "tests/test_page_number_follows_the_call.py", "tests/test_persistent_profile_keeps_state.py", "tests/test_pin.py", "tests/test_pin_dicts_are_valid.py", "tests/test_pinning_doc.py", "tests/test_pointer_server.py", "tests/test_popup_adoption_unit.py", "tests/test_prefs_composition_arm.py", "tests/test_prefs_compositioLine truncated
{"id": "wrapper.unit.all.linux", "giro": "G1", "os": ["linux"], "min_tests": 2284, "exact": true, "tests": ["tests/test_a_162_message_is_read_like_a_161_one.py", "tests/test_a_click_makes_one_mousemove_at_its_point.py", "tests/test_a_closed_context_leaves_nothing_in_the_registry.py", "tests/test_a_closed_page_says_nothing.py", "tests/test_a_closed_pipe_is_a_closed_target.py", "tests/test_a_commit_at_any_point_of_the_hand_over_reaches_the_client_once.py", "tests/test_a_context_proxy_carries_its_measured_udp_exit.py", "tests/test_a_context_route_disables_the_cache.py", "tests/test_a_detached_frame_answers_detached.py", "tests/test_a_dialog_is_a_protocol_object.py", "tests/test_a_dialog_is_answered_after_a_pause.py", "tests/test_a_download_finished_before_it_was_announced_is_finished.py", "tests/test_a_failed_expect_carries_its_call_log.py", "tests/test_a_failed_launch_stops_the_display.py", "tests/test_a_field_is_typed_after_a_pause.py", "tests/test_a_launch_asks_nobody_on_the_internet_where_it_leaves_from.py", "tests/test_a_launch_gives_the_core_its_engine_for_the_security_state.py", "tests/test_a_launch_has_one_deadline.py", "tests/test_a_launch_without_a_session_gets_one.py", "tests/test_a_live_event_does_not_overtake_the_replay_of_a_new_page.py", "tests/test_a_module_that_leaves_a_browser_open_fails.py", "tests/test_a_new_page_waits_for_the_engine.py", "tests/test_a_non_finite_number_crosses_the_wire_as_a_tag.py", "tests/test_a_page_closed_before_its_announcement_is_not_announced.py", "tests/test_a_page_is_handed_over_only_when_the_engine_says_it_is_ready.py", "tests/test_a_path_leaves_as_one_stroke.py", "tests/test_a_port_number_is_held_until_it_is_used.py", "tests/test_a_read_whose_probe_ran_out_is_the_callers_timeout.py", "tests/test_a_request_and_a_response_are_light.py", "tests/test_a_request_says_what_it_is.py", "tests/test_a_session_ends_before_the_next_test_starts.py", "tests/test_a_stroke_is_judged_by_its_shape_not_its_length.py", "tests/test_a_unit_test_does_not_read_the_seal_of_the_job.py", "tests/test_actions_without_a_point.py", "tests/test_add_script_tag.py", "tests/test_an_expect_reads_its_value_once.py", "tests/test_async_api.py", "tests/test_browser_output_is_drained.py", "tests/test_ci_downloads_are_authenticated.py", "tests/test_ci_drive_gate_goes_through_the_core.py", "tests/test_ci_host_gate.py", "tests/test_ci_lab_geoip.py", "tests/test_ci_lab_geoip_verify.py", "tests/test_ci_lab_intermediates.py", "tests/test_ci_lab_security_state.py", "tests/test_ci_real_geoip_check.py", "tests/test_ci_real_geoip_exit_code.py", "tests/test_ci_runs_once_per_commit.py", "tests/test_ci_suite_run.py", "tests/test_ci_verdict.py", "tests/test_ci_workflows_build_the_geoip_database.py", "tests/test_ci_workflows_set_the_intermediates_list.py", "tests/test_ci_workflows_set_the_security_state.py", "tests/test_cli.py", "tests/test_click_rhythm.py", "tests/test_connect_does_not_start_threads_on_the_loop.py", "tests/test_context_locale_is_a_list.py", "tests/test_core_pin.py", "tests/test_cpu_by_type_window.py", "tests/test_cross_origin_iframe.py", "tests/test_cursor_dispatch.py", "tests/test_cursor_wiring.py", "tests/test_docs_name_the_mcp_repo_as_it_is.py", "tests/test_doh_session_prefs_unit.py", "tests/test_drag_motion.py", "tests/test_e2e_hermetic.py", "tests/test_element_handle_actions.py", "tests/test_every_order_of_the_events_of_a_popup_gives_one_page_event.py", "tests/test_every_page_draws_its_own_acts.py", "tests/test_every_refusal_is_declared.py", "tests/test_every_route_command_is_answered_may_fail.py", "tests/test_every_suite_runs_on_linux_and_windows.py", "tests/test_expose_binding_refusal.py", "tests/test_fakeweb_p4_report.py", "tests/test_fission_identity_parity_e2e.py", "tests/test_fixtures_name_why_the_package_is_missing.py", "tests/test_fork.py", "tests/test_frame_dispatch.py", "tests/test_geoip_used.py", "tests/test_goto_follows_the_base_url.py", "tests/test_hook_wiring.py", "tests/test_imports.py", "tests/test_integration.py", "tests/test_juggler_event_buffer.py", "tests/test_juggler_event_listeners.py", "tests/test_juggler_injected.py", "tests/test_juggler_lives_in_the_core.py", "tests/test_juggler_posix_pipe.py", "tests/test_juggler_transport.py", "tests/test_key_delay_reaches_the_keyboard.py", "tests/test_keyboard_rhythm.py", "tests/test_launch_counters_run_on_github.py", "tests/test_launcher_config.py", "tests/test_launcher_helpers.py", "tests/test_motion_never_hides_a_programming_error.py", "tests/test_moving_page_model.py", "tests/test_navigation_response.py", "tests/test_new_page_defaults.py", "tests/test_no_event_of_any_family_is_lost_by_the_hand_over.py", "tests/test_no_legacy_in_the_wrapper.py", "tests/test_no_override_leaves_the_persona_scheme.py", "tests/test_no_thread_is_started_on_the_reader.py", "tests/test_page_number_follows_the_call.py", "tests/test_persistent_profile_keeps_state.py", "tests/test_pin.py", "tests/test_pin_dicts_are_valid.py", "tests/test_pinning_doc.py", "tLine truncated
{"id": "wrapper.unit.all.windows", "giro": "G1", "os": ["windows"], "min_tests": 2285, "exact": true, "tests": ["tests/test_a_162_message_is_read_like_a_161_one.py", "tests/test_a_click_makes_one_mousemove_at_its_point.py", "tests/test_a_closed_context_leaves_nothing_in_the_registry.py", "tests/test_a_closed_page_says_nothing.py", "tests/test_a_closed_pipe_is_a_closed_target.py", "tests/test_a_commit_at_any_point_of_the_hand_over_reaches_the_client_once.py", "tests/test_a_context_proxy_carries_its_measured_udp_exit.py", "tests/test_a_context_route_disables_the_cache.py", "tests/test_a_detached_frame_answers_detached.py", "tests/test_a_dialog_is_a_protocol_object.py", "tests/test_a_dialog_is_answered_after_a_pause.py", "tests/test_a_download_finished_before_it_was_announced_is_finished.py", "tests/test_a_failed_expect_carries_its_call_log.py", "tests/test_a_failed_launch_stops_the_display.py", "tests/test_a_field_is_typed_after_a_pause.py", "tests/test_a_launch_asks_nobody_on_the_internet_where_it_leaves_from.py", "tests/test_a_launch_gives_the_core_its_engine_for_the_security_state.py", "tests/test_a_launch_has_one_deadline.py", "tests/test_a_launch_without_a_session_gets_one.py", "tests/test_a_live_event_does_not_overtake_the_replay_of_a_new_page.py", "tests/test_a_module_that_leaves_a_browser_open_fails.py", "tests/test_a_new_page_waits_for_the_engine.py", "tests/test_a_non_finite_number_crosses_the_wire_as_a_tag.py", "tests/test_a_page_closed_before_its_announcement_is_not_announced.py", "tests/test_a_page_is_handed_over_only_when_the_engine_says_it_is_ready.py", "tests/test_a_path_leaves_as_one_stroke.py", "tests/test_a_port_number_is_held_until_it_is_used.py", "tests/test_a_read_whose_probe_ran_out_is_the_callers_timeout.py", "tests/test_a_request_and_a_response_are_light.py", "tests/test_a_request_says_what_it_is.py", "tests/test_a_session_ends_before_the_next_test_starts.py", "tests/test_a_stroke_is_judged_by_its_shape_not_its_length.py", "tests/test_a_unit_test_does_not_read_the_seal_of_the_job.py", "tests/test_actions_without_a_point.py", "tests/test_add_script_tag.py", "tests/test_an_expect_reads_its_value_once.py", "tests/test_async_api.py", "tests/test_browser_output_is_drained.py", "tests/test_ci_downloads_are_authenticated.py", "tests/test_ci_drive_gate_goes_through_the_core.py", "tests/test_ci_host_gate.py", "tests/test_ci_lab_geoip.py", "tests/test_ci_lab_geoip_verify.py", "tests/test_ci_lab_intermediates.py", "tests/test_ci_lab_security_state.py", "tests/test_ci_real_geoip_check.py", "tests/test_ci_real_geoip_exit_code.py", "tests/test_ci_runs_once_per_commit.py", "tests/test_ci_suite_run.py", "tests/test_ci_verdict.py", "tests/test_ci_workflows_build_the_geoip_database.py", "tests/test_ci_workflows_set_the_intermediates_list.py", "tests/test_ci_workflows_set_the_security_state.py", "tests/test_cli.py", "tests/test_click_rhythm.py", "tests/test_connect_does_not_start_threads_on_the_loop.py", "tests/test_context_locale_is_a_list.py", "tests/test_core_pin.py", "tests/test_cpu_by_type_window.py", "tests/test_cross_origin_iframe.py", "tests/test_cursor_dispatch.py", "tests/test_cursor_wiring.py", "tests/test_docs_name_the_mcp_repo_as_it_is.py", "tests/test_doh_session_prefs_unit.py", "tests/test_drag_motion.py", "tests/test_e2e_hermetic.py", "tests/test_element_handle_actions.py", "tests/test_every_order_of_the_events_of_a_popup_gives_one_page_event.py", "tests/test_every_page_draws_its_own_acts.py", "tests/test_every_refusal_is_declared.py", "tests/test_every_route_command_is_answered_may_fail.py", "tests/test_every_suite_runs_on_linux_and_windows.py", "tests/test_expose_binding_refusal.py", "tests/test_fakeweb_p4_report.py", "tests/test_fission_identity_parity_e2e.py", "tests/test_fixtures_name_why_the_package_is_missing.py", "tests/test_fork.py", "tests/test_frame_dispatch.py", "tests/test_geoip_used.py", "tests/test_goto_follows_the_base_url.py", "tests/test_hook_wiring.py", "tests/test_imports.py", "tests/test_integration.py", "tests/test_juggler_event_buffer.py", "tests/test_juggler_event_listeners.py", "tests/test_juggler_injected.py", "tests/test_juggler_lives_in_the_core.py", "tests/test_juggler_transport.py", "tests/test_key_delay_reaches_the_keyboard.py", "tests/test_keyboard_rhythm.py", "tests/test_launch_counters_run_on_github.py", "tests/test_launcher_config.py", "tests/test_launcher_helpers.py", "tests/test_motion_never_hides_a_programming_error.py", "tests/test_moving_page_model.py", "tests/test_navigation_response.py", "tests/test_new_page_defaults.py", "tests/test_no_event_of_any_family_is_lost_by_the_hand_over.py", "tests/test_no_legacy_in_the_wrapper.py", "tests/test_no_override_leaves_the_persona_scheme.py", "tests/test_no_thread_is_started_on_the_reader.py", "tests/test_page_number_follows_the_call.py", "tests/test_persistent_profile_keeps_state.py", "tests/test_pin.py", "tests/test_pin_dicts_are_valid.py", "tests/test_pinning_doc.py", "tests/test_pointer_server.py", "tLine truncated
{"id": "wrapper.e2e.securitystate", "giro": "G2", "os": ["linux", "windows"], "min_tests": 4, "exact": true, "tests": ["tests/test_security_state_engine_e2e.py"], "marker": "e2e", "needs_root": false, "note": "The security state the core declares, against the engine: the engine launched directly in its generate mode makes what it is given (the contract's result, security_state/ with the bytes of the full filter and of the delta, the core's own validation of it); a normal launch declares no pref of the mode and re-imports nothing; a certificate that Mozilla's CRLite test data say is revoked in a delta is refused at the first navigation (SEC_ERROR_REVOKED_CERTIFICATE) while a valid one loads, and the revoked one loads when the ready directory has no data; a ready directory with no or an empty security_state/ starts. Certificates made on the run (a fresh root trusted in cert9.db by the engine's own xpcshell, Mozilla's default test key as the key of CN=int), servers on loopback, no network. Red on firefox-67 (no generate mode)."},
{"id": "wrapper.e2e.suite.linux.1", "giro": "G2", "os": ["linux"], "min_tests": 376, "exact": true, "tests": ["tests/test_a_closed_browser_leaves_the_others_alone_e2e.py", "tests/test_a_context_that_ends_leaves_no_process_e2e.py", "tests/test_a_cors_preflight_is_not_a_request_of_the_page_e2e.py", "tests/test_a_declared_webgl_extension_survives_its_use_e2e.py", "tests/test_a_granted_permission_is_the_one_the_page_asks_for_e2e.py", "tests/test_a_launch_without_a_session_gets_one_e2e.py", "tests/test_a_left_documents_body_is_evicted_e2e.py", "tests/test_a_mouse_click_makes_one_mousemove_on_its_point_e2e.py", "tests/test_a_page_over_ipv6_gathers_on_a_machine_declared_without_it_e2e.py", "tests/test_a_popup_is_reported_when_the_engine_says_it_is_ready_as_playwright_does_e2e.py", "tests/test_a_screenshot_draws_the_text_of_the_bundled_fonts_as_the_content_does_e2e.py", "tests/test_a_served_browser_answers_a_plain_client_e2e.py", "tests/test_a_tiny_download_on_a_served_browser_is_saved_e2e.py", "tests/test_a_turn_name_over_tcp_goes_through_the_proxy_of_the_context_e2e.py", "tests/test_accept_language_on_the_wire_e2e.py", "tests/test_browser_output_is_drained.py", "tests/test_click_rhythm.py", "tests/test_closing_one_of_four_browsers_does_not_hold_the_loop_e2e.py", "tests/test_control_a_selects_all_in_a_field_e2e.py", "tests/test_cross_origin_iframe.py", "tests/test_declared_host_network_e2e.py", "tests/test_detectors_e2e.py", "tests/test_e2e.py", "tests/test_element_handle_actions.py", "tests/test_element_screenshot_e2e.py", "tests/test_every_page_draws_its_own_acts.py", "tests/test_file_chooser.py", "tests/test_fingerprint_surface.py", "tests/test_fission_frames_history_and_processes_e2e.py", "tests/test_fission_frames_workers_storage_and_special_frames_e2e.py", "tests/test_frames_outlive_the_back_forward_cache_e2e.py", "tests/test_goto_networkidle_after_spa_e2e.py", "tests/test_goto_script_redirect_e2e.py", "tests/test_hidden_display_linux.py", "tests/test_ice_names_by_the_context_proxy_e2e.py::test_the_ice_name_of_a_context_goes_by_the_proxy_of_that_context", "tests/test_ignore_https_errors_e2e.py", "tests/test_injected_node_surface.py", "tests/test_juggler_connection.py", "tests/test_juggler_posix_pipe.py", "tests/test_juggler_transport.py", "tests/test_navigation_across_processes_e2e.py", "tests/test_navigation_response.py", "tests/test_networkidle_reaches_the_client_e2e.py", "tests/test_oop_frame_element.py", "tests/test_oop_frame_geometry.py", "tests/test_page_number_follows_the_call.py", "tests/test_persistent_profile_keeps_state.py", "tests/test_pointer_position.py", "tests/test_popups_reach_the_client_e2e.py", "tests/test_preload_newtab_turns_the_privileged_about_process_off_e2e.py", "tests/test_realness_behind_a_declared_exit_e2e.py", "tests/test_resolver_race_e2e.py", "tests/test_route_header_order_e2e.py", "tests/test_same_document_goto_e2e.py", "tests/test_screencast.py", "tests/test_screencast_stop_e2e.py", "tests/test_screenshot_looks_where_you_are.py", "tests/test_security_state_engine_e2e.py", "tests/test_service_worker.py", "tests/test_service_worker_controller_e2e.py", "tests/test_set_offline_e2e.py", "tests/test_shadow_trusted_input.py", "tests/test_strict_and_force.py", "tests/test_the_callers_code_is_not_counted_e2e.py", "tests/test_the_device_enumeration_takes_the_declared_time_e2e.py", "tests/test_the_engine_is_born_in_the_job_e2e.py::test_a_launch_scans_no_process_of_the_machine", "tests/test_the_engine_is_born_in_the_job_e2e.py::test_after_close_no_process_of_the_session_is_left", "tests/test_the_hosts_file_of_the_host_is_never_read_e2e.py", "tests/test_trial_does_not_act.py", "tests/test_turn_over_tcp_is_tried_for_real_e2e.py", "tests/test_ua_widget_not_selectable.py", "tests/test_voices_e2e.py", "tests/test_wait_for_function.py", "tests/test_webgl_draws_on_the_engine_s_own_gl_e2e.py", "tests/test_webgl_noise_active.py", "tests/test_webrtc_realness.py::test_a_gateway_that_is_far_away_still_gives_the_page_a_srflx_born_through_its_relay", "tests/test_webrtc_realness.py::test_a_gather_after_the_page_loaded_through_the_gateway_costs_only_the_road_to_the_server", "tests/test_webrtc_realness.py::test_a_host_with_ipv6_addresses_gathers_through_an_ipv4_relay", "tests/test_webrtc_realness.py::test_a_proxy_that_does_not_relay_udp_gives_no_srflx_at_all", "tests/test_webrtc_realness.py::test_a_proxy_whose_relay_never_answers_gives_no_srflx_at_all", "tests/test_webrtc_realness.py::test_a_proxy_whose_udp_leaves_from_another_address_gives_no_srflx_at_all", "tests/test_webrtc_realness.py::test_not_blocked_behind_tcp_only_socks", "tests/test_webrtc_realness.py::test_the_first_candidate_of_a_gather_does_not_wait_for_a_gateway_that_is_far_away", "tests/test_webrtc_realness.py::test_the_turn_over_tcp_of_a_context_goes_through_the_proxy_of_that_context", "tests/test_webrtc_realness.py::test_two_contexts_with_two_proxies_each_gets_the_srflx_of_its_own"], "marker": "e2e", "needs_root": false, "windows_twin"Line truncated
{"id": "wrapper.e2e.suite.linux.2", "giro": "G2", "os": ["linux"], "min_tests": 411, "exact": true, "tests": ["tests/test_a_click_waits_for_the_navigation_it_plans_e2e.py", "tests/test_a_context_init_script_runs_once_e2e.py", "tests/test_a_drag_keeps_its_buttons_pressed_e2e.py", "tests/test_a_field_is_typed_after_a_pause.py", "tests/test_a_goto_to_a_response_with_no_document_ends_e2e.py", "tests/test_a_keepalive_request_reaches_the_client_e2e.py", "tests/test_a_latin_letter_on_a_cyrillic_persona_e2e.py", "tests/test_a_page_cannot_probe_the_juggler_e2e.py", "tests/test_a_page_that_moves_on_e2e.py", "tests/test_a_pointer_event_is_handled_before_the_call_returns_e2e.py", "tests/test_a_request_says_what_it_is_e2e.py", "tests/test_a_worker_comes_back_with_its_page_from_the_cache_e2e.py", "tests/test_actions_without_a_point.py", "tests/test_add_script_tag.py", "tests/test_an_isolated_page_and_the_next_e2e.py", "tests/test_bypass_csp_e2e.py", "tests/test_caller_world_handles_e2e.py", "tests/test_canvas_reads_as_drawn.py", "tests/test_canvas_render_stealth.py", "tests/test_context_locale_e2e.py", "tests/test_context_proxy_only_resolves_by_doh_e2e.py", "tests/test_doh_through_the_proxy_e2e.py", "tests/test_doh_under_stress_e2e.py", "tests/test_download_is_intercepted_e2e.py", "tests/test_drag_motion.py", "tests/test_expose_binding_e2e.py", "tests/test_fakeweb_p4_e2e.py", "tests/test_fingerprint_consistency.py", "tests/test_fission_frames_dialogs_downloads_popups_e2e.py", "tests/test_fission_frames_route_and_bindings_e2e.py", "tests/test_fission_identity_parity_e2e.py", "tests/test_fission_iframe_crash_e2e.py", "tests/test_fission_strategy1_bench.py", "tests/test_goto_to_the_same_url_e2e.py", "tests/test_http3_through_the_proxy_e2e.py", "tests/test_input_is_born_before_the_page_sees_it_e2e.py", "tests/test_juggler_actions.py", "tests/test_juggler_event_listeners.py", "tests/test_juggler_injected.py::test_a_javascript_that_THROWS_arrives_as_an_error_not_as_None", "tests/test_juggler_injected.py::test_actionability_DISTINGUISHES_instead_of_always_saying_yes", "tests/test_juggler_injected.py::test_reads_that_make_no_sense_are_REJECTED", "tests/test_juggler_injected.py::test_states_DISCRIMINATE_instead_of_always_saying_true", "tests/test_juggler_injected.py::test_the_DOM_READING_group", "tests/test_juggler_injected.py::test_the_selector_engines_respond", "tests/test_juggler_injected.py::test_the_text_reads", "tests/test_juggler_lifecycle_e2e.py", "tests/test_key_delay_reaches_the_keyboard.py", "tests/test_keyboard_rhythm.py", "tests/test_long_session_e2e.py", "tests/test_mouse.py", "tests/test_mouse_events_keep_their_values_e2e.py", "tests/test_new_page_defaults.py", "tests/test_popup_destinations_e2e.py", "tests/test_popup_pages.py", "tests/test_proxy_http_auth_e2e.py", "tests/test_proxy_reaches_the_browser.py", "tests/test_proxy_socks_auth_e2e.py", "tests/test_requestless_navigation.py", "tests/test_route_abort_code.py", "tests/test_route_e2e.py", "tests/test_route_post_data_e2e.py", "tests/test_route_sends_a_navigation_elsewhere_e2e.py", "tests/test_route_superseded_e2e.py", "tests/test_same_document_navigation.py", "tests/test_screenshot_of_text_returns_linux_e2e.py", "tests/test_scroll_into_view.py", "tests/test_scroll_only_if_needed_e2e.py", "tests/test_service_workers_blocked.py", "tests/test_set_input_files_payloads.py", "tests/test_software_compositing_is_declared_e2e.py", "tests/test_the_association_is_ready_when_the_peerconnection_is_born_e2e.py", "tests/test_the_callers_code_runs_once_e2e.py", "tests/test_the_close_returns_when_the_browser_has_exited_e2e.py", "tests/test_the_favicon_stays_out_of_sight_e2e.py", "tests/test_the_font_list_is_the_bundle_e2e.py", "tests/test_the_parent_reads_the_bundle_from_fontconfig_s_cache_linux_e2e.py", "tests/test_the_scheme_is_the_personas_e2e.py", "tests/test_the_whole_udp_chain_by_name_e2e.py::test_a_turn_srflx_by_name_arrives_through_the_relay_when_the_exit_of_the_lab_is_loopback", "tests/test_typing_a_character_without_a_key_e2e.py", "tests/test_wait_for_timeout.py", "tests/test_web_fonts_of_closed_contexts_e2e.py"], "marker": "e2e", "needs_root": false, "windows_twin": "wrapper.e2e.suite.windows.2", "note": "Part 2 of the whole e2e suite of the wrapper (every test that opens the browser: what e2e.yml runs on the published engine), on the engine under test, as two passes through scripts/ci_suite_run.py (4 browsers at once, then the wall_clock tests alone; no rerun). The files of the 2 rows of linux are the files of tests/ that tests/test_the_e2e_suite_is_accounted_for.py holds one by one: a file whole when every test of it is here, else its tests by name. Partition from the junits of runs 44942540063 and 44985244053, test time balanced (about 564 s of estimated wall time, 4 browsers). A new file is added by hand to a row of each system and the minimum of the row goes up by hand. Left out of every row, with the reason in the accounting test: the files and tests of wrapLine truncated
+6 -3
View File
@@ -1243,9 +1243,12 @@ class FrameDispatcher(Dispatcher):
frame_id, selector, what, *args, strict=strict,
timeout=deadline.left())
except juggler.ReplyTimeout as exc:
# The caller's time ran out while a probe was in flight: that
# is this read's timeout, not the probe's.
if deadline.passed():
# The probe's bound is what was left of the caller's time, so
# its running out IS the caller's time running out: this
# read's timeout, not the probe's. Not asked of the clock
# again: on Windows a wait can end before it says so. With no
# limit the probe had no bound, and this is something else.
if deadline.seconds is not None:
raise expired() from exc
raise
if found:
+31
View File
@@ -0,0 +1,31 @@
"""``FailureEvidence`` that also keeps a folder of extra files (the engine's own log of the launch, a lab server's record, a page's timeline).
The test writes whatever it wants to keep into ``evidence.files`` while it runs. When the body fails, the folder is copied next to the
rest of the evidence (``<evidence folder>/files/``) and ``meta.json`` lists it; when the body passes, it is deleted with the rest.
Nothing else differs from ``tests/_evidence_on_failure.py``.
"""
from __future__ import annotations
import json
import shutil
from _evidence_on_failure import FailureEvidence
class FailureEvidenceWithFiles(FailureEvidence):
def __init__(self, name: str):
super().__init__(name)
#: Under the helper's own temporary folder: removed with it when the body passes.
self.files = self.work / "files"
self.files.mkdir(parents=True, exist_ok=True)
def _save(self, exc_type, exc) -> None:
super()._save(exc_type, exc)
if self.saved_to is None or not self.files.exists():
return
shutil.copytree(self.files, self.saved_to / "files", dirs_exist_ok=True)
meta_path = self.saved_to / "meta.json"
meta = json.loads(meta_path.read_text(encoding="utf-8"))
meta["files"] = sorted(p.name for p in self.saved_to.iterdir())
meta["extra_files"] = sorted(str(p.relative_to(self.files)).replace("\\", "/") for p in self.files.rglob("*") if p.is_file())
meta_path.write_text(json.dumps(meta, indent=1), encoding="utf-8")
+65 -11
View File
@@ -7,6 +7,10 @@ later one read `h3` (retail Firefox 159, native DNS in loopback: h2, h3, h3; beh
came from: a connection that comes from anywhere but the relay of a gateway on this host (127.0.0.1) did not go through
the proxy.
It also keeps its own record of what it saw (``H3Server.record``, ``write_record``): per TCP connection its accept, the ALPN, every request
path and its end, per QUIC connection its first datagram, its handshake, every request and its end (with the reason), each with ``m``
(``time.perf_counter()`` of the test process) and ``t`` (``time.time()``). It only listens: no answer depends on it.
Needs `aioquic` and `h2` (pip install aioquic h2; the dev extra installs both).
"""
from __future__ import annotations
@@ -14,12 +18,15 @@ from __future__ import annotations
import asyncio
import datetime
import ipaddress
import itertools
import json
import socket
import socketserver
import ssl
import sys
import tempfile
import threading
import time
from pathlib import Path
from typing import List, Tuple
@@ -71,29 +78,35 @@ class _TcpHandler(socketserver.BaseRequestHandler):
def handle(self):
owner = self.server.owner
cid = "tcp-%d" % next(owner._ids)
owner.note("tcp_accept", conn=cid, peer=list(self.client_address[:2]))
reason = "handler ended"
try:
self.request.settimeout(10)
tls = owner._tls.wrap_socket(self.request, server_side=True)
except (ssl.SSLError, OSError):
except (ssl.SSLError, OSError) as exc:
owner.note("tcp_handshake_failed", conn=cid, error=repr(exc))
return
try:
tls.settimeout(60)
alpn = tls.selected_alpn_protocol() or "http/1.1"
owner.tcp_alpn.append(alpn)
owner.note("tcp_handshake_done", conn=cid, alpn=alpn)
if alpn == "h2":
self._h2(tls, owner)
reason = self._h2(tls, owner, cid)
else:
self._http1(tls, owner)
except (ssl.SSLError, OSError):
pass
reason = self._http1(tls, owner, cid)
except (ssl.SSLError, OSError) as exc:
reason = "error: %r" % (exc,)
finally:
owner.note("tcp_close", conn=cid, reason=reason)
try:
tls.close()
except OSError:
pass
@staticmethod
def _h2(tls, owner):
def _h2(tls, owner, cid):
import h2.config
import h2.connection
import h2.events
@@ -105,15 +118,16 @@ class _TcpHandler(socketserver.BaseRequestHandler):
while True:
data = tls.recv(65536)
if not data:
return
return "the client closed the connection (EOF)"
try:
events = conn.receive_data(data)
except h2.exceptions.ProtocolError:
except h2.exceptions.ProtocolError as exc:
tls.sendall(conn.data_to_send())
return
return "h2 protocol error: %r" % (exc,)
for event in events:
if isinstance(event, h2.events.RequestReceived):
owner.tcp_requests.append(dict(event.headers).get(":path", ""))
owner.note("tcp_request", conn=cid, stream=event.stream_id, path=dict(event.headers).get(":path", ""))
conn.send_headers(event.stream_id, [
(":status", "200"), ("content-type", "text/html; charset=utf-8"),
("content-length", str(len(PAGE))), ("alt-svc", owner.alt_svc),
@@ -122,13 +136,13 @@ class _TcpHandler(socketserver.BaseRequestHandler):
elif isinstance(event, h2.events.DataReceived):
conn.acknowledge_received_data(event.flow_controlled_length, event.stream_id)
elif isinstance(event, h2.events.ConnectionTerminated):
return
return "h2 GOAWAY from the client (error code %s)" % (event.error_code,)
out = conn.data_to_send()
if out:
tls.sendall(out)
@staticmethod
def _http1(tls, owner):
def _http1(tls, owner, cid):
head = b""
while b"\r\n\r\n" not in head:
chunk = tls.recv(4096)
@@ -140,6 +154,7 @@ class _TcpHandler(socketserver.BaseRequestHandler):
tls.sendall(b"HTTP/1.1 200 OK\r\nContent-Type: text/html; charset=utf-8\r\nContent-Length: %d\r\n"
b"Alt-Svc: %s\r\nAccess-Control-Allow-Origin: *\r\nConnection: close\r\n\r\n%s"
% (len(PAGE), owner.alt_svc.encode(), PAGE))
return "answered, Connection: close"
class H3Server:
@@ -164,6 +179,9 @@ class H3Server:
self.tcp_requests: List[str] = []
#: The ALPN each TCP connection negotiated ("h2", or "http/1.1").
self.tcp_alpn: List[str] = []
#: The server's own record of what it saw, in order (``note``): a list of dicts, each with ``m``, ``t`` and ``kind``.
self.record: List[dict] = []
self._ids = itertools.count(1)
self._dir = tempfile.TemporaryDirectory()
cert, key = _certificate(address, Path(self._dir.name))
@@ -186,8 +204,29 @@ class H3Server:
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self._http = None
self._cid = "quic-%d" % next(server._ids)
self._datagrams = 0
self._last_datagram_m = None
def datagram_received(self, data, addr):
self._datagrams += 1
self._last_datagram_m = round(time.perf_counter(), 6)
if self._datagrams == 1:
server.note("quic_first_datagram", conn=self._cid, peer=list(addr[:2]), bytes=len(data))
super().datagram_received(data, addr)
def quic_event_received(self, event):
kind = type(event).__name__
if isinstance(event, ProtocolNegotiated):
server.note("quic_protocol_negotiated", conn=self._cid, alpn=event.alpn_protocol, datagrams=self._datagrams)
elif kind == "HandshakeCompleted":
server.note("quic_handshake_done", conn=self._cid, alpn=getattr(event, "alpn_protocol", None),
datagrams=self._datagrams)
elif kind == "ConnectionTerminated":
server.note("quic_close", conn=self._cid, error_code=event.error_code, frame_type=event.frame_type,
reason=event.reason_phrase, datagrams=self._datagrams, last_datagram_m=self._last_datagram_m)
elif kind == "StreamReset":
server.note("quic_stream_reset", conn=self._cid, stream=event.stream_id, error_code=event.error_code)
if isinstance(event, ProtocolNegotiated):
self._http = H3Connection(self._quic)
peer = self._quic._network_paths[0].addr
@@ -198,6 +237,7 @@ class H3Server:
if isinstance(http_event, HeadersReceived):
headers = dict(http_event.headers)
server.h3_requests.append(headers.get(b":path", b"").decode())
server.note("quic_request", conn=self._cid, stream=http_event.stream_id, path=server.h3_requests[-1])
self._http.send_headers(http_event.stream_id, [
(b":status", b"200"), (b"content-type", b"text/html; charset=utf-8"),
(b"access-control-allow-origin", b"*")])
@@ -236,7 +276,21 @@ class H3Server:
def url(self) -> str:
return "https://%s:%d/" % (self.address, self.port)
def note(self, kind: str, **fields) -> None:
"""One line of the server's record: ``m`` is ``time.perf_counter()`` of this process, ``t`` the wall clock. Never raises."""
try:
self.record.append({"m": round(time.perf_counter(), 6), "t": round(time.time(), 4), "kind": kind, **fields})
except Exception:
pass
def write_record(self, path) -> None:
"""The record as JSON lines (what the failure evidence of a test keeps)."""
with open(path, "w", encoding="utf-8") as out:
for line in list(self.record):
out.write(json.dumps(line, default=str) + "\n")
def close(self) -> None:
self.note("server_close", quic_connections=len(self.quic_peers), tcp_connections=len(self.tcp_alpn))
self._tcp.shutdown()
self._tcp.server_close()
if not self._loop.is_closed():
+165
View File
@@ -0,0 +1,165 @@
"""A passive listener on the mDNS group (224.0.0.251, UDP 5353): what the lab heard of the engine's responder, packet by packet.
Failure evidence of ``tests/test_declared_host_network_e2e.py``. The engine's responder (dom/media/webrtc/transport/mdns_service/src/lib.rs) is
not heard in a release build: its ``trace!`` lines are compiled out (``release_max_level_info``), so the lab listens to the group itself.
IT ONLY LISTENS. It never sends a packet, never answers, never sets a multicast interface or the loop flag (those are the sender's), and it never raises:
every refusal (a bind, a join, a read, a parse) is written into its own record and the test goes on unchanged.
HOW IT BINDS, against the engine's own socket (lib.rs:124-135): the engine makes a UDP socket with SO_REUSEADDR, SO_REUSEPORT where the system has it
(not on Windows) and binds 0.0.0.0:5353. Both sockets here set the same options, so two sockets share the port and each receives every datagram sent
to the group, and the listener takes nothing from the engine:
* Linux: SO_REUSEADDR and SO_REUSEPORT, bound to the group address 224.0.0.251:5353. A socket bound to a multicast address receives only datagrams
addressed to that group, never a unicast one, so it cannot take a datagram that was meant for the engine's wildcard socket.
* Windows: SO_REUSEADDR, bound to 0.0.0.0:5353 (a multicast address cannot be bound there). The listener is started BEFORE the browser is launched, so the
engine's socket is the later one: Windows gives a unicast datagram to the socket bound last, and the engine's responder sends and answers on the group
address only (lib.rs: ``send_to(&buf, mdns_addr)``).
It joins the group on the interfaces the engine joins on: ``mdns_service_start`` is given ``nr_stealth_mdns_interfaces()``, which is ``"127.0.0.1;"``
(dom/media/webrtc/transport/nr_stealth_network.cpp:229), and the engine joins each address it is given (lib.rs:138-145) and sends through the first
(lib.rs:150-153). So the listener joins on 127.0.0.1 and nothing else.
The record (``write``): JSON lines, the first line ``{"kind": "listener", ...}`` (how the bind and the join went, and the packet counts), then one
line per packet: ``m`` (``time.perf_counter()`` of the test process, the scale of the page timeline once joined by the launch's ``started_m``), ``t`` (wall
clock), ``src`` ([address, port]), ``bytes``, ``kind`` (``query``, ``response`` or ``unparsed``), ``id``, ``questions`` ([{name, type, unicast_bit}]) and
``answers`` ([{name, type, ttl, data}]) as read by a minimal DNS parse.
"""
from __future__ import annotations
import ipaddress
import json
import socket
import struct
import sys
import threading
import time
GROUP = "224.0.0.251"
#: The engine's group, and the one interface it joins on (nr_stealth_mdns_interfaces).
MDNS_ADDRESS = (GROUP, 5353)
JOIN_INTERFACE = "127.0.0.1"
_TYPES = {1: "A", 12: "PTR", 16: "TXT", 28: "AAAA", 33: "SRV", 255: "ANY"}
def _name(data: bytes, offset: int, depth: int = 0):
"""The domain name at ``offset`` (compression followed) and the offset after it in the record the name started in."""
labels, end, jumped = [], None, False
while True:
if offset >= len(data) or depth > 20:
raise ValueError("name out of range")
length = data[offset]
if length == 0:
offset += 1
break
if length & 0xC0 == 0xC0:
pointer = ((length & 0x3F) << 8) | data[offset + 1]
if end is None:
end = offset + 2
offset, jumped, depth = pointer, True, depth + 1
continue
labels.append(data[offset + 1: offset + 1 + length].decode("utf-8", "replace"))
offset += 1 + length
return ".".join(labels), (end if jumped else offset)
def parse(data: bytes) -> dict:
"""A DNS message, minimally: its id, whether it is a query or a response, the questions and the answers."""
identifier, flags, qd, an, ns, ar = struct.unpack("!6H", data[:12])
out = {"id": identifier, "kind": "response" if flags & 0x8000 else "query", "counts": [qd, an, ns, ar], "questions": [], "answers": []}
offset = 12
for _ in range(qd):
name, offset = _name(data, offset)
qtype, qclass = struct.unpack("!HH", data[offset: offset + 4])
offset += 4
out["questions"].append({"name": name, "type": _TYPES.get(qtype, qtype), "unicast_bit": bool(qclass & 0x8000)})
for _ in range(an + ns + ar):
name, offset = _name(data, offset)
rtype, _rclass, ttl, length = struct.unpack("!HHIH", data[offset: offset + 10])
offset += 10
raw = data[offset: offset + length]
if rtype == 1 and length == 4:
value = str(ipaddress.IPv4Address(raw))
elif rtype == 28 and length == 16:
value = str(ipaddress.IPv6Address(raw))
else:
value = raw.hex()
out["answers"].append({"name": name, "type": _TYPES.get(rtype, rtype), "ttl": ttl, "data": value})
offset += length
return out
class MdnsListener:
def __init__(self):
self.packets = []
#: What happened to the listener itself: the bind, the join, a read or a parse that failed. Never raised.
self.status = []
self._socket = None
self._thread = None
self._stop = threading.Event()
def start(self) -> "MdnsListener":
try:
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
if sys.platform != "win32" and hasattr(socket, "SO_REUSEPORT"):
sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEPORT, 1)
sock.bind((GROUP if sys.platform != "win32" else "0.0.0.0", MDNS_ADDRESS[1]))
self.status.append({"what": "bound", "address": sock.getsockname()[0], "port": sock.getsockname()[1]})
except Exception as exc:
self.status.append({"what": "bind failed: the listener hears nothing", "error": repr(exc)})
return self
try:
sock.setsockopt(socket.IPPROTO_IP, socket.IP_ADD_MEMBERSHIP, socket.inet_aton(GROUP) + socket.inet_aton(JOIN_INTERFACE))
self.status.append({"what": "joined", "group": GROUP, "interface": JOIN_INTERFACE})
except Exception as exc:
self.status.append({"what": "join failed", "group": GROUP, "interface": JOIN_INTERFACE, "error": repr(exc)})
try:
sock.settimeout(0.2)
self._socket = sock
self._thread = threading.Thread(target=self._run, name="mdns-listener", daemon=True)
self._thread.start()
except Exception as exc:
self.status.append({"what": "no reader thread", "error": repr(exc)})
return self
def _run(self) -> None:
sock = self._socket
while not self._stop.is_set():
try:
data, source = sock.recvfrom(9000)
except socket.timeout:
continue
except Exception as exc:
if not self._stop.is_set():
self.status.append({"what": "read failed: the listener stops", "error": repr(exc)})
return
record = {"m": round(time.perf_counter(), 6), "t": round(time.time(), 4), "src": [source[0], source[1]], "bytes": len(data)}
try:
record.update(parse(data))
except Exception as exc:
record.update(kind="unparsed", error=repr(exc), hex=data[:64].hex())
self.packets.append(record)
def stop(self) -> None:
self._stop.set()
try:
if self._socket is not None:
self._socket.close()
except Exception:
pass
if self._thread is not None:
self._thread.join()
def summary(self) -> dict:
kinds = {}
for packet in list(self.packets):
kinds[packet["kind"]] = kinds.get(packet["kind"], 0) + 1
return {"packets": len(self.packets), "by_kind": kinds, "status": list(self.status)}
def write(self, path) -> None:
with open(path, "w", encoding="utf-8") as out:
out.write(json.dumps(dict(kind="listener", group=GROUP, join_interface=JOIN_INTERFACE, **self.summary()), default=str) + "\n")
for packet in list(self.packets):
out.write(json.dumps(packet, default=str) + "\n")
+69
View File
@@ -0,0 +1,69 @@
"""The `goto` of the tests of pages that move on their own (`test_a_page_that_moves_on_e2e.py`), and the model of where the frame goes."""
from __future__ import annotations
def _landing(url: str) -> str:
"""Where the page of `url` sends itself: /landed with the query of its round, which no other round of the module has."""
return "/landed" + url[url.index("?"):]
#: The pages (by address) the frame may still go with, for each page of the browser (by `id`): the page sent last when `goto` answered, and, from a
#: `goto` that raised, every page it may have gone with (`_goto`). `forget` takes a page out when its test ends: an `id` is reused.
_SENT: dict = {}
#: An optional hook for the evidence a failing test leaves: called as ``note(what, **fields)`` where `_goto` sends, hears the answer and hears the error.
#: The test module sets it; it only listens and changes no wait or assertion.
note = None
def forget(page) -> None:
_SENT.pop(id(page), None)
def _goto(page, url, *, the_page_before_may_move, our_page_may_stop_ours, **kwargs) -> frozenset:
"""`page.goto`, and the pages the frame may go with: ``{url}`` when `goto` answers.
- ``the_page_before_may_move``: the pages sent before ours may still be moving (the rounds of the read test go on
while they do, module docstring). A `location.replace` of one of them may win: `goto` says ours was interrupted by it, or
stopped (NS_BINDING_ABORTED), and the frame lands on the landing of THAT page.
- ``our_page_may_stop_ours``: an engine before firefox-68, where `goto` may say NS_BINDING_ABORTED for our own
document, which had committed and then moved
(`test_networkidle_is_reached_only_on_the_page_that_replaced_a_document_still_arriving`); the frame then lands on
our landing.
When `goto` raises, the frame may still go with EITHER page: Playwright raises "interrupted" as soon as a different navigation commits,
while ours goes on, commits and moves to its own landing (run 44688029161: x50-4 raised for the landing of x50-3, and the frame then
navigated to the landing of x50-4). Nothing here knows which one it is, so the pages that may be moving are all of the pages before and
ours, and the next round accepts the landing of any of them. Stock Playwright behaves the same: the model was the test's.
Any other answer is red: an error that is neither answer, an "interrupted" that names a page that cannot be moving, and a navigation that
never answers. The detector of that last one is the timeout of the `goto` itself (each caller passes one): a bound of the test stricter
than it only judged the speed of the machine."""
from invisible_playwright.sync_api import Error
before = _SENT.get(id(page), frozenset()) if the_page_before_may_move else frozenset()
if note:
note("goto", url=url, before=sorted(before))
try:
page.goto(url, **kwargs)
if note:
note("goto-answered", url=url)
except Error as e:
text = str(e)
if note:
note("goto-raised", url=url, error=text[:300])
if "NS_BINDING_ABORTED" in text:
ends = tuple(_landing(u) for u in sorted(before | ({url} if our_page_may_stop_ours else frozenset())))
assert ends, e
page.wait_for_url(lambda u: u.endswith(ends), timeout=30_000)
else:
assert before, e
assert "is interrupted by another navigation to" in text, e
named = text.split("another navigation to")[1]
assert any(_landing(u) in named for u in before), (e, sorted(before))
possible = before | {url}
else:
possible = frozenset({url})
_SENT[id(page)] = possible
return possible
+67 -4
View File
@@ -22,6 +22,8 @@ User: alice / secret.
import html
import json
import secrets
import select
import socket
import threading
import time
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
@@ -31,6 +33,8 @@ from urllib.parse import parse_qs, urlencode, urlsplit
from fakeweb import sites
CACHE_PAGES = "no-cache"
#: Most records kept per start(): a long run of the site is not a memory leak.
MAX_RECORDS = 50000
STATE = None # the State of the running site (set by start): the walk tells it the current step
USER, PASSWORD = "alice", "secret"
N_ARTICLES = 30
@@ -365,6 +369,17 @@ class State:
self.walk = 0
self.cond = threading.Condition()
self.released = set()
#: What the server itself saw, in order, for a test that saves it when it fails (`start(...)[2].state.records`; nothing else reads
#: it): one `accept` per TCP connection and one `request` per request, with `time.perf_counter()` of this process as `m_*` (the
#: scale of the client's log) and `time.time()` as `t_*`; for a held request (`/hold`) also when the hold began and ended, why
#: it ended, and when the server first saw the browser's end of the connection closed.
self.records = []
def note(self, record):
with self.lock:
if len(self.records) < MAX_RECORDS:
self.records.append(record)
return record
def set_step(self, n):
with self.cond:
@@ -388,13 +403,17 @@ class State:
self.released.add(rid)
self.cond.notify_all()
def hold(self, rid, until=0, failsafe=90.0):
def hold(self, rid, until=0, failsafe=90.0, watch=None):
"""Block until /release?id=rid arrives, or the walk reaches step `until`; the failsafe only
keeps a lost event from blocking a thread forever."""
keeps a lost event from blocking a thread forever. Returns why it ended (`released`, `step`, `failsafe`);
`watch`, if given, is called every half second while waiting (it only looks)."""
end = time.time() + failsafe
with self.cond:
while rid not in self.released and not (until and self.step >= until) and time.time() < end:
self.cond.wait(0.5)
if watch is not None:
watch()
return "released" if rid in self.released else "step" if (until and self.step >= until) else "failsafe"
def record(self, idx, method, path, q):
"""Server-side log: what the server saw, tagged with the walk step that was current."""
@@ -425,6 +444,11 @@ class Site(ThreadingHTTPServer):
self.idx = idx
self.state = state
def process_request(self, request, client_address):
self.state.note({"ev": "accept", "t": round(time.time(), 4), "m": round(time.perf_counter(), 6), "site": self.idx,
"peer": client_address[1]})
super().process_request(request, client_address)
class Handler(BaseHTTPRequestHandler):
protocol_version = "HTTP/1.1"
@@ -451,6 +475,11 @@ class Handler(BaseHTTPRequestHandler):
self.end_headers()
if body and self.command != "HEAD":
self.wfile.write(body)
rec = getattr(self, "_rec", None)
if rec is not None:
rec["status"] = code
rec["t_answer"] = round(time.time(), 4)
rec["m_answer"] = round(time.perf_counter(), 6)
def _html(self, text, code=200, headers=()):
self._send(code, "text/html; charset=utf-8", text.encode(), headers, cache=CACHE_PAGES)
@@ -460,10 +489,32 @@ class Handler(BaseHTTPRequestHandler):
def _guard(self, fn):
# Browsers abort requests on purpose; a dropped socket is not an error here.
state = self.server.state
rec = self._rec = state.note({
"ev": "request", "t_arrive": round(time.time(), 4), "m_arrive": round(time.perf_counter(), 6), "site": self.server.idx,
"peer": self.client_address[1], "method": self.command, "path": self.path, "walk": state.walk, "step": state.step,
"status": None, "t_answer": None, "m_answer": None, "t_done": None, "m_done": None, "error": None})
try:
fn()
except (BrokenPipeError, ConnectionResetError, ConnectionAbortedError, TimeoutError):
except (BrokenPipeError, ConnectionResetError, ConnectionAbortedError, TimeoutError) as exc:
rec["error"] = type(exc).__name__
self.close_connection = True
except BaseException as exc:
rec["error"] = type(exc).__name__
raise
finally:
rec["t_done"] = round(time.time(), 4)
rec["m_done"] = round(time.perf_counter(), 6)
def _peer_closed(self):
"""Whether the browser has closed its end of this connection (a peek: nothing is read from it)."""
try:
readable, _w, _x = select.select([self.connection], [], [], 0)
return bool(readable) and self.connection.recv(1, socket.MSG_PEEK) == b""
except (BlockingIOError, InterruptedError):
return False
except (OSError, ValueError):
return True
def do_GET(self):
self._guard(self._get)
@@ -570,7 +621,18 @@ class Handler(BaseHTTPRequestHandler):
return self._send(200, "text/plain", b"ok", cache="no-store")
if p == "/hold":
until = int(q.get("until", ["0"])[0] or 0)
self.server.state.hold(q.get("id", [""])[0], until)
rec = self._rec
def watch():
if rec.get("m_peer_closed_seen") is None and self._peer_closed():
rec["t_peer_closed_seen"] = round(time.time(), 4)
rec["m_peer_closed_seen"] = round(time.perf_counter(), 6)
rec["t_hold_start"], rec["m_hold_start"] = round(time.time(), 4), round(time.perf_counter(), 6)
rec["hold_until_step"], rec["m_peer_closed_seen"] = until, None
rec["hold_ended_by"] = self.server.state.hold(q.get("id", [""])[0], until, watch=watch)
rec["t_hold_end"], rec["m_hold_end"], rec["step_at_hold_end"] = round(time.time(), 4), round(time.perf_counter(), 6), self.server.state.step
watch()
return self._send(200, "application/json", b'{"held":true}', cache="no-store")
if p == "/stream":
# headers and 10 of 20 body bytes at once; the rest after a short wait
@@ -635,6 +697,7 @@ def start(ports=(8321, 8322), bind="127.0.0.1", public_host="127.0.0.1", other_h
s.shutdown()
s.server_close()
stop.state = state # the server's own record (`state.records`), kept after stop()
global STATE
STATE = state
return state.origins[0], state.origins[1], stop
+92 -8
View File
@@ -30,32 +30,98 @@ def install_route(context):
class Tracer:
"""The requests the client has heard of and not yet heard the end of (kept for the report; never compared). With
`events` (the runner's --trace) it also keeps every request event the client reports, per step, for the request-type check."""
`events` (the runner's --trace) it also keeps every request event the client reports, per step, for the request-type check.
With `log` (a list; a test that saves evidence when it fails gives it) it keeps, apart from that, one entry per event the client
hears (request, response, requestfinished, requestfailed, and the page's own framenavigated / domcontentloaded / load), each with
the step the walk is in (`self.step`, set by the walk), its wall time `t` and `time.perf_counter()` as `m`; it only listens."""
def __init__(self, context, events=False):
def __init__(self, context, events=False, log=None):
self.open = {}
self.events = [] if events else None
self.t0 = time.monotonic()
self.log = log
self.step = 0
self.detail = {}
context.on("request", self._started)
context.on("requestfinished", lambda r: self._ended(r, "finished"))
context.on("requestfailed", lambda r: self._ended(r, "failed"))
if log is not None:
context.on("response", self._answered)
context.on("page", self._page_opened)
def _started(self, r):
self.open[r] = "%s %s" % (r.resource_type, r.url.split("/", 3)[-1][:70])
self._event(r, "request")
entry = self._logged(r, "request")
if entry is not None:
self.detail[r] = {k: entry[k] for k in ("step", "m", "type", "method", "url", "frame")}
def _ended(self, r, kind):
self.open.pop(r, None)
self.detail.pop(r, None)
self._event(r, kind)
more = {}
if kind == "failed" and self.log is not None:
try:
more["failure"] = str(r.failure)[:200]
except Exception:
more["failure"] = None
self._logged(r, "requestfinished" if kind == "finished" else "requestfailed", **more)
def _event(self, r, kind):
if self.events is not None:
self.events.append({"ev": kind, "type": r.resource_type, "method": r.method,
"url": "/" + r.url.split("/", 3)[-1][:90], "t": round(time.monotonic() - self.t0, 3)})
def _logged(self, r, kind, **more):
"""One entry of the log; a failure of the recording is never the client's (the walk goes on, the entry is missing)."""
if self.log is None:
return None
try:
try:
frame = r.frame.url[:160]
except Exception:
frame = None
entry = {"ev": kind, "step": self.step, "t": round(time.time(), 4), "m": round(time.perf_counter(), 6), "req": id(r),
"type": r.resource_type, "method": r.method, "url": r.url[:200], "frame": frame}
entry.update(more)
self.log.append(entry)
return entry
except Exception:
return None
def _answered(self, response):
try:
self._logged(response.request, "response", status=response.status)
except Exception:
pass
def _page_opened(self, page):
try:
for name in ("framenavigated", "domcontentloaded", "load"):
page.on(name, lambda arg, name=name: self._page_event(page, name, arg))
self._page_event(page, "page", None)
except Exception:
pass
def _page_event(self, page, name, arg):
try:
url = (arg.url if name == "framenavigated" else page.url)[:200]
except Exception:
url = None
try:
self.log.append({"ev": name, "step": self.step, "t": round(time.time(), 4), "m": round(time.perf_counter(), 6), "page": id(page), "url": url})
except Exception:
pass
def snapshot(self):
return sorted(self.open.values())[:12]
def in_flight(self):
"""What the client counts as in flight now, with how long (`age_s`) and from which step (`step`); `log` only."""
now = time.perf_counter()
return [dict(d, age_s=round(now - d["m"], 3)) for d in sorted(self.detail.values(), key=lambda d: d["m"])]
def take_events(self):
taken, self.events = self.events, []
return taken
@@ -326,13 +392,20 @@ def snapshot(j, pg, rec):
rec["url"] = j.norm(pg.url)
def run_round(j, tracer, round_no, idle_timeout_ms):
def run_round(j, tracer, round_no, idle_timeout_ms, step_log=None):
"""`step_log`, a list (default None: nothing kept), receives each step's record as soon as it is done, with the moments of the step
(`m_*`: time.perf_counter(), the scale of the client log and of the site's record) and what the client counted as in flight when
`networkidle` returned or gave up: for a test that saves evidence when it fails. Never compared."""
out = []
walk = journey_site.STATE.begin_walk() # the site tags what it sees with the walk, stock and ours both use steps 1..N
for n, (name, method) in enumerate(STEPS, 1):
j.extra = {}
tracer.step = n
m_before_set_step = time.perf_counter()
journey_site.STATE.set_step(n) # a held response of the site is released when the walk reaches its step
rec = {"round": round_no, "n": n, "name": name, "ok": False, "error": None}
if step_log is not None:
rec["m_step_start"], rec["t_step_start"] = round(m_before_set_step, 6), round(time.time(), 4)
t0 = time.monotonic()
pg, cleanup = j.page, None
try:
@@ -340,12 +413,19 @@ def run_round(j, tracer, round_no, idle_timeout_ms):
rec["ok"] = True
except Exception as exc:
rec["error"] = first_line(exc)
if step_log is not None:
rec["m_action_end"] = round(time.perf_counter(), 6)
try:
pg.wait_for_load_state("networkidle", timeout=idle_timeout_ms)
rec["idle"] = True
except Exception:
except Exception as exc:
rec["idle"] = False
if step_log is not None:
rec["idle_error"] = first_line(exc)
rec["open_at_idle_end"] = tracer.snapshot() # for the report, not compared
if step_log is not None:
rec["m_idle_end"], rec["t_idle_end"] = round(time.perf_counter(), 6), round(time.time(), 4)
rec["in_flight_at_idle_end"] = tracer.in_flight()
if tracer.events is not None:
rec["client_events"] = tracer.take_events()
snapshot(j, pg, rec)
@@ -359,6 +439,8 @@ def run_round(j, tracer, round_no, idle_timeout_ms):
rec["error"] = rec["error"] or ("cleanup: " + first_line(exc))
rec["seconds"] = round(time.monotonic() - t0, 2)
out.append(rec)
if step_log is not None:
step_log.append(rec)
if tracer.events is not None:
# read once, at the end: a request fired on pagehide reaches the server after its step's own work is done
time.sleep(0.5)
@@ -367,9 +449,11 @@ def run_round(j, tracer, round_no, idle_timeout_ms):
return out
def drive(browser, origin_a, origin_o, rounds=1, idle_timeout_ms=15000, trace=False):
def drive(browser, origin_a, origin_o, rounds=1, idle_timeout_ms=15000, trace=False, client_log=None, step_log=None):
"""`rounds` walks, each in a fresh context and a fresh page. Returns the step records. `trace`: keep, per step, the request
events the client reported and the hits the server saw (for the report; never compared)."""
events the client reported and the hits the server saw (for the report; never compared). `client_log` and `step_log`, two lists
(default None: nothing kept), are filled as the walk goes with what the client heard (`Tracer`) and with each step's record
(`run_round`): for a test that saves evidence when it fails."""
records = []
for r in range(1, rounds + 1):
context = browser.new_context()
@@ -377,9 +461,9 @@ def drive(browser, origin_a, origin_o, rounds=1, idle_timeout_ms=15000, trace=Fa
context.set_default_timeout(TIMEOUT_MS)
context.set_default_navigation_timeout(TIMEOUT_MS)
install_route(context)
tracer = Tracer(context, events=trace)
tracer = Tracer(context, events=trace, log=client_log)
page = context.new_page()
records += run_round(Journey(context, page, origin_a, origin_o), tracer, r, idle_timeout_ms)
records += run_round(Journey(context, page, origin_a, origin_o), tracer, r, idle_timeout_ms, step_log)
finally:
try:
context.close()
+26 -59
View File
@@ -52,6 +52,8 @@ import time
import types
import pytest
import _moving_page
from _moving_page import _goto, _landing, forget
from _evidence_on_failure import FailureEvidence
@@ -60,14 +62,6 @@ pytestmark = pytest.mark.e2e
ROUNDS = 5
def _landing(url: str) -> str:
"""Where the page of `url` sends itself: /landed with the query of its round, which no other round of the module has."""
return "/landed" + url[url.index("?"):]
#: The address each page (by `id`) was last sent to, or the page it went with instead (`_goto`).
_SENT: dict = {}
#: What the client heard, for the evidence a failing test leaves (`FailureEvidence`; it only listens and changes no wait or assertion).
_CLIENT_LOG: list = []
@@ -77,43 +71,7 @@ def _note(what: str, **fields) -> None:
_CLIENT_LOG.append({"t": round(time.time(), 4), "m": round(time.perf_counter(), 6), "what": what, **fields})
def _goto(page, url, *, the_page_before_may_move, our_page_may_stop_ours, **kwargs) -> str:
"""`page.goto`, and the address of the page the frame went with: `url` when `goto` answers.
- ``the_page_before_may_move``: the page sent before ours may still be moving (the rounds of the read test go on
while it does, module docstring). Its `location.replace` may win: `goto` says ours was interrupted by it, or
stopped (NS_BINDING_ABORTED), and the frame lands on the landing of THAT page, whose address is returned.
- ``our_page_may_stop_ours``: an engine before firefox-68, where `goto` may say NS_BINDING_ABORTED for our own
document, which had committed and then moved
(`test_networkidle_is_reached_only_on_the_page_that_replaced_a_document_still_arriving`); the frame then lands on
our landing.
Any other answer is red. The detector of a navigation that never answers is the timeout of the `goto` itself (each
caller passes one): a bound of the test stricter than it only judged the speed of the machine."""
from invisible_playwright.sync_api import Error
before = _SENT.get(id(page)) if the_page_before_may_move else None
_SENT[id(page)] = url
_note("goto", url=url, before=before)
try:
page.goto(url, **kwargs)
_note("goto-answered", url=url)
return url
except Error as e:
text = str(e)
_note("goto-raised", url=url, error=text[:300])
if "NS_BINDING_ABORTED" in text:
ends = tuple(_landing(u) for u in (before, url if our_page_may_stop_ours else None) if u)
assert ends, e
page.wait_for_url(lambda u: u.endswith(ends), timeout=30_000)
went = url if page.url.endswith(_landing(url)) else before
else:
assert before is not None, e
assert "is interrupted by another navigation to" in text, e
assert _landing(before) in text.split("another navigation to")[1], e
went = before
_SENT[id(page)] = went
return went
_moving_page.note = _note
def _replace_after_load(ms: int, cross_site: bool) -> bytes:
@@ -267,19 +225,30 @@ class _on_failure:
@pytest.fixture(scope="module")
def page(firefox_binary, evidence):
def _browser(firefox_binary, evidence):
from invisible_playwright import InvisiblePlaywright
with InvisiblePlaywright(seed=4321, binary_path=firefox_binary,
headless=True) as browser:
new = browser.new_page()
new.on("request", lambda r: _note("request", url=r.url, navigation=r.is_navigation_request()))
new.on("requestfinished", lambda r: _note("requestfinished", url=r.url))
new.on("requestfailed", lambda r: _note("requestfailed", url=r.url, failure=str(r.failure)))
new.on("framenavigated", lambda f: _note("framenavigated", url=f.url, main=f.parent_frame is None))
new.on("domcontentloaded", lambda p: _note("domcontentloaded", url=p.url))
new.on("load", lambda p: _note("load", url=p.url))
yield new
yield browser
@pytest.fixture
def page(_browser):
"""A page of its own for each test, closed at its end: a page that is still moving when its test ends (`goto` raised for the page before,
and ours went on) cannot reach the next test."""
page = _browser.new_page()
page.on("request", lambda r: _note("request", url=r.url, navigation=r.is_navigation_request()))
page.on("requestfinished", lambda r: _note("requestfinished", url=r.url))
page.on("requestfailed", lambda r: _note("requestfailed", url=r.url, failure=str(r.failure)))
page.on("framenavigated", lambda f: _note("framenavigated", url=f.url, main=f.parent_frame is None))
page.on("domcontentloaded", lambda p: _note("domcontentloaded", url=p.url))
page.on("load", lambda p: _note("load", url=p.url))
try:
yield page
finally:
forget(page)
page.close()
@pytest.mark.parametrize("path", ["/head", "/r0", "/r50", "/r300",
@@ -319,8 +288,6 @@ def _a_read_right_after_goto_answers(page, site, path, engine_reaches):
assert page.evaluate("1 + 1") == 2
except Error as e:
assert "Execution context was destroyed" in str(e), e
# The next test starts on a page that stays: the last page this frame went with has landed.
page.wait_for_url(lambda u, end=_landing(_SENT[id(page)]): u.endswith(end), timeout=30_000)
@pytest.mark.parametrize("path", ["/r0", "/r50", "/x0", "/x50"])
@@ -330,12 +297,12 @@ def test_networkidle_is_reached_on_the_page_that_replaced_ours(page, site, path,
Playwright), or on the page that replaced it. Either way the page then lands, and `networkidle` is reached there.
A `goto` that never answers because the new frame forgot the navigation ([B228]) is still red; the answer that
must never come on the first page is the strict case below. Each round starts on a page that stays (the round
before waited for its landing, and so did the test before)."""
before waited for its landing; the page is the test's own)."""
older = not engine_reaches("firefox-68")
for i in range(ROUNDS):
url = "%s/i%s?n=%s-%d" % (site, path[1:], path[1:], i)
assert _goto(page, url, the_page_before_may_move=False, our_page_may_stop_ours=older,
wait_until="networkidle", timeout=30_000) == url
wait_until="networkidle", timeout=30_000) == {url}
assert page.url.split("?")[0].endswith(("/i" + path[1:], "/landed")), page.url
page.wait_for_url(lambda u, end=_landing(url): u.endswith(end), timeout=30_000)
page.wait_for_load_state("networkidle", timeout=30_000)
@@ -363,7 +330,7 @@ def test_networkidle_is_reached_only_on_the_page_that_replaced_a_document_still_
for i in range(ROUNDS):
url = "%s%s?n=%s-%d" % (site, path, path[1:], i)
assert _goto(page, url, the_page_before_may_move=False, our_page_may_stop_ours=older,
wait_until="networkidle", timeout=30_000) == url
wait_until="networkidle", timeout=30_000) == {url}
assert page.url.endswith(_landing(url)), page.url
@@ -11,12 +11,15 @@ was applied after the page was announced), and the one that answers after 25 s w
"""
from __future__ import annotations
import json
import threading
import time
from http.server import BaseHTTPRequestHandler
from types import SimpleNamespace
import pytest
from _evidence_on_failure import WIRE_LIMIT, FailureEvidence
from _servers import LocalServer
pytestmark = pytest.mark.e2e
@@ -27,15 +30,30 @@ class _Handler(BaseHTTPRequestHandler):
pass
def do_GET(self):
# The destination's own record, for a test that saves evidence when it fails (`server.records`): it only listens.
rec = {"ev": "request", "t_arrive": round(time.time(), 4), "m_arrive": round(time.perf_counter(), 6), "peer": self.client_address[1],
"path": self.path, "status": None, "m_slept": None, "m_answer": None, "m_done": None, "error": None}
records = getattr(self.server, "records", None)
if records is not None:
with self.server.records_lock:
records.append(rec)
try:
self._get(rec)
finally:
rec["m_done"] = round(time.perf_counter(), 6)
def _get(self, rec):
path, _, query = self.path.partition("?")
if path == "/nocontent":
self.send_response(204)
self.send_header("Content-Length", "0")
self.end_headers()
rec["status"] = 204
return
if path == "/slow":
ms = int(query.split("ms=")[1].split("&")[0]) if "ms=" in query else 0
time.sleep(ms / 1000.0)
rec["m_slept"] = round(time.perf_counter(), 6)
body = b"<!doctype html><html><head><title>slow</title></head><body>slow</body></html>"
else:
body = (b"<!doctype html><html><head><title>opener</title></head><body>"
@@ -52,21 +70,29 @@ class _Handler(BaseHTTPRequestHandler):
self.send_header("Cache-Control", "no-store")
self.end_headers()
self.wfile.write(body)
except OSError: # the browser left before a slow answer
pass
rec["status"] = 200
rec["m_answer"] = round(time.perf_counter(), 6)
except OSError as exc: # the browser left before a slow answer
rec["error"] = type(exc).__name__
@pytest.fixture
def site():
def site_server():
srv = LocalServer(("127.0.0.1", 0), _Handler)
srv.records, srv.records_lock = [], threading.Lock()
threading.Thread(target=srv.serve_forever, daemon=True).start()
try:
yield "http://127.0.0.1:%d/" % srv.server_address[1]
yield srv
finally:
srv.shutdown()
srv.server_close()
@pytest.fixture
def site(site_server):
return "http://127.0.0.1:%d/" % site_server.server_address[1]
def _stock_client(module):
import importlib
@@ -132,14 +158,204 @@ def test_a_slow_popup_is_reported_with_the_address_of_its_destination(firefox_bi
_drive(mode, firefox_binary, body)
class _ServerSideLog:
"""What OUR server says to the client and how it decides to, recorded from the test, with nothing changed in `src`: the methods are
wrapped at their class and put back at the end. `messages`: every protocol message the server hands to the client (a served browser:
`RemoteClient.post`, the text sent on the WebSocket; in-process: `InProcessTransport.emit_message`, the dict). `steps`: the adoption of
each engine target (`_Adoption`: attached, every note it makes, with the engine's own event names) and the two calls that decide when
the client hears of a page (`PageDispatcher.wait_until_ready`, `PageDispatcher.announce`). Both carry `t` and `m` like the engine's wire."""
LIMIT = 20000
def __init__(self):
self.messages, self.steps, self.problems = [], [], []
self._lock = threading.Lock()
self._patch = pytest.MonkeyPatch()
def _add(self, where, record):
try:
record["t"], record["m"] = round(time.time(), 4), round(time.perf_counter(), 6)
with self._lock:
if len(where) < self.LIMIT:
where.append(record)
except Exception:
pass
def _sent(self, via, message):
try:
text = message if isinstance(message, str) else json.dumps(message, default=str)
parsed = json.loads(text) if isinstance(message, str) else message
params = parsed.get("params") or {}
self._add(self.messages, {"via": via, "len": len(text), "cut": len(text) > WIRE_LIMIT, "guid": parsed.get("guid"),
"method": parsed.get("method"), "id": parsed.get("id"),
"create_type": params.get("type") if parsed.get("method") == "__create__" else None,
"msg": text[:WIRE_LIMIT]})
except Exception:
pass
def _step(self, event, /, **more):
# `event` is positional-only: a wrapped call records a field called `what` (the adoption's note) and must not collide with it.
record = {"ev": event}
record.update(more)
self._add(self.steps, record)
def _record(self, make):
"""Run `make`, which records something about a call the server makes; a failure of the recording is noted in the evidence and
never reaches the server."""
try:
make()
except BaseException as exc:
with self._lock:
if len(self.problems) < 20:
self.problems.append("recording failed: %r" % (exc,))
def install(self):
log = self
def wrap(owner, name, make):
try:
self._patch.setattr(owner, name, make(getattr(owner, name)))
except Exception as exc: # the rest is still recorded; the problem is saved with it
self.problems.append("%s.%s not wrapped: %r" % (getattr(owner, "__name__", owner), name, exc))
try:
from invisible_playwright._juggler import remote, server, transport
except Exception as exc:
self.problems.append("the server modules could not be imported: %r" % (exc,))
return
# Every wrapper takes (*args, **kwargs) and passes them on unchanged: whatever the real code passes, positional or keyword, reaches
# the wrapped method as it was. What a wrapper reads from the call is read inside `_record`, which never raises.
def post(original):
def wrapper(*args, **kwargs):
log._record(lambda: log._sent("RemoteClient.post", args[1] if len(args) > 1 else kwargs.get("text")))
return original(*args, **kwargs)
return wrapper
def emit_message(original):
def wrapper(*args, **kwargs):
log._record(lambda: log._sent("InProcessTransport.emit_message", args[1] if len(args) > 1 else kwargs.get("message")))
return original(*args, **kwargs)
return wrapper
def adoption_init(original):
def wrapper(*args, **kwargs):
result = original(*args, **kwargs)
adoption = args[0]
log._record(lambda: log._step("adoption_attached", target=adoption.target_id, opener=adoption.opener is not None,
context=adoption.context_id))
return result
return wrapper
def adoption_note(original):
def wrapper(*args, **kwargs):
adoption = args[0]
log._record(lambda: log._step("adoption_note", target=adoption.target_id, state=adoption.state,
what=args[1] if len(args) > 1 else kwargs.get("what")))
return original(*args, **kwargs)
return wrapper
def wait_until_ready(original):
def wrapper(*args, **kwargs):
page = args[0]
log._record(lambda: log._step("wait_until_ready_begin", page=page.guid))
try:
result = original(*args, **kwargs)
except BaseException as exc:
log._record(lambda: log._step("wait_until_ready_failed", page=page.guid, error=repr(exc)[:300]))
raise
log._record(lambda: log._step("wait_until_ready_end", page=page.guid))
return result
return wrapper
def announce(original):
def wrapper(*args, **kwargs):
page = args[0]
log._record(lambda: log._step("announce_begin", page=page.guid))
try:
return original(*args, **kwargs)
finally:
log._record(lambda: log._step("announce_end", page=page.guid))
return wrapper
wrap(remote.RemoteClient, "post", post)
wrap(transport.InProcessTransport, "emit_message", emit_message)
wrap(server._Adoption, "__init__", adoption_init)
wrap(server._Adoption, "note", adoption_note)
wrap(server.PageDispatcher, "wait_until_ready", wait_until_ready)
wrap(server.PageDispatcher, "announce", announce)
def uninstall(self):
self._patch.undo()
#: What each extra file of the evidence of the test below holds, field by field (written into its meta.json).
_EXTRA_FILES = {
"server-to-client.jsonl": "every protocol message OUR server handed to the client, in order: t (time.time()), m (time.perf_counter(), the scale "
"of every other file), via (RemoteClient.post for a served browser, InProcessTransport.emit_message in-process), "
"guid and method (the event or the __create__ it carries; id for a reply), create_type (the type a __create__ makes: "
"Page, Frame, ...), len, cut (msg was cut at %d characters), msg (the message as JSON text)" % WIRE_LIMIT,
"server-adoption-steps.jsonl": "what the server did with each engine target and when it told the client: t, m, ev = adoption_attached "
"(target, opener, context), adoption_note (target, state, what = the engine's event names Page.frameAttached/"
"navigationCommitted/ready/... without the 'Page.', and the adoption's own steps building/waiting/announced), "
"wait_until_ready_begin / _end / _failed (page = the Page guid), announce_begin / announce_end (page = the Page "
"guid; the `page` event is sent between them), and `problems` lines if a wrapper could not be installed",
"client-events.jsonl": "what the stock client heard, in order: t, m, ev = click, page_event (url = popup.url read in the handler of the context's "
"page event), then for that popup framenavigated (url, main = the main frame), domcontentloaded, load, close (url), and "
"expect_popup_returned (url, took_s, the time since the click)",
}
def _save_extra(folder, files, problems):
"""Add the files of the server's side to the evidence folder `FailureEvidence` saved, and say in its meta.json what each holds."""
for name, records in files.items():
with open(folder / name, "w", encoding="utf-8") as out:
for record in records:
out.write(json.dumps(record, default=str) + "\n")
meta_path = folder / "meta.json"
meta = json.loads(meta_path.read_text(encoding="utf-8"))
meta["files"] = sorted(set(meta.get("files", [])) | set(files))
meta["extra_files"] = _EXTRA_FILES
meta["extra_problems"] = problems
meta["note"] = ("client-request-log.jsonl is empty here (the destination has one request; the client's own events are client-events.jsonl); "
"fakeweb-server-record.jsonl is the destination's record: t_arrive/m_arrive when the request came, m_slept when its wait "
"ended, m_answer when the answer was written, status, error")
meta_path.write_text(json.dumps(meta, indent=1), encoding="utf-8")
@pytest.mark.parametrize("mode", MODES)
def test_a_popup_whose_destination_answers_after_25_seconds_is_reported_then(firefox_binary, site, mode):
def test_a_popup_whose_destination_answers_after_25_seconds_is_reported_then(firefox_binary, site, site_server, mode):
"""When it fails it saves, under `invpw-evidence/popup-25s-<mode>/`, the order in which the engine and then our server told the popup's
story: the engine's Juggler wire and trace (`juggler-wire.jsonl`, `juggler-engine-trace/`), what our server sent to the client
(`server-to-client.jsonl`), what it did with the target (`server-adoption-steps.jsonl`), what the client heard (`client-events.jsonl`),
the destination's record (`fakeweb-server-record.jsonl`) and a summary (`cells.json`)."""
client_events = []
summary = {"mode": mode}
def mark(ev, **more):
client_events.append(dict({"ev": ev, "t": round(time.time(), 4), "m": round(time.perf_counter(), 6)}, **more))
def watch_popups(ctx):
def on_page(popup):
mark("page_event", url=popup.url)
summary["url_at_page_event"] = popup.url
popup.on("framenavigated", lambda frame: mark("framenavigated", url=frame.url, main=frame.parent_frame is None))
popup.on("domcontentloaded", lambda p: mark("domcontentloaded", url=p.url))
popup.on("load", lambda p: mark("load", url=p.url))
popup.on("close", lambda p: mark("close", url=p.url))
ctx.on("page", on_page)
def body(ctx, page):
page.goto(site, wait_until="load", timeout=30000)
watch_popups(ctx)
t0 = time.monotonic()
mark("click")
with page.expect_popup(timeout=45000) as info:
page.click("#open25000")
took = time.monotonic() - t0
mark("expect_popup_returned", url=info.value.url, took_s=round(took, 3))
summary["took_s"] = round(took, 3)
# The lower bound is the server's: it answers after 25 s, so a popup announced before 24 s was announced
# before it was ready. There is no upper bound of ours: the limit above is expect_popup's 45 s (a popup
# dropped at 20 s, the defect this test is red on, ends in its timeout).
@@ -147,7 +363,25 @@ def test_a_popup_whose_destination_answers_after_25_seconds_is_reported_then(fir
assert info.value.url == site + "slow?ms=25000"
info.value.close()
_drive(mode, firefox_binary, body)
evidence = FailureEvidence("popup-25s-" + mode)
evidence.watch_server(SimpleNamespace(state=SimpleNamespace(lock=site_server.records_lock, records=site_server.records)))
evidence.note_cells(summary)
side = _ServerSideLog()
try:
with evidence:
side.install()
evidence.arm()
_drive(mode, firefox_binary, body)
finally:
side.uninstall()
if evidence.saved_to is not None:
try:
_save_extra(evidence.saved_to, {"server-to-client.jsonl": side.messages,
"server-adoption-steps.jsonl": side.steps + [{"ev": "problem", "what": w} for w in side.problems],
"client-events.jsonl": client_events}, side.problems)
except Exception as problem: # the evidence never hides the failure it is about
import sys
sys.stderr.write("popup evidence: the server's side could not be saved: %r\n" % (problem,))
@pytest.mark.parametrize("mode", MODES)
@@ -0,0 +1,88 @@
"""A read whose probe ran out of time ran out of the CALLER's time.
`page.inner_text("#never", timeout=300)` must fail with Playwright's
"Timeout 300ms exceeded ...". The read gives its probe exactly what is left of
the caller's deadline, so the probe's `ReplyTimeout` is the deadline's expiry.
It used to be turned into the read's timeout only when a SECOND reading of the
clock said the deadline had passed; on Windows a threading wait can return
before the monotonic clock (steps of about 15 ms) says the budget is spent, and
the core's "Runtime.callFunction: no response in 0s ..." reached the caller
(whole-e2e runs 44419689591 and 44184494839).
"""
import threading
from types import SimpleNamespace
from unittest.mock import Mock
import pytest
from invisible_core.juggler import connection as juggler
from invisible_core.juggler import deadline as deadline_module
from invisible_core.juggler.connection import EventListeners
from invisible_core.juggler.lifecycle import Lifecycle
from invisible_playwright._juggler.dispatcher import Dispatcher
from invisible_playwright._juggler.server import (
FrameDispatcher,
JugglerServer,
PageDispatcher,
)
pytestmark = pytest.mark.unit
CORE_MESSAGE = ("Runtime.callFunction: no response in 0s. If this is the "
"FIRST command, look at the readiness signal before the pipe.")
@pytest.fixture
def frame():
server = JugglerServer()
server.attach(SimpleNamespace(emit_message=lambda message: None))
context = Dispatcher(server, None)
context.options = {}
page = object.__new__(PageDispatcher)
page.context = context
page.lifecycle = Lifecycle(EventListeners(), "session")
page.injected = Mock()
page.actions = Mock()
page._frames = {}
page._told_attached = set()
page._frames_lock = threading.RLock()
page._announce_lock = threading.RLock()
page._announced = True
page._said_before_announcement = []
page._navigation_requests = {}
page._announced_closed = False
Dispatcher.__init__(page, server, context)
page.frame = FrameDispatcher(server, page, "main")
page.lifecycle._on_event("Page.frameAttached",
{"frameId": "main", "parentFrameId": None})
page.frame.enter_frames = Mock(return_value=("main", "#never"))
return page.frame
def test_a_probe_that_ran_out_is_the_read_timing_out_whatever_the_clock_says(
frame, monkeypatch):
"""The losing interleaving, on purpose: the probe's wait ended, and the
clock the deadline reads has not moved at all, so `deadline.passed()` is
False."""
monkeypatch.setattr(deadline_module, "time",
SimpleNamespace(monotonic=lambda: 100.0))
frame.injected.read_match.side_effect = juggler.ReplyTimeout(CORE_MESSAGE)
with pytest.raises(TimeoutError) as caught:
frame.op_inner_text({"selector": "#never", "timeout": 300})
assert not isinstance(caught.value, juggler.ReplyTimeout)
assert str(caught.value) == (
"Timeout 300ms exceeded waiting for '#never' to match an element")
assert frame.injected.read_match.call_count == 1
def test_a_read_with_no_limit_gave_its_probe_no_bound_and_keeps_what_it_gets(
frame):
"""`timeout=0` is no limit: the probe was given no bound, so a
`ReplyTimeout` is not the caller's deadline and travels as it is."""
frame.injected.read_match.side_effect = juggler.ReplyTimeout(CORE_MESSAGE)
with pytest.raises(juggler.ReplyTimeout, match="no response in 0s"):
frame.op_inner_text({"selector": "#never", "timeout": 0})
assert frame.injected.read_match.call_args.kwargs["timeout"] is None
+104 -31
View File
@@ -25,11 +25,17 @@ retail and died with no usable interface. Hermetic: a local TCP-only SOCKS5 prox
"""
from __future__ import annotations
import json
import os
import shutil
import statistics
import time
import pytest
from _e2e_verdicts import MDNS_RETRY_MS, opened_at_the_retry_problem
from _evidence_with_files import FailureEvidenceWithFiles
from _mdns_listener import MdnsListener
from test_webrtc_realness import _e2e_binary, _launch, candidates, decode_priority, host_candidates, is_mdns # noqa: F401
pytestmark = [pytest.mark.e2e, pytest.mark.usefixtures("the_udp_line")]
@@ -64,24 +70,45 @@ _GATHER_JS = r"""async () => {
}"""
# Two connections on one page, connected to each other in script (the loopback test many demos use).
# ``events`` is the page's own timeline for the failure evidence (``at``: ``performance.now()`` since the start of the script, ``origin``:
# ``performance.timeOrigin``, so the wall clock of an event is ``origin + at``): every ``icecandidate`` of both connections with the candidate string,
# every state change, when each ``addIceCandidate`` was called and when it settled. It only listens: nothing waits on it.
_LOOPBACK_JS = r"""async () => {
const t0 = performance.now();
const events = [];
const at = (what, extra) => { events.push(Object.assign({at: Math.round((performance.now() - t0) * 10) / 10, what}, extra || {})); };
const pc1 = new RTCPeerConnection(), pc2 = new RTCPeerConnection();
pc1.onicecandidate = e => { if (e.candidate) pc2.addIceCandidate(e.candidate).catch(() => {}); };
pc2.onicecandidate = e => { if (e.candidate) pc1.addIceCandidate(e.candidate).catch(() => {}); };
for (const [name, pc] of [['pc1', pc1], ['pc2', pc2]]) {
pc.addEventListener('icecandidate', e => at('icecandidate', {pc: name, candidate: e.candidate ? e.candidate.candidate : null}));
pc.addEventListener('iceconnectionstatechange', () => at('iceconnectionstatechange', {pc: name, state: pc.iceConnectionState}));
pc.addEventListener('connectionstatechange', () => at('connectionstatechange', {pc: name, state: pc.connectionState}));
pc.addEventListener('icegatheringstatechange', () => at('icegatheringstatechange', {pc: name, state: pc.iceGatheringState}));
pc.addEventListener('signalingstatechange', () => at('signalingstatechange', {pc: name, state: pc.signalingState}));
}
const add = (target, targetName, candidate) => {
at('addIceCandidate called', {to: targetName, candidate: candidate.candidate});
return target.addIceCandidate(candidate).then(
() => at('addIceCandidate resolved', {to: targetName, candidate: candidate.candidate}),
err => at('addIceCandidate rejected', {to: targetName, candidate: candidate.candidate, error: String(err)}));
};
pc1.onicecandidate = e => { if (e.candidate) add(pc2, 'pc2', e.candidate); };
pc2.onicecandidate = e => { if (e.candidate) add(pc1, 'pc1', e.candidate); };
const gathered = {pc1: [], pc2: []};
const keep = (name, e) => { if (e.candidate && e.candidate.candidate) gathered[name].push(e.candidate.candidate); };
pc1.addEventListener('icecandidate', e => keep('pc1', e));
pc2.addEventListener('icecandidate', e => keep('pc2', e));
const dc = pc1.createDataChannel('x');
let opened = null, echoed = false;
dc.onopen = () => { opened = Math.round(performance.now() - t0); dc.send('ping'); };
pc2.ondatachannel = ev => { ev.channel.onmessage = m => ev.channel.send('pong:' + m.data); };
dc.onmessage = m => { echoed = (m.data === 'pong:ping'); };
dc.onopen = () => { opened = Math.round(performance.now() - t0); at('datachannel open'); dc.send('ping'); };
pc2.ondatachannel = ev => { at('datachannel announced on pc2'); ev.channel.onmessage = m => ev.channel.send('pong:' + m.data); };
dc.onmessage = m => { echoed = (m.data === 'pong:ping'); at('datachannel echo', {echoed}); };
await pc1.setLocalDescription(await pc1.createOffer());
at('pc1 local description set');
await pc2.setRemoteDescription(pc1.localDescription);
await pc2.setLocalDescription(await pc2.createAnswer());
at('pc2 local description set');
await pc1.setRemoteDescription(pc2.localDescription);
at('pc1 remote description set');
// Until the channel has opened and echoed, for 30 s (the deadline of the wait). The loop also keeps the longest time it did not run: a page that
// was stopped by the machine says so, and the time the connection took is not judged then (`_e2e_verdicts.opened_at_the_retry_problem`).
const deadline = performance.now() + 30000;
@@ -92,13 +119,20 @@ _LOOPBACK_JS = r"""async () => {
stalled = Math.max(stalled, now - last);
last = now;
}
at('wait over', {opened, echoed});
// The road the connection took, read from the browser's own statistics: the nominated pair, and the protocol of each end.
let pair = null;
const pairs = [];
try {
const stats = await pc1.getStats();
const byId = {};
stats.forEach(r => { byId[r.id] = r; });
stats.forEach(r => {
if (r.type === 'candidate-pair') {
const l = byId[r.localCandidateId] || {}, rm = byId[r.remoteCandidateId] || {};
pairs.push({state: r.state, nominated: r.nominated, local: [l.protocol, l.candidateType, l.address, l.port],
remote: [rm.protocol, rm.candidateType, rm.address, rm.port], requestsSent: r.requestsSent, responsesReceived: r.responsesReceived});
}
if (r.type === 'candidate-pair' && r.state === 'succeeded' && (r.nominated || !pair)) {
const l = byId[r.localCandidateId] || {}, rm = byId[r.remoteCandidateId] || {};
pair = {local: l.protocol, remote: rm.protocol, localType: l.candidateType, remoteType: rm.candidateType,
@@ -107,7 +141,7 @@ _LOOPBACK_JS = r"""async () => {
});
} catch (e) {}
pc1.close(); pc2.close();
return {opened, echoed, pair, gathered, stalled: Math.round(stalled)};
return {opened, echoed, pair, gathered, stalled: Math.round(stalled), events, pairs, origin: performance.timeOrigin, started_at: Math.round(t0 * 10) / 10};
}"""
# Retail 159 on Windows, 12 cold launches (``captures/mdns-loopback/retail-159-win-12``): 37-52 ms in ten of twelve, two
@@ -117,14 +151,28 @@ _LOOPBACK_JS = r"""async () => {
# the machine. What the test judges is the ROAD, which the machine cannot change (see the test), and a ceiling under the
# first retry of the mDNS responder (3 s), which no machine is slow enough to reach by being slow.
RETAIL_MEDIAN_WINDOW_MS = (30, 55) # printed beside the measure, for the reader
# What the engine logs for the failure evidence of the loopback test, by its own names (MOZ_LOG; the file is MOZ_LOG_FILE, one per process and
# per launch). ``mdns_service::*`` is the Rust crate of the mDNS responder (dom/media/webrtc/transport/mdns_service/src/lib.rs, crate ``mdns_service``,
# which logs with the ``log`` macros at the crate root, so the module path is ``mdns_service``): a Rust module reaches MOZ_LOG only by a name that
# contains ``::`` (xpcom/base/Logging.cpp, ``LogModule::SetLevel`` calls ``set_rust_log_level`` only then). ``mtransport`` is the module of nICEr's own
# log and of the transport layers (``MOZ_MTLOG_MODULE("mtransport")``, dom/media/webrtc/transport/nricectx.cpp:100, nriceresolver.cpp:67 ...), ML_DEBUG is level 5.
# The engine's ``log`` crate is built with ``release_max_level_info`` (toolkit/library/rust/shared/Cargo.toml:41): a release engine keeps the info, warn and
# error lines of the responder (the ``warn!`` of a failed send, a bad packet, an interface it could not use), not its ``trace!`` lines (questions, answers,
# registrations). ``timestamp`` writes the wall clock (UTC) on each line, ``sync`` writes each line at once, ``rotate:30`` keeps at most 30 MB per process.
MDNS_MOZ_LOG = "timestamp,sync,rotate:30,mdns_service::*:5,mtransport:5"
def _session(declaration, socks, page_url, monkeypatch, seed, script):
"""One proxied launch with the declaration in the environment; runs ``script`` on the page and returns the result."""
def _session(declaration, socks, page_url, monkeypatch, seed, script, engine_log=None):
"""One proxied launch with the declaration in the environment; runs ``script`` on the page and returns the result.
``engine_log``: a folder where the engine writes its own log of this launch (failure evidence, ``MDNS_MOZ_LOG``)."""
binary = _e2e_binary()
if not binary:
pytest.skip("no patched binary (set STEALTHFOX_E2E_BINARY)")
monkeypatch.setenv(NETWORK_ENV, declaration)
if engine_log is not None:
os.makedirs(engine_log, exist_ok=True)
monkeypatch.setenv("MOZ_LOG", MDNS_MOZ_LOG)
monkeypatch.setenv("MOZ_LOG_FILE", os.path.join(engine_log, "engine-%PID.log"))
prefs = {"network.proxy.allow_hijacking_localhost": True, "network.proxy.no_proxies_on": ""}
proxy = {"server": "socks5://127.0.0.1:%d" % socks.port}
with _launch(binary_path=binary, proxy=proxy, extra_prefs=prefs, seed=seed) as browser:
@@ -231,29 +279,54 @@ def test_two_connections_on_one_page_connect_in_the_time_of_retail(local_https_p
The time itself is printed with the retail window beside it: a fast machine shows 30-55 ms, a runner shows more, and
neither is a verdict (an absolute time failed on both GitHub runners with a healthy engine)."""
runs = []
for n in range(5):
res = _session(V4_ONLY, socks5_tcp_only, local_https_page, monkeypatch, 100 + n,
lambda page: page.evaluate(_LOOPBACK_JS))
assert res["echoed"] and res["opened"] is not None, "run %d: the data channel did not open: %r" % (n, res)
runs.append(res)
for side in ("pc1", "pc2"):
hosts = [c for c in res["gathered"][side] if " typ host" in c]
udp = [c for c in hosts if " UDP " in c.upper() or " udp " in c]
assert udp, "run %d: %s gathered no UDP host candidate (the road without UDP): %r" % (n, side, res["gathered"][side])
assert any(c.split()[4].endswith(".local") for c in udp), (
"run %d: %s has no mDNS name among its UDP host candidates: %r" % (n, side, udp))
pair = res["pair"]
assert pair, "run %d: the browser reports no nominated pair: %r" % (n, res)
assert pair["local"] == "udp" and pair["remote"] == "udp", (
"run %d: the connection did not take UDP at both ends (the road through TCP): %r" % (n, pair))
# DIRECT and local: each end is a host candidate, or a peer-reflexive one. The remote end is prflx when the other connection's mDNS
# name was not resolved yet and its connectivity check arrived first: the address the check came from is learned as prflx, and
# that is the same road. What it must never be is a relay or a server-reflexive candidate (a road through the proxy or the
# network), and never TCP (checked above).
assert pair["localType"] in ("host", "prflx") and pair["remoteType"] in ("host", "prflx"), (
"run %d: the pair is not direct and local (a relay or a server-reflexive road): %r" % (n, pair))
problem = opened_at_the_retry_problem(res["opened"], res["stalled"], MDNS_RETRY_MS)
assert problem is None, "run %d: %s" % (n, problem)
launches = []
# Failure evidence (tests/_evidence_with_files.py): per launch, the engine's own log (the mDNS responder and mtransport), kept only for the launch that
# fails; and ``launches.json``, the timings and the page's timeline of EVERY launch up to it (the loop stops at the first red).
with FailureEvidenceWithFiles("declared-host-two-connections-open-in-time") as evidence:
try:
for n in range(5):
log_dir = evidence.files / ("engine-log-run-%d" % n)
launch = {"run": n, "seed": 100 + n, "moz_log": MDNS_MOZ_LOG, "started_m": round(time.perf_counter(), 6),
"started_t": round(time.time(), 4)}
launches.append(launch)
# The lab's own ear on the mDNS group (tests/_mdns_listener.py), started BEFORE the browser so that the engine's socket is the later one:
# it only listens, and what it heard of this launch is ``mdns-wire-run-N.jsonl`` (``m`` is the scale of ``started_m`` above).
listener = MdnsListener().start()
try:
res = _session(V4_ONLY, socks5_tcp_only, local_https_page, monkeypatch, 100 + n,
lambda page: page.evaluate(_LOOPBACK_JS), engine_log=str(log_dir))
finally:
launch.update(returned_m=round(time.perf_counter(), 6), returned_t=round(time.time(), 4))
listener.stop()
listener.write(evidence.files / ("mdns-wire-run-%d.jsonl" % n))
launch["mdns_wire"] = listener.summary()
page_timeline = {key: res.pop(key, None) for key in ("events", "pairs", "origin", "started_at")}
launch.update(opened=res["opened"], echoed=res["echoed"], stalled=res["stalled"], pair=res["pair"], gathered=res["gathered"],
page=page_timeline)
assert res["echoed"] and res["opened"] is not None, "run %d: the data channel did not open: %r" % (n, res)
runs.append(res)
for side in ("pc1", "pc2"):
hosts = [c for c in res["gathered"][side] if " typ host" in c]
udp = [c for c in hosts if " UDP " in c.upper() or " udp " in c]
assert udp, "run %d: %s gathered no UDP host candidate (the road without UDP): %r" % (n, side, res["gathered"][side])
assert any(c.split()[4].endswith(".local") for c in udp), (
"run %d: %s has no mDNS name among its UDP host candidates: %r" % (n, side, udp))
pair = res["pair"]
assert pair, "run %d: the browser reports no nominated pair: %r" % (n, res)
assert pair["local"] == "udp" and pair["remote"] == "udp", (
"run %d: the connection did not take UDP at both ends (the road through TCP): %r" % (n, pair))
# DIRECT and local: each end is a host candidate, or a peer-reflexive one. The remote end is prflx when the other connection's mDNS
# name was not resolved yet and its connectivity check arrived first: the address the check came from is learned as prflx, and
# that is the same road. What it must never be is a relay or a server-reflexive candidate (a road through the proxy or the
# network), and never TCP (checked above).
assert pair["localType"] in ("host", "prflx") and pair["remoteType"] in ("host", "prflx"), (
"run %d: the pair is not direct and local (a relay or a server-reflexive road): %r" % (n, pair))
problem = opened_at_the_retry_problem(res["opened"], res["stalled"], MDNS_RETRY_MS)
assert problem is None, "run %d: %s" % (n, problem)
# This launch is right: its engine log is no evidence of anything.
shutil.rmtree(log_dir, ignore_errors=True)
finally:
(evidence.files / "launches.json").write_text(json.dumps(launches, indent=1, default=str), encoding="utf-8")
times = sorted(r["opened"] for r in runs)
low, high = RETAIL_MEDIAN_WINDOW_MS
with capsys.disabled():
+21 -10
View File
@@ -15,6 +15,7 @@ import pathlib
import pytest
from _evidence_on_failure import FailureEvidence
from fakeweb import journey_site, profile_p4
pytestmark = pytest.mark.e2e
@@ -32,14 +33,24 @@ def _stock_client():
def test_the_journey_succeeds_on_every_step_and_idles_where_stock_does(firefox_binary):
"""When it fails it saves, under `invpw-evidence/fakeweb-journey-idles-where-stock-does/`, what answers whether the browser sent the
request a step holds, when the site received and answered it, and what the client heard of it before `networkidle` returned:
`fakeweb-server-record.jsonl` (the site's own record), `client-request-log.jsonl` (every request event the client heard, with the step),
`cells.json` (each step's record with `in_flight_at_idle_end`), `juggler-wire.jsonl` and `juggler-engine-trace/`."""
not_idle = json.loads((HERE / "pages.json").read_text(encoding="utf-8"))["journey_p4"]["not_idle_steps"]
origin_a, origin_o, stop = journey_site.start((0, 0))
try:
steps = profile_p4.run_on_candidate(_stock_client(), firefox_binary, origin_a, origin_o, 1)
finally:
stop()
failed = ["step %d (%s): %s" % (s["n"], s["name"], s["error"]) for s in steps if not s["ok"]]
assert not failed, "steps that did not succeed:\n " + "\n ".join(failed)
wrong = ["step %d (%s): %s" % (s["n"], s["name"], "idle, stock holds a request here" if s["idle"] else
"not idle, open: %s" % s["open_at_idle_end"]) for s in steps if s["idle"] != (s["n"] not in not_idle)]
assert not wrong, "networkidle differs from the declared outcome of stock Firefox:\n " + "\n ".join(wrong)
with FailureEvidence("fakeweb-journey-idles-where-stock-does") as evidence:
origin_a, origin_o, stop = journey_site.start((0, 0))
evidence.watch_server(stop)
step_log = []
evidence.note_cells(step_log)
try:
evidence.arm()
steps = profile_p4.run_on_candidate(_stock_client(), firefox_binary, origin_a, origin_o, 1,
client_log=evidence.client_log, step_log=step_log)
finally:
stop()
failed = ["step %d (%s): %s" % (s["n"], s["name"], s["error"]) for s in steps if not s["ok"]]
assert not failed, "steps that did not succeed:\n " + "\n ".join(failed)
wrong = ["step %d (%s): %s" % (s["n"], s["name"], "idle, stock holds a request here" if s["idle"] else
"not idle, open: %s" % s["open_at_idle_end"]) for s in steps if s["idle"] != (s["n"] not in not_idle)]
assert not wrong, "networkidle differs from the declared outcome of stock Firefox:\n " + "\n ".join(wrong)
@@ -191,50 +191,54 @@ def test_a_goto_stopped_on_its_way_raises_or_lands_and_never_lies(firefox_binary
cross = "http://localhost:%d" % server
answer, end = EXPECT[kind]
with InvisiblePlaywright(seed=42, binary_path=firefox_binary, headless=True) as browser:
page = browser.new_page()
for site, target_base in (("same", same), ("cross", cross)):
for i in range(2):
page.goto(same + "/start?k=%s&i=%d" % (kind, i))
page.goto(same + "/old?k=%s&i=%d" % (kind, i), wait_until="load")
target = target_base + "/new?k=%s&i=%d" % (kind, i)
gate = None
if answer == "stopped":
# The server keeps the goto's page until this call has
# returned: it can only return by being stopped (or by its
# own timeout, which is not the abort asserted below).
gate = GATES["k=%s&i=%d" % (kind, i)] = threading.Event()
began = time.monotonic()
error = None
# A page per iteration: a refresh queued by an earlier iteration (replayed late on its landed page) cannot reach this setup goto.
page = browser.new_page()
try:
page.goto(target, wait_until="domcontentloaded", timeout=GOTO_TIMEOUT_MS)
except Error as e:
error = e.message
finally:
if gate is not None:
gate.set()
took = time.monotonic() - began
where = (kind, site, i, error, took)
if answer == "stopped":
assert error is not None, where
assert ("NS_BINDING_ABORTED" in error
or (kind == "back"
and "is interrupted by another navigation" in error)), where
expected = same + end
if end in ("/old", "/start"):
expected = same + "%s?k=%s&i=%d" % (end, kind, i)
page.wait_for_url(expected, timeout=GOTO_TIMEOUT_MS)
else:
assert error is None, where
# It waited for its page, which the server held.
assert took >= HELD_S - 0.1, where
left = same + "/old?k=%s&i=%d" % (kind, i)
if answer == "landed-or-refreshed":
assert page.url in (target, same + end), (where, page.url)
page.goto(same + "/start?k=%s&i=%d" % (kind, i))
page.goto(same + "/old?k=%s&i=%d" % (kind, i), wait_until="load")
target = target_base + "/new?k=%s&i=%d" % (kind, i)
gate = None
if answer == "stopped":
# The server keeps the goto's page until this call has
# returned: it can only return by being stopped (or by its
# own timeout, which is not the abort asserted below).
gate = GATES["k=%s&i=%d" % (kind, i)] = threading.Event()
began = time.monotonic()
error = None
try:
page.goto(target, wait_until="domcontentloaded", timeout=GOTO_TIMEOUT_MS)
except Error as e:
error = e.message
finally:
if gate is not None:
gate.set()
took = time.monotonic() - began
where = (kind, site, i, error, took)
if answer == "stopped":
assert error is not None, where
assert ("NS_BINDING_ABORTED" in error
or (kind == "back"
and "is interrupted by another navigation" in error)), where
expected = same + end
if end in ("/old", "/start"):
expected = same + "%s?k=%s&i=%d" % (end, kind, i)
page.wait_for_url(expected, timeout=GOTO_TIMEOUT_MS)
else:
assert page.url == target, (where, page.url)
# Whatever the page did next, the goto never answers on the
# document it was leaving: that is the lie [B302] was about.
assert page.url != left, (where, page.url)
assert error is None, where
# It waited for its page, which the server held.
assert took >= HELD_S - 0.1, where
left = same + "/old?k=%s&i=%d" % (kind, i)
if answer == "landed-or-refreshed":
assert page.url in (target, same + end), (where, page.url)
else:
assert page.url == target, (where, page.url)
# Whatever the page did next, the goto never answers on the
# document it was leaving: that is the lie [B302] was about.
assert page.url != left, (where, page.url)
finally:
page.close()
@pytest.mark.wall_clock
+46 -8
View File
@@ -44,12 +44,14 @@ carries ``Alt-Svc: h3`` (tests/_h3_server.py).
"""
from __future__ import annotations
import json
import os
import socket
import time
import pytest
from _evidence_with_files import FailureEvidenceWithFiles
from _host_address import this_host_address
from _waits import wait_until
from _udp_line import (declared_udp, egress_by_proxy, expected_protocols, judge_visits, measure_servers, no_https_record,
@@ -66,6 +68,14 @@ PAUSE_MS = 2000
#: The roads where QUIC can reach the server, so a QUIC connection of the browser is what its Alt-Svc turns into.
_UDP_FREE_ROADS = ("direct", "socks5_coherent")
_NAV_JS = "() => performance.getEntriesByType('navigation')[0].nextHopProtocol"
#: What the engine logs for the failure evidence of the no-proxy test, by its own names (MOZ_LOG; the file is MOZ_LOG_FILE, one per process).
#: ``nsHttp`` is the HTTP stack of the engine (``gHttpLog``, netwerk/protocol/http/nsHttpHandler.cpp:146): Alt-Svc, Http3Session, the transaction
#: and the connection manager. The three Rust crates of HTTP/3 are named by their module path with ``::*``: ``neqo_glue`` (netwerk/socket/neqo_glue),
#: ``neqo_http3`` and ``neqo_transport`` (third_party/rust/neqo-*). A Rust module reaches MOZ_LOG only by a name that contains ``::`` (xpcom/base/Logging.cpp,
#: ``LogModule::SetLevel`` calls ``set_rust_log_level`` only then) and the engine's ``log`` crate is built with ``release_max_level_info``
#: (toolkit/library/rust/shared/Cargo.toml:41): a release engine keeps their info, warn and error lines, not their debug and trace ones.
#: ``timestamp`` writes the wall clock (UTC) on each line, ``sync`` writes each line at once, ``rotate:30`` keeps at most 30 MB per process.
H3_MOZ_LOG = "timestamp,sync,rotate:30,nsHttp:5,neqo_glue::*:5,neqo_http3::*:5,neqo_transport::*:5"
def _binary():
@@ -96,6 +106,13 @@ def _visits(road, server, monkeypatch, discover, **launch):
from invisible_playwright import InvisiblePlaywright
monkeypatch.setattr(_geo, "discover_egress_ip", discover)
# Failure evidence, only listening: a folder for the engine's own log of this launch, and a list this function fills, visit by visit.
engine_log = launch.pop("engine_log", None)
visit_log = launch.pop("visit_log", None)
if engine_log is not None:
os.makedirs(engine_log, exist_ok=True)
monkeypatch.setenv("MOZ_LOG", H3_MOZ_LOG)
monkeypatch.setenv("MOZ_LOG_FILE", os.path.join(engine_log, "engine-%PID.log"))
protocols, walls = [], []
# Firefox turns HTTP/3 off when the certificate chain ends in a root that is not one of its own (a self-signed test
# server always does): measured, the Alt-Svc is learned, the QUIC handshake of validation succeeds with the override and
@@ -109,16 +126,25 @@ def _visits(road, server, monkeypatch, discover, **launch):
for visit in range(1, visits_for(road) + 1):
url = server.url if visit == 1 else "%s?v=%d" % (server.url, visit)
started = time.monotonic()
seen = {"visit": visit, "url": url, "goto_started_m": round(time.perf_counter(), 6), "goto_started_t": round(time.time(), 4)}
if visit_log is not None:
visit_log.append(seen)
page.goto(url, wait_until="load", timeout=60000)
walls.append(round((time.monotonic() - started) * 1000))
seen.update(goto_ms=walls[-1], goto_done_m=round(time.perf_counter(), 6), quic_connections_after_goto=len(server.quic_peers))
if road in _UDP_FREE_ROADS:
# The Alt-Svc of the document is absorbed when the browser has made its own QUIC connection to the server (the
# server sees it): the next visit reads h3 from then on, and not before. Waited for as a condition with a
# deadline, not slept for: on a loaded machine that connection comes later than any pause. A road whose UDP
# leads nowhere has nothing to wait for (every visit is h2 and no QUIC arrives): it keeps the pause.
wait_until(lambda: server.quic_peers, 30, lambda: page.wait_for_timeout(100))
quic_seen = wait_until(lambda: server.quic_peers, 30, lambda: page.wait_for_timeout(100))
seen.update(wait_for_quic_ok=quic_seen, wait_for_quic_done_m=round(time.perf_counter(), 6))
page.wait_for_timeout(PAUSE_MS) # let the later resources settle
protocols.append(page.evaluate(_NAV_JS))
seen["read_started_m"] = round(time.perf_counter(), 6)
protocol = page.evaluate(_NAV_JS)
seen.update(protocol=protocol, read_done_m=round(time.perf_counter(), 6), quic_connections_at_read=len(server.quic_peers),
tcp_alpn_at_read=list(server.tcp_alpn))
protocols.append(protocol)
return protocols, walls
@@ -137,12 +163,24 @@ def test_a_page_with_no_proxy_reads_h2_then_h3_then_h3(monkeypatch):
import aioquic # noqa: F401 - the dev extra installs it: a missing one is a failure, never a skip
from _h3_server import H3Server
with H3Server(this_host_address()) as server:
assert not no_https_record(server.address), no_https_record(server.address)
protocols, walls = _visits("direct", server, monkeypatch, egress_by_proxy(direct=EXIT_DIRECT))
problems = judge_visits("direct", protocols, walls)
assert not problems, "; ".join(problems) + ". " + _report("direct", protocols, walls, server)
assert server.quic_peers, "the h3 visits did not reach the server by QUIC"
# On failure: the engine's own HTTP and HTTP/3 log of the launch, the lab server's record of every TCP and QUIC connection, and the
# protocol, the goto time and the read time of each visit (``files/``, ``tests/_evidence_with_files.py``). The times of the server record and
# of the visits are ``time.perf_counter()`` (``m``) of this process; the engine's log has the wall clock.
with FailureEvidenceWithFiles("h3-no-proxy-h2-h3-h3") as evidence:
with H3Server(this_host_address()) as server:
visit_log = []
try:
assert not no_https_record(server.address), no_https_record(server.address)
protocols, walls = _visits("direct", server, monkeypatch, egress_by_proxy(direct=EXIT_DIRECT),
engine_log=str(evidence.files / "engine-log"), visit_log=visit_log)
problems = judge_visits("direct", protocols, walls)
assert not problems, "; ".join(problems) + ". " + _report("direct", protocols, walls, server)
assert server.quic_peers, "the h3 visits did not reach the server by QUIC"
finally:
server.write_record(evidence.files / "h3-server-record.jsonl")
(evidence.files / "visits.json").write_text(json.dumps(
{"alt_svc": server.alt_svc, "address": server.address, "port": server.port, "moz_log": H3_MOZ_LOG, "visits": visit_log},
indent=1, default=str), encoding="utf-8")
def test_a_page_behind_a_gateway_that_relays_udp_starts_on_h2_reaches_h3_within_five_visits_and_the_quic_goes_by_the_relay(monkeypatch):
+215
View File
@@ -0,0 +1,215 @@
"""Where the frame goes after a `goto` of a page that moves is raised: the model of `_moving_page._goto`, on a fake page (no browser).
Playwright raises "is interrupted by another navigation to X" as soon as a DIFFERENT navigation commits (the `location.replace` of the page
of the round before, a process switch already on its way), and NS_BINDING_ABORTED when that move stops ours. Our own navigation can still go
on, commit and move to its own landing after that (run 44688029161: the frame "navigated to .../landed?i=x50-4" after `goto` of x50-4 had
raised for x-3). So after a raise the frame may go with the page before or with ours, and the next round may be interrupted by the landing of
either. Known-bad inputs: that interleaving (red on a model that picks one page), an error text that is not one of the two answers, an
"interrupted" naming a page that cannot be moving, a `goto` that never answers. The right answers stay green.
"""
from __future__ import annotations
import pytest
import _moving_page as mp
from invisible_playwright.sync_api import Error, TimeoutError as PlaywrightTimeout
pytestmark = pytest.mark.unit
SITE = "http://127.0.0.1:64063"
LANDED_SITE = "http://localhost:64063"
def sent(i, path="x50"):
return "%s/%s?i=%s-%d" % (SITE, path, path, i)
def landed(i, path="x50"):
return "%s/landed?i=%s-%d" % (LANDED_SITE, path, i)
def interrupted(i, naming, path="x50"):
return ('Navigation to "%s" is interrupted by another navigation to "%s"' % (sent(i, path), landed(naming, path)))
def aborted(i):
return 'page.goto: NS_BINDING_ABORTED; navigating to "%s"' % sent(i)
class FakePage:
"""The part of a page `_goto` uses. Each `goto` takes the next step of the script: the error it raises (or None when it answers) and the
url the frame has at that instant; `later` are the urls the frame goes to afterwards, one at each `land()` or each wait that needs it."""
def __init__(self):
self.url = "about:blank"
self.script = []
self.later = []
self.asked = []
def step(self, error=None, now=None, later=()):
self.script.append((error, now, list(later)))
return self
def goto(self, url, **kwargs):
self.asked.append(url)
error, now, later = self.script.pop(0)
self.url = now if now is not None else url
self.later = later
if error is not None:
raise Error(error)
def land(self):
self.url = self.later.pop(0)
def wait_for_url(self, predicate, timeout=None):
while not predicate(self.url):
if not self.later:
raise PlaywrightTimeout("Timeout %sms exceeded." % timeout)
self.land()
@pytest.fixture(autouse=True)
def _a_clean_ledger():
mp._SENT.clear()
yield
mp._SENT.clear()
def go(page, i, *, before_may_move=True, ours_may_stop=False, path="x50"):
return mp._goto(page, sent(i, path), the_page_before_may_move=before_may_move, our_page_may_stop_ours=ours_may_stop,
wait_until="domcontentloaded", timeout=30_000)
def test_a_goto_that_answers_is_green():
page = FakePage().step().step()
go(page, 3)
go(page, 4)
assert page.asked == [sent(3), sent(4)]
def test_a_goto_interrupted_by_the_page_before_is_green():
page = FakePage().step().step(interrupted(4, 3), now=landed(3))
go(page, 3)
go(page, 4)
def test_a_goto_stopped_by_the_page_before_is_green():
page = FakePage().step().step(aborted(4), now=landed(3))
go(page, 3)
go(page, 4)
def test_a_goto_stopped_on_an_older_engine_may_land_on_our_own_page():
page = FakePage().step(aborted(0), now=sent(0), later=[landed(0)])
go(page, 0, before_may_move=False, ours_may_stop=True)
assert page.url == landed(0)
def test_the_frame_that_goes_on_to_our_own_page_after_an_interrupted_goto_does_not_fail_the_next_round():
"""The interleaving of run 44688029161: `goto(x-4)` raises for the landing of x-3, then the frame lands on x-4. The next round is
interrupted by x-4's landing, and that is a right answer: ours was the page moving."""
page = (FakePage().step()
.step(interrupted(4, 3), now=landed(3), later=[landed(4)])
.step(interrupted(5, 4), now=landed(4)))
go(page, 3)
go(page, 4)
page.land()
assert page.url == landed(4)
go(page, 5)
def test_the_frame_that_goes_on_to_our_own_page_after_a_stopped_goto_does_not_fail_the_next_round():
page = (FakePage().step()
.step(aborted(4), now=landed(3), later=[landed(4)])
.step(interrupted(5, 4), now=landed(4)))
go(page, 3)
go(page, 4)
page.land()
go(page, 5)
def test_a_stopped_goto_waits_for_the_landing_of_any_page_that_may_be_moving():
"""After an interrupted round the frame may go with the page of round 3 or with ours (round 4): the wait of the next stopped `goto` ends
on either landing, and here ours comes."""
page = (FakePage().step()
.step(interrupted(4, 3), now=landed(3), later=[landed(4)])
.step(aborted(5), now=sent(5), later=[landed(4)]))
go(page, 3)
go(page, 4)
go(page, 5)
assert page.url == landed(4)
def test_a_stopped_goto_whose_frame_never_lands_is_red():
page = FakePage().step().step(aborted(4), now=sent(4))
go(page, 3)
with pytest.raises(PlaywrightTimeout):
go(page, 4)
@pytest.mark.parametrize("text", [
"Execution context was destroyed, most likely because of a navigation",
"Failed to find execution context",
"net::ERR_CONNECTION_REFUSED",
])
def test_an_error_that_is_neither_answer_is_red(text):
page = FakePage().step().step(text)
go(page, 3)
with pytest.raises(AssertionError):
go(page, 4)
def test_a_goto_that_never_answers_is_red_with_its_own_timeout():
page = FakePage().step().step('Timeout 30000ms exceeded.\nnavigating to "%s", waiting until "domcontentloaded"' % sent(4))
go(page, 3)
with pytest.raises(AssertionError):
go(page, 4)
@pytest.mark.parametrize("naming", [0, 1, 2, 5, 7])
def test_an_interrupted_goto_naming_a_page_that_cannot_be_moving_is_red(naming):
page = FakePage().step().step(interrupted(4, naming))
go(page, 3)
with pytest.raises(AssertionError):
go(page, 4)
def test_an_interrupted_goto_naming_a_page_that_cannot_be_moving_is_red_after_an_interrupted_round_too():
page = (FakePage().step()
.step(interrupted(4, 3), now=landed(3), later=[landed(4)])
.step(interrupted(5, 1), now=landed(4)))
go(page, 3)
go(page, 4)
page.land()
with pytest.raises(AssertionError):
go(page, 5)
def test_an_interrupted_goto_is_red_when_no_page_before_may_move():
page = FakePage().step(interrupted(0, 9), now=landed(9))
with pytest.raises(AssertionError):
go(page, 0, before_may_move=False)
def test_a_stopped_goto_is_red_when_no_page_may_stop_it():
page = FakePage().step(aborted(0), now=landed(0))
with pytest.raises(AssertionError):
go(page, 0, before_may_move=False, ours_may_stop=False)
def test_a_goto_says_which_pages_the_frame_may_go_with():
page = (FakePage().step()
.step(interrupted(4, 3), now=landed(3), later=[landed(4)])
.step())
assert go(page, 3) == {sent(3)}
assert go(page, 4) == {sent(3), sent(4)}
assert go(page, 5) == {sent(5)}
def test_a_page_forgotten_has_no_page_that_may_be_moving():
"""The ledger is by `id`, which a new page may reuse: the fixture forgets a page when its test ends."""
page = FakePage().step().step(interrupted(4, 3), now=landed(3))
go(page, 3)
mp.forget(page)
with pytest.raises(AssertionError):
go(page, 4)