From 2c53a5dcd94f093ac8c3c2acd77b902307662088 Mon Sep 17 00:00:00 2001 From: Victor Porof Date: Fri, 5 Jul 2019 10:55:23 +0200 Subject: [PATCH] Bug 1561435 - Format netwerk/, a=automatic-formatting # ignore-this-changeset Differential Revision: https://phabricator.services.mozilla.com/D35919 --HG-- extra : source : afa5bd771feba466ba7670c58f3d93233a14e202 --- .eslintrc.js | 1 - .prettierignore | 1 - netwerk/base/NetUtil.jsm | 820 ++++---- .../test/browser/browser_broadcastChannel.js | 8 +- .../cookie/test/browser/browser_cookies.js | 42 +- .../cookie/test/browser/browser_domCache.js | 18 +- .../test/browser/browser_originattributes.js | 52 +- .../test/browser/browser_serviceWorker.js | 39 +- netwerk/cookie/test/browser/head.js | 182 +- .../cookie/test/mochitest/cookiesHelper.js | 39 +- netwerk/cookie/test/unit/test_bug1155169.js | 30 +- netwerk/cookie/test/unit/test_bug1321912.js | 104 +- netwerk/cookie/test/unit/test_bug643051.js | 5 +- netwerk/cookie/test/unit/test_eviction.js | 264 +-- netwerk/cookie/test/unit/test_parser_0001.js | 8 +- netwerk/cookie/test/unit/test_parser_0019.js | 8 +- netwerk/cookie/test/unit/test_rawSameSite.js | 45 +- .../dns/mdns/libmdns/DNSServiceDiscovery.jsm | 78 +- .../dns/mdns/libmdns/MulticastDNSAndroid.jsm | 32 +- .../dns/mdns/libmdns/fallback/DNSPacket.jsm | 52 +- .../dns/mdns/libmdns/fallback/DNSRecord.jsm | 18 +- .../libmdns/fallback/DNSResourceRecord.jsm | 30 +- .../dns/mdns/libmdns/fallback/DNSTypes.jsm | 148 +- .../dns/mdns/libmdns/fallback/DataReader.jsm | 4 +- .../dns/mdns/libmdns/fallback/DataWriter.jsm | 4 +- .../mdns/libmdns/fallback/MulticastDNS.jsm | 358 ++-- .../protocol/http/UAOverridesBootstrapper.jsm | 6 +- netwerk/protocol/http/UserAgentOverrides.jsm | 63 +- netwerk/protocol/http/UserAgentUpdates.jsm | 219 ++- .../http/WellKnownOpportunisticUtils.jsm | 2 +- netwerk/test/browser/browser_NetUtil.js | 115 +- netwerk/test/browser/browser_about_cache.js | 95 +- netwerk/test/browser/browser_bug1535877.js | 12 +- .../test/browser/browser_child_resource.js | 139 +- .../browser_cookie_sync_across_tabs.js | 24 +- .../browser/browser_cross_process_redirect.js | 144 +- .../browser_nsIFormPOSTActionChannel.js | 74 +- netwerk/test/browser/browser_post_file.js | 7 +- .../browser/browser_resource_navigation.js | 95 +- netwerk/test/browser/browser_test_favicon.js | 10 +- .../test/browser/browser_test_io_activity.js | 54 +- netwerk/test/httpserver/httpd.js | 1732 +++++++++++------ netwerk/test/httpserver/test/head_utils.js | 321 +-- .../test/test_async_response_sending.js | 1462 +++++++------- .../test/test_basic_functionality.js | 94 +- .../test/httpserver/test/test_body_length.js | 21 +- .../test/httpserver/test/test_byte_range.js | 89 +- .../test/httpserver/test/test_cern_meta.js | 31 +- .../test/test_default_index_handler.js | 24 +- .../test/httpserver/test/test_empty_body.js | 16 +- .../test/test_errorhandler_exception.js | 43 +- .../test/httpserver/test/test_header_array.js | 8 +- netwerk/test/httpserver/test/test_headers.js | 34 +- netwerk/test/httpserver/test/test_host.js | 294 ++- netwerk/test/httpserver/test/test_linedata.js | 2 +- .../test/httpserver/test/test_load_module.js | 4 +- .../test/httpserver/test/test_name_scheme.js | 60 +- .../test/httpserver/test/test_processasync.js | 88 +- netwerk/test/httpserver/test/test_qi.js | 32 +- .../httpserver/test/test_registerdirectory.js | 352 ++-- .../httpserver/test/test_registerprefix.js | 40 +- .../test_request_line_split_in_two_packets.js | 84 +- .../httpserver/test/test_response_write.js | 17 +- .../test/httpserver/test/test_seizepower.js | 81 +- .../httpserver/test/test_setstatusline.js | 24 +- netwerk/test/httpserver/test/test_sjs.js | 76 +- .../httpserver/test/test_sjs_object_state.js | 173 +- .../test/httpserver/test/test_sjs_state.js | 115 +- .../test/test_sjs_throwing_exceptions.js | 7 +- .../test/httpserver/test/test_start_stop.js | 32 +- netwerk/test/mochitests/file_1331680.js | 8 +- netwerk/test/mochitests/file_chromecommon.js | 6 +- ...file_documentcookie_maxage_chromescript.js | 3 +- netwerk/test/mochitests/file_testcommon.js | 9 +- netwerk/test/mochitests/file_testloadflags.js | 46 +- .../file_testloadflags_chromescript.js | 71 +- netwerk/test/unit/client_cert_chooser.js | 12 +- netwerk/test/unit/head_cache.js | 109 +- netwerk/test/unit/head_cache2.js | 313 +-- netwerk/test/unit/head_channels.js | 172 +- netwerk/test/unit/head_cookies.js | 391 ++-- netwerk/test/unit/socks_client_subprocess.js | 66 +- netwerk/test/unit/test_1073747.js | 58 +- netwerk/test/unit/test_304_responses.js | 47 +- netwerk/test/unit/test_307_redirect.js | 73 +- netwerk/test/unit/test_421.js | 7 +- netwerk/test/unit/test_MIME_params.js | 781 +++++--- netwerk/test/unit/test_NetUtil.js | 549 +++--- netwerk/test/unit/test_URIs.js | 813 +++++--- netwerk/test/unit/test_URIs2.js | 765 +++++--- netwerk/test/unit/test_XHR_redirects.js | 112 +- netwerk/test/unit/test_about_networking.js | 44 +- netwerk/test/unit/test_about_protocol.js | 31 +- netwerk/test/unit/test_aboutblank.js | 12 +- netwerk/test/unit/test_addr_in_use_error.js | 20 +- .../unit/test_alt-data_closeWithStatus.js | 69 +- .../test/unit/test_alt-data_cross_process.js | 42 +- netwerk/test/unit/test_alt-data_overwrite.js | 104 +- netwerk/test/unit/test_alt-data_simple.js | 65 +- netwerk/test/unit/test_alt-data_stream.js | 52 +- netwerk/test/unit/test_alt-data_too_big.js | 115 +- netwerk/test/unit/test_altsvc.js | 142 +- .../test/unit/test_anonymous-coalescing.js | 41 +- .../test/unit/test_auth_dialog_permission.js | 127 +- netwerk/test/unit/test_auth_jar.js | 86 +- netwerk/test/unit/test_auth_proxy.js | 260 ++- netwerk/test/unit/test_authentication.js | 325 ++-- netwerk/test/unit/test_authpromptwrapper.js | 28 +- netwerk/test/unit/test_backgroundfilesaver.js | 309 +-- netwerk/test/unit/test_be_conservative.js | 124 +- .../test_be_conservative_error_handling.js | 117 +- netwerk/test/unit/test_bug1064258.js | 52 +- netwerk/test/unit/test_bug1177909.js | 120 +- netwerk/test/unit/test_bug1195415.js | 83 +- netwerk/test/unit/test_bug1218029.js | 78 +- netwerk/test/unit/test_bug1279246.js | 25 +- netwerk/test/unit/test_bug1312774_http1.js | 52 +- netwerk/test/unit/test_bug1312782_http1.js | 102 +- netwerk/test/unit/test_bug1355539_http1.js | 86 +- netwerk/test/unit/test_bug1378385_http1.js | 89 +- netwerk/test/unit/test_bug1411316_http1.js | 45 +- netwerk/test/unit/test_bug1527293.js | 27 +- netwerk/test/unit/test_bug203271.js | 308 +-- netwerk/test/unit/test_bug248970_cache.js | 84 +- netwerk/test/unit/test_bug248970_cookie.js | 73 +- netwerk/test/unit/test_bug261425.js | 33 +- netwerk/test/unit/test_bug263127.js | 26 +- netwerk/test/unit/test_bug282432.js | 13 +- netwerk/test/unit/test_bug321706.js | 3 +- netwerk/test/unit/test_bug331825.js | 12 +- netwerk/test/unit/test_bug336501.js | 22 +- netwerk/test/unit/test_bug337744.js | 54 +- netwerk/test/unit/test_bug365133.js | 140 +- netwerk/test/unit/test_bug368702.js | 50 +- netwerk/test/unit/test_bug369787.js | 11 +- netwerk/test/unit/test_bug371473.js | 13 +- netwerk/test/unit/test_bug376844.js | 12 +- netwerk/test/unit/test_bug376865.js | 13 +- netwerk/test/unit/test_bug379034.js | 5 +- netwerk/test/unit/test_bug380994.js | 12 +- netwerk/test/unit/test_bug388281.js | 30 +- netwerk/test/unit/test_bug396389.js | 49 +- netwerk/test/unit/test_bug401564.js | 22 +- netwerk/test/unit/test_bug411952.js | 40 +- netwerk/test/unit/test_bug412457.js | 112 +- netwerk/test/unit/test_bug412945.js | 19 +- netwerk/test/unit/test_bug414122.js | 64 +- netwerk/test/unit/test_bug427957.js | 30 +- netwerk/test/unit/test_bug429347.js | 63 +- netwerk/test/unit/test_bug455311.js | 53 +- netwerk/test/unit/test_bug464591.js | 102 +- netwerk/test/unit/test_bug468426.js | 160 +- netwerk/test/unit/test_bug468594.js | 194 +- netwerk/test/unit/test_bug470716.js | 194 +- netwerk/test/unit/test_bug477578.js | 6 +- netwerk/test/unit/test_bug479413.js | 26 +- netwerk/test/unit/test_bug479485.js | 56 +- netwerk/test/unit/test_bug482601.js | 183 +- netwerk/test/unit/test_bug482934.js | 112 +- netwerk/test/unit/test_bug484684.js | 146 +- netwerk/test/unit/test_bug490095.js | 195 +- netwerk/test/unit/test_bug504014.js | 103 +- netwerk/test/unit/test_bug510359.js | 120 +- netwerk/test/unit/test_bug515583.js | 67 +- netwerk/test/unit/test_bug526789.js | 99 +- netwerk/test/unit/test_bug528292.js | 58 +- .../test_bug536324_64bit_content_length.js | 13 +- netwerk/test/unit/test_bug540566.js | 10 +- netwerk/test/unit/test_bug543805.js | 121 +- netwerk/test/unit/test_bug553970.js | 63 +- netwerk/test/unit/test_bug561042.js | 41 +- netwerk/test/unit/test_bug561276.js | 87 +- netwerk/test/unit/test_bug580508.js | 45 +- netwerk/test/unit/test_bug586908.js | 54 +- netwerk/test/unit/test_bug596443.js | 138 +- netwerk/test/unit/test_bug618835.js | 108 +- netwerk/test/unit/test_bug633743.js | 188 +- netwerk/test/unit/test_bug650522.js | 18 +- netwerk/test/unit/test_bug650995.js | 251 ++- netwerk/test/unit/test_bug652761.js | 24 +- netwerk/test/unit/test_bug654926.js | 68 +- .../test/unit/test_bug654926_doom_and_read.js | 59 +- netwerk/test/unit/test_bug654926_test_seek.js | 51 +- netwerk/test/unit/test_bug659569.js | 78 +- netwerk/test/unit/test_bug660066.js | 33 +- netwerk/test/unit/test_bug667087.js | 13 +- netwerk/test/unit/test_bug667818.js | 37 +- netwerk/test/unit/test_bug667907.js | 43 +- netwerk/test/unit/test_bug669001.js | 152 +- netwerk/test/unit/test_bug767025.js | 168 +- netwerk/test/unit/test_bug770243.js | 135 +- netwerk/test/unit/test_bug812167.js | 117 +- netwerk/test/unit/test_bug826063.js | 17 +- netwerk/test/unit/test_bug856978.js | 28 +- netwerk/test/unit/test_bug894586.js | 97 +- netwerk/test/unit/test_bug935499.js | 5 +- .../test/unit/test_cache-control_request.js | 338 ++-- netwerk/test/unit/test_cache-entry-id.js | 193 +- .../test/unit/test_cache2-00-service-get.js | 13 +- netwerk/test/unit/test_cache2-01-basic.js | 27 +- .../unit/test_cache2-01a-basic-readonly.js | 27 +- .../unit/test_cache2-01b-basic-datasize.js | 31 +- .../test_cache2-01c-basic-hasmeta-only.js | 29 +- .../unit/test_cache2-01d-basic-not-wanted.js | 27 +- .../test_cache2-01e-basic-bypass-if-busy.js | 17 +- .../test_cache2-01f-basic-openTruncate.js | 13 +- .../unit/test_cache2-02-open-non-existing.js | 27 +- ...test_cache2-03-oncacheentryavail-throws.js | 24 +- ...st_cache2-04-oncacheentryavail-throws2x.js | 31 +- netwerk/test/unit/test_cache2-05-visit.js | 75 +- netwerk/test/unit/test_cache2-06-pb-mode.js | 28 +- .../test/unit/test_cache2-07-visit-memory.js | 74 +- .../test/unit/test_cache2-07a-open-memory.js | 81 +- ..._cache2-08-evict-disk-by-memory-storage.js | 13 +- .../unit/test_cache2-09-evict-disk-by-uri.js | 19 +- .../test/unit/test_cache2-10-evict-direct.js | 15 +- .../test_cache2-10b-evict-direct-immediate.js | 11 +- .../test/unit/test_cache2-11-evict-memory.js | 50 +- .../test/unit/test_cache2-12-evict-disk.js | 39 +- .../unit/test_cache2-13-evict-non-existing.js | 7 +- .../unit/test_cache2-14-concurent-readers.js | 27 +- ...t_cache2-14b-concurent-readers-complete.js | 56 +- .../unit/test_cache2-15-conditional-304.js | 33 +- .../unit/test_cache2-16-conditional-200.js | 47 +- netwerk/test/unit/test_cache2-17-evict-all.js | 3 +- netwerk/test/unit/test_cache2-18-not-valid.js | 25 +- netwerk/test/unit/test_cache2-19-range-206.js | 44 +- netwerk/test/unit/test_cache2-20-range-200.js | 44 +- .../test/unit/test_cache2-21-anon-storage.js | 33 +- .../test/unit/test_cache2-22-anon-visit.js | 20 +- .../unit/test_cache2-23-read-over-chunk.js | 20 +- netwerk/test/unit/test_cache2-24-exists.js | 20 +- .../unit/test_cache2-25-chunk-memory-limit.js | 35 +- .../test_cache2-26-no-outputstream-open.js | 40 +- .../unit/test_cache2-27-force-valid-for.js | 9 +- .../unit/test_cache2-28-last-access-attrs.js | 21 +- .../unit/test_cache2-28a-OPEN_SECRETLY.js | 20 +- ...ncurrent_read_resumable_entry_size_zero.js | 25 +- ...rent_read_non-resumable_entry_size_zero.js | 29 +- ...e2-29c-concurrent_read_half-interrupted.js | 25 +- ...-29d-concurrent_read_half-corrupted-206.js | 29 +- ...e-concurrent_read_half-non-206-response.js | 25 +- .../unit/test_cache2-30a-entry-pinning.js | 25 +- .../test_cache2-30b-pinning-storage-clear.js | 26 +- .../test_cache2-30c-pinning-deferred-doom.js | 194 +- .../test_cache2-30d-pinning-WasEvicted-API.js | 151 +- netwerk/test/unit/test_cache2-31-visit-all.js | 97 +- .../test/unit/test_cache2-32-clear-origin.js | 44 +- .../unit/test_cacheForOfflineUse_no-store.js | 48 +- netwerk/test/unit/test_cache_jar.js | 38 +- netwerk/test/unit/test_cacheflags.js | 405 ++-- .../test/unit/test_captive_portal_service.js | 62 +- netwerk/test/unit/test_channel_close.js | 13 +- netwerk/test/unit/test_channel_priority.js | 47 +- netwerk/test/unit/test_chunked_responses.js | 61 +- netwerk/test/unit/test_compareURIs.js | 88 +- netwerk/test/unit/test_compressappend.js | 55 +- .../test/unit/test_content_encoding_gzip.js | 259 ++- .../test/unit/test_content_length_underrun.js | 98 +- netwerk/test/unit/test_content_sniffer.js | 87 +- netwerk/test/unit/test_cookie_blacklist.js | 50 +- netwerk/test/unit/test_cookie_header.js | 34 +- netwerk/test/unit/test_cookiejars.js | 91 +- .../test/unit/test_cookiejars_safebrowsing.js | 100 +- .../test/unit/test_cookies_async_failure.js | 101 +- netwerk/test/unit/test_cookies_persistence.js | 11 +- .../test/unit/test_cookies_privatebrowsing.js | 11 +- .../test/unit/test_cookies_profile_close.js | 28 +- netwerk/test/unit/test_cookies_read.js | 3 +- .../test/unit/test_cookies_sync_failure.js | 88 +- netwerk/test/unit/test_cookies_thirdparty.js | 57 +- ...st_cookies_thirdparty_nonsecure_session.js | 25 +- .../unit/test_cookies_thirdparty_session.js | 15 +- netwerk/test/unit/test_data_protocol.js | 84 +- netwerk/test/unit/test_disabled_ftp.js | 13 +- netwerk/test/unit/test_dns_cancel.js | 64 +- netwerk/test/unit/test_dns_disable_ipv4.js | 17 +- netwerk/test/unit/test_dns_disable_ipv6.js | 19 +- netwerk/test/unit/test_dns_localredirect.js | 32 +- netwerk/test/unit/test_dns_offline.js | 48 +- netwerk/test/unit/test_dns_onion.js | 31 +- .../test/unit/test_dns_originAttributes.js | 42 +- netwerk/test/unit/test_dns_proxy_bypass.js | 37 +- netwerk/test/unit/test_dns_service.js | 15 +- netwerk/test/unit/test_domain_eviction.js | 98 +- netwerk/test/unit/test_doomentry.js | 75 +- netwerk/test/unit/test_duplicate_headers.js | 162 +- netwerk/test/unit/test_esni_dns_fetch.js | 86 +- netwerk/test/unit/test_event_sink.js | 76 +- netwerk/test/unit/test_eviction.js | 45 +- .../test_extract_charset_from_content_type.js | 246 ++- .../test_fallback_no-cache-entry_canceled.js | 114 +- .../test_fallback_no-cache-entry_passing.js | 111 +- ...k_redirect-to-different-origin_canceled.js | 107 +- ...ck_redirect-to-different-origin_passing.js | 105 +- .../test_fallback_request-error_canceled.js | 120 +- .../test_fallback_request-error_passing.js | 114 +- .../test_fallback_response-error_canceled.js | 108 +- .../test_fallback_response-error_passing.js | 105 +- netwerk/test/unit/test_file_protocol.js | 147 +- netwerk/test/unit/test_filestreams.js | 161 +- netwerk/test/unit/test_freshconnection.js | 11 +- netwerk/test/unit/test_getHost.js | 6 +- netwerk/test/unit/test_gre_resources.js | 18 +- netwerk/test/unit/test_gzipped_206.js | 111 +- netwerk/test/unit/test_head.js | 50 +- .../test_head_request_no_response_body.js | 18 +- .../test/unit/test_header_Accept-Language.js | 20 +- .../unit/test_header_Accept-Language_case.js | 39 +- .../test/unit/test_header_Server_Timing.js | 35 +- netwerk/test/unit/test_headers.js | 86 +- .../unit/test_hostnameIsLocalIPAddress.js | 5 +- netwerk/test/unit/test_http1-proxy.js | 58 +- netwerk/test/unit/test_http2-proxy.js | 170 +- netwerk/test/unit/test_http2.js | 580 ++++-- netwerk/test/unit/test_httpResponseTimeout.js | 29 +- netwerk/test/unit/test_http_headers.js | 24 +- netwerk/test/unit/test_httpauth.js | 149 +- netwerk/test/unit/test_httpcancel.js | 92 +- netwerk/test/unit/test_httpsuspend.js | 23 +- netwerk/test/unit/test_idn_blacklist.js | 309 +-- netwerk/test/unit/test_idn_urls.js | 656 ++++--- netwerk/test/unit/test_idna2008.js | 19 +- netwerk/test/unit/test_idnservice.js | 47 +- netwerk/test/unit/test_immutable.js | 61 +- netwerk/test/unit/test_inhibit_caching.js | 42 +- netwerk/test/unit/test_ioservice.js | 20 +- netwerk/test/unit/test_large_port.js | 86 +- netwerk/test/unit/test_localstreams.js | 33 +- .../test/unit/test_mismatch_last-modified.js | 174 +- netwerk/test/unit/test_mozTXTToHTMLConv.js | 312 +-- .../test/unit/test_multipart_byteranges.js | 137 +- .../test_multipart_streamconv-byte-by-byte.js | 66 +- .../test/unit/test_multipart_streamconv.js | 63 +- ...streamconv_missing_boundary_lead_dashes.js | 60 +- ...tipart_streamconv_missing_lead_boundary.js | 60 +- .../test/unit/test_nestedabout_serialize.js | 26 +- netwerk/test/unit/test_net_addr.js | 85 +- netwerk/test/unit/test_network_activity.js | 46 +- .../unit/test_network_connectivity_service.js | 152 +- netwerk/test/unit/test_nojsredir.js | 76 +- ...nsIBufferedOutputStream_writeFrom_block.js | 71 +- netwerk/test/unit/test_offline_status.js | 10 +- .../test_offlinecache_custom-directory.js | 103 +- netwerk/test/unit/test_origin.js | 118 +- .../unit/test_original_sent_received_head.js | 97 +- netwerk/test/unit/test_parse_content_type.js | 289 ++- ...artial_response_entry_size_smart_shrink.js | 55 +- netwerk/test/unit/test_permmgr.js | 46 +- .../test/unit/test_ping_aboutnetworking.js | 73 +- netwerk/test/unit/test_pinned_app_cache.js | 205 +- netwerk/test/unit/test_plaintext_sniff.js | 139 +- netwerk/test/unit/test_post.js | 98 +- netwerk/test/unit/test_predictor.js | 463 +++-- .../test/unit/test_private_cookie_changed.js | 19 +- .../test/unit/test_private_necko_channel.js | 10 +- netwerk/test/unit/test_progress.js | 38 +- ...test_protocolproxyservice-async-filters.js | 136 +- .../test/unit/test_protocolproxyservice.js | 549 +++--- .../test/unit/test_proxy-failover_canceled.js | 38 +- .../test/unit/test_proxy-failover_passing.js | 32 +- .../test/unit/test_proxy-replace_canceled.js | 32 +- .../test/unit/test_proxy-replace_passing.js | 32 +- netwerk/test/unit/test_proxyconnect.js | 155 +- netwerk/test/unit/test_psl.js | 38 +- .../test/unit/test_race_cache_with_network.js | 93 +- netwerk/test/unit/test_range_requests.js | 188 +- netwerk/test/unit/test_readline.js | 91 +- .../unit/test_redirect-caching_canceled.js | 23 +- .../unit/test_redirect-caching_failure.js | 27 +- .../unit/test_redirect-caching_passing.js | 20 +- netwerk/test/unit/test_redirect_baduri.js | 19 +- netwerk/test/unit/test_redirect_canceled.js | 16 +- .../unit/test_redirect_different-protocol.js | 26 +- netwerk/test/unit/test_redirect_failure.js | 20 +- .../test/unit/test_redirect_from_script.js | 114 +- ...redirect_from_script_after-open_passing.js | 114 +- netwerk/test/unit/test_redirect_history.js | 33 +- netwerk/test/unit/test_redirect_loop.js | 39 +- netwerk/test/unit/test_redirect_passing.js | 19 +- netwerk/test/unit/test_reentrancy.js | 52 +- netwerk/test/unit/test_referrer.js | 161 +- .../test/unit/test_referrer_cross_origin.js | 99 +- netwerk/test/unit/test_referrer_policy.js | 54 +- netwerk/test/unit/test_reopen.js | 29 +- .../unit/test_reply_without_content_type.js | 129 +- netwerk/test/unit/test_resumable_channel.js | 115 +- netwerk/test/unit/test_resumable_truncate.js | 46 +- netwerk/test/unit/test_safeoutputstream.js | 95 +- .../test/unit/test_safeoutputstream_append.js | 18 +- netwerk/test/unit/test_schema_2_migration.js | 127 +- netwerk/test/unit/test_schema_3_migration.js | 99 +- .../test/unit/test_separate_connections.js | 13 +- .../test/unit/test_signature_extraction.js | 97 +- netwerk/test/unit/test_simple.js | 35 +- .../unit/test_sockettransportsvc_available.js | 7 +- netwerk/test/unit/test_socks.js | 343 ++-- netwerk/test/unit/test_speculative_connect.js | 404 ++-- .../test_stale-while-revalidate_max-age-0.js | 24 +- .../test_stale-while-revalidate_negative.js | 24 +- .../test_stale-while-revalidate_positive.js | 24 +- netwerk/test/unit/test_standardurl.js | 1192 +++++++++--- .../unit/test_standardurl_default_port.js | 42 +- netwerk/test/unit/test_standardurl_port.js | 30 +- netwerk/test/unit/test_streamcopier.js | 48 +- .../test_substituting_protocol_handler.js | 65 +- .../test_suspend_channel_before_connect.js | 65 +- .../unit/test_suspend_channel_on_authRetry.js | 133 +- .../unit/test_suspend_channel_on_examine.js | 33 +- ...pend_channel_on_examine_merged_response.js | 136 +- .../unit/test_suspend_channel_on_modified.js | 64 +- .../test/unit/test_synthesized_response.js | 137 +- netwerk/test/unit/test_throttlechannel.js | 23 +- netwerk/test/unit/test_throttlequeue.js | 5 +- netwerk/test/unit/test_throttling.js | 40 +- .../unit/test_tldservice_nextsubdomain.js | 5 +- netwerk/test/unit/test_tls_flags.js | 154 +- .../test_tls_flags_separate_connections.js | 28 +- netwerk/test/unit/test_tls_server.js | 221 ++- .../unit/test_tls_server_multiple_clients.js | 75 +- netwerk/test/unit/test_traceable_channel.js | 52 +- ...est_trackingProtection_annotateChannels.js | 128 +- netwerk/test/unit/test_trr.js | 398 +++- netwerk/test/unit/test_udp_multicast.js | 44 +- netwerk/test/unit/test_udpsocket.js | 37 +- netwerk/test/unit/test_udpsocket_offline.js | 61 +- netwerk/test/unit/test_unescapestring.js | 13 +- netwerk/test/unit/test_unix_domain.js | 520 +++-- netwerk/test/unit/test_uri_mutator.js | 45 +- netwerk/test/unit/test_websocket_offline.js | 25 +- netwerk/test/unit/test_xmlhttprequest.js | 30 +- netwerk/test/unit_ipc/child_channel_id.js | 6 +- netwerk/test/unit_ipc/child_cookie_header.js | 44 +- netwerk/test/unit_ipc/head_channels_clone.js | 7 +- .../test_alt-data_closeWithStatus_wrap.js | 18 +- .../test_alt-data_cross_process_wrap.js | 51 +- .../unit_ipc/test_alt-data_simple_wrap.js | 18 +- netwerk/test/unit_ipc/test_bug528292_wrap.js | 7 +- .../test/unit_ipc/test_cache-entry-id_wrap.js | 9 +- netwerk/test/unit_ipc/test_channel_id.js | 8 +- .../unit_ipc/test_channel_priority_wrap.js | 29 +- .../unit_ipc/test_cookie_header_stripped.js | 44 +- netwerk/test/unit_ipc/test_cookiejars_wrap.js | 7 +- netwerk/test/unit_ipc/test_httpcancel_wrap.js | 28 +- .../test/unit_ipc/test_httpsuspend_wrap.js | 2 +- netwerk/test/unit_ipc/test_predictor_wrap.js | 18 +- .../test_redirect-caching_canceled_wrap.js | 4 +- .../test_redirect-caching_failure_wrap.js | 2 +- .../test_redirect-caching_passing_wrap.js | 10 +- .../unit_ipc/test_redirect_canceled_wrap.js | 10 +- netwerk/test/unit_ipc/test_reentrancy_wrap.js | 2 +- .../test_synthesized_response_wrap.js | 4 +- ...ackingProtection_annotateChannels_wrap1.js | 27 +- ...ackingProtection_annotateChannels_wrap2.js | 27 +- .../UrlClassifierSkipListService.jsm | 17 +- 455 files changed, 25908 insertions(+), 16247 deletions(-) diff --git a/.eslintrc.js b/.eslintrc.js index 32d1e3e14f93..64fcdc6b5fd6 100644 --- a/.eslintrc.js +++ b/.eslintrc.js @@ -45,7 +45,6 @@ module.exports = { "overrides": [{ "files": [ "devtools/**", - "netwerk/**", "nsprpub/**", "other-licenses/**", "parser/**", diff --git a/.prettierignore b/.prettierignore index 9aff06ec4cc3..fe0259597553 100644 --- a/.prettierignore +++ b/.prettierignore @@ -40,7 +40,6 @@ toolkit/components/telemetry/datareporting-prefs.js toolkit/components/telemetry/healthreport-prefs.js # Ignore all top-level directories for now. -netwerk/** nsprpub/** other-licenses/** parser/** diff --git a/netwerk/base/NetUtil.jsm b/netwerk/base/NetUtil.jsm index c975b46db5d7..babb4ec96126 100644 --- a/netwerk/base/NetUtil.jsm +++ b/netwerk/base/NetUtil.jsm @@ -4,9 +4,7 @@ * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ -var EXPORTED_SYMBOLS = [ - "NetUtil", -]; +var EXPORTED_SYMBOLS = ["NetUtil"]; /** * Necko utilities @@ -17,413 +15,435 @@ var EXPORTED_SYMBOLS = [ const PR_UINT32_MAX = 0xffffffff; -const {Services} = ChromeUtils.import("resource://gre/modules/Services.jsm"); +const { Services } = ChromeUtils.import("resource://gre/modules/Services.jsm"); -const BinaryInputStream = Components.Constructor("@mozilla.org/binaryinputstream;1", - "nsIBinaryInputStream", "setInputStream"); +const BinaryInputStream = Components.Constructor( + "@mozilla.org/binaryinputstream;1", + "nsIBinaryInputStream", + "setInputStream" +); // ////////////////////////////////////////////////////////////////////////////// // // NetUtil Object var NetUtil = { - /** - * Function to perform simple async copying from aSource (an input stream) - * to aSink (an output stream). The copy will happen on some background - * thread. Both streams will be closed when the copy completes. - * - * @param aSource - * The input stream to read from - * @param aSink - * The output stream to write to - * @param aCallback [optional] - * A function that will be called at copy completion with a single - * argument: the nsresult status code for the copy operation. - * - * @return An nsIRequest representing the copy operation (for example, this - * can be used to cancel the copying). The consumer can ignore the - * return value if desired. - */ - asyncCopy: function NetUtil_asyncCopy(aSource, aSink, - aCallback = null) { - if (!aSource || !aSink) { - let exception = new Components.Exception( - "Must have a source and a sink", - Cr.NS_ERROR_INVALID_ARG, - Components.stack.caller - ); - throw exception; + /** + * Function to perform simple async copying from aSource (an input stream) + * to aSink (an output stream). The copy will happen on some background + * thread. Both streams will be closed when the copy completes. + * + * @param aSource + * The input stream to read from + * @param aSink + * The output stream to write to + * @param aCallback [optional] + * A function that will be called at copy completion with a single + * argument: the nsresult status code for the copy operation. + * + * @return An nsIRequest representing the copy operation (for example, this + * can be used to cancel the copying). The consumer can ignore the + * return value if desired. + */ + asyncCopy: function NetUtil_asyncCopy(aSource, aSink, aCallback = null) { + if (!aSource || !aSink) { + let exception = new Components.Exception( + "Must have a source and a sink", + Cr.NS_ERROR_INVALID_ARG, + Components.stack.caller + ); + throw exception; + } + + // make a stream copier + var copier = Cc[ + "@mozilla.org/network/async-stream-copier;1" + ].createInstance(Ci.nsIAsyncStreamCopier2); + copier.init( + aSource, + aSink, + null /* Default event target */, + 0 /* Default length */, + true, + true /* Auto-close */ + ); + + var observer; + if (aCallback) { + observer = { + onStartRequest(aRequest) {}, + onStopRequest(aRequest, aStatusCode) { + aCallback(aStatusCode); + }, + }; + } else { + observer = null; + } + + // start the copying + copier.QueryInterface(Ci.nsIAsyncStreamCopier).asyncCopy(observer, null); + return copier; + }, + + /** + * Asynchronously opens a source and fetches the response. While the fetch + * is asynchronous, I/O may happen on the main thread. When reading from + * a local file, prefer using "OS.File" methods instead. + * + * @param aSource + * This argument can be one of the following: + * - An options object that will be passed to NetUtil.newChannel. + * - An existing nsIChannel. + * - An existing nsIInputStream. + * Using an nsIURI, nsIFile, or string spec directly is deprecated. + * @param aCallback + * The callback function that will be notified upon completion. It + * will get these arguments: + * 1) An nsIInputStream containing the data from aSource, if any. + * 2) The status code from opening the source. + * 3) Reference to the nsIRequest. + */ + asyncFetch: function NetUtil_asyncFetch(aSource, aCallback) { + if (!aSource || !aCallback) { + let exception = new Components.Exception( + "Must have a source and a callback", + Cr.NS_ERROR_INVALID_ARG, + Components.stack.caller + ); + throw exception; + } + + // Create a pipe that will create our output stream that we can use once + // we have gotten all the data. + let pipe = Cc["@mozilla.org/pipe;1"].createInstance(Ci.nsIPipe); + pipe.init(true, true, 0, PR_UINT32_MAX, null); + + // Create a listener that will give data to the pipe's output stream. + let listener = Cc[ + "@mozilla.org/network/simple-stream-listener;1" + ].createInstance(Ci.nsISimpleStreamListener); + listener.init(pipe.outputStream, { + onStartRequest(aRequest) {}, + onStopRequest(aRequest, aStatusCode) { + pipe.outputStream.close(); + aCallback(pipe.inputStream, aStatusCode, aRequest); + }, + }); + + // Input streams are handled slightly differently from everything else. + if (aSource instanceof Ci.nsIInputStream) { + let pump = Cc["@mozilla.org/network/input-stream-pump;1"].createInstance( + Ci.nsIInputStreamPump + ); + pump.init(aSource, 0, 0, true); + pump.asyncRead(listener, null); + return; + } + + let channel = aSource; + if (!(channel instanceof Ci.nsIChannel)) { + channel = this.newChannel(aSource); + } + + try { + channel.asyncOpen(listener); + } catch (e) { + let exception = new Components.Exception( + "Failed to open input source '" + channel.originalURI.spec + "'", + e.result, + Components.stack.caller, + aSource, + e + ); + throw exception; + } + }, + + /** + * Constructs a new URI for the given spec, character set, and base URI, or + * an nsIFile. + * + * @param aTarget + * The string spec for the desired URI or an nsIFile. + * @param aOriginCharset [optional] + * The character set for the URI. Only used if aTarget is not an + * nsIFile. + * @param aBaseURI [optional] + * The base URI for the spec. Only used if aTarget is not an + * nsIFile. + * + * @return an nsIURI object. + */ + newURI: function NetUtil_newURI(aTarget, aOriginCharset, aBaseURI) { + if (!aTarget) { + let exception = new Components.Exception( + "Must have a non-null string spec or nsIFile object", + Cr.NS_ERROR_INVALID_ARG, + Components.stack.caller + ); + throw exception; + } + + if (aTarget instanceof Ci.nsIFile) { + return Services.io.newFileURI(aTarget); + } + + return Services.io.newURI(aTarget, aOriginCharset, aBaseURI); + }, + + /** + * Constructs a new channel for the given source. + * + * Keep in mind that URIs coming from a webpage should *never* use the + * systemPrincipal as the loadingPrincipal. + * + * @param aWhatToLoad + * This argument used to be a string spec for the desired URI, an + * nsIURI, or an nsIFile. Now it should be an options object with + * the following properties: + * { + * uri: + * The full URI spec string, nsIURI or nsIFile to create the + * channel for. + * Note that this cannot be an nsIFile if you have to specify a + * non-default charset or base URI. Call NetUtil.newURI first if + * you need to construct an URI using those options. + * loadingNode: + * loadingPrincipal: + * triggeringPrincipal: + * securityFlags: + * contentPolicyType: + * These will be used as values for the nsILoadInfo object on the + * created channel. For details, see nsILoadInfo in nsILoadInfo.idl + * loadUsingSystemPrincipal: + * Set this to true to use the system principal as + * loadingPrincipal. This must be omitted if loadingPrincipal or + * loadingNode are present. + * This should be used with care as it skips security checks. + * } + * @return an nsIChannel object. + */ + newChannel: function NetUtil_newChannel(aWhatToLoad) { + // Make sure the API is called using only the options object. + if (typeof aWhatToLoad != "object" || arguments.length != 1) { + throw new Components.Exception( + "newChannel requires a single object argument", + Cr.NS_ERROR_INVALID_ARG, + Components.stack.caller + ); + } + + let { + uri, + loadingNode, + loadingPrincipal, + loadUsingSystemPrincipal, + triggeringPrincipal, + securityFlags, + contentPolicyType, + } = aWhatToLoad; + + if (!uri) { + throw new Components.Exception( + "newChannel requires the 'uri' property on the options object.", + Cr.NS_ERROR_INVALID_ARG, + Components.stack.caller + ); + } + + if (typeof uri == "string" || uri instanceof Ci.nsIFile) { + uri = this.newURI(uri); + } + + if (!loadingNode && !loadingPrincipal && !loadUsingSystemPrincipal) { + throw new Components.Exception( + "newChannel requires at least one of the 'loadingNode'," + + " 'loadingPrincipal', or 'loadUsingSystemPrincipal'" + + " properties on the options object.", + Cr.NS_ERROR_INVALID_ARG, + Components.stack.caller + ); + } + + if (loadUsingSystemPrincipal === true) { + if (loadingNode || loadingPrincipal) { + throw new Components.Exception( + "newChannel does not accept 'loadUsingSystemPrincipal'" + + " if the 'loadingNode' or 'loadingPrincipal' properties" + + " are present on the options object.", + Cr.NS_ERROR_INVALID_ARG, + Components.stack.caller + ); + } + loadingPrincipal = Services.scriptSecurityManager.getSystemPrincipal(); + } else if (loadUsingSystemPrincipal !== undefined) { + throw new Components.Exception( + "newChannel requires the 'loadUsingSystemPrincipal'" + + " property on the options object to be 'true' or 'undefined'.", + Cr.NS_ERROR_INVALID_ARG, + Components.stack.caller + ); + } + + if (securityFlags === undefined) { + if (!loadUsingSystemPrincipal) { + throw new Components.Exception( + "newChannel requires the 'securityFlags' property on" + + " the options object unless loading from system principal.", + Cr.NS_ERROR_INVALID_ARG, + Components.stack.caller + ); + } + securityFlags = Ci.nsILoadInfo.SEC_ALLOW_CROSS_ORIGIN_DATA_IS_NULL; + } + + if (contentPolicyType === undefined) { + if (!loadUsingSystemPrincipal) { + throw new Components.Exception( + "newChannel requires the 'contentPolicyType' property on" + + " the options object unless loading from system principal.", + Cr.NS_ERROR_INVALID_ARG, + Components.stack.caller + ); + } + contentPolicyType = Ci.nsIContentPolicy.TYPE_OTHER; + } + + return Services.io.newChannelFromURI( + uri, + loadingNode || null, + loadingPrincipal || null, + triggeringPrincipal || null, + securityFlags, + contentPolicyType + ); + }, + + /** + * Reads aCount bytes from aInputStream into a string. + * + * @param aInputStream + * The input stream to read from. + * @param aCount + * The number of bytes to read from the stream. + * @param aOptions [optional] + * charset + * The character encoding of stream data. + * replacement + * The character to replace unknown byte sequences. + * If unset, it causes an exceptions to be thrown. + * + * @return the bytes from the input stream in string form. + * + * @throws NS_ERROR_INVALID_ARG if aInputStream is not an nsIInputStream. + * @throws NS_BASE_STREAM_WOULD_BLOCK if reading from aInputStream would + * block the calling thread (non-blocking mode only). + * @throws NS_ERROR_FAILURE if there are not enough bytes available to read + * aCount amount of data. + * @throws NS_ERROR_ILLEGAL_INPUT if aInputStream has invalid sequences + */ + readInputStreamToString: function NetUtil_readInputStreamToString( + aInputStream, + aCount, + aOptions + ) { + if (!(aInputStream instanceof Ci.nsIInputStream)) { + let exception = new Components.Exception( + "First argument should be an nsIInputStream", + Cr.NS_ERROR_INVALID_ARG, + Components.stack.caller + ); + throw exception; + } + + if (!aCount) { + let exception = new Components.Exception( + "Non-zero amount of bytes must be specified", + Cr.NS_ERROR_INVALID_ARG, + Components.stack.caller + ); + throw exception; + } + + if (aOptions && "charset" in aOptions) { + let cis = Cc["@mozilla.org/intl/converter-input-stream;1"].createInstance( + Ci.nsIConverterInputStream + ); + try { + // When replacement is set, the character that is unknown sequence + // replaces with aOptions.replacement character. + if (!("replacement" in aOptions)) { + // aOptions.replacement isn't set. + // If input stream has unknown sequences for aOptions.charset, + // throw NS_ERROR_ILLEGAL_INPUT. + aOptions.replacement = 0; } - // make a stream copier - var copier = Cc["@mozilla.org/network/async-stream-copier;1"]. - createInstance(Ci.nsIAsyncStreamCopier2); - copier.init(aSource, aSink, - null /* Default event target */, - 0 /* Default length */, - true, true /* Auto-close */); + cis.init(aInputStream, aOptions.charset, aCount, aOptions.replacement); + let str = {}; + cis.readString(-1, str); + cis.close(); + return str.value; + } catch (e) { + // Adjust the stack so it throws at the caller's location. + throw new Components.Exception( + e.message, + e.result, + Components.stack.caller, + e.data + ); + } + } - var observer; - if (aCallback) { - observer = { - onStartRequest(aRequest) {}, - onStopRequest(aRequest, aStatusCode) { - aCallback(aStatusCode); - }, - }; - } else { - observer = null; - } + let sis = Cc["@mozilla.org/scriptableinputstream;1"].createInstance( + Ci.nsIScriptableInputStream + ); + sis.init(aInputStream); + try { + return sis.readBytes(aCount); + } catch (e) { + // Adjust the stack so it throws at the caller's location. + throw new Components.Exception( + e.message, + e.result, + Components.stack.caller, + e.data + ); + } + }, - // start the copying - copier.QueryInterface(Ci.nsIAsyncStreamCopier).asyncCopy(observer, null); - return copier; - }, + /** + * Reads aCount bytes from aInputStream into a string. + * + * @param {nsIInputStream} aInputStream + * The input stream to read from. + * @param {integer} [aCount = aInputStream.available()] + * The number of bytes to read from the stream. + * + * @return the bytes from the input stream in string form. + * + * @throws NS_ERROR_INVALID_ARG if aInputStream is not an nsIInputStream. + * @throws NS_BASE_STREAM_WOULD_BLOCK if reading from aInputStream would + * block the calling thread (non-blocking mode only). + * @throws NS_ERROR_FAILURE if there are not enough bytes available to read + * aCount amount of data. + */ + readInputStream(aInputStream, aCount) { + if (!(aInputStream instanceof Ci.nsIInputStream)) { + let exception = new Components.Exception( + "First argument should be an nsIInputStream", + Cr.NS_ERROR_INVALID_ARG, + Components.stack.caller + ); + throw exception; + } - /** - * Asynchronously opens a source and fetches the response. While the fetch - * is asynchronous, I/O may happen on the main thread. When reading from - * a local file, prefer using "OS.File" methods instead. - * - * @param aSource - * This argument can be one of the following: - * - An options object that will be passed to NetUtil.newChannel. - * - An existing nsIChannel. - * - An existing nsIInputStream. - * Using an nsIURI, nsIFile, or string spec directly is deprecated. - * @param aCallback - * The callback function that will be notified upon completion. It - * will get these arguments: - * 1) An nsIInputStream containing the data from aSource, if any. - * 2) The status code from opening the source. - * 3) Reference to the nsIRequest. - */ - asyncFetch: function NetUtil_asyncFetch(aSource, aCallback) { - if (!aSource || !aCallback) { - let exception = new Components.Exception( - "Must have a source and a callback", - Cr.NS_ERROR_INVALID_ARG, - Components.stack.caller - ); - throw exception; - } + if (!aCount) { + aCount = aInputStream.available(); + } - // Create a pipe that will create our output stream that we can use once - // we have gotten all the data. - let pipe = Cc["@mozilla.org/pipe;1"]. - createInstance(Ci.nsIPipe); - pipe.init(true, true, 0, PR_UINT32_MAX, null); - - // Create a listener that will give data to the pipe's output stream. - let listener = Cc["@mozilla.org/network/simple-stream-listener;1"]. - createInstance(Ci.nsISimpleStreamListener); - listener.init(pipe.outputStream, { - onStartRequest(aRequest) {}, - onStopRequest(aRequest, aStatusCode) { - pipe.outputStream.close(); - aCallback(pipe.inputStream, aStatusCode, aRequest); - }, - }); - - // Input streams are handled slightly differently from everything else. - if (aSource instanceof Ci.nsIInputStream) { - let pump = Cc["@mozilla.org/network/input-stream-pump;1"]. - createInstance(Ci.nsIInputStreamPump); - pump.init(aSource, 0, 0, true); - pump.asyncRead(listener, null); - return; - } - - let channel = aSource; - if (!(channel instanceof Ci.nsIChannel)) { - channel = this.newChannel(aSource); - } - - try { - channel.asyncOpen(listener); - } catch (e) { - let exception = new Components.Exception( - "Failed to open input source '" + channel.originalURI.spec + "'", - e.result, - Components.stack.caller, - aSource, - e - ); - throw exception; - } - }, - - /** - * Constructs a new URI for the given spec, character set, and base URI, or - * an nsIFile. - * - * @param aTarget - * The string spec for the desired URI or an nsIFile. - * @param aOriginCharset [optional] - * The character set for the URI. Only used if aTarget is not an - * nsIFile. - * @param aBaseURI [optional] - * The base URI for the spec. Only used if aTarget is not an - * nsIFile. - * - * @return an nsIURI object. - */ - newURI: function NetUtil_newURI(aTarget, aOriginCharset, aBaseURI) { - if (!aTarget) { - let exception = new Components.Exception( - "Must have a non-null string spec or nsIFile object", - Cr.NS_ERROR_INVALID_ARG, - Components.stack.caller - ); - throw exception; - } - - if (aTarget instanceof Ci.nsIFile) { - return Services.io.newFileURI(aTarget); - } - - return Services.io.newURI(aTarget, aOriginCharset, aBaseURI); - }, - - /** - * Constructs a new channel for the given source. - * - * Keep in mind that URIs coming from a webpage should *never* use the - * systemPrincipal as the loadingPrincipal. - * - * @param aWhatToLoad - * This argument used to be a string spec for the desired URI, an - * nsIURI, or an nsIFile. Now it should be an options object with - * the following properties: - * { - * uri: - * The full URI spec string, nsIURI or nsIFile to create the - * channel for. - * Note that this cannot be an nsIFile if you have to specify a - * non-default charset or base URI. Call NetUtil.newURI first if - * you need to construct an URI using those options. - * loadingNode: - * loadingPrincipal: - * triggeringPrincipal: - * securityFlags: - * contentPolicyType: - * These will be used as values for the nsILoadInfo object on the - * created channel. For details, see nsILoadInfo in nsILoadInfo.idl - * loadUsingSystemPrincipal: - * Set this to true to use the system principal as - * loadingPrincipal. This must be omitted if loadingPrincipal or - * loadingNode are present. - * This should be used with care as it skips security checks. - * } - * @return an nsIChannel object. - */ - newChannel: function NetUtil_newChannel(aWhatToLoad) { - // Make sure the API is called using only the options object. - if (typeof aWhatToLoad != "object" || arguments.length != 1) { - throw new Components.Exception( - "newChannel requires a single object argument", - Cr.NS_ERROR_INVALID_ARG, - Components.stack.caller - ); - } - - let { uri, - loadingNode, - loadingPrincipal, - loadUsingSystemPrincipal, - triggeringPrincipal, - securityFlags, - contentPolicyType } = aWhatToLoad; - - if (!uri) { - throw new Components.Exception( - "newChannel requires the 'uri' property on the options object.", - Cr.NS_ERROR_INVALID_ARG, - Components.stack.caller - ); - } - - if (typeof uri == "string" || uri instanceof Ci.nsIFile) { - uri = this.newURI(uri); - } - - if (!loadingNode && !loadingPrincipal && !loadUsingSystemPrincipal) { - throw new Components.Exception( - "newChannel requires at least one of the 'loadingNode'," + - " 'loadingPrincipal', or 'loadUsingSystemPrincipal'" + - " properties on the options object.", - Cr.NS_ERROR_INVALID_ARG, - Components.stack.caller - ); - } - - if (loadUsingSystemPrincipal === true) { - if (loadingNode || loadingPrincipal) { - throw new Components.Exception( - "newChannel does not accept 'loadUsingSystemPrincipal'" + - " if the 'loadingNode' or 'loadingPrincipal' properties" + - " are present on the options object.", - Cr.NS_ERROR_INVALID_ARG, - Components.stack.caller - ); - } - loadingPrincipal = Services.scriptSecurityManager - .getSystemPrincipal(); - } else if (loadUsingSystemPrincipal !== undefined) { - throw new Components.Exception( - "newChannel requires the 'loadUsingSystemPrincipal'" + - " property on the options object to be 'true' or 'undefined'.", - Cr.NS_ERROR_INVALID_ARG, - Components.stack.caller - ); - } - - if (securityFlags === undefined) { - if (!loadUsingSystemPrincipal) { - throw new Components.Exception( - "newChannel requires the 'securityFlags' property on" + - " the options object unless loading from system principal.", - Cr.NS_ERROR_INVALID_ARG, - Components.stack.caller - ); - } - securityFlags = Ci.nsILoadInfo.SEC_ALLOW_CROSS_ORIGIN_DATA_IS_NULL; - } - - if (contentPolicyType === undefined) { - if (!loadUsingSystemPrincipal) { - throw new Components.Exception( - "newChannel requires the 'contentPolicyType' property on" + - " the options object unless loading from system principal.", - Cr.NS_ERROR_INVALID_ARG, - Components.stack.caller - ); - } - contentPolicyType = Ci.nsIContentPolicy.TYPE_OTHER; - } - - return Services.io.newChannelFromURI(uri, - loadingNode || null, - loadingPrincipal || null, - triggeringPrincipal || null, - securityFlags, - contentPolicyType); - }, - - /** - * Reads aCount bytes from aInputStream into a string. - * - * @param aInputStream - * The input stream to read from. - * @param aCount - * The number of bytes to read from the stream. - * @param aOptions [optional] - * charset - * The character encoding of stream data. - * replacement - * The character to replace unknown byte sequences. - * If unset, it causes an exceptions to be thrown. - * - * @return the bytes from the input stream in string form. - * - * @throws NS_ERROR_INVALID_ARG if aInputStream is not an nsIInputStream. - * @throws NS_BASE_STREAM_WOULD_BLOCK if reading from aInputStream would - * block the calling thread (non-blocking mode only). - * @throws NS_ERROR_FAILURE if there are not enough bytes available to read - * aCount amount of data. - * @throws NS_ERROR_ILLEGAL_INPUT if aInputStream has invalid sequences - */ - readInputStreamToString: function NetUtil_readInputStreamToString(aInputStream, - aCount, - aOptions) { - if (!(aInputStream instanceof Ci.nsIInputStream)) { - let exception = new Components.Exception( - "First argument should be an nsIInputStream", - Cr.NS_ERROR_INVALID_ARG, - Components.stack.caller - ); - throw exception; - } - - if (!aCount) { - let exception = new Components.Exception( - "Non-zero amount of bytes must be specified", - Cr.NS_ERROR_INVALID_ARG, - Components.stack.caller - ); - throw exception; - } - - if (aOptions && "charset" in aOptions) { - let cis = Cc["@mozilla.org/intl/converter-input-stream;1"]. - createInstance(Ci.nsIConverterInputStream); - try { - // When replacement is set, the character that is unknown sequence - // replaces with aOptions.replacement character. - if (!("replacement" in aOptions)) { - // aOptions.replacement isn't set. - // If input stream has unknown sequences for aOptions.charset, - // throw NS_ERROR_ILLEGAL_INPUT. - aOptions.replacement = 0; - } - - cis.init(aInputStream, aOptions.charset, aCount, - aOptions.replacement); - let str = {}; - cis.readString(-1, str); - cis.close(); - return str.value; - } catch (e) { - // Adjust the stack so it throws at the caller's location. - throw new Components.Exception(e.message, e.result, - Components.stack.caller, e.data); - } - } - - let sis = Cc["@mozilla.org/scriptableinputstream;1"]. - createInstance(Ci.nsIScriptableInputStream); - sis.init(aInputStream); - try { - return sis.readBytes(aCount); - } catch (e) { - // Adjust the stack so it throws at the caller's location. - throw new Components.Exception(e.message, e.result, - Components.stack.caller, e.data); - } - }, - - /** - * Reads aCount bytes from aInputStream into a string. - * - * @param {nsIInputStream} aInputStream - * The input stream to read from. - * @param {integer} [aCount = aInputStream.available()] - * The number of bytes to read from the stream. - * - * @return the bytes from the input stream in string form. - * - * @throws NS_ERROR_INVALID_ARG if aInputStream is not an nsIInputStream. - * @throws NS_BASE_STREAM_WOULD_BLOCK if reading from aInputStream would - * block the calling thread (non-blocking mode only). - * @throws NS_ERROR_FAILURE if there are not enough bytes available to read - * aCount amount of data. - */ - readInputStream(aInputStream, aCount) { - if (!(aInputStream instanceof Ci.nsIInputStream)) { - let exception = new Components.Exception( - "First argument should be an nsIInputStream", - Cr.NS_ERROR_INVALID_ARG, - Components.stack.caller - ); - throw exception; - } - - if (!aCount) { - aCount = aInputStream.available(); - } - - let stream = new BinaryInputStream(aInputStream); - let result = new ArrayBuffer(aCount); - stream.readArrayBuffer(result.byteLength, result); - return result; - }, + let stream = new BinaryInputStream(aInputStream); + let result = new ArrayBuffer(aCount); + stream.readArrayBuffer(result.byteLength, result); + return result; + }, }; diff --git a/netwerk/cookie/test/browser/browser_broadcastChannel.js b/netwerk/cookie/test/browser/browser_broadcastChannel.js index 33c340b299e0..c44c57c8e517 100644 --- a/netwerk/cookie/test/browser/browser_broadcastChannel.js +++ b/netwerk/cookie/test/browser/browser_broadcastChannel.js @@ -15,7 +15,7 @@ CookiePolicyHelper.runTest("BroadcastChannel", { ok(true, "BroadcastChannel cannot be used!"); is(e.name, "SecurityError", "We want a security error message."); } - } + }, }); CookiePolicyHelper.runTest("BroadcastChannel in workers", { @@ -25,7 +25,9 @@ CookiePolicyHelper.runTest("BroadcastChannel in workers", { postMessage(true); } - let blob = new w.Blob([nonBlockingCode.toString() + "; nonBlockingCode();"]); + let blob = new w.Blob([ + nonBlockingCode.toString() + "; nonBlockingCode();", + ]); ok(blob, "Blob has been created"); let blobURL = w.URL.createObjectURL(blob); @@ -73,5 +75,5 @@ CookiePolicyHelper.runTest("BroadcastChannel in workers", { } }; }); - } + }, }); diff --git a/netwerk/cookie/test/browser/browser_cookies.js b/netwerk/cookie/test/browser/browser_cookies.js index 791aad8585ac..b23ed3423724 100644 --- a/netwerk/cookie/test/browser/browser_cookies.js +++ b/netwerk/cookie/test/browser/browser_cookies.js @@ -2,17 +2,27 @@ CookiePolicyHelper.runTest("document.cookies", { cookieJarAccessAllowed: async _ => { let hasCookie = !!content.document.cookie.length; - await content.fetch("server.sjs").then(r => r.text()).then(text => { - is(text, hasCookie ? "cookie-present" : "cookie-not-present", "document.cookie is consistent with fetch requests"); - }); + await content + .fetch("server.sjs") + .then(r => r.text()) + .then(text => { + is( + text, + hasCookie ? "cookie-present" : "cookie-not-present", + "document.cookie is consistent with fetch requests" + ); + }); content.document.cookie = "name=value"; ok(content.document.cookie.includes("name=value"), "Some cookies for me"); ok(content.document.cookie.includes("foopy=1"), "Some cookies for me"); - await content.fetch("server.sjs").then(r => r.text()).then(text => { - is(text, "cookie-present", "We should have cookies"); - }); + await content + .fetch("server.sjs") + .then(r => r.text()) + .then(text => { + is(text, "cookie-present", "We should have cookies"); + }); ok(!!content.document.cookie.length, "Some Cookies for me"); }, @@ -22,14 +32,20 @@ CookiePolicyHelper.runTest("document.cookies", { content.document.cookie = "name=value"; is(content.document.cookie, "", "No cookies for me"); - await content.fetch("server.sjs").then(r => r.text()).then(text => { - is(text, "cookie-not-present", "We should not have cookies"); - }); + await content + .fetch("server.sjs") + .then(r => r.text()) + .then(text => { + is(text, "cookie-not-present", "We should not have cookies"); + }); // Let's do it twice. - await content.fetch("server.sjs").then(r => r.text()).then(text => { - is(text, "cookie-not-present", "We should not have cookies"); - }); + await content + .fetch("server.sjs") + .then(r => r.text()) + .then(text => { + is(text, "cookie-not-present", "We should not have cookies"); + }); is(content.document.cookie, "", "Still no cookies for me"); - } + }, }); diff --git a/netwerk/cookie/test/browser/browser_domCache.js b/netwerk/cookie/test/browser/browser_domCache.js index 89ada5ed5a9a..32536bcaaf6e 100644 --- a/netwerk/cookie/test/browser/browser_domCache.js +++ b/netwerk/cookie/test/browser/browser_domCache.js @@ -1,13 +1,23 @@ CookiePolicyHelper.runTest("DOM Cache", { cookieJarAccessAllowed: async w => { await w.caches.open("wow").then( - _ => { ok(true, "DOM Cache can be used!"); }, - _ => { ok(false, "DOM Cache can be used!"); }); + _ => { + ok(true, "DOM Cache can be used!"); + }, + _ => { + ok(false, "DOM Cache can be used!"); + } + ); }, cookieJarAccessDenied: async w => { await w.caches.open("wow").then( - _ => { ok(false, "DOM Cache cannot be used!"); }, - _ => { ok(true, "DOM Cache cannot be used!"); }); + _ => { + ok(false, "DOM Cache cannot be used!"); + }, + _ => { + ok(true, "DOM Cache cannot be used!"); + } + ); }, }); diff --git a/netwerk/cookie/test/browser/browser_originattributes.js b/netwerk/cookie/test/browser/browser_originattributes.js index e60c6c5a0713..ecdad67372bc 100644 --- a/netwerk/cookie/test/browser/browser_originattributes.js +++ b/netwerk/cookie/test/browser/browser_originattributes.js @@ -14,7 +14,7 @@ let cm = Cc["@mozilla.org/cookiemanager;1"].getService(Ci.nsICookieManager); // returns the newly opened tab async function openTabInUserContext(uri, userContextId) { // open the tab in the correct userContextId - let tab = BrowserTestUtils.addTab(gBrowser, uri, {userContextId}); + let tab = BrowserTestUtils.addTab(gBrowser, uri, { userContextId }); // select tab and make sure its browser is focused gBrowser.selectedTab = tab; @@ -24,15 +24,16 @@ async function openTabInUserContext(uri, userContextId) { // wait for tab load await BrowserTestUtils.browserLoaded(browser); - return {tab, browser}; + return { tab, browser }; } add_task(async function setup() { // make sure userContext is enabled. await new Promise(resolve => { - SpecialPowers.pushPrefEnv({"set": [ - ["privacy.userContext.enabled", true] - ]}, resolve); + SpecialPowers.pushPrefEnv( + { set: [["privacy.userContext.enabled", true]] }, + resolve + ); }); }); @@ -41,15 +42,17 @@ add_task(async function test() { // which should only be visible in that context for (let userContextId of Object.keys(USER_CONTEXTS)) { // open our tab in the given user context - let {tab, browser} = await openTabInUserContext(TEST_URL, userContextId); + let { tab, browser } = await openTabInUserContext(TEST_URL, userContextId); - await ContentTask.spawn(browser, - {names: COOKIE_NAMES, value: USER_CONTEXTS[userContextId]}, - function(opts) { - for (let name of opts.names) { - content.document.cookie = name + "=" + opts.value; - } - }); + await ContentTask.spawn( + browser, + { names: COOKIE_NAMES, value: USER_CONTEXTS[userContextId] }, + function(opts) { + for (let name of opts.names) { + content.document.cookie = name + "=" + opts.value; + } + } + ); // remove the tab gBrowser.removeTab(tab); @@ -59,7 +62,7 @@ add_task(async function test() { await checkCookies(expectedValues, "before removal"); // remove cookies that belongs to user context id #1 - cm.removeCookiesWithOriginAttributes(JSON.stringify({userContextId: 1})); + cm.removeCookiesWithOriginAttributes(JSON.stringify({ userContextId: 1 })); expectedValues[1] = undefined; await checkCookies(expectedValues, "after removal"); @@ -72,18 +75,25 @@ async function checkCookies(expectedValues, time) { let expectedValue = expectedValues[userContextId]; for (let name of COOKIE_NAMES) { - is(cookiesFromTitle[name], expectedValue, - `User context ${userContextId}: ${name} should be correct from title ${time}`); - is(cookiesFromManager[name], expectedValue, - `User context ${userContextId}: ${name} should be correct from manager ${time}`); + is( + cookiesFromTitle[name], + expectedValue, + `User context ${userContextId}: ${name} should be correct from title ${time}` + ); + is( + cookiesFromManager[name], + expectedValue, + `User context ${userContextId}: ${name} should be correct from manager ${time}` + ); } - } } function getCookiesFromManager(userContextId) { let cookies = {}; - let enumerator = cm.getCookiesWithOriginAttributes(JSON.stringify({userContextId})); + let enumerator = cm.getCookiesWithOriginAttributes( + JSON.stringify({ userContextId }) + ); for (let cookie of enumerator) { cookies[cookie.name] = cookie.value; } @@ -91,7 +101,7 @@ function getCookiesFromManager(userContextId) { } async function getCookiesFromJS(userContextId) { - let {tab, browser} = await openTabInUserContext(TEST_URL, userContextId); + let { tab, browser } = await openTabInUserContext(TEST_URL, userContextId); // get the cookies let cookieString = await ContentTask.spawn(browser, null, function() { diff --git a/netwerk/cookie/test/browser/browser_serviceWorker.js b/netwerk/cookie/test/browser/browser_serviceWorker.js index fd6f021450b7..f3608e477763 100644 --- a/netwerk/cookie/test/browser/browser_serviceWorker.js +++ b/netwerk/cookie/test/browser/browser_serviceWorker.js @@ -7,18 +7,37 @@ CookiePolicyHelper.runTest("ServiceWorker", { ], cookieJarAccessAllowed: async w => { - await w.navigator.serviceWorker.register("file_empty.js").then( - reg => { ok(true, "ServiceWorker can be used!"); return reg; }, - _ => { ok(false, "ServiceWorker cannot be used! " + _); }).then( - reg => reg.unregister(), - _ => { ok(false, "unregister failed"); }). - catch(e => ok(false, "Promise rejected: " + e)); + await w.navigator.serviceWorker + .register("file_empty.js") + .then( + reg => { + ok(true, "ServiceWorker can be used!"); + return reg; + }, + _ => { + ok(false, "ServiceWorker cannot be used! " + _); + } + ) + .then( + reg => reg.unregister(), + _ => { + ok(false, "unregister failed"); + } + ) + .catch(e => ok(false, "Promise rejected: " + e)); }, cookieJarAccessDenied: async w => { - await w.navigator.serviceWorker.register("file_empty.js").then( - _ => { ok(false, "ServiceWorker cannot be used!"); }, - _ => { ok(true, "ServiceWorker cannot be used!"); }). - catch(e => ok(false, "Promise rejected: " + e)); + await w.navigator.serviceWorker + .register("file_empty.js") + .then( + _ => { + ok(false, "ServiceWorker cannot be used!"); + }, + _ => { + ok(true, "ServiceWorker cannot be used!"); + } + ) + .catch(e => ok(false, "Promise rejected: " + e)); }, }); diff --git a/netwerk/cookie/test/browser/head.js b/netwerk/cookie/test/browser/head.js index 300cd284c5d1..84ea9bc8e676 100644 --- a/netwerk/cookie/test/browser/head.js +++ b/netwerk/cookie/test/browser/head.js @@ -20,52 +20,60 @@ const TEST_TOP_PAGE = TEST_DOMAIN + TEST_PATH + "file_empty.html"; this.CookiePolicyHelper = { runTest(testName, config) { // Testing allowed to blocked by cookie behavior - this._createTest(testName, - config.cookieJarAccessAllowed, - config.cookieJarAccessDenied, - config.prefs, - { - fromBehavior: BEHAVIOR_ACCEPT, - toBehavior: BEHAVIOR_REJECT, - fromPermission: PERM_DEFAULT, - toPermission: PERM_DEFAULT, - }); + this._createTest( + testName, + config.cookieJarAccessAllowed, + config.cookieJarAccessDenied, + config.prefs, + { + fromBehavior: BEHAVIOR_ACCEPT, + toBehavior: BEHAVIOR_REJECT, + fromPermission: PERM_DEFAULT, + toPermission: PERM_DEFAULT, + } + ); // Testing blocked to allowed by cookie behavior - this._createTest(testName, - config.cookieJarAccessDenied, - config.cookieJarAccessAllowed, - config.prefs, - { - fromBehavior: BEHAVIOR_REJECT, - toBehavior: BEHAVIOR_ACCEPT, - fromPermission: PERM_DEFAULT, - toPermission: PERM_DEFAULT, - }); + this._createTest( + testName, + config.cookieJarAccessDenied, + config.cookieJarAccessAllowed, + config.prefs, + { + fromBehavior: BEHAVIOR_REJECT, + toBehavior: BEHAVIOR_ACCEPT, + fromPermission: PERM_DEFAULT, + toPermission: PERM_DEFAULT, + } + ); // Testing allowed to blocked by cookie permission - this._createTest(testName, - config.cookieJarAccessAllowed, - config.cookieJarAccessDenied, - config.prefs, - { - fromBehavior: BEHAVIOR_REJECT, - toBehavior: BEHAVIOR_REJECT, - fromPermission: PERM_ALLOW, - toPermission: PERM_DEFAULT, - }); + this._createTest( + testName, + config.cookieJarAccessAllowed, + config.cookieJarAccessDenied, + config.prefs, + { + fromBehavior: BEHAVIOR_REJECT, + toBehavior: BEHAVIOR_REJECT, + fromPermission: PERM_ALLOW, + toPermission: PERM_DEFAULT, + } + ); // Testing blocked to allowed by cookie permission - this._createTest(testName, - config.cookieJarAccessDenied, - config.cookieJarAccessAllowed, - config.prefs, - { - fromBehavior: BEHAVIOR_ACCEPT, - toBehavior: BEHAVIOR_ACCEPT, - fromPermission: PERM_DENY, - toPermission: PERM_DEFAULT, - }); + this._createTest( + testName, + config.cookieJarAccessDenied, + config.cookieJarAccessAllowed, + config.prefs, + { + fromBehavior: BEHAVIOR_ACCEPT, + toBehavior: BEHAVIOR_ACCEPT, + fromPermission: PERM_DENY, + toPermission: PERM_DEFAULT, + } + ); }, _createTest(testName, goodCb, badCb, prefs, config) { @@ -75,16 +83,16 @@ this.CookiePolicyHelper = { await SpecialPowers.flushPrefEnv(); if (prefs) { - await SpecialPowers.pushPrefEnv({"set": prefs }); + await SpecialPowers.pushPrefEnv({ set: prefs }); } let uri = Services.io.newURI(TEST_DOMAIN); // Let's set the first cookie pref. Services.perms.add(uri, "cookie", config.fromPermission); - await SpecialPowers.pushPrefEnv({"set": [ - ["network.cookie.cookieBehavior", config.fromBehavior], - ]}); + await SpecialPowers.pushPrefEnv({ + set: [["network.cookie.cookieBehavior", config.fromBehavior]], + }); // Let's open a tab and load content. let tab = BrowserTestUtils.addTab(gBrowser, TEST_TOP_PAGE); @@ -94,10 +102,9 @@ this.CookiePolicyHelper = { await BrowserTestUtils.browserLoaded(browser); // Let's create an iframe. - await ContentTask.spawn(browser, { url: TEST_TOP_PAGE }, - async obj => { + await ContentTask.spawn(browser, { url: TEST_TOP_PAGE }, async obj => { return new content.Promise(resolve => { - let ifr = content.document.createElement('iframe'); + let ifr = content.document.createElement("iframe"); ifr.setAttribute("id", "iframe"); ifr.src = obj.url; ifr.onload = resolve; @@ -106,36 +113,50 @@ this.CookiePolicyHelper = { }); // Let's exec the "good" callback. - info("Executing the test after setting the cookie behavior to " + config.fromBehavior + " and permission to " + config.fromPermission); - await ContentTask.spawn(browser, - { callback: goodCb.toString() }, - async obj => { - let runnableStr = `(() => {return (${obj.callback});})();`; - let runnable = eval(runnableStr); // eslint-disable-line no-eval - await runnable(content); + info( + "Executing the test after setting the cookie behavior to " + + config.fromBehavior + + " and permission to " + + config.fromPermission + ); + await ContentTask.spawn( + browser, + { callback: goodCb.toString() }, + async obj => { + let runnableStr = `(() => {return (${obj.callback});})();`; + let runnable = eval(runnableStr); // eslint-disable-line no-eval + await runnable(content); - let ifr = content.document.getElementById("iframe"); - await runnable(ifr.contentWindow); - }); + let ifr = content.document.getElementById("iframe"); + await runnable(ifr.contentWindow); + } + ); // Now, let's change the cookie settings Services.perms.add(uri, "cookie", config.toPermission); - await SpecialPowers.pushPrefEnv({"set": [ - ["network.cookie.cookieBehavior", config.toBehavior], - ]}); + await SpecialPowers.pushPrefEnv({ + set: [["network.cookie.cookieBehavior", config.toBehavior]], + }); // We still want the good callback to succeed. - info("Executing the test after setting the cookie behavior to " + config.toBehavior + " and permission to " + config.toPermission); - await ContentTask.spawn(browser, - { callback: goodCb.toString() }, - async obj => { - let runnableStr = `(() => {return (${obj.callback});})();`; - let runnable = eval(runnableStr); // eslint-disable-line no-eval - await runnable(content); + info( + "Executing the test after setting the cookie behavior to " + + config.toBehavior + + " and permission to " + + config.toPermission + ); + await ContentTask.spawn( + browser, + { callback: goodCb.toString() }, + async obj => { + let runnableStr = `(() => {return (${obj.callback});})();`; + let runnable = eval(runnableStr); // eslint-disable-line no-eval + await runnable(content); - let ifr = content.document.getElementById("iframe"); - await runnable(ifr.contentWindow); - }); + let ifr = content.document.getElementById("iframe"); + await runnable(ifr.contentWindow); + } + ); // Let's close the tab. BrowserTestUtils.removeTab(tab); @@ -149,20 +170,25 @@ this.CookiePolicyHelper = { // Let's exec the "bad" callback. info("Executing the test in a new tab"); - await ContentTask.spawn(browser, - { callback: badCb.toString() }, - async obj => { - let runnableStr = `(() => {return (${obj.callback});})();`; - let runnable = eval(runnableStr); // eslint-disable-line no-eval - await runnable(content); - }); + await ContentTask.spawn( + browser, + { callback: badCb.toString() }, + async obj => { + let runnableStr = `(() => {return (${obj.callback});})();`; + let runnable = eval(runnableStr); // eslint-disable-line no-eval + await runnable(content); + } + ); // Let's close the tab. BrowserTestUtils.removeTab(tab); // Cleanup. await new Promise(resolve => { - Services.clearData.deleteData(Ci.nsIClearDataService.CLEAR_ALL, resolve); + Services.clearData.deleteData( + Ci.nsIClearDataService.CLEAR_ALL, + resolve + ); }); }); }, diff --git a/netwerk/cookie/test/mochitest/cookiesHelper.js b/netwerk/cookie/test/mochitest/cookiesHelper.js index 50414ece4c61..41b0065d418c 100644 --- a/netwerk/cookie/test/mochitest/cookiesHelper.js +++ b/netwerk/cookie/test/mochitest/cookiesHelper.js @@ -6,13 +6,18 @@ async function cleanupData() { const chromeScript = SpecialPowers.loadChromeScript(_ => { // eslint-disable-next-line no-undef addMessageListener("go", __ => { - const {Services} = ChromeUtils.import("resource://gre/modules/Services.jsm"); - Services.clearData.deleteData(Services.clearData.CLEAR_COOKIES | - Services.clearData.CLEAR_ALL_CACHES | - Services.clearData.CLEAR_DOM_STORAGES, ___ => { - // eslint-disable-next-line no-undef - sendAsyncMessage("done"); - }); + const { Services } = ChromeUtils.import( + "resource://gre/modules/Services.jsm" + ); + Services.clearData.deleteData( + Services.clearData.CLEAR_COOKIES | + Services.clearData.CLEAR_ALL_CACHES | + Services.clearData.CLEAR_DOM_STORAGES, + ___ => { + // eslint-disable-next-line no-undef + sendAsyncMessage("done"); + } + ); }); }); @@ -26,23 +31,33 @@ async function cleanupData() { } async function checkLastRequest(type, state) { - let json = await fetch("cookie.sjs?last&" + Math.random()).then(r => r.json()); + let json = await fetch("cookie.sjs?last&" + Math.random()).then(r => + r.json() + ); is(json.type, type, "Type: " + type); is(json.hasCookie, state == ALLOWED, "Fetch has cookies"); } async function runTests(currentTest) { await cleanupData(); - await SpecialPowers.pushPrefEnv({ set: [["network.cookie.cookieBehavior", 2]] }); + await SpecialPowers.pushPrefEnv({ + set: [["network.cookie.cookieBehavior", 2]], + }); let windowBlocked = window.open("cookie.sjs?window&" + Math.random()); - await new Promise(resolve => { windowBlocked.onload = resolve; }); + await new Promise(resolve => { + windowBlocked.onload = resolve; + }); await currentTest(windowBlocked, BLOCKED); windowBlocked.close(); await cleanupData(); - await SpecialPowers.pushPrefEnv({ set: [["network.cookie.cookieBehavior", 1]] }); + await SpecialPowers.pushPrefEnv({ + set: [["network.cookie.cookieBehavior", 1]], + }); let windowAllowed = window.open("cookie.sjs?window&" + Math.random()); - await new Promise(resolve => { windowAllowed.onload = resolve; }); + await new Promise(resolve => { + windowAllowed.onload = resolve; + }); await currentTest(windowAllowed, ALLOWED); windowAllowed.close(); diff --git a/netwerk/cookie/test/unit/test_bug1155169.js b/netwerk/cookie/test/unit/test_bug1155169.js index fee2e02c1687..82e5c03c5b2e 100644 --- a/netwerk/cookie/test/unit/test_bug1155169.js +++ b/netwerk/cookie/test/unit/test_bug1155169.js @@ -1,9 +1,8 @@ -const {Services} = ChromeUtils.import("resource://gre/modules/Services.jsm"); +const { Services } = ChromeUtils.import("resource://gre/modules/Services.jsm"); const URI = Services.io.newURI("http://example.org/"); -const cs = Cc["@mozilla.org/cookieService;1"] - .getService(Ci.nsICookieService); +const cs = Cc["@mozilla.org/cookieService;1"].getService(Ci.nsICookieService); function run_test() { // Allow all cookies. @@ -14,29 +13,44 @@ function run_test() { // Add a new cookie. setCookie("foo=bar", { - type: "added", isSession: true, isSecure: false, isHttpOnly: false, + type: "added", + isSession: true, + isSecure: false, + isHttpOnly: false, }); // Update cookie with isHttpOnly=true. setCookie("foo=bar; HttpOnly", { - type: "changed", isSession: true, isSecure: false, isHttpOnly: true, + type: "changed", + isSession: true, + isSecure: false, + isHttpOnly: true, }); // Update cookie with isSecure=true. setCookie("foo=bar; Secure", { - type: "changed", isSession: true, isSecure: true, isHttpOnly: false, + type: "changed", + isSession: true, + isSecure: true, + isHttpOnly: false, }); // Update cookie with isSession=false. let expiry = new Date(); expiry.setUTCFullYear(expiry.getUTCFullYear() + 2); setCookie(`foo=bar; Expires=${expiry.toGMTString()}`, { - type: "changed", isSession: false, isSecure: false, isHttpOnly: false, + type: "changed", + isSession: false, + isSecure: false, + isHttpOnly: false, }); // Reset cookie. setCookie("foo=bar", { - type: "changed", isSession: true, isSecure: false, isHttpOnly: false, + type: "changed", + isSession: true, + isSecure: false, + isHttpOnly: false, }); } diff --git a/netwerk/cookie/test/unit/test_bug1321912.js b/netwerk/cookie/test/unit/test_bug1321912.js index 4dff0eb3a3e8..aa7693c0668c 100644 --- a/netwerk/cookie/test/unit/test_bug1321912.js +++ b/netwerk/cookie/test/unit/test_bug1321912.js @@ -1,4 +1,4 @@ -const {Services} = ChromeUtils.import("resource://gre/modules/Services.jsm"); +const { Services } = ChromeUtils.import("resource://gre/modules/Services.jsm"); do_get_profile(); const dirSvc = Services.dirsvc; @@ -7,52 +7,66 @@ let dbFile = dirSvc.get("ProfD", Ci.nsIFile); dbFile.append("cookies.sqlite"); let storage = Services.storage; -let properties = Cc["@mozilla.org/hash-property-bag;1"]. - createInstance(Ci.nsIWritablePropertyBag); +let properties = Cc["@mozilla.org/hash-property-bag;1"].createInstance( + Ci.nsIWritablePropertyBag +); properties.setProperty("shared", true); let conn = storage.openDatabase(dbFile); // Write the schema v7 to the database. conn.schemaVersion = 7; -conn.executeSimpleSQL("CREATE TABLE moz_cookies (" + - "id INTEGER PRIMARY KEY, " + - "baseDomain TEXT, " + - "originAttributes TEXT NOT NULL DEFAULT '', " + - "name TEXT, " + - "value TEXT, " + - "host TEXT, " + - "path TEXT, " + - "expiry INTEGER, " + - "lastAccessed INTEGER, " + - "creationTime INTEGER, " + - "isSecure INTEGER, " + - "isHttpOnly INTEGER, " + - "appId INTEGER DEFAULT 0, " + - "inBrowserElement INTEGER DEFAULT 0, " + - "CONSTRAINT moz_uniqueid UNIQUE (name, host, path, originAttributes)" + -")"); -conn.executeSimpleSQL("CREATE INDEX moz_basedomain ON moz_cookies (baseDomain, " + - "originAttributes)"); +conn.executeSimpleSQL( + "CREATE TABLE moz_cookies (" + + "id INTEGER PRIMARY KEY, " + + "baseDomain TEXT, " + + "originAttributes TEXT NOT NULL DEFAULT '', " + + "name TEXT, " + + "value TEXT, " + + "host TEXT, " + + "path TEXT, " + + "expiry INTEGER, " + + "lastAccessed INTEGER, " + + "creationTime INTEGER, " + + "isSecure INTEGER, " + + "isHttpOnly INTEGER, " + + "appId INTEGER DEFAULT 0, " + + "inBrowserElement INTEGER DEFAULT 0, " + + "CONSTRAINT moz_uniqueid UNIQUE (name, host, path, originAttributes)" + + ")" +); +conn.executeSimpleSQL( + "CREATE INDEX moz_basedomain ON moz_cookies (baseDomain, " + + "originAttributes)" +); conn.executeSimpleSQL("PRAGMA synchronous = OFF"); conn.executeSimpleSQL("PRAGMA journal_mode = WAL"); conn.executeSimpleSQL("PRAGMA wal_autocheckpoint = 16"); let now = Date.now(); -conn.executeSimpleSQL("INSERT INTO moz_cookies(" + - "baseDomain, host, name, value, path, expiry, " + - "lastAccessed, creationTime, isSecure, isHttpOnly) VALUES (" + - "'foo.com', '.foo.com', 'foo', 'bar=baz', '/', " + - now + ", " + now + ", " + now + ", 1, 1)"); +conn.executeSimpleSQL( + "INSERT INTO moz_cookies(" + + "baseDomain, host, name, value, path, expiry, " + + "lastAccessed, creationTime, isSecure, isHttpOnly) VALUES (" + + "'foo.com', '.foo.com', 'foo', 'bar=baz', '/', " + + now + + ", " + + now + + ", " + + now + + ", 1, 1)" +); // Now start the cookie service, and then check the fields in the table. // Get sessionEnumerator to wait for the initialization in cookie thread const enumerator = Services.cookies.sessionEnumerator; Assert.equal(conn.schemaVersion, 10); -let stmt = conn.createStatement("SELECT sql FROM sqlite_master " + - "WHERE type = 'table' AND " + - " name = 'moz_cookies'"); +let stmt = conn.createStatement( + "SELECT sql FROM sqlite_master " + + "WHERE type = 'table' AND " + + " name = 'moz_cookies'" +); try { Assert.ok(stmt.executeStep()); let sql = stmt.getString(0); @@ -61,17 +75,25 @@ try { stmt.finalize(); } -stmt = conn.createStatement("SELECT * FROM moz_cookies " + - "WHERE baseDomain = 'foo.com' AND " + - " host = '.foo.com' AND " + - " name = 'foo' AND " + - " value = 'bar=baz' AND " + - " path = '/' AND " + - " expiry = " + now + " AND " + - " lastAccessed = " + now + " AND " + - " creationTime = " + now + " AND " + - " isSecure = 1 AND " + - " isHttpOnly = 1"); +stmt = conn.createStatement( + "SELECT * FROM moz_cookies " + + "WHERE baseDomain = 'foo.com' AND " + + " host = '.foo.com' AND " + + " name = 'foo' AND " + + " value = 'bar=baz' AND " + + " path = '/' AND " + + " expiry = " + + now + + " AND " + + " lastAccessed = " + + now + + " AND " + + " creationTime = " + + now + + " AND " + + " isSecure = 1 AND " + + " isHttpOnly = 1" +); try { Assert.ok(stmt.executeStep()); } finally { diff --git a/netwerk/cookie/test/unit/test_bug643051.js b/netwerk/cookie/test/unit/test_bug643051.js index 349dfe236961..4deba3a91791 100644 --- a/netwerk/cookie/test/unit/test_bug643051.js +++ b/netwerk/cookie/test/unit/test_bug643051.js @@ -1,5 +1,5 @@ -const {NetUtil} = ChromeUtils.import("resource://gre/modules/NetUtil.jsm"); -const {Services} = ChromeUtils.import("resource://gre/modules/Services.jsm"); +const { NetUtil } = ChromeUtils.import("resource://gre/modules/NetUtil.jsm"); +const { Services } = ChromeUtils.import("resource://gre/modules/Services.jsm"); function run_test() { // Allow all cookies. @@ -23,4 +23,3 @@ function run_test() { actual = cs.getCookieString(uri, null, null); Assert.equal(actual, expected); } - diff --git a/netwerk/cookie/test/unit/test_eviction.js b/netwerk/cookie/test/unit/test_eviction.js index 86794d7ce5bf..1d93d04a4bf9 100644 --- a/netwerk/cookie/test/unit/test_eviction.js +++ b/netwerk/cookie/test/unit/test_eviction.js @@ -1,4 +1,4 @@ -const {Services} = ChromeUtils.import("resource://gre/modules/Services.jsm"); +const { Services } = ChromeUtils.import("resource://gre/modules/Services.jsm"); const BASE_HOSTNAMES = ["example.org", "example.co.uk"]; const SUBDOMAINS = ["", "pub.", "www.", "other."]; @@ -7,138 +7,178 @@ const cs = Cc["@mozilla.org/cookieService;1"].getService(Ci.nsICookieService); const cm = cs.QueryInterface(Ci.nsICookieManager); function run_test() { - Services.prefs.setIntPref("network.cookie.staleThreshold", 0); - add_task(async function() { - await test_basic_eviction("example.org"); - cm.removeAll(); - }); + Services.prefs.setIntPref("network.cookie.staleThreshold", 0); + add_task(async function() { + await test_basic_eviction("example.org"); + cm.removeAll(); + }); - run_next_test(); + run_next_test(); } async function test_basic_eviction(base_host) { - Services.prefs.setIntPref("network.cookie.quotaPerHost", 2); - Services.prefs.setIntPref("network.cookie.maxPerHost", 5); + Services.prefs.setIntPref("network.cookie.quotaPerHost", 2); + Services.prefs.setIntPref("network.cookie.maxPerHost", 5); - const BASE_URI = Services.io.newURI("http://" + base_host); - const FOO_PATH = Services.io.newURI("http://" + base_host + "/foo/"); - const BAR_PATH = Services.io.newURI("http://" + base_host + "/bar/"); + const BASE_URI = Services.io.newURI("http://" + base_host); + const FOO_PATH = Services.io.newURI("http://" + base_host + "/foo/"); + const BAR_PATH = Services.io.newURI("http://" + base_host + "/bar/"); - await setCookie("session_foo_path_1", null, "/foo", null, FOO_PATH); - await setCookie("session_foo_path_2", null, "/foo", null, FOO_PATH); - await setCookie("session_foo_path_3", null, "/foo", null, FOO_PATH); - await setCookie("session_foo_path_4", null, "/foo", null, FOO_PATH); - await setCookie("session_foo_path_5", null, "/foo", null, FOO_PATH); - verifyCookies(["session_foo_path_1", - "session_foo_path_2", - "session_foo_path_3", - "session_foo_path_4", - "session_foo_path_5"], BASE_URI); + await setCookie("session_foo_path_1", null, "/foo", null, FOO_PATH); + await setCookie("session_foo_path_2", null, "/foo", null, FOO_PATH); + await setCookie("session_foo_path_3", null, "/foo", null, FOO_PATH); + await setCookie("session_foo_path_4", null, "/foo", null, FOO_PATH); + await setCookie("session_foo_path_5", null, "/foo", null, FOO_PATH); + verifyCookies( + [ + "session_foo_path_1", + "session_foo_path_2", + "session_foo_path_3", + "session_foo_path_4", + "session_foo_path_5", + ], + BASE_URI + ); - // Check if cookies are evicted by creation time. - await setCookie("session_foo_path_6", null, "/foo", null, FOO_PATH); - verifyCookies(["session_foo_path_4", - "session_foo_path_5", - "session_foo_path_6"], BASE_URI); + // Check if cookies are evicted by creation time. + await setCookie("session_foo_path_6", null, "/foo", null, FOO_PATH); + verifyCookies( + ["session_foo_path_4", "session_foo_path_5", "session_foo_path_6"], + BASE_URI + ); - await setCookie("session_bar_path_1", null, "/bar", null, BAR_PATH); - await setCookie("session_bar_path_2", null, "/bar", null, BAR_PATH); + await setCookie("session_bar_path_1", null, "/bar", null, BAR_PATH); + await setCookie("session_bar_path_2", null, "/bar", null, BAR_PATH); - verifyCookies(["session_foo_path_4", - "session_foo_path_5", - "session_foo_path_6", - "session_bar_path_1", - "session_bar_path_2"], BASE_URI); + verifyCookies( + [ + "session_foo_path_4", + "session_foo_path_5", + "session_foo_path_6", + "session_bar_path_1", + "session_bar_path_2", + ], + BASE_URI + ); - // Check if cookies are evicted by last accessed time. - cs.getCookieString(FOO_PATH, null); - await setCookie("session_foo_path_7", null, "/foo", null, FOO_PATH); - verifyCookies(["session_foo_path_5", - "session_foo_path_6", - "session_foo_path_7"], BASE_URI); + // Check if cookies are evicted by last accessed time. + cs.getCookieString(FOO_PATH, null); + await setCookie("session_foo_path_7", null, "/foo", null, FOO_PATH); + verifyCookies( + ["session_foo_path_5", "session_foo_path_6", "session_foo_path_7"], + BASE_URI + ); - const EXPIRED_TIME = 3; + const EXPIRED_TIME = 3; - await setCookie("non_session_expired_foo_path_1", null, "/foo", EXPIRED_TIME, FOO_PATH); - await setCookie("non_session_expired_foo_path_2", null, "/foo", EXPIRED_TIME, FOO_PATH); - verifyCookies(["session_foo_path_5", - "session_foo_path_6", - "session_foo_path_7", - "non_session_expired_foo_path_1", - "non_session_expired_foo_path_2"], BASE_URI); + await setCookie( + "non_session_expired_foo_path_1", + null, + "/foo", + EXPIRED_TIME, + FOO_PATH + ); + await setCookie( + "non_session_expired_foo_path_2", + null, + "/foo", + EXPIRED_TIME, + FOO_PATH + ); + verifyCookies( + [ + "session_foo_path_5", + "session_foo_path_6", + "session_foo_path_7", + "non_session_expired_foo_path_1", + "non_session_expired_foo_path_2", + ], + BASE_URI + ); - // Check if expired cookies are evicted first. - await new Promise(resolve => do_timeout(EXPIRED_TIME * 1000, resolve)); - await setCookie("session_foo_path_8", null, "/foo", null, FOO_PATH); - verifyCookies(["session_foo_path_6", - "session_foo_path_7", - "session_foo_path_8"], BASE_URI); + // Check if expired cookies are evicted first. + await new Promise(resolve => do_timeout(EXPIRED_TIME * 1000, resolve)); + await setCookie("session_foo_path_8", null, "/foo", null, FOO_PATH); + verifyCookies( + ["session_foo_path_6", "session_foo_path_7", "session_foo_path_8"], + BASE_URI + ); } // Verify that the given cookie names exist, and are ordered from least to most recently accessed function verifyCookies(names, uri) { - Assert.equal(cm.countCookiesFromHost(uri.host), names.length); - let actual_cookies = []; - for (let cookie of cm.getCookiesFromHost(uri.host, {})) { - actual_cookies.push(cookie); - } - if (names.length != actual_cookies.length) { - let left = names.filter(function(n) { - return actual_cookies.findIndex(function(c) { - return c.name == n; - }) == -1; - }); - let right = actual_cookies.filter(function(c) { - return names.findIndex(function(n) { - return c.name == n; - }) == -1; - }).map(function(c) { return c.name; }); - if (left.length) { - info("unexpected cookies: " + left); - } - if (right.length) { - info("expected cookies: " + right); - } - } - Assert.equal(names.length, actual_cookies.length); - actual_cookies.sort(function(a, b) { - if (a.lastAccessed < b.lastAccessed) - return -1; - if (a.lastAccessed > b.lastAccessed) - return 1; - return 0; + Assert.equal(cm.countCookiesFromHost(uri.host), names.length); + let actual_cookies = []; + for (let cookie of cm.getCookiesFromHost(uri.host, {})) { + actual_cookies.push(cookie); + } + if (names.length != actual_cookies.length) { + let left = names.filter(function(n) { + return ( + actual_cookies.findIndex(function(c) { + return c.name == n; + }) == -1 + ); }); - for (var i = 0; i < names.length; i++) { - Assert.equal(names[i], actual_cookies[i].name); - Assert.equal(names[i].startsWith("session"), actual_cookies[i].isSession); + let right = actual_cookies + .filter(function(c) { + return ( + names.findIndex(function(n) { + return c.name == n; + }) == -1 + ); + }) + .map(function(c) { + return c.name; + }); + if (left.length) { + info("unexpected cookies: " + left); } + if (right.length) { + info("expected cookies: " + right); + } + } + Assert.equal(names.length, actual_cookies.length); + actual_cookies.sort(function(a, b) { + if (a.lastAccessed < b.lastAccessed) { + return -1; + } + if (a.lastAccessed > b.lastAccessed) { + return 1; + } + return 0; + }); + for (var i = 0; i < names.length; i++) { + Assert.equal(names[i], actual_cookies[i].name); + Assert.equal(names[i].startsWith("session"), actual_cookies[i].isSession); + } } var lastValue = 0; function setCookie(name, domain, path, maxAge, url) { - let value = name + "=" + ++lastValue; - var s = "setting cookie " + value; - if (domain) { - value += "; Domain=" + domain; - s += " (d=" + domain + ")"; - } - if (path) { - value += "; Path=" + path; - s += " (p=" + path + ")"; - } - if (maxAge) { - value += "; Max-Age=" + maxAge; - s += " (non-session)"; - } else { - s += " (session)"; - } - s += " for " + url.spec; - info(s); - cs.setCookieStringFromHttp(url, null, null, value, null, null); - return new Promise(function(resolve) { - // Windows XP has low precision timestamps that cause our cookie eviction - // algorithm to produce different results from other platforms. We work around - // this by ensuring that there's a clear gap between each cookie update. - do_timeout(10, resolve); - }); + let value = name + "=" + ++lastValue; + var s = "setting cookie " + value; + if (domain) { + value += "; Domain=" + domain; + s += " (d=" + domain + ")"; + } + if (path) { + value += "; Path=" + path; + s += " (p=" + path + ")"; + } + if (maxAge) { + value += "; Max-Age=" + maxAge; + s += " (non-session)"; + } else { + s += " (session)"; + } + s += " for " + url.spec; + info(s); + cs.setCookieStringFromHttp(url, null, null, value, null, null); + return new Promise(function(resolve) { + // Windows XP has low precision timestamps that cause our cookie eviction + // algorithm to produce different results from other platforms. We work around + // this by ensuring that there's a clear gap between each cookie update. + do_timeout(10, resolve); + }); } diff --git a/netwerk/cookie/test/unit/test_parser_0001.js b/netwerk/cookie/test/unit/test_parser_0001.js index 893a4a50d47a..40f70d01e138 100644 --- a/netwerk/cookie/test/unit/test_parser_0001.js +++ b/netwerk/cookie/test/unit/test_parser_0001.js @@ -1,5 +1,5 @@ -const {NetUtil} = ChromeUtils.import("resource://gre/modules/NetUtil.jsm"); -const {Services} = ChromeUtils.import("resource://gre/modules/Services.jsm"); +const { NetUtil } = ChromeUtils.import("resource://gre/modules/NetUtil.jsm"); +const { Services } = ChromeUtils.import("resource://gre/modules/Services.jsm"); function inChildProcess() { return Services.appinfo.processType != Ci.nsIXULRuntime.PROCESS_TYPE_DEFAULT; @@ -7,8 +7,9 @@ function inChildProcess() { function run_test() { // Allow all cookies if the pref service is available in this process. - if (!inChildProcess()) + if (!inChildProcess()) { Services.prefs.setIntPref("network.cookie.cookieBehavior", 0); + } let cs = Cc["@mozilla.org/cookieService;1"].getService(Ci.nsICookieService); @@ -21,4 +22,3 @@ function run_test() { let actual = cs.getCookieStringFromHttp(uri, null, null); Assert.equal(actual, expected); } - diff --git a/netwerk/cookie/test/unit/test_parser_0019.js b/netwerk/cookie/test/unit/test_parser_0019.js index 4c326e20c16a..d5fdc7946ae8 100644 --- a/netwerk/cookie/test/unit/test_parser_0019.js +++ b/netwerk/cookie/test/unit/test_parser_0019.js @@ -1,5 +1,5 @@ -const {NetUtil} = ChromeUtils.import("resource://gre/modules/NetUtil.jsm"); -const {Services} = ChromeUtils.import("resource://gre/modules/Services.jsm"); +const { NetUtil } = ChromeUtils.import("resource://gre/modules/NetUtil.jsm"); +const { Services } = ChromeUtils.import("resource://gre/modules/Services.jsm"); function inChildProcess() { return Services.appinfo.processType != Ci.nsIXULRuntime.PROCESS_TYPE_DEFAULT; @@ -7,8 +7,9 @@ function inChildProcess() { function run_test() { // Allow all cookies if the pref service is available in this process. - if (!inChildProcess()) + if (!inChildProcess()) { Services.prefs.setIntPref("network.cookie.cookieBehavior", 0); + } let cs = Cc["@mozilla.org/cookieService;1"].getService(Ci.nsICookieService); @@ -21,4 +22,3 @@ function run_test() { let actual = cs.getCookieStringFromHttp(uri, null, null); Assert.equal(actual, expected); } - diff --git a/netwerk/cookie/test/unit/test_rawSameSite.js b/netwerk/cookie/test/unit/test_rawSameSite.js index 70f5bd0af440..8aaac3a2aaf1 100644 --- a/netwerk/cookie/test/unit/test_rawSameSite.js +++ b/netwerk/cookie/test/unit/test_rawSameSite.js @@ -1,5 +1,5 @@ -const {NetUtil} = ChromeUtils.import("resource://gre/modules/NetUtil.jsm"); -const {Services} = ChromeUtils.import("resource://gre/modules/Services.jsm"); +const { NetUtil } = ChromeUtils.import("resource://gre/modules/NetUtil.jsm"); +const { Services } = ChromeUtils.import("resource://gre/modules/Services.jsm"); function inChildProcess() { return Services.appinfo.processType != Ci.nsIXULRuntime.PROCESS_TYPE_DEFAULT; @@ -12,14 +12,16 @@ add_task(async _ => { dbFile.append("cookies.sqlite"); let storage = Services.storage; - let properties = Cc["@mozilla.org/hash-property-bag;1"]. - createInstance(Ci.nsIWritablePropertyBag); + let properties = Cc["@mozilla.org/hash-property-bag;1"].createInstance( + Ci.nsIWritablePropertyBag + ); properties.setProperty("shared", true); let conn = storage.openDatabase(dbFile); conn.schemaVersion = 9; conn.executeSimpleSQL("DROP TABLE IF EXISTS moz_cookies"); - conn.executeSimpleSQL("CREATE TABLE moz_cookies (" + + conn.executeSimpleSQL( + "CREATE TABLE moz_cookies (" + "id INTEGER PRIMARY KEY, " + "baseDomain TEXT, " + "originAttributes TEXT NOT NULL DEFAULT '', " + @@ -35,22 +37,32 @@ add_task(async _ => { "inBrowserElement INTEGER DEFAULT 0, " + "sameSite INTEGER DEFAULT 0, " + "CONSTRAINT moz_uniqueid UNIQUE (name, host, path, originAttributes)" + - ")"); + ")" + ); conn.close(); // Allow all cookies if the pref service is available in this process. if (!inChildProcess()) { Services.prefs.setIntPref("network.cookie.cookieBehavior", 0); - Services.prefs.setBoolPref("network.cookieSettings.unblocked_for_testing", true); + Services.prefs.setBoolPref( + "network.cookieSettings.unblocked_for_testing", + true + ); Services.prefs.setBoolPref("network.cookie.sameSite.laxByDefault", true); - Services.prefs.setBoolPref("network.cookie.sameSite.noneRequiresSecure", true); + Services.prefs.setBoolPref( + "network.cookie.sameSite.noneRequiresSecure", + true + ); } let cs = Cc["@mozilla.org/cookieService;1"].getService(Ci.nsICookieService); let uri = NetUtil.newURI("http://example.org/"); - let principal = Services.scriptSecurityManager.createCodebasePrincipal(uri, {}); + let principal = Services.scriptSecurityManager.createCodebasePrincipal( + uri, + {} + ); let channel = NetUtil.newChannel({ uri, @@ -60,18 +72,17 @@ add_task(async _ => { }); let tests = [ - { cookie: "foo=b;max-age=3600, c=d;path=/; sameSite=strict", + { + cookie: "foo=b;max-age=3600, c=d;path=/; sameSite=strict", sameSite: 2, rawSameSite: 2, }, - { cookie: "foo=b;max-age=3600, c=d;path=/; sameSite=lax", + { + cookie: "foo=b;max-age=3600, c=d;path=/; sameSite=lax", sameSite: 1, rawSameSite: 1, }, - { cookie: "foo=b;max-age=3600, c=d;path=/", - sameSite: 1, - rawSameSite: 0, - }, + { cookie: "foo=b;max-age=3600, c=d;path=/", sameSite: 1, rawSameSite: 0 }, ]; for (let i = 0; i < tests.length; ++i) { @@ -93,7 +104,9 @@ add_task(async _ => { conn = storage.openDatabase(dbFile); Assert.equal(conn.schemaVersion, 10); - let stmt = conn.createStatement("SELECT sameSite, rawSameSite FROM moz_cookies"); + let stmt = conn.createStatement( + "SELECT sameSite, rawSameSite FROM moz_cookies" + ); let success = stmt.executeStep(); Assert.ok(success); diff --git a/netwerk/dns/mdns/libmdns/DNSServiceDiscovery.jsm b/netwerk/dns/mdns/libmdns/DNSServiceDiscovery.jsm index 8c5f82682e2b..2d9ff0a61353 100644 --- a/netwerk/dns/mdns/libmdns/DNSServiceDiscovery.jsm +++ b/netwerk/dns/mdns/libmdns/DNSServiceDiscovery.jsm @@ -3,23 +3,29 @@ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ "use strict"; -const {AppConstants} = ChromeUtils.import("resource://gre/modules/AppConstants.jsm"); -const {Services} = ChromeUtils.import("resource://gre/modules/Services.jsm"); +const { AppConstants } = ChromeUtils.import( + "resource://gre/modules/AppConstants.jsm" +); +const { Services } = ChromeUtils.import("resource://gre/modules/Services.jsm"); -const {MulticastDNS} = ChromeUtils.import( - (AppConstants.platform == "android" && !Services.prefs.getBoolPref("network.mdns.use_js_fallback")) - ? "resource://gre/modules/MulticastDNSAndroid.jsm" - : "resource://gre/modules/MulticastDNS.jsm"); +const { MulticastDNS } = ChromeUtils.import( + AppConstants.platform == "android" && + !Services.prefs.getBoolPref("network.mdns.use_js_fallback") + ? "resource://gre/modules/MulticastDNSAndroid.jsm" + : "resource://gre/modules/MulticastDNS.jsm" +); -const DNSSERVICEINFO_CONTRACT_ID = "@mozilla.org/toolkit/components/mdnsresponder/dns-info;1"; +const DNSSERVICEINFO_CONTRACT_ID = + "@mozilla.org/toolkit/components/mdnsresponder/dns-info;1"; function log(aMsg) { dump("-*- nsDNSServiceDiscovery.js : " + aMsg + "\n"); } function generateUuid() { - var uuidGenerator = Cc["@mozilla.org/uuid-generator;1"]. - getService(Ci.nsIUUIDGenerator); + var uuidGenerator = Cc["@mozilla.org/uuid-generator;1"].getService( + Ci.nsIUUIDGenerator + ); return uuidGenerator.generateUUID().toString(); } @@ -40,9 +46,17 @@ function ListenerWrapper(aListener, aMdns) { ListenerWrapper.prototype = { // Helper function for transforming an Object into nsIDNSServiceInfo. makeServiceInfo(aServiceInfo) { - let serviceInfo = Cc[DNSSERVICEINFO_CONTRACT_ID].createInstance(Ci.nsIDNSServiceInfo); + let serviceInfo = Cc[DNSSERVICEINFO_CONTRACT_ID].createInstance( + Ci.nsIDNSServiceInfo + ); - for (let name of ["host", "address", "port", "serviceName", "serviceType"]) { + for (let name of [ + "host", + "address", + "port", + "serviceName", + "serviceType", + ]) { try { serviceInfo[name] = aServiceInfo[name]; } catch (e) { @@ -54,10 +68,11 @@ ListenerWrapper.prototype = { try { attributes = _toPropertyBag2(aServiceInfo.attributes); } catch (err) { - // Ignore unset attributes in object. - log("Caught unset attributes error: " + err + " - " + err.stack); - attributes = Cc["@mozilla.org/hash-property-bag;1"] - .createInstance(Ci.nsIWritablePropertyBag2); + // Ignore unset attributes in object. + log("Caught unset attributes error: " + err + " - " + err.stack); + attributes = Cc["@mozilla.org/hash-property-bag;1"].createInstance( + Ci.nsIWritablePropertyBag2 + ); } serviceInfo.attributes = attributes; @@ -113,15 +128,24 @@ ListenerWrapper.prototype = { log("onRegistrationFailed: (" + aErrorCode + ")"); this.registrationStarting = false; this.stopRegistration = true; - this.listener.onRegistrationFailed(this.makeServiceInfo(aServiceInfo), aErrorCode); + this.listener.onRegistrationFailed( + this.makeServiceInfo(aServiceInfo), + aErrorCode + ); }, onUnregistrationFailed(aServiceInfo, aErrorCode) { log("onUnregistrationFailed: (" + aErrorCode + ")"); - this.listener.onUnregistrationFailed(this.makeServiceInfo(aServiceInfo), aErrorCode); + this.listener.onUnregistrationFailed( + this.makeServiceInfo(aServiceInfo), + aErrorCode + ); }, onResolveFailed(aServiceInfo, aErrorCode) { log("onResolveFailed: (" + aErrorCode + ")"); - this.listener.onResolveFailed(this.makeServiceInfo(aServiceInfo), aErrorCode); + this.listener.onResolveFailed( + this.makeServiceInfo(aServiceInfo), + aErrorCode + ); }, }; @@ -131,7 +155,10 @@ function nsDNSServiceDiscovery() { } nsDNSServiceDiscovery.prototype = { - QueryInterface: ChromeUtils.generateQI([Ci.nsISupportsWeakReference, Ci.nsIDNSServiceDiscovery]), + QueryInterface: ChromeUtils.generateQI([ + Ci.nsISupportsWeakReference, + Ci.nsIDNSServiceDiscovery, + ]), startDiscovery(aServiceType, aListener) { log("startDiscovery"); @@ -141,13 +168,13 @@ nsDNSServiceDiscovery.prototype = { return { QueryInterface: ChromeUtils.generateQI([Ci.nsICancelable]), - cancel: (function() { + cancel: function() { if (this.discoveryStarting || this.stopDiscovery) { this.stopDiscovery = true; return; } this.mdns.stopDiscovery(aServiceType, listener); - }).bind(listener), + }.bind(listener), }; }, @@ -159,13 +186,13 @@ nsDNSServiceDiscovery.prototype = { return { QueryInterface: ChromeUtils.generateQI([Ci.nsICancelable]), - cancel: (function() { + cancel: function() { if (this.registrationStarting || this.stopRegistration) { this.stopRegistration = true; return; } this.mdns.unregisterService(aServiceInfo, listener); - }).bind(listener), + }.bind(listener), }; }, @@ -182,8 +209,9 @@ function _toPropertyBag2(obj) { return obj.QueryInterface(Ci.nsIPropertyBag2); } - let result = Cc["@mozilla.org/hash-property-bag;1"] - .createInstance(Ci.nsIWritablePropertyBag2); + let result = Cc["@mozilla.org/hash-property-bag;1"].createInstance( + Ci.nsIWritablePropertyBag2 + ); for (let name in obj) { result.setPropertyAsAString(name, obj[name]); } diff --git a/netwerk/dns/mdns/libmdns/MulticastDNSAndroid.jsm b/netwerk/dns/mdns/libmdns/MulticastDNSAndroid.jsm index 15ed99018ba8..8737f33eca7e 100644 --- a/netwerk/dns/mdns/libmdns/MulticastDNSAndroid.jsm +++ b/netwerk/dns/mdns/libmdns/MulticastDNSAndroid.jsm @@ -7,14 +7,18 @@ var EXPORTED_SYMBOLS = ["MulticastDNS"]; -const {EventDispatcher} = ChromeUtils.import("resource://gre/modules/Messaging.jsm"); +const { EventDispatcher } = ChromeUtils.import( + "resource://gre/modules/Messaging.jsm" +); const DEBUG = false; var log = function(s) {}; if (DEBUG) { - log = ChromeUtils.import("resource://gre/modules/AndroidLog.jsm", {}) - .AndroidLog.d.bind(null, "MulticastDNS"); + log = ChromeUtils.import( + "resource://gre/modules/AndroidLog.jsm", + {} + ).AndroidLog.d.bind(null, "MulticastDNS"); } const FAILURE_INTERNAL_ERROR = -65537; @@ -28,18 +32,20 @@ function send(type, data, callback) { for (let i in data) { try { msg[i] = data[i]; - } catch (e) { - } + } catch (e) {} } - EventDispatcher.instance.sendRequestForResult(msg) - .then(result => callback(result, null), - err => callback(null, typeof err === "number" ? err : FAILURE_INTERNAL_ERROR)); + EventDispatcher.instance + .sendRequestForResult(msg) + .then( + result => callback(result, null), + err => + callback(null, typeof err === "number" ? err : FAILURE_INTERNAL_ERROR) + ); } // Receives service found/lost event from NsdManager -function ServiceManager() { -} +function ServiceManager() {} ServiceManager.prototype = { listeners: {}, @@ -145,11 +151,11 @@ function parsePropertyBag2(bag) { } let attributes = []; - for (let {name} of bag.enumerator) { + for (let { name } of bag.enumerator) { let value = bag.getPropertyAsACString(name); attributes.push({ - "name": name, - "value": value, + name, + value, }); } diff --git a/netwerk/dns/mdns/libmdns/fallback/DNSPacket.jsm b/netwerk/dns/mdns/libmdns/fallback/DNSPacket.jsm index d40f0d8a9d2c..1f0ce675aa89 100644 --- a/netwerk/dns/mdns/libmdns/fallback/DNSPacket.jsm +++ b/netwerk/dns/mdns/libmdns/fallback/DNSPacket.jsm @@ -8,12 +8,20 @@ var EXPORTED_SYMBOLS = ["DNSPacket"]; -const {Services} = ChromeUtils.import("resource://gre/modules/Services.jsm"); +const { Services } = ChromeUtils.import("resource://gre/modules/Services.jsm"); -const {DataReader} = ChromeUtils.import("resource://gre/modules/DataReader.jsm"); -const {DataWriter} = ChromeUtils.import("resource://gre/modules/DataWriter.jsm"); -const {DNSRecord} = ChromeUtils.import("resource://gre/modules/DNSRecord.jsm"); -const {DNSResourceRecord} = ChromeUtils.import("resource://gre/modules/DNSResourceRecord.jsm"); +const { DataReader } = ChromeUtils.import( + "resource://gre/modules/DataReader.jsm" +); +const { DataWriter } = ChromeUtils.import( + "resource://gre/modules/DataWriter.jsm" +); +const { DNSRecord } = ChromeUtils.import( + "resource://gre/modules/DNSRecord.jsm" +); +const { DNSResourceRecord } = ChromeUtils.import( + "resource://gre/modules/DNSResourceRecord.jsm" +); const DEBUG = true; @@ -25,7 +33,7 @@ let DNS_PACKET_SECTION_TYPES = [ "QD", // Question "AN", // Answer "NS", // Authority - "AR", // Additional + "AR", // Additional ]; /** @@ -125,7 +133,7 @@ class DNSPacket { this._flags = _valueToFlags(0x0000); this._records = {}; - DNS_PACKET_SECTION_TYPES.forEach((sectionType) => { + DNS_PACKET_SECTION_TYPES.forEach(sectionType => { this._records[sectionType] = []; }); } @@ -142,20 +150,24 @@ class DNSPacket { let recordCounts = {}; // Parse the record counts. - DNS_PACKET_SECTION_TYPES.forEach((sectionType) => { + DNS_PACKET_SECTION_TYPES.forEach(sectionType => { recordCounts[sectionType] = reader.getValue(2); }); // Parse the actual records. - DNS_PACKET_SECTION_TYPES.forEach((sectionType) => { + DNS_PACKET_SECTION_TYPES.forEach(sectionType => { let recordCount = recordCounts[sectionType]; for (let i = 0; i < recordCount; i++) { if (sectionType === "QD") { - packet.addRecord(sectionType, - DNSRecord.parseFromPacketReader(reader)); + packet.addRecord( + sectionType, + DNSRecord.parseFromPacketReader(reader) + ); } else { - packet.addRecord(sectionType, - DNSResourceRecord.parseFromPacketReader(reader)); + packet.addRecord( + sectionType, + DNSResourceRecord.parseFromPacketReader(reader) + ); } } }); @@ -182,7 +194,7 @@ class DNSPacket { getRecords(sectionTypes, recordType) { let records = []; - sectionTypes.forEach((sectionType) => { + sectionTypes.forEach(sectionType => { records = records.concat(this._records[sectionType]); }); @@ -203,13 +215,13 @@ class DNSPacket { writer.putValue(_flagsToValue(this._flags), 2); // Write lengths of record sections (2 bytes each) - DNS_PACKET_SECTION_TYPES.forEach((sectionType) => { + DNS_PACKET_SECTION_TYPES.forEach(sectionType => { writer.putValue(this._records[sectionType].length, 2); }); // Write records - DNS_PACKET_SECTION_TYPES.forEach((sectionType) => { - this._records[sectionType].forEach((record) => { + DNS_PACKET_SECTION_TYPES.forEach(sectionType => { + this._records[sectionType].forEach(record => { writer.putBytes(record.serialize()); }); }); @@ -222,12 +234,12 @@ class DNSPacket { } toJSONObject() { - let result = {flags: this._flags}; - DNS_PACKET_SECTION_TYPES.forEach((sectionType) => { + let result = { flags: this._flags }; + DNS_PACKET_SECTION_TYPES.forEach(sectionType => { result[sectionType] = []; let records = this._records[sectionType]; - records.forEach((record) => { + records.forEach(record => { result[sectionType].push(record.toJSONObject()); }); }); diff --git a/netwerk/dns/mdns/libmdns/fallback/DNSRecord.jsm b/netwerk/dns/mdns/libmdns/fallback/DNSRecord.jsm index 43662f940065..68a6b1af4153 100644 --- a/netwerk/dns/mdns/libmdns/fallback/DNSRecord.jsm +++ b/netwerk/dns/mdns/libmdns/fallback/DNSRecord.jsm @@ -8,22 +8,26 @@ var EXPORTED_SYMBOLS = ["DNSRecord"]; -const {DataWriter} = ChromeUtils.import("resource://gre/modules/DataWriter.jsm"); -const {DNS_CLASS_CODES, DNS_RECORD_TYPES} = ChromeUtils.import("resource://gre/modules/DNSTypes.jsm"); +const { DataWriter } = ChromeUtils.import( + "resource://gre/modules/DataWriter.jsm" +); +const { DNS_CLASS_CODES, DNS_RECORD_TYPES } = ChromeUtils.import( + "resource://gre/modules/DNSTypes.jsm" +); class DNSRecord { constructor(properties = {}) { - this.name = properties.name || ""; + this.name = properties.name || ""; this.recordType = properties.recordType || DNS_RECORD_TYPES.ANY; - this.classCode = properties.classCode || DNS_CLASS_CODES.IN; + this.classCode = properties.classCode || DNS_CLASS_CODES.IN; this.cacheFlush = properties.cacheFlush || false; } static parseFromPacketReader(reader) { - let name = reader.getLabel(); + let name = reader.getLabel(); let recordType = reader.getValue(2); - let classCode = reader.getValue(2); - let cacheFlush = !!((classCode & 0x8000)); + let classCode = reader.getValue(2); + let cacheFlush = !!(classCode & 0x8000); classCode &= 0xff; return new this({ diff --git a/netwerk/dns/mdns/libmdns/fallback/DNSResourceRecord.jsm b/netwerk/dns/mdns/libmdns/fallback/DNSResourceRecord.jsm index a4094abfa2b2..c67a351df60c 100644 --- a/netwerk/dns/mdns/libmdns/fallback/DNSResourceRecord.jsm +++ b/netwerk/dns/mdns/libmdns/fallback/DNSResourceRecord.jsm @@ -8,10 +8,18 @@ var EXPORTED_SYMBOLS = ["DNSResourceRecord"]; -const {DataReader} = ChromeUtils.import("resource://gre/modules/DataReader.jsm"); -const {DataWriter} = ChromeUtils.import("resource://gre/modules/DataWriter.jsm"); -const {DNSRecord} = ChromeUtils.import("resource://gre/modules/DNSRecord.jsm"); -const {DNS_RECORD_TYPES} = ChromeUtils.import("resource://gre/modules/DNSTypes.jsm"); +const { DataReader } = ChromeUtils.import( + "resource://gre/modules/DataReader.jsm" +); +const { DataWriter } = ChromeUtils.import( + "resource://gre/modules/DataWriter.jsm" +); +const { DNSRecord } = ChromeUtils.import( + "resource://gre/modules/DNSRecord.jsm" +); +const { DNS_RECORD_TYPES } = ChromeUtils.import( + "resource://gre/modules/DNSTypes.jsm" +); const DNS_RESOURCE_RECORD_DEFAULT_TTL = 120; // 120 seconds @@ -19,14 +27,14 @@ class DNSResourceRecord extends DNSRecord { constructor(properties = {}) { super(properties); - this.ttl = properties.ttl || DNS_RESOURCE_RECORD_DEFAULT_TTL; + this.ttl = properties.ttl || DNS_RESOURCE_RECORD_DEFAULT_TTL; this.data = properties.data || {}; } static parseFromPacketReader(reader) { let record = super.parseFromPacketReader(reader); - let ttl = reader.getValue(4); + let ttl = reader.getValue(4); let recordData = reader.getBytes(reader.getValue(2)); let packetData = reader.data; @@ -50,7 +58,7 @@ class DNSResourceRecord extends DNSRecord { break; } - record.ttl = ttl; + record.ttl = ttl; record.data = data; return record; @@ -137,7 +145,7 @@ function _parseTXT(recordData, packetData) { let label = reader.getLabel(packetData); if (label.length > 0) { let parts = label.split("."); - parts.forEach((part) => { + parts.forEach(part => { let [name] = part.split("=", 1); let value = part.substr(name.length + 1); result[name] = value; @@ -154,9 +162,9 @@ function _parseSRV(recordData, packetData) { let reader = new DataReader(recordData); let priority = reader.getValue(2); - let weight = reader.getValue(2); - let port = reader.getValue(2); - let target = reader.getLabel(packetData); + let weight = reader.getValue(2); + let port = reader.getValue(2); + let target = reader.getLabel(packetData); return { priority, weight, port, target }; } diff --git a/netwerk/dns/mdns/libmdns/fallback/DNSTypes.jsm b/netwerk/dns/mdns/libmdns/fallback/DNSTypes.jsm index 37e0fa375472..1186c9abeb41 100644 --- a/netwerk/dns/mdns/libmdns/fallback/DNSTypes.jsm +++ b/netwerk/dns/mdns/libmdns/fallback/DNSTypes.jsm @@ -14,87 +14,87 @@ var EXPORTED_SYMBOLS = [ ]; let DNS_QUERY_RESPONSE_CODES = { - QUERY: 0, // RFC 1035 - Query - RESPONSE: 1, // RFC 1035 - Reponse + QUERY: 0, // RFC 1035 - Query + RESPONSE: 1, // RFC 1035 - Reponse }; let DNS_AUTHORITATIVE_ANSWER_CODES = { - NO: 0, // RFC 1035 - Not Authoritative - YES: 1, // RFC 1035 - Is Authoritative + NO: 0, // RFC 1035 - Not Authoritative + YES: 1, // RFC 1035 - Is Authoritative }; let DNS_CLASS_CODES = { - IN: 0x01, // RFC 1035 - Internet - CS: 0x02, // RFC 1035 - CSNET - CH: 0x03, // RFC 1035 - CHAOS - HS: 0x04, // RFC 1035 - Hesiod - NONE: 0xfe, // RFC 2136 - None - ANY: 0xff, // RFC 1035 - Any + IN: 0x01, // RFC 1035 - Internet + CS: 0x02, // RFC 1035 - CSNET + CH: 0x03, // RFC 1035 - CHAOS + HS: 0x04, // RFC 1035 - Hesiod + NONE: 0xfe, // RFC 2136 - None + ANY: 0xff, // RFC 1035 - Any }; let DNS_RECORD_TYPES = { - SIGZERO: 0, // RFC 2931 - A: 1, // RFC 1035 - NS: 2, // RFC 1035 - MD: 3, // RFC 1035 - MF: 4, // RFC 1035 - CNAME: 5, // RFC 1035 - SOA: 6, // RFC 1035 - MB: 7, // RFC 1035 - MG: 8, // RFC 1035 - MR: 9, // RFC 1035 - NULL: 10, // RFC 1035 - WKS: 11, // RFC 1035 - PTR: 12, // RFC 1035 - HINFO: 13, // RFC 1035 - MINFO: 14, // RFC 1035 - MX: 15, // RFC 1035 - TXT: 16, // RFC 1035 - RP: 17, // RFC 1183 - AFSDB: 18, // RFC 1183 - X25: 19, // RFC 1183 - ISDN: 20, // RFC 1183 - RT: 21, // RFC 1183 - NSAP: 22, // RFC 1706 - NSAP_PTR: 23, // RFC 1348 - SIG: 24, // RFC 2535 - KEY: 25, // RFC 2535 - PX: 26, // RFC 2163 - GPOS: 27, // RFC 1712 - AAAA: 28, // RFC 1886 - LOC: 29, // RFC 1876 - NXT: 30, // RFC 2535 - EID: 31, // RFC ???? - NIMLOC: 32, // RFC ???? - SRV: 33, // RFC 2052 - ATMA: 34, // RFC ???? - NAPTR: 35, // RFC 2168 - KX: 36, // RFC 2230 - CERT: 37, // RFC 2538 - DNAME: 39, // RFC 2672 - OPT: 41, // RFC 2671 - APL: 42, // RFC 3123 - DS: 43, // RFC 4034 - SSHFP: 44, // RFC 4255 - IPSECKEY: 45, // RFC 4025 - RRSIG: 46, // RFC 4034 - NSEC: 47, // RFC 4034 - DNSKEY: 48, // RFC 4034 - DHCID: 49, // RFC 4701 - NSEC3: 50, // RFC ???? - NSEC3PARAM: 51, // RFC ???? - HIP: 55, // RFC 5205 - SPF: 99, // RFC 4408 - UINFO: 100, // RFC ???? - UID: 101, // RFC ???? - GID: 102, // RFC ???? - UNSPEC: 103, // RFC ???? - TKEY: 249, // RFC 2930 - TSIG: 250, // RFC 2931 - IXFR: 251, // RFC 1995 - AXFR: 252, // RFC 1035 - MAILB: 253, // RFC 1035 - MAILA: 254, // RFC 1035 - ANY: 255, // RFC 1035 - DLV: 32769, // RFC 4431 + SIGZERO: 0, // RFC 2931 + A: 1, // RFC 1035 + NS: 2, // RFC 1035 + MD: 3, // RFC 1035 + MF: 4, // RFC 1035 + CNAME: 5, // RFC 1035 + SOA: 6, // RFC 1035 + MB: 7, // RFC 1035 + MG: 8, // RFC 1035 + MR: 9, // RFC 1035 + NULL: 10, // RFC 1035 + WKS: 11, // RFC 1035 + PTR: 12, // RFC 1035 + HINFO: 13, // RFC 1035 + MINFO: 14, // RFC 1035 + MX: 15, // RFC 1035 + TXT: 16, // RFC 1035 + RP: 17, // RFC 1183 + AFSDB: 18, // RFC 1183 + X25: 19, // RFC 1183 + ISDN: 20, // RFC 1183 + RT: 21, // RFC 1183 + NSAP: 22, // RFC 1706 + NSAP_PTR: 23, // RFC 1348 + SIG: 24, // RFC 2535 + KEY: 25, // RFC 2535 + PX: 26, // RFC 2163 + GPOS: 27, // RFC 1712 + AAAA: 28, // RFC 1886 + LOC: 29, // RFC 1876 + NXT: 30, // RFC 2535 + EID: 31, // RFC ???? + NIMLOC: 32, // RFC ???? + SRV: 33, // RFC 2052 + ATMA: 34, // RFC ???? + NAPTR: 35, // RFC 2168 + KX: 36, // RFC 2230 + CERT: 37, // RFC 2538 + DNAME: 39, // RFC 2672 + OPT: 41, // RFC 2671 + APL: 42, // RFC 3123 + DS: 43, // RFC 4034 + SSHFP: 44, // RFC 4255 + IPSECKEY: 45, // RFC 4025 + RRSIG: 46, // RFC 4034 + NSEC: 47, // RFC 4034 + DNSKEY: 48, // RFC 4034 + DHCID: 49, // RFC 4701 + NSEC3: 50, // RFC ???? + NSEC3PARAM: 51, // RFC ???? + HIP: 55, // RFC 5205 + SPF: 99, // RFC 4408 + UINFO: 100, // RFC ???? + UID: 101, // RFC ???? + GID: 102, // RFC ???? + UNSPEC: 103, // RFC ???? + TKEY: 249, // RFC 2930 + TSIG: 250, // RFC 2931 + IXFR: 251, // RFC 1995 + AXFR: 252, // RFC 1035 + MAILB: 253, // RFC 1035 + MAILA: 254, // RFC 1035 + ANY: 255, // RFC 1035 + DLV: 32769, // RFC 4431 }; diff --git a/netwerk/dns/mdns/libmdns/fallback/DataReader.jsm b/netwerk/dns/mdns/libmdns/fallback/DataReader.jsm index 4f3b0f525d64..bb070c8edf0f 100644 --- a/netwerk/dns/mdns/libmdns/fallback/DataReader.jsm +++ b/netwerk/dns/mdns/libmdns/fallback/DataReader.jsm @@ -105,7 +105,9 @@ function _uint8ArrayToString(uint8Array) { let results = []; for (let i = 0; i < length; i += 1024) { - results.push(String.fromCharCode.apply(null, uint8Array.subarray(i, i + 1024))); + results.push( + String.fromCharCode.apply(null, uint8Array.subarray(i, i + 1024)) + ); } return results.join(""); diff --git a/netwerk/dns/mdns/libmdns/fallback/DataWriter.jsm b/netwerk/dns/mdns/libmdns/fallback/DataWriter.jsm index eb2c202c41f6..9188d2865419 100644 --- a/netwerk/dns/mdns/libmdns/fallback/DataWriter.jsm +++ b/netwerk/dns/mdns/libmdns/fallback/DataWriter.jsm @@ -66,7 +66,7 @@ class DataWriter { // Eliminate any trailing '.'s in the label (valid in text representation). label = label.replace(/\.$/, ""); let parts = label.split("."); - parts.forEach((part) => { + parts.forEach(part => { this.putLengthString(part); }); this.putValue(0); @@ -74,7 +74,7 @@ class DataWriter { putLengthString(string) { if (string.length > 0xff) { - throw new Error("String too long."); + throw new Error("String too long."); } this.putValue(string.length); for (let i = 0; i < string.length; i++) { diff --git a/netwerk/dns/mdns/libmdns/fallback/MulticastDNS.jsm b/netwerk/dns/mdns/libmdns/fallback/MulticastDNS.jsm index a117bcb41078..24349ccb6d7d 100644 --- a/netwerk/dns/mdns/libmdns/fallback/MulticastDNS.jsm +++ b/netwerk/dns/mdns/libmdns/fallback/MulticastDNS.jsm @@ -8,33 +8,56 @@ var EXPORTED_SYMBOLS = ["MulticastDNS"]; -const {Services} = ChromeUtils.import("resource://gre/modules/Services.jsm"); -const {clearTimeout, setTimeout} = ChromeUtils.import("resource://gre/modules/Timer.jsm"); +const { Services } = ChromeUtils.import("resource://gre/modules/Services.jsm"); +const { clearTimeout, setTimeout } = ChromeUtils.import( + "resource://gre/modules/Timer.jsm" +); -const {DNSPacket} = ChromeUtils.import("resource://gre/modules/DNSPacket.jsm"); -const {DNSRecord} = ChromeUtils.import("resource://gre/modules/DNSRecord.jsm"); -const {DNSResourceRecord} = ChromeUtils.import("resource://gre/modules/DNSResourceRecord.jsm"); -const {DNS_AUTHORITATIVE_ANSWER_CODES, DNS_CLASS_CODES, DNS_QUERY_RESPONSE_CODES, DNS_RECORD_TYPES} = ChromeUtils.import("resource://gre/modules/DNSTypes.jsm"); +const { DNSPacket } = ChromeUtils.import( + "resource://gre/modules/DNSPacket.jsm" +); +const { DNSRecord } = ChromeUtils.import( + "resource://gre/modules/DNSRecord.jsm" +); +const { DNSResourceRecord } = ChromeUtils.import( + "resource://gre/modules/DNSResourceRecord.jsm" +); +const { + DNS_AUTHORITATIVE_ANSWER_CODES, + DNS_CLASS_CODES, + DNS_QUERY_RESPONSE_CODES, + DNS_RECORD_TYPES, +} = ChromeUtils.import("resource://gre/modules/DNSTypes.jsm"); const NS_NETWORK_LINK_TOPIC = "network:link-status-changed"; -let networkInfoService = Cc["@mozilla.org/network-info-service;1"] - .createInstance(Ci.nsINetworkInfoService); +let networkInfoService = Cc[ + "@mozilla.org/network-info-service;1" +].createInstance(Ci.nsINetworkInfoService); const DEBUG = true; const MDNS_MULTICAST_GROUP = "224.0.0.251"; -const MDNS_PORT = 5353; -const DEFAULT_TTL = 120; +const MDNS_PORT = 5353; +const DEFAULT_TTL = 120; function debug(msg) { dump("MulticastDNS: " + msg + "\n"); } function ServiceKey(svc) { - return "" + svc.serviceType.length + "/" + svc.serviceType + "|" + - svc.serviceName.length + "/" + svc.serviceName + "|" + - svc.port; + return ( + "" + + svc.serviceType.length + + "/" + + svc.serviceType + + "|" + + svc.serviceName.length + + "/" + + svc.serviceName + + "|" + + svc.port + ); } function TryGet(obj, name) { @@ -77,9 +100,11 @@ class PublishedService { } equals(svc) { - return (this.port == svc.port) && - (this.serviceName == svc.serviceName) && - (this.serviceType == svc.serviceType); + return ( + this.port == svc.port && + this.serviceName == svc.serviceName && + this.serviceType == svc.serviceType + ); } generateKey() { @@ -87,7 +112,7 @@ class PublishedService { } ptrMatch(name) { - return name == (this.serviceType + "." + this.domainName); + return name == this.serviceType + "." + this.domainName; } clearAdvertiseTimer() { @@ -101,17 +126,23 @@ class PublishedService { class MulticastDNS { constructor() { - this._listeners = new Map(); - this._sockets = new Map(); - this._services = new Map(); - this._discovered = new Map(); - this._querySocket = undefined; + this._listeners = new Map(); + this._sockets = new Map(); + this._services = new Map(); + this._discovered = new Map(); + this._querySocket = undefined; this._broadcastReceiverSocket = undefined; - this._broadcastTimer = undefined; + this._broadcastTimer = undefined; this._networkLinkObserver = { observe: (subject, topic, data) => { - DEBUG && debug(NS_NETWORK_LINK_TOPIC + "(" + data + "); Clearing list of previously discovered services"); + DEBUG && + debug( + NS_NETWORK_LINK_TOPIC + + "(" + + data + + "); Clearing list of previously discovered services" + ); this._discovered.clear(); }, }; @@ -124,7 +155,10 @@ class MulticastDNS { if (!this._isNetworkLinkObserverAttached) { DEBUG && debug("Attaching observer " + NS_NETWORK_LINK_TOPIC); - Services.obs.addObserver(this._networkLinkObserver, NS_NETWORK_LINK_TOPIC); + Services.obs.addObserver( + this._networkLinkObserver, + NS_NETWORK_LINK_TOPIC + ); this._isNetworkLinkObserverAttached = true; } } @@ -137,7 +171,10 @@ class MulticastDNS { this._networkLinkObserverTimeout = setTimeout(() => { DEBUG && debug("Detaching observer " + NS_NETWORK_LINK_TOPIC); - Services.obs.removeObserver(this._networkLinkObserver, NS_NETWORK_LINK_TOPIC); + Services.obs.removeObserver( + this._networkLinkObserver, + NS_NETWORK_LINK_TOPIC + ); this._isNetworkLinkObserverAttached = false; this._networkLinkObserverTimeout = null; }, 5000); @@ -199,22 +236,32 @@ class MulticastDNS { try { publishedService = new PublishedService(aServiceInfo); } catch (e) { - DEBUG && debug("Error constructing PublishedService: " + e + " - " + e.stack); - setTimeout(() => aListener.onRegistrationFailed(aServiceInfo, Cr.NS_ERROR_FAILURE)); + DEBUG && + debug("Error constructing PublishedService: " + e + " - " + e.stack); + setTimeout(() => + aListener.onRegistrationFailed(aServiceInfo, Cr.NS_ERROR_FAILURE) + ); return; } // Ensure such a service does not already exist. if (this._services.get(publishedService.key)) { - setTimeout(() => aListener.onRegistrationFailed(aServiceInfo, Cr.NS_ERROR_FAILURE)); + setTimeout(() => + aListener.onRegistrationFailed(aServiceInfo, Cr.NS_ERROR_FAILURE) + ); return; } // Make sure that the service addr is '0.0.0.0', or there is at least one // socket open on the address the service is open on. - this._getSockets().then((sockets) => { - if (publishedService.address != "0.0.0.0" && !sockets.get(publishedService.address)) { - setTimeout(() => aListener.onRegistrationFailed(aServiceInfo, Cr.NS_ERROR_FAILURE)); + this._getSockets().then(sockets => { + if ( + publishedService.address != "0.0.0.0" && + !sockets.get(publishedService.address) + ) { + setTimeout(() => + aListener.onRegistrationFailed(aServiceInfo, Cr.NS_ERROR_FAILURE) + ); return; } @@ -237,13 +284,17 @@ class MulticastDNS { try { serviceKey = ServiceKey(aServiceInfo); } catch (e) { - setTimeout(() => aListener.onUnregistrationFailed(aServiceInfo, Cr.NS_ERROR_FAILURE)); + setTimeout(() => + aListener.onUnregistrationFailed(aServiceInfo, Cr.NS_ERROR_FAILURE) + ); return; } let publishedService = this._services.get(serviceKey); if (!publishedService) { - setTimeout(() => aListener.onUnregistrationFailed(aServiceInfo, Cr.NS_ERROR_FAILURE)); + setTimeout(() => + aListener.onUnregistrationFailed(aServiceInfo, Cr.NS_ERROR_FAILURE) + ); return; } @@ -252,7 +303,9 @@ class MulticastDNS { // Delete the service from the service map. if (!this._services.delete(serviceKey)) { - setTimeout(() => aListener.onUnregistrationFailed(aServiceInfo, Cr.NS_ERROR_FAILURE)); + setTimeout(() => + aListener.onUnregistrationFailed(aServiceInfo, Cr.NS_ERROR_FAILURE) + ); return; } @@ -268,8 +321,15 @@ class MulticastDNS { _respondToQuery(serviceKey, message) { let address = message.fromAddr.address; let port = message.fromAddr.port; - DEBUG && debug("_respondToQuery(): key=" + serviceKey + ", fromAddr=" - + address + ":" + port); + DEBUG && + debug( + "_respondToQuery(): key=" + + serviceKey + + ", fromAddr=" + + address + + ":" + + port + ); let publishedService = this._services.get(serviceKey); if (!publishedService) { @@ -277,15 +337,20 @@ class MulticastDNS { return; } - DEBUG && debug("_respondToQuery(): key=" + serviceKey + ": SENDING RESPONSE"); - this._advertiseServiceHelper(publishedService, {address, port}); + DEBUG && + debug("_respondToQuery(): key=" + serviceKey + ": SENDING RESPONSE"); + this._advertiseServiceHelper(publishedService, { address, port }); } _advertiseService(serviceKey, firstAdv) { DEBUG && debug("_advertiseService(): key=" + serviceKey); let publishedService = this._services.get(serviceKey); if (!publishedService) { - debug("_advertiseService Could not find service to advertise (key=" + serviceKey + ")"); + debug( + "_advertiseService Could not find service to advertise (key=" + + serviceKey + + ")" + ); return; } @@ -307,10 +372,10 @@ class MulticastDNS { _advertiseServiceHelper(svc, target) { if (!target) { - target = {address: MDNS_MULTICAST_GROUP, port: MDNS_PORT}; + target = { address: MDNS_MULTICAST_GROUP, port: MDNS_PORT }; } - return this._getSockets().then((sockets) => { + return this._getSockets().then(sockets => { sockets.forEach((socket, address) => { if (svc.address == "0.0.0.0" || address == svc.address) { let packet = this._makeServicePacket(svc, [address]); @@ -318,8 +383,10 @@ class MulticastDNS { try { socket.send(target.address, target.port, data); } catch (err) { - DEBUG && debug("Failed to send packet to " - + target.address + ":" + target.port); + DEBUG && + debug( + "Failed to send packet to " + target.address + ":" + target.port + ); } } }); @@ -355,14 +422,14 @@ class MulticastDNS { let msSinceAdv = now - publishedService.lastAdvertised; // If msSinceAdv is more than 90% of the way to the TTL, advertise now. - if (msSinceAdv > (DEFAULT_TTL * 1000 * 0.9)) { + if (msSinceAdv > DEFAULT_TTL * 1000 * 0.9) { bcastServices.push(publishedService); continue; } // Otherwise, calculate the next time to advertise for this service. // We set that at 95% of the time to the TTL expiry. - let nextAdvWait = (DEFAULT_TTL * 1000 * 0.95) - msSinceAdv; + let nextAdvWait = DEFAULT_TTL * 1000 * 0.95 - msSinceAdv; if (nextBcastWait === undefined || nextBcastWait > nextAdvWait) { nextBcastWait = nextAdvWait; } @@ -370,13 +437,21 @@ class MulticastDNS { // Schedule an immediate advertisement of all services to be advertised now. for (let svc of bcastServices) { - svc.advertiseTimer = setTimeout(() => this._advertiseService(svc.key)); + svc.advertiseTimer = setTimeout(() => this._advertiseService(svc.key)); } // Schedule next broadcast check for the next bcast time. if (nextBcastWait !== undefined) { - DEBUG && debug("_checkStartBroadcastTimer(): Scheduling next check in " + nextBcastWait + "ms"); - this._broadcastTimer = setTimeout(() => this._checkStartBroadcastTimer(), nextBcastWait); + DEBUG && + debug( + "_checkStartBroadcastTimer(): Scheduling next check in " + + nextBcastWait + + "ms" + ); + this._broadcastTimer = setTimeout( + () => this._checkStartBroadcastTimer(), + nextBcastWait + ); } } @@ -386,12 +461,15 @@ class MulticastDNS { packet.setFlag("QR", DNS_QUERY_RESPONSE_CODES.QUERY); // PTR Record - packet.addRecord("QD", new DNSRecord({ - name, - recordType: DNS_RECORD_TYPES.PTR, - classCode: DNS_CLASS_CODES.IN, - cacheFlush: true, - })); + packet.addRecord( + "QD", + new DNSRecord({ + name, + recordType: DNS_RECORD_TYPES.PTR, + classCode: DNS_CLASS_CODES.IN, + cacheFlush: true, + }) + ); let data = packet.serialize(); @@ -400,7 +478,7 @@ class MulticastDNS { // multicast queries/announcements on all interfaces. this._getBroadcastReceiverSocket(); - this._getQuerySocket().then((querySocket) => { + this._getQuerySocket().then(querySocket => { DEBUG && debug('sending query on query socket ("' + name + '")'); querySocket.send(MDNS_MULTICAST_GROUP, MDNS_PORT, data); }); @@ -408,7 +486,8 @@ class MulticastDNS { // Automatically announce previously-discovered // services that match and haven't expired yet. setTimeout(() => { - DEBUG && debug('announcing previously discovered services ("' + name + '")'); + DEBUG && + debug('announcing previously discovered services ("' + name + '")'); let { serviceType } = _parseServiceDomainName(name); this._clearExpiredDiscoveries(); @@ -419,7 +498,7 @@ class MulticastDNS { } let listeners = this._listeners.get(serviceInfo.serviceType) || []; - listeners.forEach((listener) => { + listeners.forEach(listener => { listener.onServiceFound(serviceInfo); }); }); @@ -435,16 +514,20 @@ class MulticastDNS { } _handleQueryPacket(packet, message) { - packet.getRecords(["QD"]).forEach((record) => { + packet.getRecords(["QD"]).forEach(record => { // Don't respond if the query's class code is not IN or ANY. - if (record.classCode !== DNS_CLASS_CODES.IN && - record.classCode !== DNS_CLASS_CODES.ANY) { + if ( + record.classCode !== DNS_CLASS_CODES.IN && + record.classCode !== DNS_CLASS_CODES.ANY + ) { return; } // Don't respond if the query's record type is not PTR or ANY. - if (record.recordType !== DNS_RECORD_TYPES.PTR && - record.recordType !== DNS_RECORD_TYPES.ANY) { + if ( + record.recordType !== DNS_RECORD_TYPES.PTR && + record.recordType !== DNS_RECORD_TYPES.ANY + ) { return; } @@ -465,46 +548,59 @@ class MulticastDNS { let host = service.host || _hostname; // e.g.: foo-bar-service._http._tcp.local - let serviceDomainName = service.serviceName + "." + service.serviceType + ".local"; + let serviceDomainName = + service.serviceName + "." + service.serviceType + ".local"; // PTR Record - packet.addRecord("AN", new DNSResourceRecord({ - name: service.serviceType + ".local", // e.g.: _http._tcp.local - recordType: DNS_RECORD_TYPES.PTR, - data: serviceDomainName, - })); + packet.addRecord( + "AN", + new DNSResourceRecord({ + name: service.serviceType + ".local", // e.g.: _http._tcp.local + recordType: DNS_RECORD_TYPES.PTR, + data: serviceDomainName, + }) + ); // SRV Record - packet.addRecord("AR", new DNSResourceRecord({ - name: serviceDomainName, - recordType: DNS_RECORD_TYPES.SRV, - classCode: DNS_CLASS_CODES.IN, - cacheFlush: true, - data: { - priority: 0, - weight: 0, - port: service.port, - target: host, // e.g.: My-Android-Phone.local - }, - })); + packet.addRecord( + "AR", + new DNSResourceRecord({ + name: serviceDomainName, + recordType: DNS_RECORD_TYPES.SRV, + classCode: DNS_CLASS_CODES.IN, + cacheFlush: true, + data: { + priority: 0, + weight: 0, + port: service.port, + target: host, // e.g.: My-Android-Phone.local + }, + }) + ); // A Records for (let address of addresses) { - packet.addRecord("AR", new DNSResourceRecord({ + packet.addRecord( + "AR", + new DNSResourceRecord({ name: host, recordType: DNS_RECORD_TYPES.A, data: address, - })); + }) + ); } // TXT Record - packet.addRecord("AR", new DNSResourceRecord({ - name: serviceDomainName, - recordType: DNS_RECORD_TYPES.TXT, - classCode: DNS_CLASS_CODES.IN, - cacheFlush: true, - data: service.serviceAttrs || {}, - })); + packet.addRecord( + "AR", + new DNSResourceRecord({ + name: serviceDomainName, + recordType: DNS_RECORD_TYPES.TXT, + classCode: DNS_CLASS_CODES.IN, + cacheFlush: true, + data: service.serviceAttrs || {}, + }) + ); return packet; } @@ -518,7 +614,7 @@ class MulticastDNS { let ptrRecords = packet.getRecords(["AN", "AR"], DNS_RECORD_TYPES.PTR); let aRecords = packet.getRecords(["AN", "AR"], DNS_RECORD_TYPES.A); - srvRecords.forEach((record) => { + srvRecords.forEach(record => { let data = record.data || {}; services[record.name] = { @@ -528,7 +624,7 @@ class MulticastDNS { }; }); - txtRecords.forEach((record) => { + txtRecords.forEach(record => { if (!services[record.name]) { return; } @@ -536,24 +632,26 @@ class MulticastDNS { services[record.name].attributes = record.data; }); - aRecords.forEach((record) => { + aRecords.forEach(record => { if (IsIpv4Address(record.data)) { hosts[record.name] = record.data; } }); - ptrRecords.forEach((record) => { + ptrRecords.forEach(record => { let name = record.data; if (!services[name]) { return; } - let {host, port} = services[name]; + let { host, port } = services[name]; if (!host || !port) { return; } - let { serviceName, serviceType, domainName } = _parseServiceDomainName(name); + let { serviceName, serviceType, domainName } = _parseServiceDomainName( + name + ); if (!serviceName || !serviceType || !domainName) { return; } @@ -579,12 +677,17 @@ class MulticastDNS { } _onServiceFound(serviceInfo, ttl = 0) { - let expireTime = Date.now() + (ttl * 1000); - let key = serviceInfo.serviceName + "." + - serviceInfo.serviceType + "." + - serviceInfo.domainName + " @" + - serviceInfo.address + ":" + - serviceInfo.port; + let expireTime = Date.now() + ttl * 1000; + let key = + serviceInfo.serviceName + + "." + + serviceInfo.serviceType + + "." + + serviceInfo.domainName + + " @" + + serviceInfo.address + + ":" + + serviceInfo.port; // If this service was already discovered, just update // its expiration time and don't re-emit it. @@ -599,7 +702,7 @@ class MulticastDNS { }); let listeners = this._listeners.get(serviceInfo.serviceType) || []; - listeners.forEach((listener) => { + listeners.forEach(listener => { listener.onServiceFound(serviceInfo); }); @@ -636,10 +739,15 @@ class MulticastDNS { _getBroadcastReceiverSocket() { return new Promise((resolve, reject) => { if (!this._broadcastReceiverSocket) { - this._broadcastReceiverSocket = _openSocket("0.0.0.0", MDNS_PORT, { - onPacketReceived: this._onPacketReceived.bind(this), - onStopListening: this._onStopListening.bind(this), - }, /* multicastInterface = */ "0.0.0.0"); + this._broadcastReceiverSocket = _openSocket( + "0.0.0.0", + MDNS_PORT, + { + onPacketReceived: this._onPacketReceived.bind(this), + onStopListening: this._onStopListening.bind(this), + }, + /* multicastInterface = */ "0.0.0.0" + ); } resolve(this._broadcastReceiverSocket); }); @@ -656,14 +764,14 @@ class MulticastDNS { * already handling them. */ _getSockets() { - return new Promise((resolve) => { + return new Promise(resolve => { if (this._sockets.size > 0) { resolve(this._sockets); return; } Promise.all([getAddresses(), getHostname()]).then(() => { - _addresses.forEach((address) => { + _addresses.forEach(address => { let socket = _openSocket(address, MDNS_PORT, null); this._sockets.set(address, socket); }); @@ -675,17 +783,20 @@ class MulticastDNS { _checkCloseSockets() { // Nothing to do if no sockets to close. - if (this._sockets.size == 0) + if (this._sockets.size == 0) { return; + } // Don't close sockets if discovery listeners are still present. - if (this._listeners.size > 0) + if (this._listeners.size > 0) { return; + } // Don't close sockets if advertised services are present. // Since we need to listen for service queries and respond to them. - if (this._services.size > 0) + if (this._services.size > 0) { return; + } this._closeSockets(); } @@ -757,10 +868,12 @@ function getAddresses() { networkInfoService.listNetworkAddresses({ onListedNetworkAddresses(aAddressArray) { - _addresses = aAddressArray.filter((address) => { - return !address.includes("%p2p") && // No WiFi Direct interfaces - !address.includes(":") && // XXX: No IPv6 for now - address != "127.0.0.1"; // No ipv4 loopback addresses. + _addresses = aAddressArray.filter(address => { + return ( + !address.includes("%p2p") && // No WiFi Direct interfaces + !address.includes(":") && // XXX: No IPv6 for now + address != "127.0.0.1" + ); // No ipv4 loopback addresses. }); DEBUG && debug("getAddresses(): " + _addresses); @@ -781,7 +894,7 @@ let _hostname; * @private */ function getHostname() { - return new Promise((resolve) => { + return new Promise(resolve => { if (_hostname) { resolve(_hostname); return; @@ -848,8 +961,15 @@ function _propertyBagToObject(propBag) { * @private */ function _openSocket(addr, port, handler, multicastInterface) { - let socket = Cc["@mozilla.org/network/udp-socket;1"].createInstance(Ci.nsIUDPSocket); - socket.init2(addr, port, Services.scriptSecurityManager.getSystemPrincipal(), true); + let socket = Cc["@mozilla.org/network/udp-socket;1"].createInstance( + Ci.nsIUDPSocket + ); + socket.init2( + addr, + port, + Services.scriptSecurityManager.getSystemPrincipal(), + true + ); if (handler) { socket.asyncListen({ diff --git a/netwerk/protocol/http/UAOverridesBootstrapper.jsm b/netwerk/protocol/http/UAOverridesBootstrapper.jsm index 26672ea49847..6f773f740ea8 100644 --- a/netwerk/protocol/http/UAOverridesBootstrapper.jsm +++ b/netwerk/protocol/http/UAOverridesBootstrapper.jsm @@ -4,8 +4,10 @@ "use strict"; -const {Services} = ChromeUtils.import("resource://gre/modules/Services.jsm"); -const {UserAgentOverrides} = ChromeUtils.import("resource://gre/modules/UserAgentOverrides.jsm"); +const { Services } = ChromeUtils.import("resource://gre/modules/Services.jsm"); +const { UserAgentOverrides } = ChromeUtils.import( + "resource://gre/modules/UserAgentOverrides.jsm" +); function UAOverridesBootstrapper() { this.init(); diff --git a/netwerk/protocol/http/UserAgentOverrides.jsm b/netwerk/protocol/http/UserAgentOverrides.jsm index 1614ed906d46..fd1f42c84989 100644 --- a/netwerk/protocol/http/UserAgentOverrides.jsm +++ b/netwerk/protocol/http/UserAgentOverrides.jsm @@ -4,36 +4,43 @@ "use strict"; -var EXPORTED_SYMBOLS = [ "UserAgentOverrides" ]; +var EXPORTED_SYMBOLS = ["UserAgentOverrides"]; -const {XPCOMUtils} = ChromeUtils.import("resource://gre/modules/XPCOMUtils.jsm"); -const {Services} = ChromeUtils.import("resource://gre/modules/Services.jsm"); -const {UserAgentUpdates} = ChromeUtils.import("resource://gre/modules/UserAgentUpdates.jsm"); +const { XPCOMUtils } = ChromeUtils.import( + "resource://gre/modules/XPCOMUtils.jsm" +); +const { Services } = ChromeUtils.import("resource://gre/modules/Services.jsm"); +const { UserAgentUpdates } = ChromeUtils.import( + "resource://gre/modules/UserAgentUpdates.jsm" +); const PREF_OVERRIDES_ENABLED = "general.useragent.site_specific_overrides"; const MAX_OVERRIDE_FOR_HOST_CACHE_SIZE = 250; // lazy load nsHttpHandler to improve startup performance. XPCOMUtils.defineLazyGetter(this, "DEFAULT_UA", function() { - return Cc["@mozilla.org/network/protocol;1?name=http"] - .getService(Ci.nsIHttpProtocolHandler) - .userAgent; + return Cc["@mozilla.org/network/protocol;1?name=http"].getService( + Ci.nsIHttpProtocolHandler + ).userAgent; }); var gPrefBranch; -var gOverrides = new Map; +var gOverrides = new Map(); var gUpdatedOverrides; -var gOverrideForHostCache = new Map; +var gOverrideForHostCache = new Map(); var gInitialized = false; var gOverrideFunctions = [ - function(aHttpChannel) { return UserAgentOverrides.getOverrideForURI(aHttpChannel.URI); }, + function(aHttpChannel) { + return UserAgentOverrides.getOverrideForURI(aHttpChannel.URI); + }, ]; -var gBuiltUAs = new Map; +var gBuiltUAs = new Map(); var UserAgentOverrides = { init: function uao_init() { - if (gInitialized) + if (gInitialized) { return; + } gPrefBranch = Services.prefs.getBranch("general.useragent.override."); gPrefBranch.addObserver("", buildOverrides); @@ -41,7 +48,10 @@ var UserAgentOverrides = { Services.prefs.addObserver(PREF_OVERRIDES_ENABLED, buildOverrides); try { - Services.obs.addObserver(HTTP_on_useragent_request, "http-on-useragent-request"); + Services.obs.addObserver( + HTTP_on_useragent_request, + "http-on-useragent-request" + ); } catch (x) { // The http-on-useragent-request notification is disallowed in content processes. } @@ -53,7 +63,9 @@ var UserAgentOverrides = { for (let domain in overrides) { overrides[domain] = getUserAgentFromOverride(overrides[domain]); } - overrides.get = function(key) { return this[key]; }; + overrides.get = function(key) { + return this[key]; + }; } gUpdatedOverrides = overrides; }); @@ -75,15 +87,14 @@ var UserAgentOverrides = { getOverrideForURI: function uao_getOverrideForURI(aURI) { let host = aURI.asciiHost; - if (!gInitialized || - (!gOverrides.size && !gUpdatedOverrides) || - !(host)) { + if (!gInitialized || (!gOverrides.size && !gUpdatedOverrides) || !host) { return null; } let override = gOverrideForHostCache.get(host); - if (override !== undefined) + if (override !== undefined) { return override; + } function findOverride(overrides) { let searchHost = host; @@ -100,8 +111,9 @@ var UserAgentOverrides = { return userAgent; } - override = (gOverrides.size && findOverride(gOverrides)) - || (gUpdatedOverrides && findOverride(gUpdatedOverrides)); + override = + (gOverrides.size && findOverride(gOverrides)) || + (gUpdatedOverrides && findOverride(gUpdatedOverrides)); if (gOverrideForHostCache.size >= MAX_OVERRIDE_FOR_HOST_CACHE_SIZE) { gOverrideForHostCache.clear(); @@ -112,15 +124,19 @@ var UserAgentOverrides = { }, uninit: function uao_uninit() { - if (!gInitialized) + if (!gInitialized) { return; + } gInitialized = false; gPrefBranch.removeObserver("", buildOverrides); Services.prefs.removeObserver(PREF_OVERRIDES_ENABLED, buildOverrides); - Services.obs.removeObserver(HTTP_on_useragent_request, "http-on-useragent-request"); + Services.obs.removeObserver( + HTTP_on_useragent_request, + "http-on-useragent-request" + ); }, }; @@ -143,8 +159,9 @@ function buildOverrides() { gOverrides.clear(); gOverrideForHostCache.clear(); - if (!Services.prefs.getBoolPref(PREF_OVERRIDES_ENABLED)) + if (!Services.prefs.getBoolPref(PREF_OVERRIDES_ENABLED)) { return; + } let domains = gPrefBranch.getChildList(""); diff --git a/netwerk/protocol/http/UserAgentUpdates.jsm b/netwerk/protocol/http/UserAgentUpdates.jsm index 7b0f9a36d480..30410ad11b87 100644 --- a/netwerk/protocol/http/UserAgentUpdates.jsm +++ b/netwerk/protocol/http/UserAgentUpdates.jsm @@ -6,35 +6,50 @@ var EXPORTED_SYMBOLS = ["UserAgentUpdates"]; -const {AppConstants} = ChromeUtils.import("resource://gre/modules/AppConstants.jsm"); -const {Services} = ChromeUtils.import("resource://gre/modules/Services.jsm"); -const {XPCOMUtils} = ChromeUtils.import("resource://gre/modules/XPCOMUtils.jsm"); +const { AppConstants } = ChromeUtils.import( + "resource://gre/modules/AppConstants.jsm" +); +const { Services } = ChromeUtils.import("resource://gre/modules/Services.jsm"); +const { XPCOMUtils } = ChromeUtils.import( + "resource://gre/modules/XPCOMUtils.jsm" +); XPCOMUtils.defineLazyGlobalGetters(this, ["XMLHttpRequest"]); ChromeUtils.defineModuleGetter( - this, "FileUtils", "resource://gre/modules/FileUtils.jsm"); + this, + "FileUtils", + "resource://gre/modules/FileUtils.jsm" +); ChromeUtils.defineModuleGetter( - this, "NetUtil", "resource://gre/modules/NetUtil.jsm"); + this, + "NetUtil", + "resource://gre/modules/NetUtil.jsm" +); + +ChromeUtils.defineModuleGetter(this, "OS", "resource://gre/modules/osfile.jsm"); ChromeUtils.defineModuleGetter( - this, "OS", "resource://gre/modules/osfile.jsm"); - - -ChromeUtils.defineModuleGetter( - this, "UpdateUtils", "resource://gre/modules/UpdateUtils.jsm"); + this, + "UpdateUtils", + "resource://gre/modules/UpdateUtils.jsm" +); XPCOMUtils.defineLazyServiceGetter( - this, "gUpdateTimer", "@mozilla.org/updates/timer-manager;1", "nsIUpdateTimerManager"); - -XPCOMUtils.defineLazyGetter(this, "gDecoder", - function() { return new TextDecoder(); } + this, + "gUpdateTimer", + "@mozilla.org/updates/timer-manager;1", + "nsIUpdateTimerManager" ); -XPCOMUtils.defineLazyGetter(this, "gEncoder", - function() { return new TextEncoder(); } -); +XPCOMUtils.defineLazyGetter(this, "gDecoder", function() { + return new TextDecoder(); +}); + +XPCOMUtils.defineLazyGetter(this, "gEncoder", function() { + return new TextEncoder(); +}); const TIMER_ID = "user-agent-updates-timer"; @@ -58,7 +73,10 @@ var gInitialized = false; function readChannel(url) { return new Promise((resolve, reject) => { try { - let channel = NetUtil.newChannel({uri: url, loadUsingSystemPrincipal: true}); + let channel = NetUtil.newChannel({ + uri: url, + loadUsingSystemPrincipal: true, + }); channel.contentType = "application/json"; NetUtil.asyncFetch(channel, (inputStream, status) => { @@ -73,8 +91,16 @@ function readChannel(url) { resolve(data); }); } catch (ex) { - reject(new Error("UserAgentUpdates: Could not fetch " + url + " " + - ex + "\n" + ex.stack)); + reject( + new Error( + "UserAgentUpdates: Could not fetch " + + url + + " " + + ex + + "\n" + + ex.stack + ) + ); } }); } @@ -119,32 +145,40 @@ var UserAgentUpdates = { // try loading from profile dir, then from app dir let dirs = [KEY_PREFDIR, KEY_APPDIR]; - dirs.reduce((prevLoad, dir) => { - let file = FileUtils.getFile(dir, [FILE_UPDATES], true).path; - // tryNext returns promise to read file under dir and parse it - let tryNext = () => OS.File.read(file).then( - (bytes) => { - let update = JSON.parse(gDecoder.decode(bytes)); - if (!update) { - throw new Error("invalid update"); - } - return update; + dirs + .reduce((prevLoad, dir) => { + let file = FileUtils.getFile(dir, [FILE_UPDATES], true).path; + // tryNext returns promise to read file under dir and parse it + let tryNext = () => + OS.File.read(file).then(bytes => { + let update = JSON.parse(gDecoder.decode(bytes)); + if (!update) { + throw new Error("invalid update"); + } + return update; + }); + // try to load next one if the previous load failed + return prevLoad ? prevLoad.catch(tryNext) : tryNext(); + }, null) + .catch(ex => { + if (AppConstants.platform !== "android") { + // All previous (non-Android) load attempts have failed, so we bail. + throw new Error( + "UserAgentUpdates: Failed to load " + + FILE_UPDATES + + ex + + "\n" + + ex.stack + ); } - ); - // try to load next one if the previous load failed - return prevLoad ? prevLoad.catch(tryNext) : tryNext(); - }, null).catch((ex) => { - if (AppConstants.platform !== "android") { - // All previous (non-Android) load attempts have failed, so we bail. - throw new Error("UserAgentUpdates: Failed to load " + FILE_UPDATES + - ex + "\n" + ex.stack); - } - // Make one last attempt to read from the Fennec APK root. - return readChannel("resource://android/" + FILE_UPDATES); - }).then((update) => { - // Apply update if loading was successful - this._applyUpdate(update); - }).catch(Cu.reportError); + // Make one last attempt to read from the Fennec APK root. + return readChannel("resource://android/" + FILE_UPDATES); + }) + .then(update => { + // Apply update if loading was successful + this._applyUpdate(update); + }) + .catch(Cu.reportError); this._scheduleUpdate(); }, @@ -152,21 +186,22 @@ var UserAgentUpdates = { let file = FileUtils.getFile(KEY_PREFDIR, [FILE_UPDATES], true); let path = file.path; let bytes = gEncoder.encode(JSON.stringify(update)); - OS.File.writeAtomic(path, bytes, {tmpPath: path + ".tmp"}).then( - () => { - this._lastUpdated = Date.now(); - Services.prefs.setCharPref( - PREF_UPDATES_LASTUPDATED, this._lastUpdated.toString()); - }, - Cu.reportError - ); + OS.File.writeAtomic(path, bytes, { tmpPath: path + ".tmp" }).then(() => { + this._lastUpdated = Date.now(); + Services.prefs.setCharPref( + PREF_UPDATES_LASTUPDATED, + this._lastUpdated.toString() + ); + }, Cu.reportError); }, _getPref(name, def) { try { switch (typeof def) { - case "number": return Services.prefs.getIntPref(name); - case "boolean": return Services.prefs.getBoolPref(name); + case "number": + return Services.prefs.getIntPref(name); + case "boolean": + return Services.prefs.getBoolPref(name); } return Services.prefs.getCharPref(name); } catch (e) { @@ -176,15 +211,33 @@ var UserAgentUpdates = { _getParameters() { return { - "%DATE%": function() { return Date.now().toString(); }, - "%PRODUCT%": function() { return Services.appinfo.name; }, - "%APP_ID%": function() { return Services.appinfo.ID; }, - "%APP_VERSION%": function() { return Services.appinfo.version; }, - "%BUILD_ID%": function() { return Services.appinfo.appBuildID; }, - "%OS%": function() { return Services.appinfo.OS; }, - "%CHANNEL%": function() { return UpdateUtils.UpdateChannel; }, - "%DISTRIBUTION%": function() { return this._getPref(PREF_APP_DISTRIBUTION, ""); }, - "%DISTRIBUTION_VERSION%": function() { return this._getPref(PREF_APP_DISTRIBUTION_VERSION, ""); }, + "%DATE%": function() { + return Date.now().toString(); + }, + "%PRODUCT%": function() { + return Services.appinfo.name; + }, + "%APP_ID%": function() { + return Services.appinfo.ID; + }, + "%APP_VERSION%": function() { + return Services.appinfo.version; + }, + "%BUILD_ID%": function() { + return Services.appinfo.appBuildID; + }, + "%OS%": function() { + return Services.appinfo.OS; + }, + "%CHANNEL%": function() { + return UpdateUtils.UpdateChannel; + }, + "%DISTRIBUTION%": function() { + return this._getPref(PREF_APP_DISTRIBUTION, ""); + }, + "%DISTRIBUTION_VERSION%": function() { + return this._getPref(PREF_APP_DISTRIBUTION_VERSION, ""); + }, }; }, @@ -216,21 +269,28 @@ var UserAgentUpdates = { _update() { let url = this._getUpdateURL(); - url && this._fetchUpdate(url, - response => { // success - // apply update and save overrides to profile - this._applyUpdate(response); - this._saveToFile(response); - this._scheduleUpdate(); // cancel any retries - }, - response => { // error - this._scheduleUpdate(true /* retry */); - }); + url && + this._fetchUpdate( + url, + response => { + // success + // apply update and save overrides to profile + this._applyUpdate(response); + this._saveToFile(response); + this._scheduleUpdate(); // cancel any retries + }, + response => { + // error + this._scheduleUpdate(true /* retry */); + } + ); }, _scheduleUpdate(retry) { // only schedule updates in the main process - if (Services.appinfo.processType !== Ci.nsIXULRuntime.PROCESS_TYPE_DEFAULT) { + if ( + Services.appinfo.processType !== Ci.nsIXULRuntime.PROCESS_TYPE_DEFAULT + ) { return; } let interval = this._getPref(PREF_UPDATES_INTERVAL, 604800 /* 1 week */); @@ -257,7 +317,9 @@ var UserAgentUpdates = { } else if (data === PREF_UPDATES_LASTUPDATED) { // reload from file if there has been an update let lastUpdated = parseInt( - this._getPref(PREF_UPDATES_LASTUPDATED, "0"), 0); + this._getPref(PREF_UPDATES_LASTUPDATED, "0"), + 0 + ); if (lastUpdated > this._lastUpdated) { this._applySavedUpdate(); this._lastUpdated = lastUpdated; @@ -267,8 +329,5 @@ var UserAgentUpdates = { } }, - QueryInterface: ChromeUtils.generateQI([ - Ci.nsIObserver, - Ci.nsITimerCallback, - ]), + QueryInterface: ChromeUtils.generateQI([Ci.nsIObserver, Ci.nsITimerCallback]), }; diff --git a/netwerk/protocol/http/WellKnownOpportunisticUtils.jsm b/netwerk/protocol/http/WellKnownOpportunisticUtils.jsm index 43319dc1f467..7e9c604aafb5 100644 --- a/netwerk/protocol/http/WellKnownOpportunisticUtils.jsm +++ b/netwerk/protocol/http/WellKnownOpportunisticUtils.jsm @@ -1,7 +1,7 @@ /* -*- indent-tabs-mode: nil; js-indent-level: 2 -*- */ /* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this file, -* You can obtain one at http://mozilla.org/MPL/2.0/. */ + * You can obtain one at http://mozilla.org/MPL/2.0/. */ "use strict"; diff --git a/netwerk/test/browser/browser_NetUtil.js b/netwerk/test/browser/browser_NetUtil.js index 197c5b04dfb9..8c2ebd2f3522 100644 --- a/netwerk/test/browser/browser_NetUtil.js +++ b/netwerk/test/browser/browser_NetUtil.js @@ -14,54 +14,74 @@ function test() { } function nextTest() { - if (tests.length) + if (tests.length) { executeSoon(tests.shift()); - else + } else { executeSoon(finish); + } } -var tests = [ - test_asyncFetchBadCert, -]; +var tests = [test_asyncFetchBadCert]; function test_asyncFetchBadCert() { // Try a load from an untrusted cert, with errors supressed - NetUtil.asyncFetch({ - uri: "https://untrusted.example.com", - loadUsingSystemPrincipal: true - }, function (aInputStream, aStatusCode, aRequest) { - ok(!Components.isSuccessCode(aStatusCode), "request failed"); - ok(aRequest instanceof Ci.nsIHttpChannel, "request is an nsIHttpChannel"); - - // Now try again with a channel whose notificationCallbacks doesn't suprress errors - let channel = NetUtil.newChannel({ + NetUtil.asyncFetch( + { uri: "https://untrusted.example.com", - loadUsingSystemPrincipal: true}); - channel.notificationCallbacks = { - QueryInterface: ChromeUtils.generateQI([Ci.nsIProgressEventSink, - Ci.nsIInterfaceRequestor]), - getInterface (aIID) { return this.QueryInterface(aIID); }, - onProgress () {}, - onStatus () {} - }; - NetUtil.asyncFetch(channel, function (aInputStream, aStatusCode, aRequest) { + loadUsingSystemPrincipal: true, + }, + function(aInputStream, aStatusCode, aRequest) { ok(!Components.isSuccessCode(aStatusCode), "request failed"); ok(aRequest instanceof Ci.nsIHttpChannel, "request is an nsIHttpChannel"); - // Now try a valid request - NetUtil.asyncFetch({ - uri: "https://example.com", - loadUsingSystemPrincipal: true - }, function (aInputStream, aStatusCode, aRequest) { - info("aStatusCode for valid request: " + aStatusCode); - ok(Components.isSuccessCode(aStatusCode), "request succeeded"); - ok(aRequest instanceof Ci.nsIHttpChannel, "request is an nsIHttpChannel"); - ok(aRequest.requestSucceeded, "HTTP request succeeded"); - - nextTest(); + // Now try again with a channel whose notificationCallbacks doesn't suprress errors + let channel = NetUtil.newChannel({ + uri: "https://untrusted.example.com", + loadUsingSystemPrincipal: true, }); - }); - }); + channel.notificationCallbacks = { + QueryInterface: ChromeUtils.generateQI([ + Ci.nsIProgressEventSink, + Ci.nsIInterfaceRequestor, + ]), + getInterface(aIID) { + return this.QueryInterface(aIID); + }, + onProgress() {}, + onStatus() {}, + }; + NetUtil.asyncFetch(channel, function( + aInputStream, + aStatusCode, + aRequest + ) { + ok(!Components.isSuccessCode(aStatusCode), "request failed"); + ok( + aRequest instanceof Ci.nsIHttpChannel, + "request is an nsIHttpChannel" + ); + + // Now try a valid request + NetUtil.asyncFetch( + { + uri: "https://example.com", + loadUsingSystemPrincipal: true, + }, + function(aInputStream, aStatusCode, aRequest) { + info("aStatusCode for valid request: " + aStatusCode); + ok(Components.isSuccessCode(aStatusCode), "request succeeded"); + ok( + aRequest instanceof Ci.nsIHttpChannel, + "request is an nsIHttpChannel" + ); + ok(aRequest.requestSucceeded, "HTTP request succeeded"); + + nextTest(); + } + ); + }); + } + ); } function WindowListener(aURL, aCallback) { @@ -72,15 +92,20 @@ WindowListener.prototype = { onOpenWindow(aXULWindow) { var domwindow = aXULWindow.docShell.domWindow; var self = this; - domwindow.addEventListener("load", function() { - if (domwindow.document.location.href != self.url) - return; + domwindow.addEventListener( + "load", + function() { + if (domwindow.document.location.href != self.url) { + return; + } - // Allow other window load listeners to execute before passing to callback - executeSoon(function() { - self.callback(domwindow); - }); - }, {once: true}); + // Allow other window load listeners to execute before passing to callback + executeSoon(function() { + self.callback(domwindow); + }); + }, + { once: true } + ); }, onCloseWindow(aXULWindow) {}, -} +}; diff --git a/netwerk/test/browser/browser_about_cache.js b/netwerk/test/browser/browser_about_cache.js index 0c5421057f57..29bdea6fb822 100644 --- a/netwerk/test/browser/browser_about_cache.js +++ b/netwerk/test/browser/browser_about_cache.js @@ -4,28 +4,48 @@ * Open a dummy page, then open about:cache and verify the opened page shows up in the cache. */ add_task(async function() { - const kRoot = getRootDirectory(gTestPath).replace("chrome://mochitests/content/", - "https://example.com/"); + const kRoot = getRootDirectory(gTestPath).replace( + "chrome://mochitests/content/", + "https://example.com/" + ); const kTestPage = kRoot + "dummy.html"; // Open the dummy page to get it cached. - let tab = await BrowserTestUtils.openNewForegroundTab(gBrowser, kTestPage, true); + let tab = await BrowserTestUtils.openNewForegroundTab( + gBrowser, + kTestPage, + true + ); BrowserTestUtils.removeTab(tab); - tab = await BrowserTestUtils.openNewForegroundTab(gBrowser, "about:cache", true); + tab = await BrowserTestUtils.openNewForegroundTab( + gBrowser, + "about:cache", + true + ); let expectedPageCheck = function(uri) { info("Saw load for " + uri); // Can't easily use searchParms and new URL() because it's an about: URI... return uri.startsWith("about:cache?") && uri.includes("storage=disk"); }; - let diskPageLoaded = BrowserTestUtils.browserLoaded(tab.linkedBrowser, false, expectedPageCheck); + let diskPageLoaded = BrowserTestUtils.browserLoaded( + tab.linkedBrowser, + false, + expectedPageCheck + ); await ContentTask.spawn(tab.linkedBrowser, null, function() { - ok(!content.document.nodePrincipal.isSystemPrincipal, - "about:cache should not have system principal"); + ok( + !content.document.nodePrincipal.isSystemPrincipal, + "about:cache should not have system principal" + ); let principalURI = content.document.nodePrincipal.URI; let channel = content.docShell.currentDocumentChannel; ok(!channel.loadInfo.loadingPrincipal, "Loading principal should be null."); - is(principalURI && principalURI.spec, content.document.location.href, "Principal matches location"); - let links = [... content.document.querySelectorAll("a[href*=disk]")]; + is( + principalURI && principalURI.spec, + content.document.location.href, + "Principal matches location" + ); + let links = [...content.document.querySelectorAll("a[href*=disk]")]; is(links.length, 1, "Should have 1 link to the disk entries"); links[0].click(); }); @@ -37,35 +57,64 @@ add_task(async function() { return uri.startsWith("about:cache-entry") && uri.includes("dummy.html"); }; let triggeringURISpec = tab.linkedBrowser.currentURI.spec; - let entryLoaded = BrowserTestUtils.browserLoaded(tab.linkedBrowser, false, expectedPageCheck); + let entryLoaded = BrowserTestUtils.browserLoaded( + tab.linkedBrowser, + false, + expectedPageCheck + ); await ContentTask.spawn(tab.linkedBrowser, kTestPage, function(kTestPage) { - ok(!content.document.nodePrincipal.isSystemPrincipal, - "about:cache with query params should still not have system principal"); + ok( + !content.document.nodePrincipal.isSystemPrincipal, + "about:cache with query params should still not have system principal" + ); let principalURI = content.document.nodePrincipal.URI; - is(principalURI && principalURI.spec, content.document.location.href, "Principal matches location"); + is( + principalURI && principalURI.spec, + content.document.location.href, + "Principal matches location" + ); let channel = content.docShell.currentDocumentChannel; principalURI = channel.loadInfo.triggeringPrincipal.URI; - is(principalURI && principalURI.spec, "about:cache", "Triggering principal matches previous location"); + is( + principalURI && principalURI.spec, + "about:cache", + "Triggering principal matches previous location" + ); ok(!channel.loadInfo.loadingPrincipal, "Loading principal should be null."); - let links = [... content.document.querySelectorAll("a[href*='" + kTestPage + "']")]; + let links = [ + ...content.document.querySelectorAll("a[href*='" + kTestPage + "']"), + ]; is(links.length, 1, "Should have 1 link to the entry for " + kTestPage); links[0].click(); }); await entryLoaded; info("about:cache entry loaded"); - - await ContentTask.spawn(tab.linkedBrowser, triggeringURISpec, function(triggeringURISpec) { - ok(!content.document.nodePrincipal.isSystemPrincipal, - "about:cache-entry should also not have system principal"); + await ContentTask.spawn(tab.linkedBrowser, triggeringURISpec, function( + triggeringURISpec + ) { + ok( + !content.document.nodePrincipal.isSystemPrincipal, + "about:cache-entry should also not have system principal" + ); let principalURI = content.document.nodePrincipal.URI; - is(principalURI && principalURI.spec, content.document.location.href, "Principal matches location"); + is( + principalURI && principalURI.spec, + content.document.location.href, + "Principal matches location" + ); let channel = content.docShell.currentDocumentChannel; principalURI = channel.loadInfo.triggeringPrincipal.URI; - is(principalURI && principalURI.spec, triggeringURISpec, "Triggering principal matches previous location"); + is( + principalURI && principalURI.spec, + triggeringURISpec, + "Triggering principal matches previous location" + ); ok(!channel.loadInfo.loadingPrincipal, "Loading principal should be null."); - ok(content.document.querySelectorAll("th").length, - "Should have several table headers with data."); + ok( + content.document.querySelectorAll("th").length, + "Should have several table headers with data." + ); }); BrowserTestUtils.removeTab(tab); }); diff --git a/netwerk/test/browser/browser_bug1535877.js b/netwerk/test/browser/browser_bug1535877.js index 5af97e2886c1..0bd0a98d1163 100644 --- a/netwerk/test/browser/browser_bug1535877.js +++ b/netwerk/test/browser/browser_bug1535877.js @@ -2,10 +2,14 @@ add_task(_ => { try { - Cc["@mozilla.org/network/effective-tld-service;1"] - .createInstance(Ci.nsISupports); + Cc["@mozilla.org/network/effective-tld-service;1"].createInstance( + Ci.nsISupports + ); } catch (e) { - is(e.result, Cr.NS_ERROR_XPC_CI_RETURNED_FAILURE, - "Component creation as an instance fails with expected code"); + is( + e.result, + Cr.NS_ERROR_XPC_CI_RETURNED_FAILURE, + "Component creation as an instance fails with expected code" + ); } }); diff --git a/netwerk/test/browser/browser_child_resource.js b/netwerk/test/browser/browser_child_resource.js index e42f08cb5020..111617b5a212 100644 --- a/netwerk/test/browser/browser_child_resource.js +++ b/netwerk/test/browser/browser_child_resource.js @@ -8,21 +8,24 @@ const TEST_URL = "http://example.com/browser/netwerk/test/browser/dummy.html"; const expectedRemote = gMultiProcessBrowser ? "true" : ""; -const resProtocol = Cc["@mozilla.org/network/protocol;1?name=resource"] - .getService(Ci.nsIResProtocolHandler); +const resProtocol = Cc[ + "@mozilla.org/network/protocol;1?name=resource" +].getService(Ci.nsIResProtocolHandler); function frameScript() { - const {Services} = ChromeUtils.import("resource://gre/modules/Services.jsm"); - let resProtocol = Cc["@mozilla.org/network/protocol;1?name=resource"] - .getService(Ci.nsIResProtocolHandler); + const { Services } = ChromeUtils.import( + "resource://gre/modules/Services.jsm" + ); + let resProtocol = Cc[ + "@mozilla.org/network/protocol;1?name=resource" + ].getService(Ci.nsIResProtocolHandler); addMessageListener("Test:ResolveURI", function({ data: uri }) { uri = Services.io.newURI(uri); try { let resolved = resProtocol.resolveURI(uri); sendAsyncMessage("Test:ResolvedURI", resolved); - } - catch (e) { + } catch (e) { sendAsyncMessage("Test:ResolvedURI", null); } }); @@ -30,7 +33,7 @@ function frameScript() { function waitForEvent(obj, name, capturing, chromeEvent) { info("Waiting for " + name); - return new Promise((resolve) => { + return new Promise(resolve => { function listener(event) { info("Saw " + name); obj.removeEventListener(name, listener, capturing, chromeEvent); @@ -45,14 +48,13 @@ function resolveURI(uri) { uri = Services.io.newURI(uri); try { return resProtocol.resolveURI(uri); - } - catch (e) { + } catch (e) { return null; } } function remoteResolveURI(uri) { - return new Promise((resolve) => { + return new Promise(resolve => { let manager = gBrowser.selectedBrowser.messageManager; function listener({ data: resolved }) { @@ -69,7 +71,10 @@ var loadTestTab = async function() { gBrowser.selectedTab = BrowserTestUtils.addTab(gBrowser, TEST_URL); let browser = gBrowser.selectedBrowser; await BrowserTestUtils.browserLoaded(browser); - browser.messageManager.loadFrameScript("data:,(" + frameScript.toString() + ")();", true); + browser.messageManager.loadFrameScript( + "data:,(" + frameScript.toString() + ")();", + true + ); return browser; }; @@ -77,16 +82,24 @@ var loadTestTab = async function() { var restart = async function() { let browser = gBrowser.selectedBrowser; // If the tab isn't remote this would crash the main process so skip it - if (browser.getAttribute("remote") != "true") + if (browser.getAttribute("remote") != "true") { return browser; + } await BrowserTestUtils.crashBrowser(browser); browser.reload(); await BrowserTestUtils.browserLoaded(browser); - is(browser.getAttribute("remote"), expectedRemote, "Browser should be in the right process"); - browser.messageManager.loadFrameScript("data:,(" + frameScript.toString() + ")();", true); + is( + browser.getAttribute("remote"), + expectedRemote, + "Browser should be in the right process" + ); + browser.messageManager.loadFrameScript( + "data:,(" + frameScript.toString() + ")();", + true + ); return browser; }; @@ -95,7 +108,11 @@ add_task(async function() { let browser = await loadTestTab(); // This must be loaded in the remote process for this test to be useful - is(browser.getAttribute("remote"), expectedRemote, "Browser should be in the right process"); + is( + browser.getAttribute("remote"), + expectedRemote, + "Browser should be in the right process" + ); let local = resolveURI("resource://gre/modules/Services.jsm"); let remote = await remoteResolveURI("resource://gre/modules/Services.jsm"); @@ -109,14 +126,28 @@ add_task(async function() { let browser = await loadTestTab(); info("Set"); - resProtocol.setSubstitution("testing", Services.io.newURI("chrome://global/content")); + resProtocol.setSubstitution( + "testing", + Services.io.newURI("chrome://global/content") + ); let local = resolveURI("resource://testing/test.js"); let remote = await remoteResolveURI("resource://testing/test.js"); - is(local, "chrome://global/content/test.js", "Should resolve in main process"); - is(remote, "chrome://global/content/test.js", "Should resolve in child process"); + is( + local, + "chrome://global/content/test.js", + "Should resolve in main process" + ); + is( + remote, + "chrome://global/content/test.js", + "Should resolve in child process" + ); info("Change"); - resProtocol.setSubstitution("testing", Services.io.newURI("chrome://global/skin")); + resProtocol.setSubstitution( + "testing", + Services.io.newURI("chrome://global/skin") + ); local = resolveURI("resource://testing/test.js"); remote = await remoteResolveURI("resource://testing/test.js"); is(local, "chrome://global/skin/test.js", "Should resolve in main process"); @@ -137,21 +168,43 @@ add_task(async function() { let browser = await loadTestTab(); info("Set"); - resProtocol.setSubstitution("testing", Services.io.newURI("chrome://global/content")); + resProtocol.setSubstitution( + "testing", + Services.io.newURI("chrome://global/content") + ); let local = resolveURI("resource://testing/test.js"); let remote = await remoteResolveURI("resource://testing/test.js"); - is(local, "chrome://global/content/test.js", "Should resolve in main process"); - is(remote, "chrome://global/content/test.js", "Should resolve in child process"); + is( + local, + "chrome://global/content/test.js", + "Should resolve in main process" + ); + is( + remote, + "chrome://global/content/test.js", + "Should resolve in child process" + ); await restart(); local = resolveURI("resource://testing/test.js"); remote = await remoteResolveURI("resource://testing/test.js"); - is(local, "chrome://global/content/test.js", "Should resolve in main process"); - is(remote, "chrome://global/content/test.js", "Should resolve in child process"); + is( + local, + "chrome://global/content/test.js", + "Should resolve in main process" + ); + is( + remote, + "chrome://global/content/test.js", + "Should resolve in child process" + ); info("Change"); - resProtocol.setSubstitution("testing", Services.io.newURI("chrome://global/skin")); + resProtocol.setSubstitution( + "testing", + Services.io.newURI("chrome://global/skin") + ); await restart(); @@ -178,19 +231,41 @@ add_task(async function() { let browser = await loadTestTab(); info("Set"); - resProtocol.setSubstitution("testing", Services.io.newURI("chrome://global/content")); - resProtocol.setSubstitution("testing2", Services.io.newURI("resource://testing")); + resProtocol.setSubstitution( + "testing", + Services.io.newURI("chrome://global/content") + ); + resProtocol.setSubstitution( + "testing2", + Services.io.newURI("resource://testing") + ); let local = resolveURI("resource://testing2/test.js"); let remote = await remoteResolveURI("resource://testing2/test.js"); - is(local, "chrome://global/content/test.js", "Should resolve in main process"); - is(remote, "chrome://global/content/test.js", "Should resolve in child process"); + is( + local, + "chrome://global/content/test.js", + "Should resolve in main process" + ); + is( + remote, + "chrome://global/content/test.js", + "Should resolve in child process" + ); info("Clear"); resProtocol.setSubstitution("testing", null); local = resolveURI("resource://testing2/test.js"); remote = await remoteResolveURI("resource://testing2/test.js"); - is(local, "chrome://global/content/test.js", "Should resolve in main process"); - is(remote, "chrome://global/content/test.js", "Should resolve in child process"); + is( + local, + "chrome://global/content/test.js", + "Should resolve in main process" + ); + is( + remote, + "chrome://global/content/test.js", + "Should resolve in child process" + ); resProtocol.setSubstitution("testing2", null); local = resolveURI("resource://testing2/test.js"); diff --git a/netwerk/test/browser/browser_cookie_sync_across_tabs.js b/netwerk/test/browser/browser_cookie_sync_across_tabs.js index 772fb951c893..fe23afac6eee 100644 --- a/netwerk/test/browser/browser_cookie_sync_across_tabs.js +++ b/netwerk/test/browser/browser_cookie_sync_across_tabs.js @@ -8,14 +8,24 @@ add_task(async function() { info("Make sure cookie changes in one process are visible in the other"); - const kRoot = getRootDirectory(gTestPath).replace("chrome://mochitests/content/", - "https://example.com/"); + const kRoot = getRootDirectory(gTestPath).replace( + "chrome://mochitests/content/", + "https://example.com/" + ); const kTestPage = kRoot + "dummy.html"; Services.cookies.removeAll(); - let tab1 = await BrowserTestUtils.openNewForegroundTab({ gBrowser, url: kTestPage, forceNewProcess: true }); - let tab2 = await BrowserTestUtils.openNewForegroundTab({ gBrowser, url: kTestPage, forceNewProcess: true }); + let tab1 = await BrowserTestUtils.openNewForegroundTab({ + gBrowser, + url: kTestPage, + forceNewProcess: true, + }); + let tab2 = await BrowserTestUtils.openNewForegroundTab({ + gBrowser, + url: kTestPage, + forceNewProcess: true, + }); let browser1 = gBrowser.getBrowserForTab(tab1); let browser2 = gBrowser.getBrowserForTab(tab2); @@ -49,7 +59,11 @@ add_task(async function() { }); await ContentTask.spawn(browser2, null, async function() { - is(content.document.cookie, "a1=other_test; a2=again", "Cookie should be set"); + is( + content.document.cookie, + "a1=other_test; a2=again", + "Cookie should be set" + ); content.document.cookie = "a1=; expires=Thu, 01-Jan-1970 00:00:01 GMT;"; content.document.cookie = "a2=; expires=Thu, 01-Jan-1970 00:00:01 GMT;"; }); diff --git a/netwerk/test/browser/browser_cross_process_redirect.js b/netwerk/test/browser/browser_cross_process_redirect.js index e2784e34881e..d776a8d1d1b0 100644 --- a/netwerk/test/browser/browser_cross_process_redirect.js +++ b/netwerk/test/browser/browser_cross_process_redirect.js @@ -10,7 +10,12 @@ const gRegistrar = Components.manager.QueryInterface(Ci.nsIComponentRegistrar); let gLoadedInProcess2Promise = null; function _createProcessChooser(remoteTab, from, to, rejectPromise = false) { - let processChooser = new ProcessChooser(remoteTab, "example.com", "example.org", rejectPromise); + let processChooser = new ProcessChooser( + remoteTab, + "example.com", + "example.org", + rejectPromise + ); registerCleanupFunction(function() { processChooser.unregister(); }); @@ -90,21 +95,35 @@ ProcessChooser.prototype = { // nsISupports QueryInterface: ChromeUtils.generateQI([Ci.nsIObserver]), -} +}; add_task(async function() { - info("Check that a redirect in process A may be correctly handled in process B"); + info( + "Check that a redirect in process A may be correctly handled in process B" + ); - const kRoot1 = getRootDirectory(gTestPath).replace("chrome://mochitests/content/", - "https://example.com/"); - const kRoot2 = getRootDirectory(gTestPath).replace("chrome://mochitests/content/", - "https://example.org/"); + const kRoot1 = getRootDirectory(gTestPath).replace( + "chrome://mochitests/content/", + "https://example.com/" + ); + const kRoot2 = getRootDirectory(gTestPath).replace( + "chrome://mochitests/content/", + "https://example.org/" + ); const kRoot3 = getRootDirectory(gTestPath); // This process will attempt to load the page that redirects to a different origin - let tab1 = await BrowserTestUtils.openNewForegroundTab({ gBrowser, url: kRoot1 + "dummy.html", forceNewProcess: true }); + let tab1 = await BrowserTestUtils.openNewForegroundTab({ + gBrowser, + url: kRoot1 + "dummy.html", + forceNewProcess: true, + }); // This process will eventually receive the redirected channel. - let tab2 = await BrowserTestUtils.openNewForegroundTab({ gBrowser, url: kRoot2 + "dummy.html", forceNewProcess: true }); + let tab2 = await BrowserTestUtils.openNewForegroundTab({ + gBrowser, + url: kRoot2 + "dummy.html", + forceNewProcess: true, + }); let browser1 = gBrowser.getBrowserForTab(tab1); let browser2 = gBrowser.getBrowserForTab(tab2); @@ -112,7 +131,11 @@ add_task(async function() { // This is for testing purposes only. // This "process chooser" will direct the channel to be opened in the second // tab, and thus in the second parent. - let processChooser = _createProcessChooser(browser2.frameLoader.remoteTab, "example.com", "example.org"); + let processChooser = _createProcessChooser( + browser2.frameLoader.remoteTab, + "example.com", + "example.org" + ); info("Loading redirected URL"); // Open the URL in the first process. We expect it to wind up in the second @@ -120,18 +143,32 @@ add_task(async function() { // Define the child listener in the new channel. await ContentTask.spawn(browser2, null, async function(arg) { - function ChannelListener(childListener) { this.childListener = childListener; } + function ChannelListener(childListener) { + this.childListener = childListener; + } ChannelListener.prototype = { onStartRequest(aRequest) { info("onStartRequest"); let channel = aRequest.QueryInterface(Ci.nsIChannel); - Assert.equal(channel.URI.spec, this.childListener.URI, "Make sure the channel has the proper URI"); - Assert.equal(channel.originalURI.spec, this.childListener.originalURI, "Make sure the originalURI is correct"); + Assert.equal( + channel.URI.spec, + this.childListener.URI, + "Make sure the channel has the proper URI" + ); + Assert.equal( + channel.originalURI.spec, + this.childListener.originalURI, + "Make sure the originalURI is correct" + ); }, onStopRequest(aRequest, aStatusCode) { info("onStopRequest"); Assert.equal(aStatusCode, Cr.NS_OK, "Check the status code"); - Assert.equal(this.gotData, true, "Check that the channel received data"); + Assert.equal( + this.gotData, + true, + "Check that the channel received data" + ); if (this.childListener.onComplete) { this.childListener.onComplete(); } @@ -141,10 +178,17 @@ add_task(async function() { this.gotData = true; info("onDataAvailable"); }, - QueryInterface: ChromeUtils.generateQI([Ci.nsIStreamListener,Ci.nsIRequestObserver]) + QueryInterface: ChromeUtils.generateQI([ + Ci.nsIStreamListener, + Ci.nsIRequestObserver, + ]), }; - function ChildListener(uri, originalURI, resolve) { this.URI = uri; this.originalURI = originalURI; this.resolve = resolve;} + function ChildListener(uri, originalURI, resolve) { + this.URI = uri; + this.originalURI = originalURI; + this.resolve = resolve; + } ChildListener.prototype = { // nsIChildProcessChannelListener onChannelReady(aChildChannel, aIdentifier) { @@ -161,32 +205,54 @@ add_task(async function() { }, lockFactory() {}, // nsISupports - QueryInterface: ChromeUtils.generateQI([Ci.nsIChildProcessChannelListener, Ci.nsIFactory]), - classID: Components.ID("{a6c142a9-eb38-4a09-a940-b71cdad479e1}") - } + QueryInterface: ChromeUtils.generateQI([ + Ci.nsIChildProcessChannelListener, + Ci.nsIFactory, + ]), + classID: Components.ID("{a6c142a9-eb38-4a09-a940-b71cdad479e1}"), + }; content.window.ChildListener = ChildListener; }); // This promise instantiates a ChildListener and is resolved when the redirected // channel is completed. - let loadedInProcess2Promise = ContentTask.spawn(browser2, { URI: kRoot2 + "dummy.html", originalURI: kRoot1 + "redirect.sjs?" + kRoot2 + "dummy.html"}, async function(arg) { - // We register the listener in process no. 2 - return new Promise(resolve => { - var childListener = new content.window.ChildListener(arg.URI, arg.originalURI, resolve); - var registrar = Components.manager.QueryInterface(Ci.nsIComponentRegistrar); - childListener.onComplete = () => { - registrar.unregisterFactory(childListener.classID, childListener); - } - registrar.registerFactory(childListener.classID, "", - "@mozilla.org/network/childProcessChannelListener;1", - childListener); - }); - }); + let loadedInProcess2Promise = ContentTask.spawn( + browser2, + { + URI: kRoot2 + "dummy.html", + originalURI: kRoot1 + "redirect.sjs?" + kRoot2 + "dummy.html", + }, + async function(arg) { + // We register the listener in process no. 2 + return new Promise(resolve => { + var childListener = new content.window.ChildListener( + arg.URI, + arg.originalURI, + resolve + ); + var registrar = Components.manager.QueryInterface( + Ci.nsIComponentRegistrar + ); + childListener.onComplete = () => { + registrar.unregisterFactory(childListener.classID, childListener); + }; + registrar.registerFactory( + childListener.classID, + "", + "@mozilla.org/network/childProcessChannelListener;1", + childListener + ); + }); + } + ); let browser1LoadHasStopped = BrowserTestUtils.browserStopped(browser1); - await BrowserTestUtils.loadURI(browser1, kRoot1 + "redirect.sjs?" + kRoot2 + "dummy.html"); + await BrowserTestUtils.loadURI( + browser1, + kRoot1 + "redirect.sjs?" + kRoot2 + "dummy.html" + ); // Check that the channel was delivered to process no. 2 await loadedInProcess2Promise; @@ -195,9 +261,17 @@ add_task(async function() { await browser1LoadHasStopped; // check that a rejected promise also works. - processChooser = _createProcessChooser(browser2.frameLoader.remoteTab, "example.com", "example.org", true); + processChooser = _createProcessChooser( + browser2.frameLoader.remoteTab, + "example.com", + "example.org", + true + ); let browser1LoadHasStoppedAgain = BrowserTestUtils.browserStopped(browser1); - await BrowserTestUtils.loadURI(browser1, kRoot1 + "redirect.sjs?" + kRoot2 + "dummy.html"); + await BrowserTestUtils.loadURI( + browser1, + kRoot1 + "redirect.sjs?" + kRoot2 + "dummy.html" + ); await browser1LoadHasStoppedAgain; info("this is done now"); diff --git a/netwerk/test/browser/browser_nsIFormPOSTActionChannel.js b/netwerk/test/browser/browser_nsIFormPOSTActionChannel.js index 27cf91c904ce..71fc50f6816e 100644 --- a/netwerk/test/browser/browser_nsIFormPOSTActionChannel.js +++ b/netwerk/test/browser/browser_nsIFormPOSTActionChannel.js @@ -17,8 +17,7 @@ const NORMAL_ACTION_URI = ACTION_BASE + "normal.html"; const UPLOAD_ACTION_URI = ACTION_BASE + "upload.html"; const POST_ACTION_URI = ACTION_BASE + "post.html"; -function CustomProtocolHandler() { -} +function CustomProtocolHandler() {} CustomProtocolHandler.prototype = { /** nsIProtocolHandler */ get scheme() { @@ -28,8 +27,10 @@ CustomProtocolHandler.prototype = { return -1; }, get protocolFlags() { - return Ci.nsIProtocolHandler.URI_NORELATIVE | - Ci.nsIProtocolHandler.URI_IS_LOCAL_RESOURCE; + return ( + Ci.nsIProtocolHandler.URI_NORELATIVE | + Ci.nsIProtocolHandler.URI_IS_LOCAL_RESOURCE + ); }, newChannel(aURI, aLoadInfo) { return new CustomChannel(aURI, aLoadInfo); @@ -48,9 +49,11 @@ CustomProtocolHandler.prototype = { lockFactory() {}, /** nsISupports */ - QueryInterface: ChromeUtils.generateQI([Ci.nsIProtocolHandler, - Ci.nsIFactory]), - classID: Components.ID("{16d594bc-d9d8-47ae-a139-ea714dc0c35c}") + QueryInterface: ChromeUtils.generateQI([ + Ci.nsIProtocolHandler, + Ci.nsIFactory, + ]), + classID: Components.ID("{16d594bc-d9d8-47ae-a139-ea714dc0c35c}"), }; function CustomChannel(aURI, aLoadInfo) { @@ -94,8 +97,7 @@ CustomChannel.prototype = { get contentType() { return "text/html"; }, - set contentType(val) { - }, + set contentType(val) {}, contentCharset: "UTF-8", get contentLength() { return -1; @@ -137,8 +139,9 @@ document.getElementById('form').submit(); var postData = ""; var headers = {}; if (this._uploadStream) { - var bstream = Cc["@mozilla.org/binaryinputstream;1"] - .createInstance(Ci.nsIBinaryInputStream); + var bstream = Cc["@mozilla.org/binaryinputstream;1"].createInstance( + Ci.nsIBinaryInputStream + ); bstream.setInputStream(this._uploadStream); postData = bstream.readBytes(bstream.available()); @@ -160,22 +163,23 @@ document.getElementById('form').submit(); `; - var stream = Cc["@mozilla.org/io/string-input-stream;1"] - .createInstance(Ci.nsIStringInputStream); + var stream = Cc["@mozilla.org/io/string-input-stream;1"].createInstance( + Ci.nsIStringInputStream + ); stream.setData(data, data.length); var runnable = { run: () => { try { aListener.onStartRequest(this, null); - } catch(e) {} + } catch (e) {} try { aListener.onDataAvailable(this, stream, 0, stream.available()); - } catch(e) {} + } catch (e) {} try { aListener.onStopRequest(this, null, Cr.NS_OK); - } catch(e) {} - } + } catch (e) {} + }, }; Services.tm.dispatchToMainThread(runnable); }, @@ -184,7 +188,7 @@ document.getElementById('form').submit(); get name() { return this.uri.spec; }, - isPending () { + isPending() { return false; }, get status() { @@ -192,9 +196,10 @@ document.getElementById('form').submit(); }, cancel(status) {}, loadGroup: null, - loadFlags: Ci.nsIRequest.LOAD_NORMAL | - Ci.nsIRequest.INHIBIT_CACHING | - Ci.nsIRequest.LOAD_BYPASS_CACHE, + loadFlags: + Ci.nsIRequest.LOAD_NORMAL | + Ci.nsIRequest.INHIBIT_CACHING | + Ci.nsIRequest.LOAD_BYPASS_CACHE, }; function frameScript() { @@ -203,11 +208,17 @@ function frameScript() { if (content) { var frame = content.document.getElementById("frame"); if (frame) { - var upload_stream = frame.contentDocument.getElementById("upload_stream"); + var upload_stream = frame.contentDocument.getElementById( + "upload_stream" + ); var post_data = frame.contentDocument.getElementById("post_data"); var headers = frame.contentDocument.getElementById("upload_headers"); if (upload_stream && post_data && headers) { - sendAsyncMessage("Test:IFrameLoaded", [upload_stream.value, post_data.value, headers.value]); + sendAsyncMessage("Test:IFrameLoaded", [ + upload_stream.value, + post_data.value, + headers.value, + ]); return; } } @@ -225,7 +236,10 @@ function loadTestTab(uri) { var browser = gBrowser.selectedBrowser; let manager = browser.messageManager; - browser.messageManager.loadFrameScript("data:,(" + frameScript.toString() + ")();", true); + browser.messageManager.loadFrameScript( + "data:,(" + frameScript.toString() + ")();", + true + ); return new Promise(resolve => { function listener({ data: [hasUploadStream, postData, headers] }) { @@ -241,9 +255,12 @@ function loadTestTab(uri) { add_task(async function() { var handler = new CustomProtocolHandler(); var registrar = Components.manager.QueryInterface(Ci.nsIComponentRegistrar); - registrar.registerFactory(handler.classID, "", - "@mozilla.org/network/protocol;1?name=" + handler.scheme, - handler); + registrar.registerFactory( + handler.classID, + "", + "@mozilla.org/network/protocol;1?name=" + handler.scheme, + handler + ); registerCleanupFunction(function() { registrar.unregisterFactory(handler.classID, handler); }); @@ -267,8 +284,7 @@ add_task(async function() { var [hasUploadStream, postData, headers] = await loadTestTab(POST_FORM_URI); is(hasUploadStream, "yes", "post action should have uploadStream"); - is(postData, "foo=bar\r\n", - "POST data is received correctly"); + is(postData, "foo=bar\r\n", "POST data is received correctly"); is(headers["Content-Type"], "text/plain", "Content-Type header is correct"); is(headers["Content-Length"], undefined, "Content-Length header is correct"); diff --git a/netwerk/test/browser/browser_post_file.js b/netwerk/test/browser/browser_post_file.js index 6040fcbe2c2a..30b5d7a5f732 100644 --- a/netwerk/test/browser/browser_post_file.js +++ b/netwerk/test/browser/browser_post_file.js @@ -2,7 +2,7 @@ * Tests for bug 1241100: Post to local file should not overwrite the file. */ -const {OS} = ChromeUtils.import("resource://gre/modules/osfile.jsm"); +const { OS } = ChromeUtils.import("resource://gre/modules/osfile.jsm"); async function createTestFile(filename, content) { let path = OS.Path.join(OS.Constants.Path.tmpDir, filename); @@ -78,7 +78,10 @@ add_task(async function() { gBrowser.selectedTab = BrowserTestUtils.addTab(gBrowser, postURI); let browser = gBrowser.selectedBrowser; - browser.messageManager.loadFrameScript("data:,(" + frameScript.toString() + ")();", true); + browser.messageManager.loadFrameScript( + "data:,(" + frameScript.toString() + ")();", + true + ); await new Promise(resolve => { let manager = browser.messageManager; diff --git a/netwerk/test/browser/browser_resource_navigation.js b/netwerk/test/browser/browser_resource_navigation.js index 0c5a8cc4a667..0210eb45658b 100644 --- a/netwerk/test/browser/browser_resource_navigation.js +++ b/netwerk/test/browser/browser_resource_navigation.js @@ -8,46 +8,69 @@ add_task(async function() { info("Make sure navigation through links in resource:// pages work"); - await BrowserTestUtils.withNewTab({ gBrowser, url: "resource://gre/" }, async function(browser) { - // Following a directory link shall properly open the directory (bug 1224046) - await ContentTask.spawn(browser, {}, function() { - let link = Array.prototype.filter.call(content.document.getElementsByClassName('dir'), function(element) { - let name = element.textContent; - // Depending whether resource:// is backed by jar: or file://, - // directories either have a trailing slash or they don't. - if (name.endsWith("/")) { - name = name.slice(0, -1); - } - return name == "components"; - })[0]; - // First ensure the link is in the viewport - link.scrollIntoView(); - // Then click on it. - link.click(); - }); + await BrowserTestUtils.withNewTab( + { gBrowser, url: "resource://gre/" }, + async function(browser) { + // Following a directory link shall properly open the directory (bug 1224046) + await ContentTask.spawn(browser, {}, function() { + let link = Array.prototype.filter.call( + content.document.getElementsByClassName("dir"), + function(element) { + let name = element.textContent; + // Depending whether resource:// is backed by jar: or file://, + // directories either have a trailing slash or they don't. + if (name.endsWith("/")) { + name = name.slice(0, -1); + } + return name == "components"; + } + )[0]; + // First ensure the link is in the viewport + link.scrollIntoView(); + // Then click on it. + link.click(); + }); - await BrowserTestUtils.browserLoaded(browser, undefined, "resource://gre/components/"); + await BrowserTestUtils.browserLoaded( + browser, + undefined, + "resource://gre/components/" + ); - // Following the parent link shall properly open the parent (bug 1366180) - await ContentTask.spawn(browser, {}, function() { - let link = content.document.getElementById('UI_goUp').getElementsByTagName('a')[0]; - // The link should always be high enough in the page to be in the viewport. - link.click(); - }); + // Following the parent link shall properly open the parent (bug 1366180) + await ContentTask.spawn(browser, {}, function() { + let link = content.document + .getElementById("UI_goUp") + .getElementsByTagName("a")[0]; + // The link should always be high enough in the page to be in the viewport. + link.click(); + }); - await BrowserTestUtils.browserLoaded(browser, undefined, "resource://gre/"); + await BrowserTestUtils.browserLoaded( + browser, + undefined, + "resource://gre/" + ); - // Following a link to a given file shall properly open the file. - await ContentTask.spawn(browser, {}, function() { - let link = Array.prototype.filter.call(content.document.getElementsByClassName('file'), function(element) { - return element.textContent == "greprefs.js"; - })[0]; - link.scrollIntoView(); - link.click(); - }); + // Following a link to a given file shall properly open the file. + await ContentTask.spawn(browser, {}, function() { + let link = Array.prototype.filter.call( + content.document.getElementsByClassName("file"), + function(element) { + return element.textContent == "greprefs.js"; + } + )[0]; + link.scrollIntoView(); + link.click(); + }); - await BrowserTestUtils.browserLoaded(browser, undefined, "resource://gre/greprefs.js"); + await BrowserTestUtils.browserLoaded( + browser, + undefined, + "resource://gre/greprefs.js" + ); - ok(true, "Got to the end of the test!"); - }); + ok(true, "Got to the end of the test!"); + } + ); }); diff --git a/netwerk/test/browser/browser_test_favicon.js b/netwerk/test/browser/browser_test_favicon.js index f5b96f2f5832..58ad4d949d2a 100644 --- a/netwerk/test/browser/browser_test_favicon.js +++ b/netwerk/test/browser/browser_test_favicon.js @@ -2,9 +2,13 @@ // domain. The cookie should be considered third party. add_task(async function() { - const iconUrl = "http://example.org/browser/netwerk/test/browser/damonbowling.jpg"; - const pageUrl = "http://example.com/browser/netwerk/test/browser/file_favicon.html"; - await SpecialPowers.pushPrefEnv({"set": [["network.cookie.cookieBehavior", 1]]}); + const iconUrl = + "http://example.org/browser/netwerk/test/browser/damonbowling.jpg"; + const pageUrl = + "http://example.com/browser/netwerk/test/browser/file_favicon.html"; + await SpecialPowers.pushPrefEnv({ + set: [["network.cookie.cookieBehavior", 1]], + }); let promise = TestUtils.topicObserved("cookie-rejected", subject => { let uri = subject.QueryInterface(Ci.nsIURI); diff --git a/netwerk/test/browser/browser_test_io_activity.js b/netwerk/test/browser/browser_test_io_activity.js index a86a92756ca3..e33b7ffdb035 100644 --- a/netwerk/test/browser/browser_test_io_activity.js +++ b/netwerk/test/browser/browser_test_io_activity.js @@ -4,8 +4,10 @@ * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ -const ROOT_URL = getRootDirectory(gTestPath).replace("chrome://mochitests/content/", - "https://example.com/"); +const ROOT_URL = getRootDirectory(gTestPath).replace( + "chrome://mochitests/content/", + "https://example.com/" +); const TEST_URL = "about:license"; const TEST_URL2 = ROOT_URL + "ioactivity.html"; @@ -15,34 +17,32 @@ var gotSqlite = false; var gotEmptyData = false; function processResults(results) { - for (let data of results) { - console.log(data.location); - gotEmptyData = data.rx == 0 && data.tx == 0 && !gotEmptyData - gotSocket = data.location.startsWith("socket://127.0.0.1:") || gotSocket; - gotFile = data.location.endsWith("aboutLicense.css") || gotFile; - gotSqlite = data.location.endsWith("places.sqlite") || gotSqlite; - } -}; + for (let data of results) { + console.log(data.location); + gotEmptyData = data.rx == 0 && data.tx == 0 && !gotEmptyData; + gotSocket = data.location.startsWith("socket://127.0.0.1:") || gotSocket; + gotFile = data.location.endsWith("aboutLicense.css") || gotFile; + gotSqlite = data.location.endsWith("places.sqlite") || gotSqlite; + } +} add_task(async function testRequestIOActivity() { - await SpecialPowers.pushPrefEnv({ - "set": [ - ["io.activity.enabled", true], - ] - }); - waitForExplicitFinish(); - Services.obs.notifyObservers(null, "profile-initial-state"); + await SpecialPowers.pushPrefEnv({ + set: [["io.activity.enabled", true]], + }); + waitForExplicitFinish(); + Services.obs.notifyObservers(null, "profile-initial-state"); - await BrowserTestUtils.withNewTab(TEST_URL, async function(browser) { - await BrowserTestUtils.withNewTab(TEST_URL2, async function(browser) { - let results = await ChromeUtils.requestIOActivity(); - processResults(results); + await BrowserTestUtils.withNewTab(TEST_URL, async function(browser) { + await BrowserTestUtils.withNewTab(TEST_URL2, async function(browser) { + let results = await ChromeUtils.requestIOActivity(); + processResults(results); - ok(gotSocket, "A socket was used"); - // test deactivated for now - // ok(gotFile, "A file was used"); - ok(gotSqlite, "A sqlite DB was used"); - ok(!gotEmptyData, "Every I/O event had data"); - }); + ok(gotSocket, "A socket was used"); + // test deactivated for now + // ok(gotFile, "A file was used"); + ok(gotSqlite, "A sqlite DB was used"); + ok(!gotEmptyData, "Every I/O event had data"); }); + }); }); diff --git a/netwerk/test/httpserver/httpd.js b/netwerk/test/httpserver/httpd.js index 3d60c50837fa..777a99e0f41c 100644 --- a/netwerk/test/httpserver/httpd.js +++ b/netwerk/test/httpserver/httpd.js @@ -50,7 +50,7 @@ var DEBUG_TIMESTAMP = false; // non-const so tweakable in server tests var gGlobalObject = Cu.getGlobalForObject(this); -const {Services} = ChromeUtils.import("resource://gre/modules/Services.jsm"); +const { Services } = ChromeUtils.import("resource://gre/modules/Services.jsm"); /** * Asserts that the given condition holds. If it doesn't, the given message is @@ -65,7 +65,13 @@ function NS_ASSERT(cond, msg) { dumpn("###!!! Stack follows:"); var stack = new Error().stack.split(/\n/); - dumpn(stack.map(function(val) { return "###!!! " + val; }).join("\n")); + dumpn( + stack + .map(function(val) { + return "###!!! " + val; + }) + .join("\n") + ); throw Components.Exception("", Cr.NS_ERROR_ABORT); } @@ -76,8 +82,7 @@ function HttpError(code, description) { this.code = code; this.description = description; } -HttpError.prototype = -{ +HttpError.prototype = { toString() { return this.code + " " + this.description; }, @@ -114,23 +119,24 @@ var HTTP_505 = new HttpError(505, "HTTP Version Not Supported"); /** Creates a hash with fields corresponding to the values in arr. */ function array2obj(arr) { var obj = {}; - for (var i = 0; i < arr.length; i++) + for (var i = 0; i < arr.length; i++) { obj[arr[i]] = arr[i]; + } return obj; } /** Returns an array of the integers x through y, inclusive. */ function range(x, y) { var arr = []; - for (var i = x; i <= y; i++) + for (var i = x; i <= y; i++) { arr.push(i); + } return arr; } /** An object (hash) whose fields are the numbers of all HTTP error codes. */ const HTTP_ERROR_CODES = array2obj(range(400, 417).concat(range(500, 505))); - /** * The character used to distinguish hidden files from non-hidden files, a la * the leading dot in Apache. Since that mechanism also hides files from @@ -159,17 +165,19 @@ function dumpn(str) { if (DEBUG) { var prefix = "HTTPD-INFO | "; if (DEBUG_TIMESTAMP) { - if (firstStamp === 0) + if (firstStamp === 0) { firstStamp = Date.now(); + } var elapsed = Date.now() - firstStamp; // milliseconds var min = Math.floor(elapsed / 60000); var sec = (elapsed % 60000) / 1000; - if (sec < 10) + if (sec < 10) { prefix += min + ":0" + sec.toFixed(3) + " | "; - else + } else { prefix += min + ":" + sec.toFixed(3) + " | "; + } } dump(prefix + str + "\n"); @@ -183,7 +191,6 @@ function dumpStack() { stack.forEach(dumpn); } - /** The XPCOM thread manager. */ var gThreadManager = null; @@ -192,36 +199,52 @@ var gThreadManager = null; * speedup over doing the same from base principles. See the docs at * http://developer.mozilla.org/en/docs/Components.Constructor for details. */ -const ServerSocket = CC("@mozilla.org/network/server-socket;1", - "nsIServerSocket", - "init"); -const ServerSocketIPv6 = CC("@mozilla.org/network/server-socket;1", - "nsIServerSocket", - "initIPv6"); -const ScriptableInputStream = CC("@mozilla.org/scriptableinputstream;1", - "nsIScriptableInputStream", - "init"); -const Pipe = CC("@mozilla.org/pipe;1", - "nsIPipe", - "init"); -const FileInputStream = CC("@mozilla.org/network/file-input-stream;1", - "nsIFileInputStream", - "init"); -const ConverterInputStream = CC("@mozilla.org/intl/converter-input-stream;1", - "nsIConverterInputStream", - "init"); -const WritablePropertyBag = CC("@mozilla.org/hash-property-bag;1", - "nsIWritablePropertyBag2"); -const SupportsString = CC("@mozilla.org/supports-string;1", - "nsISupportsString"); +const ServerSocket = CC( + "@mozilla.org/network/server-socket;1", + "nsIServerSocket", + "init" +); +const ServerSocketIPv6 = CC( + "@mozilla.org/network/server-socket;1", + "nsIServerSocket", + "initIPv6" +); +const ScriptableInputStream = CC( + "@mozilla.org/scriptableinputstream;1", + "nsIScriptableInputStream", + "init" +); +const Pipe = CC("@mozilla.org/pipe;1", "nsIPipe", "init"); +const FileInputStream = CC( + "@mozilla.org/network/file-input-stream;1", + "nsIFileInputStream", + "init" +); +const ConverterInputStream = CC( + "@mozilla.org/intl/converter-input-stream;1", + "nsIConverterInputStream", + "init" +); +const WritablePropertyBag = CC( + "@mozilla.org/hash-property-bag;1", + "nsIWritablePropertyBag2" +); +const SupportsString = CC( + "@mozilla.org/supports-string;1", + "nsISupportsString" +); /* These two are non-const only so a test can overwrite them. */ -var BinaryInputStream = CC("@mozilla.org/binaryinputstream;1", - "nsIBinaryInputStream", - "setInputStream"); -var BinaryOutputStream = CC("@mozilla.org/binaryoutputstream;1", - "nsIBinaryOutputStream", - "setOutputStream"); +var BinaryInputStream = CC( + "@mozilla.org/binaryinputstream;1", + "nsIBinaryInputStream", + "setInputStream" +); +var BinaryOutputStream = CC( + "@mozilla.org/binaryoutputstream;1", + "nsIBinaryOutputStream", + "setOutputStream" +); /** * Returns the RFC 822/1123 representation of a date. @@ -246,8 +269,20 @@ function toDateString(date) { // const wkdayStrings = ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"]; - const monthStrings = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", - "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"]; + const monthStrings = [ + "Jan", + "Feb", + "Mar", + "Apr", + "May", + "Jun", + "Jul", + "Aug", + "Sep", + "Oct", + "Nov", + "Dec", + ]; /** * Processes a date and returns the encoded UTC time as a string according to @@ -260,15 +295,15 @@ function toDateString(date) { */ function toTime(date) { var hrs = date.getUTCHours(); - var rv = (hrs < 10) ? "0" + hrs : hrs; + var rv = hrs < 10 ? "0" + hrs : hrs; var mins = date.getUTCMinutes(); rv += ":"; - rv += (mins < 10) ? "0" + mins : mins; + rv += mins < 10 ? "0" + mins : mins; var secs = date.getUTCSeconds(); rv += ":"; - rv += (secs < 10) ? "0" + secs : secs; + rv += secs < 10 ? "0" + secs : secs; return rv; } @@ -287,7 +322,7 @@ function toDateString(date) { var month = date.getUTCMonth(); var year = date.getUTCFullYear(); - var rv = (day < 10) ? "0" + day : day; + var rv = day < 10 ? "0" + day : day; rv += " " + monthStrings[month]; rv += " " + year; @@ -309,14 +344,17 @@ function toDateString(date) { */ function printObj(o, showMembers) { var s = "******************************\n"; - s += "o = {\n"; + s += "o = {\n"; for (var i in o) { - if (typeof(i) != "string" || - (showMembers || (i.length > 0 && i[0] != "_"))) + if ( + typeof i != "string" || + (showMembers || (i.length > 0 && i[0] != "_")) + ) { s += " " + i + ": " + o[i] + ",\n"; + } } - s += " };\n"; - s += "******************************"; + s += " };\n"; + s += "******************************"; dumpn(s); } @@ -324,8 +362,9 @@ function printObj(o, showMembers) { * Instantiates a new HTTP server. */ function nsHttpServer() { - if (!gThreadManager) + if (!gThreadManager) { gThreadManager = Cc["@mozilla.org/thread-manager;1"].getService(); + } /** The port on which this server listens. */ this._port = undefined; @@ -363,8 +402,7 @@ function nsHttpServer() { */ this._connections = {}; } -nsHttpServer.prototype = -{ +nsHttpServer.prototype = { // NSISERVERSOCKETLISTENER /** @@ -385,8 +423,9 @@ nsHttpServer.prototype = const SEGMENT_SIZE = 8192; const SEGMENT_COUNT = 1024; try { - var input = trans.openInputStream(0, SEGMENT_SIZE, SEGMENT_COUNT) - .QueryInterface(Ci.nsIAsyncInputStream); + var input = trans + .openInputStream(0, SEGMENT_SIZE, SEGMENT_COUNT) + .QueryInterface(Ci.nsIAsyncInputStream); var output = trans.openOutputStream(0, 0, 0); } catch (e) { dumpn("*** error opening transport streams: " + e); @@ -397,8 +436,15 @@ nsHttpServer.prototype = var connectionNumber = ++this._connectionGen; try { - var conn = new Connection(input, output, this, socket.port, trans.port, - connectionNumber, trans); + var conn = new Connection( + input, + output, + this, + socket.port, + trans.port, + connectionNumber, + trans + ); var reader = new RequestReader(conn); // XXX add request timeout functionality here! @@ -447,15 +493,16 @@ nsHttpServer.prototype = // Notify asynchronously so that any pending teardown in stop() has a // chance to run first. var self = this; - var stopEvent = - { - run() { - dumpn("*** _notifyStopped async callback"); - self._notifyStopped(); - }, - }; - gThreadManager.currentThread - .dispatch(stopEvent, Ci.nsIThread.DISPATCH_NORMAL); + var stopEvent = { + run() { + dumpn("*** _notifyStopped async callback"); + self._notifyStopped(); + }, + }; + gThreadManager.currentThread.dispatch( + stopEvent, + Ci.nsIThread.DISPATCH_NORMAL + ); } }, @@ -469,8 +516,9 @@ nsHttpServer.prototype = }, _start(port, host) { - if (this._socket) + if (this._socket) { throw Components.Exception("", Cr.NS_ERROR_ALREADY_INITIALIZED); + } this._port = port; this._doQuit = this._socketClosed = false; @@ -482,14 +530,24 @@ nsHttpServer.prototype = // network.http.max-persistent-connections-per-proxy concurrent // connections, plus a safety margin in case some other process is // talking to the server as well. - var maxConnections = 5 + Math.max( - Services.prefs.getIntPref("network.http.max-persistent-connections-per-server"), - Services.prefs.getIntPref("network.http.max-persistent-connections-per-proxy")); + var maxConnections = + 5 + + Math.max( + Services.prefs.getIntPref( + "network.http.max-persistent-connections-per-server" + ), + Services.prefs.getIntPref( + "network.http.max-persistent-connections-per-proxy" + ) + ); try { var loopback = true; - if (this._host != "127.0.0.1" && this._host != "localhost" && - this._host != "[::1]") { + if ( + this._host != "127.0.0.1" && + this._host != "localhost" && + this._host != "[::1]" + ) { loopback = false; } @@ -502,19 +560,26 @@ nsHttpServer.prototype = for (var i = 100; i; i--) { var temp = null; if (this._host.includes(":")) { - temp = new ServerSocketIPv6(this._port, - loopback, // true = localhost, false = everybody - maxConnections); + temp = new ServerSocketIPv6( + this._port, + loopback, // true = localhost, false = everybody + maxConnections + ); } else { - temp = new ServerSocket(this._port, - loopback, // true = localhost, false = everybody - maxConnections); + temp = new ServerSocket( + this._port, + loopback, // true = localhost, false = everybody + maxConnections + ); } var allowed = Services.io.allowPort(temp.port, "http"); if (!allowed) { - dumpn(">>>Warning: obtained ServerSocket listens on a blocked " + - "port: " + temp.port); + dumpn( + ">>>Warning: obtained ServerSocket listens on a blocked " + + "port: " + + temp.port + ); } if (!allowed && this._port == -1) { @@ -528,15 +593,22 @@ nsHttpServer.prototype = } if (!socket) { - throw new Error("No socket server available. Are there no available ports?"); + throw new Error( + "No socket server available. Are there no available ports?" + ); } socket.asyncListen(this); this._port = socket.port; this._identity._initialize(socket.port, host, true); this._socket = socket; - dumpn(">>> listening on port " + socket.port + ", " + maxConnections + - " pending connections"); + dumpn( + ">>> listening on port " + + socket.port + + ", " + + maxConnections + + " pending connections" + ); } catch (e) { dump("\n!!! could not start server on port " + port + ": " + e + "\n\n"); throw Components.Exception("", Cr.NS_ERROR_NOT_AVAILABLE); @@ -547,8 +619,9 @@ nsHttpServer.prototype = // see nsIHttpServer.stop // stop(callback) { - if (!this._socket) + if (!this._socket) { throw Components.Exception("", Cr.NS_ERROR_UNEXPECTED); + } // If no argument was provided to stop, return a promise. let returnValue = undefined; @@ -558,9 +631,12 @@ nsHttpServer.prototype = }); } - this._stopCallback = typeof callback === "function" - ? callback - : function() { callback.onStopped(); }; + this._stopCallback = + typeof callback === "function" + ? callback + : function() { + callback.onStopped(); + }; dumpn(">>> stopping listening on port " + this._socket.port); this._socket.close(); @@ -581,8 +657,9 @@ nsHttpServer.prototype = // see nsIHttpServer.registerFile // registerFile(path, file) { - if (file && (!file.exists() || file.isDirectory())) + if (file && (!file.exists() || file.isDirectory())) { throw Components.Exception("", Cr.NS_ERROR_INVALID_ARG); + } this._handler.registerFile(path, file); }, @@ -592,11 +669,13 @@ nsHttpServer.prototype = // registerDirectory(path, directory) { // XXX true path validation! - if (path.charAt(0) != "/" || - path.charAt(path.length - 1) != "/" || - (directory && - (!directory.exists() || !directory.isDirectory()))) + if ( + path.charAt(0) != "/" || + path.charAt(path.length - 1) != "/" || + (directory && (!directory.exists() || !directory.isDirectory())) + ) { throw Components.Exception("", Cr.NS_ERROR_INVALID_ARG); + } // XXX determine behavior of nonexistent /foo/bar when a /foo/bar/ mapping // exists! @@ -696,14 +775,15 @@ nsHttpServer.prototype = return this; }, - // NSISUPPORTS // // see nsISupports.QueryInterface // - QueryInterface: ChromeUtils.generateQI(["nsIHttpServer", "nsIServerSocketListener"]), - + QueryInterface: ChromeUtils.generateQI([ + "nsIHttpServer", + "nsIServerSocketListener", + ]), // NON-XPCOM PUBLIC API @@ -727,8 +807,9 @@ nsHttpServer.prototype = // looking forward to ES5, there's no less ugly yet still O(1) way to do // this. // - for (var n in this._connections) + for (var n in this._connections) { return true; + } return false; }, @@ -762,17 +843,23 @@ nsHttpServer.prototype = * the connection that was closed */ _connectionClosed(connection) { - NS_ASSERT(connection.number in this._connections, - "closing a connection " + this + " that we never added to the " + - "set of open connections?"); - NS_ASSERT(this._connections[connection.number] === connection, - "connection number mismatch? " + - this._connections[connection.number]); + NS_ASSERT( + connection.number in this._connections, + "closing a connection " + + this + + " that we never added to the " + + "set of open connections?" + ); + NS_ASSERT( + this._connections[connection.number] === connection, + "connection number mismatch? " + this._connections[connection.number] + ); delete this._connections[connection.number]; // Fire a pending server-stopped notification if it's our responsibility. - if (!this._hasOpenConnections() && this._socketClosed) + if (!this._hasOpenConnections() && this._socketClosed) { this._notifyStopped(); + } // Bug 508125: Add a GC here else we'll use gigabytes of memory running // mochitests. We can't rely on xpcshell doing an automated GC, as that // would interfere with testing GC stuff... @@ -801,18 +888,18 @@ var HttpServer = nsHttpServer; // IPv4address = 1*digit "." 1*digit "." 1*digit "." 1*digit // -const HOST_REGEX = - new RegExp("^(?:" + - // *( domainlabel "." ) - "(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\\.)*" + - // toplabel - "[a-z](?:[a-z0-9-]*[a-z0-9])?" + - "|" + - // IPv4 address - "\\d+\\.\\d+\\.\\d+\\.\\d+" + - ")$", - "i"); - +const HOST_REGEX = new RegExp( + "^(?:" + + // *( domainlabel "." ) + "(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\\.)*" + + // toplabel + "[a-z](?:[a-z0-9-]*[a-z0-9])?" + + "|" + + // IPv4 address + "\\d+\\.\\d+\\.\\d+\\.\\d+" + + ")$", + "i" +); /** * Represents the identity of a server. An identity consists of a set of @@ -855,18 +942,18 @@ function ServerIdentity() { * Note the "x" prefix on hostnames, which prevents collisions with special * JS names like "prototype". */ - this._locations = { "xlocalhost": {} }; + this._locations = { xlocalhost: {} }; } -ServerIdentity.prototype = -{ +ServerIdentity.prototype = { // NSIHTTPSERVERIDENTITY // // see nsIHttpServerIdentity.primaryScheme // get primaryScheme() { - if (this._primaryPort === -1) + if (this._primaryPort === -1) { throw Components.Exception("", Cr.NS_ERROR_NOT_INITIALIZED); + } return this._primaryScheme; }, @@ -874,8 +961,9 @@ ServerIdentity.prototype = // see nsIHttpServerIdentity.primaryHost // get primaryHost() { - if (this._primaryPort === -1) + if (this._primaryPort === -1) { throw Components.Exception("", Cr.NS_ERROR_NOT_INITIALIZED); + } return this._primaryHost; }, @@ -883,8 +971,9 @@ ServerIdentity.prototype = // see nsIHttpServerIdentity.primaryPort // get primaryPort() { - if (this._primaryPort === -1) + if (this._primaryPort === -1) { throw Components.Exception("", Cr.NS_ERROR_NOT_INITIALIZED); + } return this._primaryPort; }, @@ -895,8 +984,9 @@ ServerIdentity.prototype = this._validate(scheme, host, port); var entry = this._locations["x" + host]; - if (!entry) + if (!entry) { this._locations["x" + host] = entry = {}; + } entry[port] = scheme; }, @@ -908,16 +998,19 @@ ServerIdentity.prototype = this._validate(scheme, host, port); var entry = this._locations["x" + host]; - if (!entry) + if (!entry) { return false; + } var present = port in entry; delete entry[port]; - if (this._primaryScheme == scheme && - this._primaryHost == host && - this._primaryPort == port && - this._defaultPort !== -1) { + if ( + this._primaryScheme == scheme && + this._primaryHost == host && + this._primaryPort == port && + this._defaultPort !== -1 + ) { // Always keep at least one identity in existence at any time, unless // we're in the process of shutting down (the last condition above). this._primaryPort = -1; @@ -933,8 +1026,10 @@ ServerIdentity.prototype = has(scheme, host, port) { this._validate(scheme, host, port); - return "x" + host in this._locations && - scheme === this._locations["x" + host][port]; + return ( + "x" + host in this._locations && + scheme === this._locations["x" + host][port] + ); }, // @@ -944,8 +1039,9 @@ ServerIdentity.prototype = this._validate("http", host, port); var entry = this._locations["x" + host]; - if (!entry) + if (!entry) { return ""; + } return entry[port] || ""; }, @@ -963,7 +1059,6 @@ ServerIdentity.prototype = this._primaryPort = port; }, - // NSISUPPORTS // @@ -971,7 +1066,6 @@ ServerIdentity.prototype = // QueryInterface: ChromeUtils.generateQI(["nsIHttpServerIdentity"]), - // PRIVATE IMPLEMENTATION /** @@ -980,10 +1074,11 @@ ServerIdentity.prototype = */ _initialize(port, host, addSecondaryDefault) { this._host = host; - if (this._primaryPort !== -1) + if (this._primaryPort !== -1) { this.add("http", host, port); - else + } else { this.setPrimary("http", "localhost", port); + } this._defaultPort = port; // Only add this if we're being called at server startup @@ -1009,9 +1104,11 @@ ServerIdentity.prototype = // This is a *very* tricky bit of reasoning here; make absolutely sure the // tests for this code pass before you commit changes to it. - if (this._primaryScheme == "http" && - this._primaryHost == this._host && - this._primaryPort == this._defaultPort) { + if ( + this._primaryScheme == "http" && + this._primaryHost == this._host && + this._primaryPort == this._defaultPort + ) { // Make sure we don't trigger the readding logic in .remove(), then remove // the default location. var port = this._defaultPort; @@ -1049,7 +1146,6 @@ ServerIdentity.prototype = }, }; - /** * Represents a connection to the server (and possibly in the future the thread * on which the connection is processed). @@ -1067,8 +1163,15 @@ ServerIdentity.prototype = * @param number : uint * a serial number used to uniquely identify this connection */ -function Connection(input, output, server, port, outgoingPort, number, - transport) { +function Connection( + input, + output, + server, + port, + outgoingPort, + number, + transport +) { dumpn("*** opening new connection " + number + " on port " + outgoingPort); /** Stream of incoming data. */ @@ -1109,15 +1212,16 @@ function Connection(input, output, server, port, outgoingPort, number, /** whether or not 1st line of request has been received */ this._requestStarted = false; } -Connection.prototype = -{ +Connection.prototype = { /** Closes this connection's input/output streams. */ close() { - if (this._closed) - return; + if (this._closed) { + return; + } - dumpn("*** closing connection " + this.number + - " on port " + this._outgoingPort); + dumpn( + "*** closing connection " + this.number + " on port " + this._outgoingPort + ); this.input.close(); this.output.close(); @@ -1127,8 +1231,11 @@ Connection.prototype = server._connectionClosed(this); // If an error triggered a server shutdown, act on it now - if (server._doQuit) - server.stop(function() { /* not like we can do anything better */ }); + if (server._doQuit) { + server.stop(function() { + /* not like we can do anything better */ + }); + } }, /** @@ -1167,9 +1274,14 @@ Connection.prototype = /** Converts this to a string for debugging purposes. */ toString() { - return ""; + return ( + "" + ); }, requestStarted() { @@ -1177,21 +1289,16 @@ Connection.prototype = }, }; - - /** Returns an array of count bytes from the given input stream. */ function readBytes(inputStream, count) { return new BinaryInputStream(inputStream).readByteArray(count); } - - /** Request reader processing states; see RequestReader for details. */ const READER_IN_REQUEST_LINE = 0; -const READER_IN_HEADERS = 1; -const READER_IN_BODY = 2; -const READER_FINISHED = 3; - +const READER_IN_HEADERS = 1; +const READER_IN_BODY = 2; +const READER_FINISHED = 3; /** * Reads incoming request data asynchronously, does any necessary preprocessing, @@ -1245,8 +1352,7 @@ function RequestReader(connection) { */ this._lastHeaderName = this._lastHeaderValue = undefined; } -RequestReader.prototype = -{ +RequestReader.prototype = { // NSIINPUTSTREAMCALLBACK /** @@ -1258,31 +1364,42 @@ RequestReader.prototype = * the stream of incoming data from the connection */ onInputStreamReady(input) { - dumpn("*** onInputStreamReady(input=" + input + ") on thread " + - gThreadManager.currentThread + " (main is " + - gThreadManager.mainThread + ")"); + dumpn( + "*** onInputStreamReady(input=" + + input + + ") on thread " + + gThreadManager.currentThread + + " (main is " + + gThreadManager.mainThread + + ")" + ); dumpn("*** this._state == " + this._state); // Handle cases where we get more data after a request error has been // discovered but *before* we can close the connection. var data = this._data; - if (!data) + if (!data) { return; + } try { data.appendBytes(readBytes(input, input.available())); } catch (e) { if (streamClosed(e)) { - dumpn("*** WARNING: unexpected error when reading from socket; will " + - "be treated as if the input stream had been closed"); + dumpn( + "*** WARNING: unexpected error when reading from socket; will " + + "be treated as if the input stream had been closed" + ); dumpn("*** WARNING: actual error was: " + e); } // We've lost a race -- input has been closed, but we're still expecting // to read more data. available() will throw in this case, and since // we're dead in the water now, destroy the connection. - dumpn("*** onInputStreamReady called on a closed input, destroying " + - "connection"); + dumpn( + "*** onInputStreamReady called on a closed input, destroying " + + "connection" + ); this._connection.close(); return; } @@ -1293,21 +1410,24 @@ RequestReader.prototype = break; case READER_IN_REQUEST_LINE: - if (!this._processRequestLine()) + if (!this._processRequestLine()) { break; - /* fall through */ + } + /* fall through */ case READER_IN_HEADERS: - if (!this._processHeaders()) + if (!this._processHeaders()) { break; - /* fall through */ + } + /* fall through */ case READER_IN_BODY: this._processBody(); } - if (this._state != READER_FINISHED) + if (this._state != READER_FINISHED) { input.asyncWait(this, 0, 0, gThreadManager.currentThread); + } }, // @@ -1315,7 +1435,6 @@ RequestReader.prototype = // QueryInterface: ChromeUtils.generateQI(["nsIInputStreamCallback"]), - // PRIVATE API /** @@ -1332,12 +1451,14 @@ RequestReader.prototype = var data = this._data; var line = {}; var readSuccess; - while ((readSuccess = data.readLine(line)) && line.value == "") + while ((readSuccess = data.readLine(line)) && line.value == "") { dumpn("*** ignoring beginning blank line..."); + } // if we don't have a full line, wait until we do - if (!readSuccess) + if (!readSuccess) { return false; + } // we have the first non-blank line try { @@ -1374,8 +1495,8 @@ RequestReader.prototype = // them, particularly chunked (which by its nature can have no // meaningful Content-Length header)! this._contentLength = request.hasHeader("Content-Length") - ? parseInt(request.getHeader("Content-Length"), 10) - : 0; + ? parseInt(request.getHeader("Content-Length"), 10) + : 0; dumpn("_processHeaders, Content-length=" + this._contentLength); this._state = READER_IN_BODY; @@ -1403,8 +1524,14 @@ RequestReader.prototype = if (this._contentLength > 0) { var data = this._data.purge(); var count = Math.min(data.length, this._contentLength); - dumpn("*** loading data=" + data + " len=" + data.length + - " excess=" + (data.length - count)); + dumpn( + "*** loading data=" + + data + + " len=" + + data.length + + " excess=" + + (data.length - count) + ); var bos = new BinaryOutputStream(this._metadata._bodyOutputStream); bos.writeByteArray(data, count); @@ -1470,9 +1597,16 @@ RequestReader.prototype = // NB: We allow an empty port here because, oddly, a colon may be // present even without a port number, e.g. "example.com:"; in this // case the default port applies. - if ((!HOST_REGEX.test(host) && host != "[::1]") || !/^\d*$/.test(port)) { - dumpn("*** malformed hostname (" + hostPort + ") in Host " + - "header, 400 time"); + if ( + (!HOST_REGEX.test(host) && host != "[::1]") || + !/^\d*$/.test(port) + ) { + dumpn( + "*** malformed hostname (" + + hostPort + + ") in Host " + + "header, 400 time" + ); throw HTTP_400; } @@ -1485,8 +1619,12 @@ RequestReader.prototype = var scheme = identity.getScheme(host, port); if (!scheme) { - dumpn("*** unrecognized hostname (" + hostPort + ") in Host " + - "header, 400 time"); + dumpn( + "*** unrecognized hostname (" + + hostPort + + ") in Host " + + "header, 400 time" + ); throw HTTP_400; } @@ -1495,16 +1633,20 @@ RequestReader.prototype = metadata._port = port; } } else { - NS_ASSERT(metadata._host === undefined, - "HTTP/1.0 doesn't allow absolute paths in the request line!"); + NS_ASSERT( + metadata._host === undefined, + "HTTP/1.0 doesn't allow absolute paths in the request line!" + ); metadata._scheme = identity.primaryScheme; metadata._host = identity.primaryHost; metadata._port = identity.primaryPort; } - NS_ASSERT(identity.has(metadata._scheme, metadata._host, metadata._port), - "must have a location we recognize by now!"); + NS_ASSERT( + identity.has(metadata._scheme, metadata._host, metadata._port), + "must have a location we recognize by now!" + ); }, /** @@ -1524,8 +1666,11 @@ RequestReader.prototype = if (e instanceof HttpError) { var code = e.code; } else { - dumpn("!!! UNEXPECTED ERROR: " + e + - (e.lineNumber ? ", line " + e.lineNumber : "")); + dumpn( + "!!! UNEXPECTED ERROR: " + + e + + (e.lineNumber ? ", line " + e.lineNumber : "") + ); // no idea what happened -- be paranoid and shut down code = 500; @@ -1555,7 +1700,6 @@ RequestReader.prototype = this._connection.process(this._metadata); }, - // PARSING /** @@ -1592,14 +1736,14 @@ RequestReader.prototype = // determine HTTP version try { metadata._httpVersion = new nsHttpVersion(match[1]); - if (!metadata._httpVersion.atLeast(nsHttpVersion.HTTP_1_0)) + if (!metadata._httpVersion.atLeast(nsHttpVersion.HTTP_1_0)) { throw new Error("unsupported HTTP version"); + } } catch (e) { // we support HTTP/1.0 and HTTP/1.1 only throw HTTP_501; } - var fullPath = request[1]; if (metadata._method == "CONNECT") { @@ -1643,7 +1787,10 @@ RequestReader.prototype = throw HTTP_400; } - if (!serverIdentity.has(scheme, host, port) || fullPath.charAt(0) != "/") { + if ( + !serverIdentity.has(scheme, host, port) || + fullPath.charAt(0) != "/" + ) { dumpn("*** serverIdentity unknown or path does not start with '/'"); throw HTTP_400; } @@ -1687,10 +1834,12 @@ RequestReader.prototype = while (true) { dumpn("*** Last name: '" + lastName + "'"); dumpn("*** Last val: '" + lastVal + "'"); - NS_ASSERT(!((lastVal === undefined) ^ (lastName === undefined)), - lastName === undefined ? - "lastVal without lastName? lastVal: '" + lastVal + "'" : - "lastName without lastVal? lastName: '" + lastName + "'"); + NS_ASSERT( + !((lastVal === undefined) ^ (lastName === undefined)), + lastName === undefined + ? "lastVal without lastName? lastVal: '" + lastVal + "'" + : "lastName without lastVal? lastName: '" + lastName + "'" + ); if (!data.readLine(line)) { // save any data we have from the header we might still be processing @@ -1755,9 +1904,9 @@ RequestReader.prototype = }, }; - /** The character codes for CR and LF. */ -const CR = 0x0D, LF = 0x0A; +const CR = 0x0d, + LF = 0x0a; /** * Calculates the number of characters before the first CRLF pair in array, or @@ -1775,13 +1924,13 @@ const CR = 0x0D, LF = 0x0A; */ function findCRLF(array, start) { for (var i = array.indexOf(CR, start); i >= 0; i = array.indexOf(CR, i + 1)) { - if (array[i + 1] == LF) + if (array[i + 1] == LF) { return i; + } } return -1; } - /** * A container which provides line-by-line access to the arrays of bytes with * which it is seeded. @@ -1793,8 +1942,7 @@ function LineData() { /** Start index from which to search for CRLF. */ this._start = 0; } -LineData.prototype = -{ +LineData.prototype = { /** * Appends the bytes in the given array to the internal data cache maintained * by this. @@ -1837,8 +1985,9 @@ LineData.prototype = // But if our data ends in a CR, we have to back up one, because // the first byte in the next packet might be an LF and if we // start looking at data.length we won't find it. - if (data.length > 0 && data[data.length - 1] === CR) + if (data.length > 0 && data[data.length - 1] === CR) { --this._start; + } return false; } @@ -1876,16 +2025,15 @@ LineData.prototype = }, }; - - /** * Creates a request-handling function for an nsIHttpRequestHandler object. */ function createHandlerFunc(handler) { - return function(metadata, response) { handler.handle(metadata, response); }; + return function(metadata, response) { + handler.handle(metadata, response); + }; } - /** * The default handler for directories; writes an HTML response containing a * slightly-formatted directory listing. @@ -1901,12 +2049,17 @@ function defaultIndexHandler(metadata, response) { // stick rules (don't want to pollute the default path-space). // - var body = "\ + var body = + "\ \ - " + path + "\ + " + + path + + "\ \ \ -

" + path + '

\ +

" + + path + + '

\
    '; var directory = metadata.getProperty("directory"); @@ -1917,10 +2070,13 @@ function defaultIndexHandler(metadata, response) { while (files.hasMoreElements()) { var f = files.nextFile; let name = f.leafName; - if (!f.isHidden() && - (name.charAt(name.length - 1) != HIDDEN_CHAR || - name.charAt(name.length - 2) == HIDDEN_CHAR)) + if ( + !f.isHidden() && + (name.charAt(name.length - 1) != HIDDEN_CHAR || + name.charAt(name.length - 2) == HIDDEN_CHAR) + ) { fileList.push(f); + } } fileList.sort(fileSort); @@ -1929,21 +2085,29 @@ function defaultIndexHandler(metadata, response) { var file = fileList[i]; try { let name = file.leafName; - if (name.charAt(name.length - 1) == HIDDEN_CHAR) + if (name.charAt(name.length - 1) == HIDDEN_CHAR) { name = name.substring(0, name.length - 1); + } var sep = file.isDirectory() ? "/" : ""; // Note: using " to delimit the attribute here because encodeURIComponent // passes through '. - var item = '
  1. ' + - htmlEscape(name) + sep + - "
  2. "; + var item = + '
  3. ' + + htmlEscape(name) + + sep + + "
  4. "; body += item; - } catch (e) { /* some file system error, ignore the file */ } + } catch (e) { + /* some file system error, ignore the file */ + } } - body += "
\ + body += " \ \ "; @@ -1954,18 +2118,21 @@ function defaultIndexHandler(metadata, response) { * Sorts a and b (nsIFile objects) into an aesthetically pleasing order. */ function fileSort(a, b) { - var dira = a.isDirectory(), dirb = b.isDirectory(); + var dira = a.isDirectory(), + dirb = b.isDirectory(); - if (dira && !dirb) + if (dira && !dirb) { return -1; - if (dirb && !dira) + } + if (dirb && !dira) { return 1; + } - var namea = a.leafName.toLowerCase(), nameb = b.leafName.toLowerCase(); + var namea = a.leafName.toLowerCase(), + nameb = b.leafName.toLowerCase(); return nameb > namea ? -1 : 1; } - /** * Converts an externally-provided path into an internal path for use in * determining file mappings. @@ -1979,14 +2146,16 @@ function fileSort(a, b) { * if path is incorrectly encoded */ function toInternalPath(path, encoded) { - if (encoded) + if (encoded) { path = decodeURI(path); + } var comps = path.split("/"); for (var i = 0, sz = comps.length; i < sz; i++) { var comp = comps[i]; - if (comp.charAt(comp.length - 1) == HIDDEN_CHAR) + if (comp.charAt(comp.length - 1) == HIDDEN_CHAR) { comps[i] = comp + HIDDEN_CHAR; + } } return comps.join("/"); } @@ -2008,29 +2177,35 @@ const PERMS_READONLY = (4 << 6) | (4 << 3) | 4; */ function maybeAddHeaders(file, metadata, response) { var name = file.leafName; - if (name.charAt(name.length - 1) == HIDDEN_CHAR) + if (name.charAt(name.length - 1) == HIDDEN_CHAR) { name = name.substring(0, name.length - 1); + } var headerFile = file.parent; headerFile.append(name + HEADERS_SUFFIX); - if (!headerFile.exists()) + if (!headerFile.exists()) { return; + } const PR_RDONLY = 0x01; - var fis = new FileInputStream(headerFile, PR_RDONLY, PERMS_READONLY, - Ci.nsIFileInputStream.CLOSE_ON_EOF); + var fis = new FileInputStream( + headerFile, + PR_RDONLY, + PERMS_READONLY, + Ci.nsIFileInputStream.CLOSE_ON_EOF + ); try { var lis = new ConverterInputStream(fis, "UTF-8", 1024, 0x0); lis.QueryInterface(Ci.nsIUnicharLineInputStream); - var line = {value: ""}; + var line = { value: "" }; var more = lis.readLine(line); - if (!more && line.value == "") + if (!more && line.value == "") { return; - + } // request line @@ -2047,7 +2222,11 @@ function maybeAddHeaders(file, metadata, response) { description = status.substring(space + 1, status.length); } - response.setStatusLine(metadata.httpVersion, parseInt(code, 10), description); + response.setStatusLine( + metadata.httpVersion, + parseInt(code, 10), + description + ); line.value = ""; more = lis.readLine(line); @@ -2058,9 +2237,11 @@ function maybeAddHeaders(file, metadata, response) { var header = line.value; var colon = header.indexOf(":"); - response.setHeader(header.substring(0, colon), - header.substring(colon + 1, header.length), - false); // allow overriding server-set headers + response.setHeader( + header.substring(0, colon), + header.substring(colon + 1, header.length), + false + ); // allow overriding server-set headers line.value = ""; more = lis.readLine(line); @@ -2073,7 +2254,6 @@ function maybeAddHeaders(file, metadata, response) { } } - /** * An object which handles requests for a server, executing default and * overridden behaviors as instructed by the code which uses and manipulates it. @@ -2150,8 +2330,7 @@ function ServerHandler(server) { /** Entire-server state storage for nsISupports values. */ this._objectState = {}; } -ServerHandler.prototype = -{ +ServerHandler.prototype = { // PUBLIC API /** @@ -2180,8 +2359,10 @@ ServerHandler.prototype = } else { var longestPrefix = ""; for (let prefix in this._overridePrefixes) { - if (prefix.length > longestPrefix.length && - path.substr(0, prefix.length) == prefix) { + if ( + prefix.length > longestPrefix.length && + path.substr(0, prefix.length) == prefix + ) { longestPrefix = prefix; } } @@ -2202,16 +2383,18 @@ ServerHandler.prototype = dumpn("*** unexpected error: e == " + e); throw HTTP_500; } - if (e.code !== 404) + if (e.code !== 404) { throw e; + } dumpn("*** default: " + (path in this._defaultPaths)); response = new Response(connection); - if (path in this._defaultPaths) + if (path in this._defaultPaths) { this._defaultPaths[path](request, response); - else + } else { throw HTTP_404; + } } } catch (e) { if (response.partiallySent()) { @@ -2222,20 +2405,28 @@ ServerHandler.prototype = var errorCode = "internal"; try { - if (!(e instanceof HttpError)) + if (!(e instanceof HttpError)) { throw e; + } errorCode = e.code; dumpn("*** errorCode == " + errorCode); response = new Response(connection); - if (e.customErrorHandling) + if (e.customErrorHandling) { e.customErrorHandling(response); + } this._handleError(errorCode, request, response); return; } catch (e2) { - dumpn("*** error handling " + errorCode + " error: " + - "e2 == " + e2 + ", shutting down server"); + dumpn( + "*** error handling " + + errorCode + + " error: " + + "e2 == " + + e2 + + ", shutting down server" + ); connection.server._requestQuit(); response.abort(e2); @@ -2260,14 +2451,14 @@ ServerHandler.prototype = file = file.clone(); var self = this; - this._overridePaths[path] = - function(request, response) { - if (!file.exists()) - throw HTTP_404; + this._overridePaths[path] = function(request, response) { + if (!file.exists()) { + throw HTTP_404; + } - response.setStatusLine(request.httpVersion, 200, "OK"); - self._writeFileResponse(request, file, response, 0, file.fileSize); - }; + response.setStatusLine(request.httpVersion, 200, "OK"); + self._writeFileResponse(request, file, response, 0, file.fileSize); + }; }, // @@ -2275,8 +2466,9 @@ ServerHandler.prototype = // registerPathHandler(path, handler) { // XXX true path validation! - if (path.charAt(0) != "/" && path != "CONNECT") + if (path.charAt(0) != "/" && path != "CONNECT") { throw Components.Exception("", Cr.NS_ERROR_INVALID_ARG); + } this._handlerToField(handler, this._overridePaths, path); }, @@ -2286,8 +2478,9 @@ ServerHandler.prototype = // registerPrefixHandler(path, handler) { // XXX true path validation! - if (path.charAt(0) != "/" || path.charAt(path.length - 1) != "/") + if (path.charAt(0) != "/" || path.charAt(path.length - 1) != "/") { throw Components.Exception("", Cr.NS_ERROR_INVALID_ARG); + } this._handlerToField(handler, this._overridePrefixes, path); }, @@ -2304,8 +2497,9 @@ ServerHandler.prototype = // the path-to-directory mapping code requires that the first character not // be "/", or it will go into an infinite loop - if (key.charAt(0) == "/") + if (key.charAt(0) == "/") { throw Components.Exception("", Cr.NS_ERROR_INVALID_ARG); + } key = toInternalPath(key, false); @@ -2322,9 +2516,14 @@ ServerHandler.prototype = // see nsIHttpServer.registerErrorHandler // registerErrorHandler(err, handler) { - if (!(err in HTTP_ERROR_CODES)) - dumpn("*** WARNING: registering non-HTTP/1.1 error code " + - "(" + err + ") handler -- was this intentional?"); + if (!(err in HTTP_ERROR_CODES)) { + dumpn( + "*** WARNING: registering non-HTTP/1.1 error code " + + "(" + + err + + ") handler -- was this intentional?" + ); + } this._handlerToField(handler, this._overrideErrors, err); }, @@ -2333,10 +2532,11 @@ ServerHandler.prototype = // see nsIHttpServer.setIndexHandler // setIndexHandler(handler) { - if (!handler) + if (!handler) { handler = defaultIndexHandler; - else if (typeof(handler) != "function") + } else if (typeof handler != "function") { handler = createHandlerFunc(handler); + } this._indexHandler = handler; }, @@ -2345,10 +2545,11 @@ ServerHandler.prototype = // see nsIHttpServer.registerContentType // registerContentType(ext, type) { - if (!type) + if (!type) { delete this._mimeMappings[ext]; - else + } else { this._mimeMappings[ext] = headerUtils.normalizeFieldValue(type); + } }, // PRIVATE API @@ -2365,12 +2566,13 @@ ServerHandler.prototype = */ _handlerToField(handler, dict, key) { // for convenience, handler can be a function if this is run from xpcshell - if (typeof(handler) == "function") + if (typeof handler == "function") { dict[key] = handler; - else if (handler) + } else if (handler) { dict[key] = createHandlerFunc(handler); - else + } else { delete dict[key]; + } }, /** @@ -2411,27 +2613,40 @@ ServerHandler.prototype = } // alternately, the file might not exist - if (!file.exists()) + if (!file.exists()) { throw HTTP_404; + } var start, end; - if (metadata._httpVersion.atLeast(nsHttpVersion.HTTP_1_1) && - metadata.hasHeader("Range") && - this._getTypeFromFile(file) !== SJS_TYPE) { - var rangeMatch = metadata.getHeader("Range").match(/^bytes=(\d+)?-(\d+)?$/); + if ( + metadata._httpVersion.atLeast(nsHttpVersion.HTTP_1_1) && + metadata.hasHeader("Range") && + this._getTypeFromFile(file) !== SJS_TYPE + ) { + var rangeMatch = metadata + .getHeader("Range") + .match(/^bytes=(\d+)?-(\d+)?$/); if (!rangeMatch) { - dumpn("*** Range header bogosity: '" + metadata.getHeader("Range") + "'"); + dumpn( + "*** Range header bogosity: '" + metadata.getHeader("Range") + "'" + ); throw HTTP_400; } - if (rangeMatch[1] !== undefined) + if (rangeMatch[1] !== undefined) { start = parseInt(rangeMatch[1], 10); + } - if (rangeMatch[2] !== undefined) + if (rangeMatch[2] !== undefined) { end = parseInt(rangeMatch[2], 10); + } if (start === undefined && end === undefined) { - dumpn("*** More Range header bogosity: '" + metadata.getHeader("Range") + "'"); + dumpn( + "*** More Range header bogosity: '" + + metadata.getHeader("Range") + + "'" + ); throw HTTP_400; } @@ -2439,12 +2654,13 @@ ServerHandler.prototype = // end of the file. if (start === undefined) { start = Math.max(0, file.fileSize - end); - end = file.fileSize - 1; + end = file.fileSize - 1; } // start and end are inclusive - if (end === undefined || end >= file.fileSize) + if (end === undefined || end >= file.fileSize) { end = file.fileSize - 1; + } if (start !== undefined && start >= file.fileSize) { var HTTP_416 = new HttpError(416, "Requested Range Not Satisfiable"); @@ -2469,8 +2685,17 @@ ServerHandler.prototype = } // finally... - dumpn("*** handling '" + path + "' as mapping to " + file.path + " from " + - start + " to " + end + " inclusive"); + dumpn( + "*** handling '" + + path + + "' as mapping to " + + file.path + + " from " + + start + + " to " + + end + + " inclusive" + ); this._writeFileResponse(metadata, file, response, start, end - start + 1); }, @@ -2494,8 +2719,12 @@ ServerHandler.prototype = var type = this._getTypeFromFile(file); if (type === SJS_TYPE) { - let fis = new FileInputStream(file, PR_RDONLY, PERMS_READONLY, - Ci.nsIFileInputStream.CLOSE_ON_EOF); + let fis = new FileInputStream( + file, + PR_RDONLY, + PERMS_READONLY, + Ci.nsIFileInputStream.CLOSE_ON_EOF + ); try { var s = Cu.Sandbox(gGlobalObject); @@ -2549,11 +2778,17 @@ ServerHandler.prototype = try { s.handleRequest(metadata, response); } catch (e) { - dump("*** error running SJS at " + file.path + ": " + - e + " on line " + - (e instanceof Error - ? e.lineNumber + " in httpd.js" - : (e.lineNumber - line)) + "\n"); + dump( + "*** error running SJS at " + + file.path + + ": " + + e + + " on line " + + (e instanceof Error + ? e.lineNumber + " in httpd.js" + : e.lineNumber - line) + + "\n" + ); throw HTTP_500; } } finally { @@ -2561,20 +2796,28 @@ ServerHandler.prototype = } } else { try { - response.setHeader("Last-Modified", - toDateString(file.lastModifiedTime), - false); - } catch (e) { /* lastModifiedTime threw, ignore */ } + response.setHeader( + "Last-Modified", + toDateString(file.lastModifiedTime), + false + ); + } catch (e) { + /* lastModifiedTime threw, ignore */ + } response.setHeader("Content-Type", type, false); maybeAddHeaders(file, metadata, response); response.setHeader("Content-Length", "" + count, false); - let fis = new FileInputStream(file, PR_RDONLY, PERMS_READONLY, - Ci.nsIFileInputStream.CLOSE_ON_EOF); + let fis = new FileInputStream( + file, + PR_RDONLY, + PERMS_READONLY, + Ci.nsIFileInputStream.CLOSE_ON_EOF + ); offset = offset || 0; - count = count || file.fileSize; + count = count || file.fileSize; NS_ASSERT(offset === 0 || offset < file.fileSize, "bad offset"); NS_ASSERT(count >= 0, "bad count"); NS_ASSERT(offset + count <= file.fileSize, "bad total data size"); @@ -2583,10 +2826,11 @@ ServerHandler.prototype = if (offset !== 0) { // Seek (or read, if seeking isn't supported) to the correct offset so // the data sent to the client matches the requested range. - if (fis instanceof Ci.nsISeekableStream) + if (fis instanceof Ci.nsISeekableStream) { fis.seek(Ci.nsISeekableStream.NS_SEEK_SET, offset); - else + } else { new ScriptableInputStream(fis).read(offset); + } } } catch (e) { fis.close(); @@ -2594,41 +2838,46 @@ ServerHandler.prototype = } let writeMore = function() { - gThreadManager.currentThread - .dispatch(writeData, Ci.nsIThread.DISPATCH_NORMAL); + gThreadManager.currentThread.dispatch( + writeData, + Ci.nsIThread.DISPATCH_NORMAL + ); }; var input = new BinaryInputStream(fis); var output = new BinaryOutputStream(response.bodyOutputStream); - var writeData = - { - run() { - var chunkSize = Math.min(65536, count); - count -= chunkSize; - NS_ASSERT(count >= 0, "underflow"); + var writeData = { + run() { + var chunkSize = Math.min(65536, count); + count -= chunkSize; + NS_ASSERT(count >= 0, "underflow"); - try { - var data = input.readByteArray(chunkSize); - NS_ASSERT(data.length === chunkSize, - "incorrect data returned? got " + data.length + - ", expected " + chunkSize); - output.writeByteArray(data, data.length); - if (count === 0) { - fis.close(); - response.finish(); - } else { - writeMore(); - } - } catch (e) { - try { - fis.close(); - } finally { - response.finish(); - } - throw e; + try { + var data = input.readByteArray(chunkSize); + NS_ASSERT( + data.length === chunkSize, + "incorrect data returned? got " + + data.length + + ", expected " + + chunkSize + ); + output.writeByteArray(data, data.length); + if (count === 0) { + fis.close(); + response.finish(); + } else { + writeMore(); } - }, - }; + } catch (e) { + try { + fis.close(); + } finally { + response.finish(); + } + throw e; + } + }, + }; writeMore(); @@ -2650,8 +2899,9 @@ ServerHandler.prototype = */ _getState(path, k) { var state = this._state; - if (path in state && k in state[path]) + if (path in state && k in state[path]) { return state[path][k]; + } return ""; }, @@ -2667,11 +2917,13 @@ ServerHandler.prototype = * the value to be set */ _setState(path, k, v) { - if (typeof v !== "string") + if (typeof v !== "string") { throw new Error("non-string value passed"); + } var state = this._state; - if (!(path in state)) + if (!(path in state)) { state[path] = {}; + } state[path][k] = v; }, @@ -2686,8 +2938,9 @@ ServerHandler.prototype = */ _getSharedState(k) { var state = this._sharedState; - if (k in state) + if (k in state) { return state[k]; + } return ""; }, @@ -2701,8 +2954,9 @@ ServerHandler.prototype = * the value to be set */ _setSharedState(k, v) { - if (typeof v !== "string") + if (typeof v !== "string") { throw new Error("non-string value passed"); + } this._sharedState[k] = v; }, @@ -2716,8 +2970,9 @@ ServerHandler.prototype = * the corresponding object, or null if none was present */ _getObjectState(k) { - if (typeof k !== "string") + if (typeof k !== "string") { throw new Error("non-string key passed"); + } return this._objectState[k] || null; }, @@ -2731,13 +2986,17 @@ ServerHandler.prototype = * the object to be associated with the given key; may be null */ _setObjectState(k, v) { - if (typeof k !== "string") + if (typeof k !== "string") { throw new Error("non-string key passed"); - if (typeof v !== "object") + } + if (typeof v !== "object") { throw new Error("non-object value passed"); + } if (v && !("QueryInterface" in v)) { - throw new Error("must pass an nsISupports; use wrappedJSObject to ease " + - "pain when using the server from JS"); + throw new Error( + "must pass an nsISupports; use wrappedJSObject to ease " + + "pain when using the server from JS" + ); } this._objectState[k] = v; @@ -2760,12 +3019,13 @@ ServerHandler.prototype = var dot = name.lastIndexOf("."); if (dot > 0) { var ext = name.slice(dot + 1); - if (ext in this._mimeMappings) + if (ext in this._mimeMappings) { return this._mimeMappings[ext]; + } } return Cc["@mozilla.org/uriloader/external-helper-app-service;1"] - .getService(Ci.nsIMIMEService) - .getTypeFromFile(file); + .getService(Ci.nsIMIMEService) + .getTypeFromFile(file); } catch (e) { return "application/octet-stream"; } @@ -2808,29 +3068,33 @@ ServerHandler.prototype = // requested path was /foo/bar, because relative links on the page // will all be incorrect -- we really need the ability to easily // redirect here instead - if (tmp == path.substring(1) && - tmp.length != 0 && - tmp.charAt(tmp.length - 1) != "/") + if ( + tmp == path.substring(1) && + tmp.length != 0 && + tmp.charAt(tmp.length - 1) != "/" + ) { file = null; - else + } else { break; + } } // if we've finished trying all prefixes, exit - if (tmp == "") + if (tmp == "") { break; + } tmp = tmp.substring(0, tmp.lastIndexOf("/")); } // no mapping applies, so 404 - if (!file) + if (!file) { throw HTTP_404; - + } // last, get the file for the path within the determined directory var parentFolder = file.parent; - var dirIsRoot = (parentFolder == null); + var dirIsRoot = parentFolder == null; // Strategy here is to append components individually, making sure we // never move above the given directory; this allows paths such as @@ -2842,15 +3106,17 @@ ServerHandler.prototype = for (var i = 0, sz = comps.length; i < sz; i++) { var comp = comps[i]; - if (comp == "..") + if (comp == "..") { file = file.parent; - else if (comp == "." || comp == "") + } else if (comp == "." || comp == "") { continue; - else + } else { file.append(comp); + } - if (!dirIsRoot && file.equals(parentFolder)) + if (!dirIsRoot && file.equals(parentFolder)) { throw HTTP_403; + } } return file; @@ -2891,14 +3157,16 @@ ServerHandler.prototype = * fallback for 505, per HTTP specs) */ _handleError(errorCode, metadata, response) { - if (!metadata) + if (!metadata) { throw Components.Exception("", Cr.NS_ERROR_NULL_POINTER); + } var errorX00 = errorCode - (errorCode % 100); try { - if (!(errorCode in HTTP_ERROR_CODES)) + if (!(errorCode in HTTP_ERROR_CODES)) { dumpn("*** WARNING: requested invalid error: " + errorCode); + } // RFC 2616 says that we should try to handle an error by its class if we // can't otherwise handle it -- if that fails, we revert to handling it as @@ -2907,10 +3175,11 @@ ServerHandler.prototype = // actually handle the error try { - if (errorCode in this._overrideErrors) + if (errorCode in this._overrideErrors) { this._overrideErrors[errorCode](metadata, response); - else + } else { this._defaultErrors[errorCode](metadata, response); + } } catch (e) { if (response.partiallySent()) { response.abort(e); @@ -2918,18 +3187,26 @@ ServerHandler.prototype = } // don't retry the handler that threw - if (errorX00 == errorCode) + if (errorX00 == errorCode) { throw HTTP_500; + } - dumpn("*** error in handling for error code " + errorCode + ", " + - "falling back to " + errorX00 + "..."); + dumpn( + "*** error in handling for error code " + + errorCode + + ", " + + "falling back to " + + errorX00 + + "..." + ); response = new Response(response._connection); - if (errorX00 in this._overrideErrors) + if (errorX00 in this._overrideErrors) { this._overrideErrors[errorX00](metadata, response); - else if (errorX00 in this._defaultErrors) + } else if (errorX00 in this._defaultErrors) { this._defaultErrors[errorX00](metadata, response); - else + } else { throw HTTP_500; + } } } catch (e) { if (response.partiallySent()) { @@ -2938,15 +3215,20 @@ ServerHandler.prototype = } // we've tried everything possible for a meaningful error -- now try 500 - dumpn("*** error in handling for error code " + errorX00 + ", falling " + - "back to 500..."); + dumpn( + "*** error in handling for error code " + + errorX00 + + ", falling " + + "back to 500..." + ); try { response = new Response(response._connection); - if (500 in this._overrideErrors) + if (500 in this._overrideErrors) { this._overrideErrors[500](metadata, response); - else + } else { this._defaultErrors[500](metadata, response); + } } catch (e2) { dumpn("*** multiple errors in default error handlers!"); dumpn("*** e == " + e + ", e2 == " + e2); @@ -2963,8 +3245,7 @@ ServerHandler.prototype = /** * This object contains the default handlers for the various HTTP error codes. */ - _defaultErrors: - { + _defaultErrors: { 400(metadata, response) { // none of the data in metadata is reliable, so hard-code everything here response.setStatusLine("1.1", 400, "Bad Request"); @@ -2977,7 +3258,8 @@ ServerHandler.prototype = response.setStatusLine(metadata.httpVersion, 403, "Forbidden"); response.setHeader("Content-Type", "text/html;charset=utf-8", false); - var body = "\ + var body = + "\ 403 Forbidden\ \

403 Forbidden

\ @@ -2989,26 +3271,30 @@ ServerHandler.prototype = response.setStatusLine(metadata.httpVersion, 404, "Not Found"); response.setHeader("Content-Type", "text/html;charset=utf-8", false); - var body = "\ + var body = + "\ 404 Not Found\ \

404 Not Found

\

\ " + - htmlEscape(metadata.path) + - " was not found.\ + htmlEscape(metadata.path) + + " was not found.\

\ \ "; response.bodyOutputStream.write(body, body.length); }, 416(metadata, response) { - response.setStatusLine(metadata.httpVersion, - 416, - "Requested Range Not Satisfiable"); + response.setStatusLine( + metadata.httpVersion, + 416, + "Requested Range Not Satisfiable" + ); response.setHeader("Content-Type", "text/html;charset=utf-8", false); - var body = "\ + var body = + "\ \ 416 Requested Range Not Satisfiable\ \ @@ -3021,12 +3307,15 @@ ServerHandler.prototype = response.bodyOutputStream.write(body, body.length); }, 500(metadata, response) { - response.setStatusLine(metadata.httpVersion, - 500, - "Internal Server Error"); + response.setStatusLine( + metadata.httpVersion, + 500, + "Internal Server Error" + ); response.setHeader("Content-Type", "text/html;charset=utf-8", false); - var body = "\ + var body = + "\ 500 Internal Server Error\ \

500 Internal Server Error

\ @@ -3040,7 +3329,8 @@ ServerHandler.prototype = response.setStatusLine(metadata.httpVersion, 501, "Not Implemented"); response.setHeader("Content-Type", "text/html;charset=utf-8", false); - var body = "\ + var body = + "\ 501 Not Implemented\ \

501 Not Implemented

\ @@ -3053,7 +3343,8 @@ ServerHandler.prototype = response.setStatusLine("1.1", 505, "HTTP Version Not Supported"); response.setHeader("Content-Type", "text/html;charset=utf-8", false); - var body = "\ + var body = + "\ 505 HTTP Version Not Supported\ \

505 HTTP Version Not Supported

\ @@ -3068,13 +3359,13 @@ ServerHandler.prototype = /** * Contains handlers for the default set of URIs contained in this server. */ - _defaultPaths: - { + _defaultPaths: { "/": function(metadata, response) { response.setStatusLine(metadata.httpVersion, 200, "OK"); response.setHeader("Content-Type", "text/html;charset=utf-8", false); - var body = "\ + var body = + "\ httpd.js\ \

httpd.js

\ @@ -3091,22 +3382,28 @@ ServerHandler.prototype = response.setStatusLine(metadata.httpVersion, 200, "OK"); response.setHeader("Content-Type", "text/plain;charset=utf-8", false); - var body = "Request-URI: " + - metadata.scheme + "://" + metadata.host + ":" + metadata.port + - metadata.path + "\n\n"; + var body = + "Request-URI: " + + metadata.scheme + + "://" + + metadata.host + + ":" + + metadata.port + + metadata.path + + "\n\n"; body += "Request (semantically equivalent, slightly reformatted):\n\n"; body += metadata.method + " " + metadata.path; - if (metadata.queryString) - body += "?" + metadata.queryString; + if (metadata.queryString) { + body += "?" + metadata.queryString; + } body += " HTTP/" + metadata.httpVersion + "\r\n"; var headEnum = metadata.headers; while (headEnum.hasMoreElements()) { - var fieldName = headEnum.getNext() - .QueryInterface(Ci.nsISupportsString) - .data; + var fieldName = headEnum.getNext().QueryInterface(Ci.nsISupportsString) + .data; body += fieldName + ": " + metadata.getHeader(fieldName) + "\r\n"; } @@ -3115,7 +3412,6 @@ ServerHandler.prototype = }, }; - /** * Maps absolute paths to files on the local file system (as nsILocalFiles). */ @@ -3123,8 +3419,7 @@ function FileMap() { /** Hash which will map paths to nsILocalFiles. */ this._map = {}; } -FileMap.prototype = -{ +FileMap.prototype = { // PUBLIC API /** @@ -3137,10 +3432,11 @@ FileMap.prototype = * the file to map to key, or null to remove a mapping */ put(key, value) { - if (value) + if (value) { this._map[key] = value.clone(); - else + } else { delete this._map[key]; + } }, /** @@ -3158,7 +3454,6 @@ FileMap.prototype = }, }; - // Response CONSTANTS // token = * @@ -3168,27 +3463,138 @@ FileMap.prototype = // | "," | ";" | ":" | "\" | <"> // | "/" | "[" | "]" | "?" | "=" // | "{" | "}" | SP | HT -const IS_TOKEN_ARRAY = - [0, 0, 0, 0, 0, 0, 0, 0, // 0 - 0, 0, 0, 0, 0, 0, 0, 0, // 8 - 0, 0, 0, 0, 0, 0, 0, 0, // 16 - 0, 0, 0, 0, 0, 0, 0, 0, // 24 +const IS_TOKEN_ARRAY = [ + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, // 0 + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, // 8 + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, // 16 + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, // 24 - 0, 1, 0, 1, 1, 1, 1, 1, // 32 - 0, 0, 1, 1, 0, 1, 1, 0, // 40 - 1, 1, 1, 1, 1, 1, 1, 1, // 48 - 1, 1, 0, 0, 0, 0, 0, 0, // 56 + 0, + 1, + 0, + 1, + 1, + 1, + 1, + 1, // 32 + 0, + 0, + 1, + 1, + 0, + 1, + 1, + 0, // 40 + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, // 48 + 1, + 1, + 0, + 0, + 0, + 0, + 0, + 0, // 56 - 0, 1, 1, 1, 1, 1, 1, 1, // 64 - 1, 1, 1, 1, 1, 1, 1, 1, // 72 - 1, 1, 1, 1, 1, 1, 1, 1, // 80 - 1, 1, 1, 0, 0, 0, 1, 1, // 88 - - 1, 1, 1, 1, 1, 1, 1, 1, // 96 - 1, 1, 1, 1, 1, 1, 1, 1, // 104 - 1, 1, 1, 1, 1, 1, 1, 1, // 112 - 1, 1, 1, 0, 1, 0, 1]; // 120 + 0, + 1, + 1, + 1, + 1, + 1, + 1, + 1, // 64 + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, // 72 + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, // 80 + 1, + 1, + 1, + 0, + 0, + 0, + 1, + 1, // 88 + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, // 96 + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, // 104 + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, // 112 + 1, + 1, + 1, + 0, + 1, + 0, + 1, +]; // 120 /** * Determines whether the given character code is a CTL. @@ -3199,7 +3605,7 @@ const IS_TOKEN_ARRAY = * true if code is a CTL, false otherwise */ function isCTL(code) { - return (code >= 0 && code <= 31) || (code == 127); + return (code >= 0 && code <= 31) || code == 127; } /** @@ -3287,24 +3693,30 @@ function Response(connection) { */ this._powerSeized = false; } -Response.prototype = -{ +Response.prototype = { // PUBLIC CONSTRUCTION API // // see nsIHttpResponse.bodyOutputStream // get bodyOutputStream() { - if (this._finished) + if (this._finished) { throw Components.Exception("", Cr.NS_ERROR_NOT_AVAILABLE); + } if (!this._bodyOutputStream) { - var pipe = new Pipe(true, false, Response.SEGMENT_SIZE, PR_UINT32_MAX, - null); + var pipe = new Pipe( + true, + false, + Response.SEGMENT_SIZE, + PR_UINT32_MAX, + null + ); this._bodyOutputStream = pipe.outputStream; this._bodyInputStream = pipe.inputStream; - if (this._processAsync || this._powerSeized) + if (this._processAsync || this._powerSeized) { this._startAsyncProcessor(); + } } return this._bodyOutputStream; @@ -3314,8 +3726,9 @@ Response.prototype = // see nsIHttpResponse.write // write(data) { - if (this._finished) + if (this._finished) { throw Components.Exception("", Cr.NS_ERROR_NOT_AVAILABLE); + } var dataAsString = String(data); this.bodyOutputStream.write(dataAsString, dataAsString.length); @@ -3325,22 +3738,25 @@ Response.prototype = // see nsIHttpResponse.setStatusLine // setStatusLine(httpVersion, code, description) { - if (!this._headers || this._finished || this._powerSeized) + if (!this._headers || this._finished || this._powerSeized) { throw Components.Exception("", Cr.NS_ERROR_NOT_AVAILABLE); + } this._ensureAlive(); - if (!(code >= 0 && code < 1000)) + if (!(code >= 0 && code < 1000)) { throw Components.Exception("", Cr.NS_ERROR_INVALID_ARG); + } try { var httpVer; // avoid version construction for the most common cases - if (!httpVersion || httpVersion == "1.1") + if (!httpVersion || httpVersion == "1.1") { httpVer = nsHttpVersion.HTTP_1_1; - else if (httpVersion == "1.0") + } else if (httpVersion == "1.0") { httpVer = nsHttpVersion.HTTP_1_0; - else + } else { httpVer = new nsHttpVersion(httpVersion); + } } catch (e) { throw Components.Exception("", Cr.NS_ERROR_INVALID_ARG); } @@ -3350,11 +3766,14 @@ Response.prototype = // // XXX this ends up disallowing octets which aren't Unicode, I think -- not // much to do if description is IDL'd as string - if (!description) + if (!description) { description = ""; - for (var i = 0; i < description.length; i++) - if (isCTL(description.charCodeAt(i)) && description.charAt(i) != "\t") + } + for (var i = 0; i < description.length; i++) { + if (isCTL(description.charCodeAt(i)) && description.charAt(i) != "\t") { throw Components.Exception("", Cr.NS_ERROR_INVALID_ARG); + } + } // set the values only after validation to preserve atomicity this._httpDescription = description; @@ -3366,16 +3785,18 @@ Response.prototype = // see nsIHttpResponse.setHeader // setHeader(name, value, merge) { - if (!this._headers || this._finished || this._powerSeized) + if (!this._headers || this._finished || this._powerSeized) { throw Components.Exception("", Cr.NS_ERROR_NOT_AVAILABLE); + } this._ensureAlive(); this._headers.setHeader(name, value, merge); }, setHeaderNoCheck(name, value) { - if (!this._headers || this._finished || this._powerSeized) + if (!this._headers || this._finished || this._powerSeized) { throw Components.Exception("", Cr.NS_ERROR_NOT_AVAILABLE); + } this._ensureAlive(); this._headers.setHeaderNoCheck(name, value); @@ -3385,12 +3806,15 @@ Response.prototype = // see nsIHttpResponse.processAsync // processAsync() { - if (this._finished) + if (this._finished) { throw Components.Exception("", Cr.NS_ERROR_UNEXPECTED); - if (this._powerSeized) + } + if (this._powerSeized) { throw Components.Exception("", Cr.NS_ERROR_NOT_AVAILABLE); - if (this._processAsync) + } + if (this._processAsync) { return; + } this._ensureAlive(); dumpn("*** processing connection " + this._connection.number + " async"); @@ -3409,61 +3833,73 @@ Response.prototype = * until finish() is called. Since that delay is easily avoided by simply * getting bodyOutputStream or calling write(""), we don't worry about it. */ - if (this._bodyOutputStream && !this._asyncCopier) + if (this._bodyOutputStream && !this._asyncCopier) { this._startAsyncProcessor(); + } }, // // see nsIHttpResponse.seizePower // seizePower() { - if (this._processAsync) + if (this._processAsync) { throw Components.Exception("", Cr.NS_ERROR_NOT_AVAILABLE); - if (this._finished) + } + if (this._finished) { throw Components.Exception("", Cr.NS_ERROR_UNEXPECTED); - if (this._powerSeized) + } + if (this._powerSeized) { return; + } this._ensureAlive(); - dumpn("*** forcefully seizing power over connection " + - this._connection.number + "..."); + dumpn( + "*** forcefully seizing power over connection " + + this._connection.number + + "..." + ); // Purge any already-written data without sending it. We could as easily // swap out the streams entirely, but that makes it possible to acquire and // unknowingly use a stale reference, so we require there only be one of // each stream ever for any response to avoid this complication. - if (this._asyncCopier) + if (this._asyncCopier) { this._asyncCopier.cancel(Cr.NS_BINDING_ABORTED); + } this._asyncCopier = null; if (this._bodyOutputStream) { var input = new BinaryInputStream(this._bodyInputStream); var avail; - while ((avail = input.available()) > 0) + while ((avail = input.available()) > 0) { input.readByteArray(avail); + } } this._powerSeized = true; - if (this._bodyOutputStream) + if (this._bodyOutputStream) { this._startAsyncProcessor(); + } }, // // see nsIHttpResponse.finish // finish() { - if (!this._processAsync && !this._powerSeized) + if (!this._processAsync && !this._powerSeized) { throw Components.Exception("", Cr.NS_ERROR_UNEXPECTED); - if (this._finished) + } + if (this._finished) { return; + } dumpn("*** finishing connection " + this._connection.number); this._startAsyncProcessor(); // in case bodyOutputStream was never accessed - if (this._bodyOutputStream) + if (this._bodyOutputStream) { this._bodyOutputStream.close(); + } this._finished = true; }, - // NSISUPPORTS // @@ -3471,7 +3907,6 @@ Response.prototype = // QueryInterface: ChromeUtils.generateQI(["nsIHttpResponse"]), - // POST-CONSTRUCTION API (not exposed externally) /** @@ -3489,9 +3924,10 @@ Response.prototype = get httpCode() { this._ensureAlive(); - var codeString = (this._httpCode < 10 ? "0" : "") + - (this._httpCode < 100 ? "0" : "") + - this._httpCode; + var codeString = + (this._httpCode < 10 ? "0" : "") + + (this._httpCode < 100 ? "0" : "") + + this._httpCode; return codeString; }, @@ -3544,8 +3980,10 @@ Response.prototype = complete() { dumpn("*** complete()"); if (this._processAsync || this._powerSeized) { - NS_ASSERT(this._processAsync ^ this._powerSeized, - "can't both send async and relinquish power"); + NS_ASSERT( + this._processAsync ^ this._powerSeized, + "can't both send async and relinquish power" + ); return; } @@ -3554,8 +3992,9 @@ Response.prototype = this._startAsyncProcessor(); // Now make sure we finish processing this request! - if (this._bodyOutputStream) + if (this._bodyOutputStream) { this._bodyOutputStream.close(); + } }, /** @@ -3599,12 +4038,15 @@ Response.prototype = // way to handle both cases without removing bodyOutputStream access and // moving its effective write(data, length) method onto Response, which // would be slower and require more code than this anyway. - gThreadManager.currentThread.dispatch({ - run() { - dumpn("*** canceling copy asynchronously..."); - copier.cancel(Cr.NS_ERROR_UNEXPECTED); + gThreadManager.currentThread.dispatch( + { + run() { + dumpn("*** canceling copy asynchronously..."); + copier.cancel(Cr.NS_ERROR_UNEXPECTED); + }, }, - }, Ci.nsIThread.DISPATCH_NORMAL); + Ci.nsIThread.DISPATCH_NORMAL + ); } else { this.end(); } @@ -3618,8 +4060,9 @@ Response.prototype = NS_ASSERT(!this._ended, "ending this response twice?!?!"); this._connection.close(); - if (this._bodyOutputStream) + if (this._bodyOutputStream) { this._bodyOutputStream.close(); + } this._finished = true; this._ended = true; @@ -3669,17 +4112,23 @@ Response.prototype = NS_ASSERT(!this._powerSeized); // request-line - var statusLine = "HTTP/" + this.httpVersion + " " + - this.httpCode + " " + - this.httpDescription + "\r\n"; + var statusLine = + "HTTP/" + + this.httpVersion + + " " + + this.httpCode + + " " + + this.httpDescription + + "\r\n"; // header post-processing var headers = this._headers; headers.setHeader("Connection", "close", false); headers.setHeader("Server", "httpd.js", false); - if (!headers.hasHeader("Date")) + if (!headers.hasHeader("Date")) { headers.setHeader("Date", toDateString(Date.now()), false); + } // Any response not being processed asynchronously must have an associated // Content-Length header for reasons of backwards compatibility with the @@ -3697,7 +4146,6 @@ Response.prototype = headers.setHeader("Content-Length", "" + avail, false); } - // construct and send response dumpn("*** header post-processing completed, sending response head..."); @@ -3707,12 +4155,12 @@ Response.prototype = // headers var headEnum = headers.enumerator; while (headEnum.hasMoreElements()) { - var fieldName = headEnum.getNext() - .QueryInterface(Ci.nsISupportsString) - .data; + var fieldName = headEnum.getNext().QueryInterface(Ci.nsISupportsString) + .data; var values = headers.getHeaderValues(fieldName); - for (var i = 0, sz = values.length; i < sz; i++) + for (var i = 0, sz = values.length; i < sz; i++) { preambleData.push(fieldName + ": " + values[i] + "\r\n"); + } } // end request-line/headers @@ -3724,33 +4172,40 @@ Response.prototype = responseHeadPipe.outputStream.write(preamble, preamble.length); var response = this; - var copyObserver = - { - onStartRequest(request) { - dumpn("*** preamble copying started"); - }, + var copyObserver = { + onStartRequest(request) { + dumpn("*** preamble copying started"); + }, - onStopRequest(request, statusCode) { - dumpn("*** preamble copying complete " + - "[status=0x" + statusCode.toString(16) + "]"); + onStopRequest(request, statusCode) { + dumpn( + "*** preamble copying complete " + + "[status=0x" + + statusCode.toString(16) + + "]" + ); - if (!Components.isSuccessCode(statusCode)) { - dumpn("!!! header copying problems: non-success statusCode, " + - "ending response"); + if (!Components.isSuccessCode(statusCode)) { + dumpn( + "!!! header copying problems: non-success statusCode, " + + "ending response" + ); - response.end(); - } else { - response._sendBody(); - } - }, + response.end(); + } else { + response._sendBody(); + } + }, - QueryInterface: ChromeUtils.generateQI(["nsIRequestObserver"]), - }; + QueryInterface: ChromeUtils.generateQI(["nsIRequestObserver"]), + }; - this._asyncCopier = - new WriteThroughCopier(responseHeadPipe.inputStream, - this._connection.output, - copyObserver, null); + this._asyncCopier = new WriteThroughCopier( + responseHeadPipe.inputStream, + this._connection.output, + copyObserver, + null + ); responseHeadPipe.outputStream.close(); @@ -3775,32 +4230,35 @@ Response.prototype = } var response = this; - var copyObserver = - { - onStartRequest(request) { - dumpn("*** onStartRequest"); - }, + var copyObserver = { + onStartRequest(request) { + dumpn("*** onStartRequest"); + }, - onStopRequest(request, statusCode) { - dumpn("*** onStopRequest [status=0x" + statusCode.toString(16) + "]"); + onStopRequest(request, statusCode) { + dumpn("*** onStopRequest [status=0x" + statusCode.toString(16) + "]"); - if (statusCode === Cr.NS_BINDING_ABORTED) { - dumpn("*** terminating copy observer without ending the response"); - } else { - if (!Components.isSuccessCode(statusCode)) - dumpn("*** WARNING: non-success statusCode in onStopRequest"); - - response.end(); + if (statusCode === Cr.NS_BINDING_ABORTED) { + dumpn("*** terminating copy observer without ending the response"); + } else { + if (!Components.isSuccessCode(statusCode)) { + dumpn("*** WARNING: non-success statusCode in onStopRequest"); } - }, - QueryInterface: ChromeUtils.generateQI(["nsIRequestObserver"]), - }; + response.end(); + } + }, + + QueryInterface: ChromeUtils.generateQI(["nsIRequestObserver"]), + }; dumpn("*** starting async copier of body data..."); - this._asyncCopier = - new WriteThroughCopier(this._bodyInputStream, this._connection.output, - copyObserver, null); + this._asyncCopier = new WriteThroughCopier( + this._bodyInputStream, + this._connection.output, + copyObserver, + null + ); }, /** Ensures that this hasn't been ended. */ @@ -3822,14 +4280,18 @@ function notImplemented() { /** Returns true iff the given exception represents stream closure. */ function streamClosed(e) { - return e === Cr.NS_BASE_STREAM_CLOSED || - (typeof e === "object" && e.result === Cr.NS_BASE_STREAM_CLOSED); + return ( + e === Cr.NS_BASE_STREAM_CLOSED || + (typeof e === "object" && e.result === Cr.NS_BASE_STREAM_CLOSED) + ); } /** Returns true iff the given exception represents a blocked stream. */ function wouldBlock(e) { - return e === Cr.NS_BASE_STREAM_WOULD_BLOCK || - (typeof e === "object" && e.result === Cr.NS_BASE_STREAM_WOULD_BLOCK); + return ( + e === Cr.NS_BASE_STREAM_WOULD_BLOCK || + (typeof e === "object" && e.result === Cr.NS_BASE_STREAM_WOULD_BLOCK) + ); } /** @@ -3848,8 +4310,9 @@ function wouldBlock(e) { * if source, sink, or observer are null */ function WriteThroughCopier(source, sink, observer, context) { - if (!source || !sink || !observer) + if (!source || !sink || !observer) { throw Components.Exception("", Cr.NS_ERROR_NULL_POINTER); + } /** Stream from which data is being read. */ this._source = source; @@ -3894,18 +4357,23 @@ function WriteThroughCopier(source, sink, observer, context) { this._waitToReadData(); this._waitForSinkClosure(); } catch (e) { - dumpn("!!! error starting copy: " + e + - ("lineNumber" in e ? ", line " + e.lineNumber : "")); + dumpn( + "!!! error starting copy: " + + e + + ("lineNumber" in e ? ", line " + e.lineNumber : "") + ); dumpn(e.stack); this.cancel(Cr.NS_ERROR_UNEXPECTED); } } -WriteThroughCopier.prototype = -{ +WriteThroughCopier.prototype = { /* nsISupports implementation */ - QueryInterface: ChromeUtils.generateQI(["nsIInputStreamCallback", "nsIOutputStreamCallback", "nsIRequest"]), - + QueryInterface: ChromeUtils.generateQI([ + "nsIInputStreamCallback", + "nsIOutputStreamCallback", + "nsIRequest", + ]), // NSIINPUTSTREAMCALLBACK @@ -3917,8 +4385,9 @@ WriteThroughCopier.prototype = * the input stream on whose data we have been waiting */ onInputStreamReady(input) { - if (this._source === null) + if (this._source === null) { return; + } dumpn("*** onInputStreamReady"); @@ -3944,7 +4413,8 @@ WriteThroughCopier.prototype = // with the result NS_ERROR_UNEXPECTED. // - var bytesWanted = 0, bytesConsumed = -1; + var bytesWanted = 0, + bytesConsumed = -1; try { input = new BinaryInputStream(input); @@ -3961,8 +4431,9 @@ WriteThroughCopier.prototype = // Handle the zero-data edge case in the same place as all other edge // cases are handled. - if (bytesWanted === 0) + if (bytesWanted === 0) { throw Components.Exception("", Cr.NS_BASE_STREAM_CLOSED); + } } catch (e) { let rv; if (streamClosed(e)) { @@ -3981,8 +4452,10 @@ WriteThroughCopier.prototype = NS_ASSERT(bytesConsumed > 0); NS_ASSERT(pendingData.length > 0, "no pending data somehow?"); - NS_ASSERT(pendingData[pendingData.length - 1].length > 0, - "buffered zero bytes of data?"); + NS_ASSERT( + pendingData[pendingData.length - 1].length > 0, + "buffered zero bytes of data?" + ); NS_ASSERT(this._source !== null); @@ -4001,11 +4474,15 @@ WriteThroughCopier.prototype = // already -- if data's already queued, the code that actually writes the // data will make sure to wait on unconsumed pending data. try { - if (pendingData.length === 1) + if (pendingData.length === 1) { this._waitToWriteData(); + } } catch (e) { - dumpn("!!! error waiting to write data just read, swallowing and " + - "writing only what we already have: " + e); + dumpn( + "!!! error waiting to write data just read, swallowing and " + + "writing only what we already have: " + + e + ); this._doneWritingToSink(Cr.NS_ERROR_UNEXPECTED); return; } @@ -4020,7 +4497,6 @@ WriteThroughCopier.prototype = } }, - // NSIOUTPUTSTREAMCALLBACK /** @@ -4032,8 +4508,9 @@ WriteThroughCopier.prototype = * this._sink */ onOutputStreamReady(output) { - if (this._sink === null) + if (this._sink === null) { return; + } dumpn("*** onOutputStreamReady"); @@ -4051,7 +4528,6 @@ WriteThroughCopier.prototype = return; } - NS_ASSERT(pendingData[0].length > 0, "queued up an empty quantum?"); // @@ -4077,26 +4553,32 @@ WriteThroughCopier.prototype = // is unusably broken for asynchronous output streams; see bug 532834 // for details. var bytesWritten = output.write(quantum, quantum.length); - if (bytesWritten === quantum.length) + if (bytesWritten === quantum.length) { pendingData.shift(); - else + } else { pendingData[0] = quantum.substring(bytesWritten); + } dumpn("*** wrote " + bytesWritten + " bytes of data"); } catch (e) { if (wouldBlock(e)) { - NS_ASSERT(pendingData.length > 0, - "stream-blocking exception with no data to write?"); - NS_ASSERT(pendingData[0].length > 0, - "stream-blocking exception with empty quantum?"); + NS_ASSERT( + pendingData.length > 0, + "stream-blocking exception with no data to write?" + ); + NS_ASSERT( + pendingData[0].length > 0, + "stream-blocking exception with empty quantum?" + ); this._waitToWriteData(); return; } - if (streamClosed(e)) + if (streamClosed(e)) { dumpn("!!! output stream prematurely closed, signaling error..."); - else + } else { dumpn("!!! unknown error: " + e + ", quantum=" + quantum); + } this._doneWritingToSink(Cr.NS_ERROR_UNEXPECTED); return; @@ -4125,7 +4607,7 @@ WriteThroughCopier.prototype = * reason if over time the output stream permitted more and more data to * be written to it without blocking.) */ - this._waitForSinkClosure(); + this._waitForSinkClosure(); } else { /* * On the other hand, if we can't have more data because the input @@ -4137,7 +4619,6 @@ WriteThroughCopier.prototype = } }, - // NSIREQUEST /** Returns true if the cancel observer hasn't been notified yet. */ @@ -4179,7 +4660,6 @@ WriteThroughCopier.prototype = this._doneReadingSource(status); }, - // PRIVATE IMPLEMENTATION /** @@ -4194,10 +4674,11 @@ WriteThroughCopier.prototype = dumpn("*** _doneReadingSource(0x" + e.toString(16) + ")"); this._finishSource(e); - if (this._pendingData.length === 0) + if (this._pendingData.length === 0) { this._sink = null; - else + } else { NS_ASSERT(this._sink !== null, "null output?"); + } // If we've written out all data read up to this point, then it's time to // signal completion. @@ -4246,21 +4727,23 @@ WriteThroughCopier.prototype = } var self = this; - var event = - { - run() { - dumpn("*** onStopRequest async callback"); + var event = { + run() { + dumpn("*** onStopRequest async callback"); - self._completed = true; - try { - self._observer.onStopRequest(self, self.status); - } catch (e) { - NS_ASSERT(false, - "how are we throwing an exception here? we control " + - "all the callers! " + e); - } - }, - }; + self._completed = true; + try { + self._observer.onStopRequest(self, self.status); + } catch (e) { + NS_ASSERT( + false, + "how are we throwing an exception here? we control " + + "all the callers! " + + e + ); + } + }, + }; gThreadManager.currentThread.dispatch(event, Ci.nsIThread.DISPATCH_NORMAL); }, @@ -4270,8 +4753,12 @@ WriteThroughCopier.prototype = */ _waitToReadData() { dumpn("*** _waitToReadData"); - this._source.asyncWait(this, 0, Response.SEGMENT_SIZE, - gThreadManager.mainThread); + this._source.asyncWait( + this, + 0, + Response.SEGMENT_SIZE, + gThreadManager.mainThread + ); }, /** @@ -4284,8 +4771,12 @@ WriteThroughCopier.prototype = NS_ASSERT(pendingData.length > 0, "no pending data to write?"); NS_ASSERT(pendingData[0].length > 0, "buffered an empty write?"); - this._sink.asyncWait(this, 0, pendingData[0].length, - gThreadManager.mainThread); + this._sink.asyncWait( + this, + 0, + pendingData[0].length, + gThreadManager.mainThread + ); }, /** @@ -4302,8 +4793,12 @@ WriteThroughCopier.prototype = _waitForSinkClosure() { dumpn("*** _waitForSinkClosure"); - this._sink.asyncWait(this, Ci.nsIAsyncOutputStream.WAIT_CLOSURE_ONLY, 0, - gThreadManager.mainThread); + this._sink.asyncWait( + this, + Ci.nsIAsyncOutputStream.WAIT_CLOSURE_ONLY, + 0, + gThreadManager.mainThread + ); }, /** @@ -4323,12 +4818,10 @@ WriteThroughCopier.prototype = }, }; - /** * A container for utility functions used with HTTP headers. */ -const headerUtils = -{ +const headerUtils = { /** * Normalizes fieldName (by converting it to lowercase) and ensures it is a * valid header field name (although not necessarily one specified in RFC @@ -4393,11 +4886,12 @@ const headerUtils = // that should have taken care of all CTLs, so val should contain no CTLs dumpn("*** Normalized value: '" + val + "'"); - for (var i = 0, len = val.length; i < len; i++) + for (var i = 0, len = val.length; i < len; i++) { if (isCTL(val.charCodeAt(i))) { dump("*** Char " + i + " has charcode " + val.charCodeAt(i)); throw Components.Exception("", Cr.NS_ERROR_INVALID_ARG); } + } // XXX disallows quoted-pair where CHAR is a CTL -- will not invalidly // normalize, however, so this can be construed as a tightening of the @@ -4406,8 +4900,6 @@ const headerUtils = }, }; - - /** * Converts the given string into a string which is safe for use in an HTML * context. @@ -4420,12 +4912,12 @@ const headerUtils = function htmlEscape(str) { // this is naive, but it'll work var s = ""; - for (var i = 0; i < str.length; i++) + for (var i = 0; i < str.length; i++) { s += "&#" + str.charCodeAt(i) + ";"; + } return s; } - /** * Constructs an object representing an HTTP version (see section 3.1). * @@ -4437,8 +4929,9 @@ function htmlEscape(str) { */ function nsHttpVersion(versionString) { var matches = /^(\d+)\.(\d+)$/.exec(versionString); - if (!matches) + if (!matches) { throw new Error("Not a valid HTTP version!"); + } /** The major version number of this, as a number. */ this.major = parseInt(matches[1], 10); @@ -4446,12 +4939,16 @@ function nsHttpVersion(versionString) { /** The minor version number of this, as a number. */ this.minor = parseInt(matches[2], 10); - if (isNaN(this.major) || isNaN(this.minor) || - this.major < 0 || this.minor < 0) + if ( + isNaN(this.major) || + isNaN(this.minor) || + this.major < 0 || + this.minor < 0 + ) { throw new Error("Not a valid HTTP version!"); + } } -nsHttpVersion.prototype = -{ +nsHttpVersion.prototype = { /** * Returns the standard string representation of the HTTP version represented * by this (e.g., "1.1"). @@ -4468,22 +4965,21 @@ nsHttpVersion.prototype = * the version to compare against this */ equals(otherVersion) { - return this.major == otherVersion.major && - this.minor == otherVersion.minor; + return this.major == otherVersion.major && this.minor == otherVersion.minor; }, /** True if this >= otherVersion, false otherwise. */ atLeast(otherVersion) { - return this.major > otherVersion.major || - (this.major == otherVersion.major && - this.minor >= otherVersion.minor); + return ( + this.major > otherVersion.major || + (this.major == otherVersion.major && this.minor >= otherVersion.minor) + ); }, }; nsHttpVersion.HTTP_1_0 = new nsHttpVersion("1.0"); nsHttpVersion.HTTP_1_1 = new nsHttpVersion("1.1"); - /** * An object which stores HTTP headers for a request or response. * @@ -4508,8 +5004,7 @@ function nsHttpHeaders() { */ this._headers = {}; } -nsHttpHeaders.prototype = -{ +nsHttpHeaders.prototype = { /** * Sets the header represented by name and value in this. * @@ -4528,14 +5023,18 @@ nsHttpHeaders.prototype = // syntax prevents joining individual headers into a single header using // ",". See also if (merge && name in this._headers) { - if (name === "www-authenticate" || - name === "proxy-authenticate" || - name === "set-cookie") { + if ( + name === "www-authenticate" || + name === "proxy-authenticate" || + name === "set-cookie" + ) { this._headers[name].push(value); } else { this._headers[name][0] += "," + value; - NS_ASSERT(this._headers[name].length === 1, - "how'd a non-special header have multiple values?"); + NS_ASSERT( + this._headers[name].length === 1, + "how'd a non-special header have multiple values?" + ); } } else { this._headers[name] = [value]; @@ -4590,8 +5089,9 @@ nsHttpHeaders.prototype = getHeaderValues(fieldName) { var name = headerUtils.normalizeFieldName(fieldName); - if (name in this._headers) + if (name in this._headers) { return this._headers[name]; + } throw Components.Exception("", Cr.NS_ERROR_NOT_AVAILABLE); }, @@ -4608,7 +5108,7 @@ nsHttpHeaders.prototype = */ hasHeader(fieldName) { var name = headerUtils.normalizeFieldName(fieldName); - return (name in this._headers); + return name in this._headers; }, /** @@ -4629,7 +5129,6 @@ nsHttpHeaders.prototype = }, }; - /** * Constructs an nsISimpleEnumerator for the given array of items. * @@ -4640,14 +5139,14 @@ function nsSimpleEnumerator(items) { this._items = items; this._nextIndex = 0; } -nsSimpleEnumerator.prototype = -{ +nsSimpleEnumerator.prototype = { hasMoreElements() { return this._nextIndex < this._items.length; }, getNext() { - if (!this.hasMoreElements()) + if (!this.hasMoreElements()) { throw Components.Exception("", Cr.NS_ERROR_NOT_AVAILABLE); + } return this._items[this._nextIndex++]; }, @@ -4657,7 +5156,6 @@ nsSimpleEnumerator.prototype = QueryInterface: ChromeUtils.generateQI(["nsISimpleEnumerator"]), }; - /** * A representation of the data in an HTTP request. * @@ -4703,8 +5201,7 @@ function Request(port) { */ this._bag = null; } -Request.prototype = -{ +Request.prototype = { // SERVER METADATA // @@ -4804,7 +5301,6 @@ Request.prototype = return this._bag.getProperty(name); }, - // NSISUPPORTS // @@ -4812,13 +5308,13 @@ Request.prototype = // QueryInterface: ChromeUtils.generateQI(["nsIHttpRequest"]), - // PRIVATE IMPLEMENTATION /** Ensures a property bag has been created for ad-hoc behaviors. */ _ensurePropertyBag() { - if (!this._bag) + if (!this._bag) { this._bag = new WritablePropertyBag(); + } }, }; @@ -4851,8 +5347,7 @@ Request.prototype = */ function server(port, basePath) { if (basePath) { - var lp = Cc["@mozilla.org/file/local;1"] - .createInstance(Ci.nsIFile); + var lp = Cc["@mozilla.org/file/local;1"].createInstance(Ci.nsIFile); lp.initWithPath(basePath); } @@ -4860,19 +5355,22 @@ function server(port, basePath) { DEBUG = true; var srv = new nsHttpServer(); - if (lp) + if (lp) { srv.registerDirectory("/", lp); + } srv.registerContentType("sjs", SJS_TYPE); srv.identity.setPrimary("http", "localhost", port); srv.start(port); var thread = gThreadManager.currentThread; - while (!srv.isStopped()) + while (!srv.isStopped()) { thread.processNextEvent(true); + } // get rid of any pending requests - while (thread.hasPendingEvents()) + while (thread.hasPendingEvents()) { thread.processNextEvent(true); + } DEBUG = false; } diff --git a/netwerk/test/httpserver/test/head_utils.js b/netwerk/test/httpserver/test/head_utils.js index 8b19a8395eb0..72904d3efe9e 100644 --- a/netwerk/test/httpserver/test/head_utils.js +++ b/netwerk/test/httpserver/test/head_utils.js @@ -13,8 +13,10 @@ load(_HTTPD_JS_PATH.path); // if these tests fail, we'll want the debug output var linDEBUG = true; -var {XPCOMUtils} = ChromeUtils.import("resource://gre/modules/XPCOMUtils.jsm"); -var {NetUtil} = ChromeUtils.import("resource://gre/modules/NetUtil.jsm"); +var { XPCOMUtils } = ChromeUtils.import( + "resource://gre/modules/XPCOMUtils.jsm" +); +var { NetUtil } = ChromeUtils.import("resource://gre/modules/NetUtil.jsm"); /** * Constructs a new nsHttpServer instance. This function is intended to @@ -33,8 +35,10 @@ function createServer() { * the URL of the channel to create */ function makeChannel(url) { - return NetUtil.newChannel({uri: url, loadUsingSystemPrincipal: true}) - .QueryInterface(Ci.nsIHttpChannel); + return NetUtil.newChannel({ + uri: url, + loadUsingSystemPrincipal: true, + }).QueryInterface(Ci.nsIHttpChannel); } /** @@ -47,7 +51,6 @@ function makeBIS(stream) { return new BinaryInputStream(stream); } - /** * Returns the contents of the file as a string. * @@ -58,8 +61,12 @@ function makeBIS(stream) { */ function fileContents(file) { const PR_RDONLY = 0x01; - var fis = new FileInputStream(file, PR_RDONLY, 0o444, - Ci.nsIFileInputStream.CLOSE_ON_EOF); + var fis = new FileInputStream( + file, + PR_RDONLY, + 0o444, + Ci.nsIFileInputStream.CLOSE_ON_EOF + ); var sis = new ScriptableInputStream(fis); var contents = sis.read(file.fileSize); sis.close(); @@ -80,14 +87,14 @@ function* LineIterator(data) { var index = 0; do { index = data.indexOf("\r\n"); - if (index >= 0) + if (index >= 0) { yield data.substring(0, index); - else + } else { yield data; + } data = data.substring(index + 2); - } - while (index >= 0); + } while (index >= 0); } /** @@ -103,14 +110,18 @@ function* LineIterator(data) { function expectLines(iter, expectedLines) { var index = 0; for (var line of iter) { - if (expectedLines.length == index) - throw new Error(`Error: got more than ${expectedLines.length} expected lines!`); + if (expectedLines.length == index) { + throw new Error( + `Error: got more than ${expectedLines.length} expected lines!` + ); + } var expected = expectedLines[index++]; - if (expected !== line) + if (expected !== line) { throw new Error(`Error on line ${index}! actual: '${line}', expect: '${expected}'`); + } } if (expectedLines.length !== index) { @@ -148,8 +159,9 @@ function writeDetails(request, response) { */ function skipHeaders(iter) { var line = iter.next().value; - while (line !== "") + while (line !== "") { line = iter.next().value; + } } /** @@ -162,8 +174,9 @@ function skipHeaders(iter) { * the expected exception */ function isException(e, code) { - if (e !== code && e.result !== code) + if (e !== code && e.result !== code) { do_throw("unexpected error: " + e); + } } /** @@ -180,7 +193,6 @@ function callLater(msecs, callback) { do_timeout(msecs, callback); } - /** ***************************************************** * SIMPLE SUPPORT FOR LOADING/TESTING A SERIES OF URLS * *******************************************************/ @@ -192,7 +204,9 @@ function callLater(msecs, callback) { function testComplete(srv) { return function complete() { do_test_pending(); - srv.stop(function quit() { do_test_finished(); }); + srv.stop(function quit() { + do_test_finished(); + }); }; } @@ -218,7 +232,7 @@ function testComplete(srv) { * nothing needs to be done */ function Test(path, initChannel, onStartRequest, onStopRequest) { - function nil() { } + function nil() {} this.path = path; this.initChannel = initChannel || nil; @@ -254,7 +268,10 @@ function runHttpTests(testArray, done) { test.initChannel(ch); } catch (e) { try { - do_report_unexpected_exception(e, "testArray[" + testIndex + "].initChannel(ch)"); + do_report_unexpected_exception( + e, + "testArray[" + testIndex + "].initChannel(ch)" + ); } catch (x) { /* swallow and let tests continue */ } @@ -268,65 +285,74 @@ function runHttpTests(testArray, done) { var testIndex = -1; /** Stream listener for the channels. */ - var listener = - { - /** Current channel being observed by this. */ - _channel: null, - /** Array of bytes of data in body of response. */ - _data: [], + var listener = { + /** Current channel being observed by this. */ + _channel: null, + /** Array of bytes of data in body of response. */ + _data: [], - onStartRequest(request) { - Assert.ok(request === this._channel); - var ch = request.QueryInterface(Ci.nsIHttpChannel) - .QueryInterface(Ci.nsIHttpChannelInternal); + onStartRequest(request) { + Assert.ok(request === this._channel); + var ch = request + .QueryInterface(Ci.nsIHttpChannel) + .QueryInterface(Ci.nsIHttpChannelInternal); - this._data.length = 0; + this._data.length = 0; + try { try { - try { - testArray[testIndex].onStartRequest(ch); - } catch (e) { - do_report_unexpected_exception(e, "testArray[" + testIndex + "].onStartRequest"); - } + testArray[testIndex].onStartRequest(ch); } catch (e) { - do_note_exception(e, "!!! swallowing onStartRequest exception so onStopRequest is " + - "called..."); + do_report_unexpected_exception( + e, + "testArray[" + testIndex + "].onStartRequest" + ); } - }, - onDataAvailable(request, inputStream, offset, count) { - var quantum = 262144; // just above half the argument-count limit - var bis = makeBIS(inputStream); - for (var start = 0; start < count; start += quantum) { - var newData = bis.readByteArray(Math.min(quantum, count - start)); - Array.prototype.push.apply(this._data, newData); - } - }, - onStopRequest(request, status) { - this._channel = null; + } catch (e) { + do_note_exception( + e, + "!!! swallowing onStartRequest exception so onStopRequest is " + + "called..." + ); + } + }, + onDataAvailable(request, inputStream, offset, count) { + var quantum = 262144; // just above half the argument-count limit + var bis = makeBIS(inputStream); + for (var start = 0; start < count; start += quantum) { + var newData = bis.readByteArray(Math.min(quantum, count - start)); + Array.prototype.push.apply(this._data, newData); + } + }, + onStopRequest(request, status) { + this._channel = null; - var ch = request.QueryInterface(Ci.nsIHttpChannel) - .QueryInterface(Ci.nsIHttpChannelInternal); + var ch = request + .QueryInterface(Ci.nsIHttpChannel) + .QueryInterface(Ci.nsIHttpChannelInternal); - // NB: The onStopRequest callback must run before performNextTest here, - // because the latter runs the next test's initChannel callback, and - // we want one test to be sequentially processed before the next - // one. + // NB: The onStopRequest callback must run before performNextTest here, + // because the latter runs the next test's initChannel callback, and + // we want one test to be sequentially processed before the next + // one. + try { + testArray[testIndex].onStopRequest(ch, status, this._data); + } finally { try { - testArray[testIndex].onStopRequest(ch, status, this._data); + performNextTest(); } finally { - try { - performNextTest(); - } finally { - do_test_finished(); - } + do_test_finished(); } - }, - QueryInterface: ChromeUtils.generateQI(["nsIStreamListener", "nsIRequestObserver"]), - }; + } + }, + QueryInterface: ChromeUtils.generateQI([ + "nsIStreamListener", + "nsIRequestObserver", + ]), + }; performNextTest(); } - /** ************************************** * RAW REQUEST FORMAT TESTING FUNCTIONS * ****************************************/ @@ -350,16 +376,24 @@ function runHttpTests(testArray, done) { * environment between tests */ function RawTest(host, port, data, responseCheck) { - if (0 > port || 65535 < port || port % 1 !== 0) + if (0 > port || 65535 < port || port % 1 !== 0) { throw new Error("bad port"); - if (!(data instanceof Array)) + } + if (!(data instanceof Array)) { data = [data]; - if (data.length <= 0) + } + if (data.length <= 0) { throw new Error("bad data length"); + } // eslint-disable-next-line no-control-regex - if (!data.every(function(v) { return /^[\x00-\xff]*$/.test(v); })) + if ( + !data.every(function(v) { + return /^[\x00-\xff]*$/.test(v); + }) + ) { throw new Error("bad data contained non-byte-valued character"); + } this.host = host; this.port = port; @@ -380,12 +414,12 @@ function RawTest(host, port, data, responseCheck) { function runRawTests(testArray, done, beforeTestCallback) { do_test_pending(); - var sts = Cc["@mozilla.org/network/socket-transport-service;1"] - .getService(Ci.nsISocketTransportService); + var sts = Cc["@mozilla.org/network/socket-transport-service;1"].getService( + Ci.nsISocketTransportService + ); - var currentThread = Cc["@mozilla.org/thread-manager;1"] - .getService() - .currentThread; + var currentThread = Cc["@mozilla.org/thread-manager;1"].getService() + .currentThread; /** Kicks off running the next test in the array. */ function performNextTest() { @@ -402,16 +436,17 @@ function runRawTests(testArray, done, beforeTestCallback) { if (beforeTestCallback) { try { beforeTestCallback(testIndex); - } catch (e) { /* We don't care if this call fails */ } + } catch (e) { + /* We don't care if this call fails */ + } } var rawTest = testArray[testIndex]; - var transport = - sts.createTransport([], rawTest.host, rawTest.port, null); + var transport = sts.createTransport([], rawTest.host, rawTest.port, null); var inStream = transport.openInputStream(0, 0, 0); - var outStream = transport.openOutputStream(0, 0, 0); + var outStream = transport.openOutputStream(0, 0, 0); // reset dataIndex = 0; @@ -432,8 +467,12 @@ function runRawTests(testArray, done, beforeTestCallback) { // guarantee that 'stream' passed in here been QIed to nsIAsyncOutputStream // since the last GC. stream = stream.QueryInterface(Ci.nsIAsyncOutputStream); - stream.asyncWait(writer, 0, testArray[testIndex].data[dataIndex].length, - currentThread); + stream.asyncWait( + writer, + 0, + testArray[testIndex].data[dataIndex].length, + currentThread + ); } /** Index of the test being run. */ @@ -449,80 +488,80 @@ function runRawTests(testArray, done, beforeTestCallback) { var received = ""; /** Reads data from the socket. */ - var reader = - { - onInputStreamReady(stream) { - Assert.ok(stream === this.stream); + var reader = { + onInputStreamReady(stream) { + Assert.ok(stream === this.stream); + try { + var bis = new BinaryInputStream(stream); + + var av = 0; try { - var bis = new BinaryInputStream(stream); + av = bis.available(); + } catch (e) { + /* default to 0 */ + do_note_exception(e); + } - var av = 0; - try { - av = bis.available(); - } catch (e) { - /* default to 0 */ - do_note_exception(e); + if (av > 0) { + var quantum = 262144; + for (var start = 0; start < av; start += quantum) { + var bytes = bis.readByteArray(Math.min(quantum, av - start)); + received += String.fromCharCode.apply(null, bytes); } + waitForMoreInput(stream); + return; + } + } catch (e) { + do_report_unexpected_exception(e); + } - if (av > 0) { - var quantum = 262144; - for (var start = 0; start < av; start += quantum) { - var bytes = bis.readByteArray(Math.min(quantum, av - start)); - received += String.fromCharCode.apply(null, bytes); - } - waitForMoreInput(stream); - return; - } + var rawTest = testArray[testIndex]; + try { + rawTest.responseCheck(received); + } catch (e) { + do_report_unexpected_exception(e); + } finally { + try { + stream.close(); + performNextTest(); } catch (e) { do_report_unexpected_exception(e); } - - var rawTest = testArray[testIndex]; - try { - rawTest.responseCheck(received); - } catch (e) { - do_report_unexpected_exception(e); - } finally { - try { - stream.close(); - performNextTest(); - } catch (e) { - do_report_unexpected_exception(e); - } - } - }, - }; + } + }, + }; /** Writes data to the socket. */ - var writer = - { - onOutputStreamReady(stream) { - var str = testArray[testIndex].data[dataIndex]; + var writer = { + onOutputStreamReady(stream) { + var str = testArray[testIndex].data[dataIndex]; - var written = 0; - try { - written = stream.write(str, str.length); - if (written == str.length) - dataIndex++; - else - testArray[testIndex].data[dataIndex] = str.substring(written); - } catch (e) { - do_note_exception(e); - /* stream could have been closed, just ignore */ + var written = 0; + try { + written = stream.write(str, str.length); + if (written == str.length) { + dataIndex++; + } else { + testArray[testIndex].data[dataIndex] = str.substring(written); } + } catch (e) { + do_note_exception(e); + /* stream could have been closed, just ignore */ + } - try { - // Keep writing data while we can write and - // until there's no more data to read - if (written > 0 && dataIndex < testArray[testIndex].data.length) - waitToWriteOutput(stream); - else - stream.close(); - } catch (e) { - do_report_unexpected_exception(e); + try { + // Keep writing data while we can write and + // until there's no more data to read + if (written > 0 && dataIndex < testArray[testIndex].data.length) { + waitToWriteOutput(stream); + } else { + stream.close(); } - }, - }; + } catch (e) { + do_report_unexpected_exception(e); + } + }, + }; performNextTest(); } diff --git a/netwerk/test/httpserver/test/test_async_response_sending.js b/netwerk/test/httpserver/test/test_async_response_sending.js index ecb029c651ca..73f50c43924c 100644 --- a/netwerk/test/httpserver/test/test_async_response_sending.js +++ b/netwerk/test/httpserver/test/test_async_response_sending.js @@ -4,7 +4,6 @@ * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - /* * Ensures that data a request handler writes out in response is sent only as * quickly as the client can receive it, without racing ahead and being forced @@ -22,9 +21,9 @@ gThreadManager = Cc["@mozilla.org/thread-manager;1"].createInstance(); function run_test() { do_test_pending(); tests.push(function testsComplete(_) { - dumpn("******************\n" + - "* TESTS COMPLETE *\n" + - "******************"); + dumpn( + "******************\n" + "* TESTS COMPLETE *\n" + "******************" + ); do_test_finished(); }); @@ -40,13 +39,13 @@ function runNextTest() { test(runNextTest); } catch (e) { var msg = "exception running test " + testIndex + ": " + e; - if (e && "stack" in e) + if (e && "stack" in e) { msg += "\nstack follows:\n" + e.stack; + } do_throw(msg); } } - /** *********** * TEST DATA * *************/ @@ -76,32 +75,30 @@ const LATTER_HALF_THIRD_SEGMENT = [11, 12]; const TWO_HALF_SEGMENTS = [1, 2, 1, 2]; - /** ******* * TESTS * *********/ -var tests = - [ - sourceClosedWithoutWrite, - writeOneSegmentThenClose, - simpleWriteThenRead, - writeLittleBeforeReading, - writeMultipleSegmentsThenRead, - writeLotsBeforeReading, - writeLotsBeforeReading2, - writeThenReadPartial, - manyPartialWrites, - partialRead, - partialWrite, - sinkClosedImmediately, - sinkClosedWithReadableData, - sinkClosedAfterWrite, - sourceAndSinkClosed, - sinkAndSourceClosed, - sourceAndSinkClosedWithPendingData, - sinkAndSourceClosedWithPendingData, - ]; +var tests = [ + sourceClosedWithoutWrite, + writeOneSegmentThenClose, + simpleWriteThenRead, + writeLittleBeforeReading, + writeMultipleSegmentsThenRead, + writeLotsBeforeReading, + writeLotsBeforeReading2, + writeThenReadPartial, + manyPartialWrites, + partialRead, + partialWrite, + sinkClosedImmediately, + sinkClosedWithReadableData, + sinkClosedAfterWrite, + sourceAndSinkClosed, + sinkAndSourceClosed, + sourceAndSinkClosedWithPendingData, + sinkAndSourceClosedWithPendingData, +]; var testIndex = -1; function sourceClosedWithoutWrite(next) { @@ -149,8 +146,10 @@ function writeMultipleSegmentsThenRead(next) { t.addToSource(TWO_SEGMENTS); t.makeSourceReadable(TWO_SEGMENTS.length); - t.makeSinkWritableAndWaitFor(TWO_SEGMENTS.length, - [FIRST_SEGMENT, SECOND_SEGMENT]); + t.makeSinkWritableAndWaitFor(TWO_SEGMENTS.length, [ + FIRST_SEGMENT, + SECOND_SEGMENT, + ]); t.closeSource(Cr.NS_OK); t.expect(Cr.NS_OK, [TWO_SEGMENTS]); } @@ -229,23 +228,28 @@ function partialWrite(next) { t.addToSource(SEGMENT); t.makeSourceReadable(SEGMENT.length); - t.makeSinkWritableByIncrementsAndWaitFor(SEGMENT.length, - [QUARTER_SEGMENT, - MIDDLE_HALF_SEGMENT, - LAST_QUARTER_SEGMENT]); + t.makeSinkWritableByIncrementsAndWaitFor(SEGMENT.length, [ + QUARTER_SEGMENT, + MIDDLE_HALF_SEGMENT, + LAST_QUARTER_SEGMENT, + ]); t.addToSource(SEGMENT); t.makeSourceReadable(SEGMENT.length); - t.makeSinkWritableByIncrementsAndWaitFor(SEGMENT.length, - [HALF_SEGMENT, SECOND_HALF_SEGMENT]); + t.makeSinkWritableByIncrementsAndWaitFor(SEGMENT.length, [ + HALF_SEGMENT, + SECOND_HALF_SEGMENT, + ]); t.addToSource(THREE_SEGMENTS); t.makeSourceReadable(THREE_SEGMENTS.length); - t.makeSinkWritableByIncrementsAndWaitFor(THREE_SEGMENTS.length, - [HALF_SEGMENT, SECOND_HALF_SEGMENT, - SECOND_SEGMENT, - HALF_THIRD_SEGMENT, - LATTER_HALF_THIRD_SEGMENT]); + t.makeSinkWritableByIncrementsAndWaitFor(THREE_SEGMENTS.length, [ + HALF_SEGMENT, + SECOND_HALF_SEGMENT, + SECOND_SEGMENT, + HALF_THIRD_SEGMENT, + LATTER_HALF_THIRD_SEGMENT, + ]); t.closeSource(Cr.NS_OK); t.expect(Cr.NS_OK, [SEGMENT, SEGMENT, THREE_SEGMENTS]); @@ -317,7 +321,6 @@ function sinkAndSourceClosedWithPendingData(next) { t.expect(Cr.NS_ERROR_UNEXPECTED, []); } - /** *********** * UTILITIES * *************/ @@ -325,8 +328,9 @@ function sinkAndSourceClosedWithPendingData(next) { /** Returns the sum of the elements in arr. */ function sum(arr) { var s = 0; - for (var i = 0, sz = arr.length; i < sz; i++) + for (var i = 0, sz = arr.length; i < sz; i++) { s += arr[i]; + } return s; } @@ -374,7 +378,6 @@ function note(m) { dumpn(asterisks + "\n* " + m + " *\n" + asterisks); } - /** ********* * MOCKERY * ***********/ @@ -384,8 +387,12 @@ function note(m) { * PUBLIC API! If you use any of these I will knowingly break your code by * changing the names of variables and properties. */ -var BinaryInputStream = function BIS(stream) { return stream; }; -var BinaryOutputStream = function BOS(stream) { return stream; }; +var BinaryInputStream = function BIS(stream) { + return stream; +}; +var BinaryOutputStream = function BOS(stream) { + return stream; +}; Response.SEGMENT_SIZE = SEGMENT.length; /** @@ -413,556 +420,650 @@ function CustomPipe(name) { this._status = Cr.NS_OK; /** The input end of this pipe. */ - var input = this.inputStream = - { - /** A name for this stream, used in debugging output. */ - name: name + " input", + var input = (this.inputStream = { + /** A name for this stream, used in debugging output. */ + name: name + " input", - /** - * The number of bytes of data available to be read from this pipe, or - * Infinity if any amount of data in this pipe is made readable as soon as - * it is written to the pipe output. - */ - _readable: 0, + /** + * The number of bytes of data available to be read from this pipe, or + * Infinity if any amount of data in this pipe is made readable as soon as + * it is written to the pipe output. + */ + _readable: 0, - /** - * Data regarding a pending stream-ready callback on this, or null if no - * callback is currently waiting to be called. - */ - _waiter: null, + /** + * Data regarding a pending stream-ready callback on this, or null if no + * callback is currently waiting to be called. + */ + _waiter: null, - /** - * The event currently dispatched to make a stream-ready callback, if any - * such callback is currently ready to be made and not already in - * progress, or null when no callback is waiting to happen. - */ - _event: null, + /** + * The event currently dispatched to make a stream-ready callback, if any + * such callback is currently ready to be made and not already in + * progress, or null when no callback is waiting to happen. + */ + _event: null, - /** - * A stream-ready constructor to wrap an existing callback to intercept - * stream-ready notifications, or null if notifications shouldn't be - * wrapped at all. - */ - _streamReadyInterceptCreator: null, + /** + * A stream-ready constructor to wrap an existing callback to intercept + * stream-ready notifications, or null if notifications shouldn't be + * wrapped at all. + */ + _streamReadyInterceptCreator: null, - /** - * Registers a stream-ready wrapper creator function so that a - * stream-ready callback made in the future can be wrapped. - */ - interceptStreamReadyCallbacks(streamReadyInterceptCreator) { - dumpn("*** [" + this.name + "].interceptStreamReadyCallbacks"); + /** + * Registers a stream-ready wrapper creator function so that a + * stream-ready callback made in the future can be wrapped. + */ + interceptStreamReadyCallbacks(streamReadyInterceptCreator) { + dumpn("*** [" + this.name + "].interceptStreamReadyCallbacks"); - Assert.ok(this._streamReadyInterceptCreator === null, - "intercepting twice"); - this._streamReadyInterceptCreator = streamReadyInterceptCreator; - if (this._waiter) { - this._waiter.callback = - new streamReadyInterceptCreator(this._waiter.callback); - } - }, + Assert.ok( + this._streamReadyInterceptCreator === null, + "intercepting twice" + ); + this._streamReadyInterceptCreator = streamReadyInterceptCreator; + if (this._waiter) { + this._waiter.callback = new streamReadyInterceptCreator( + this._waiter.callback + ); + } + }, - /** - * Removes a previously-registered stream-ready wrapper creator function, - * also clearing any current wrapping. - */ - removeStreamReadyInterceptor() { - dumpn("*** [" + this.name + "].removeStreamReadyInterceptor()"); + /** + * Removes a previously-registered stream-ready wrapper creator function, + * also clearing any current wrapping. + */ + removeStreamReadyInterceptor() { + dumpn("*** [" + this.name + "].removeStreamReadyInterceptor()"); - Assert.ok(this._streamReadyInterceptCreator !== null, - "removing interceptor when none present?"); - this._streamReadyInterceptCreator = null; - if (this._waiter) - this._waiter.callback = this._waiter.callback.wrappedCallback; - }, + Assert.ok( + this._streamReadyInterceptCreator !== null, + "removing interceptor when none present?" + ); + this._streamReadyInterceptCreator = null; + if (this._waiter) { + this._waiter.callback = this._waiter.callback.wrappedCallback; + } + }, - // - // see nsIAsyncInputStream.asyncWait - // - asyncWait: function asyncWait(callback, flags, requestedCount, target) { - dumpn("*** [" + this.name + "].asyncWait"); + // + // see nsIAsyncInputStream.asyncWait + // + asyncWait: function asyncWait(callback, flags, requestedCount, target) { + dumpn("*** [" + this.name + "].asyncWait"); - Assert.ok(callback && typeof callback !== "function"); + Assert.ok(callback && typeof callback !== "function"); - var closureOnly = - (flags & Ci.nsIAsyncInputStream.WAIT_CLOSURE_ONLY) !== 0; + var closureOnly = + (flags & Ci.nsIAsyncInputStream.WAIT_CLOSURE_ONLY) !== 0; - Assert.ok(this._waiter === null || - (this._waiter.closureOnly && !closureOnly), - "asyncWait already called with a non-closure-only " + - "callback? unexpected!"); + Assert.ok( + this._waiter === null || (this._waiter.closureOnly && !closureOnly), + "asyncWait already called with a non-closure-only " + + "callback? unexpected!" + ); - this._waiter = - { - callback: - this._streamReadyInterceptCreator - ? new this._streamReadyInterceptCreator(callback) - : callback, - closureOnly, - requestedCount, - eventTarget: target, - }; + this._waiter = { + callback: this._streamReadyInterceptCreator + ? new this._streamReadyInterceptCreator(callback) + : callback, + closureOnly, + requestedCount, + eventTarget: target, + }; - if (!Components.isSuccessCode(self._status) || - (!closureOnly && this._readable >= requestedCount && - self._data.length >= requestedCount)) { - this._notify(); - } - }, - - // - // see nsIAsyncInputStream.closeWithStatus - // - closeWithStatus: function closeWithStatus(status) { - dumpn("*** [" + this.name + "].closeWithStatus" + - "(" + status + ")"); - - if (!Components.isSuccessCode(self._status)) { - dumpn("*** ignoring second closure of [input " + this.name + "] " + - "(status " + self._status + ")"); - return; - } - - if (Components.isSuccessCode(status)) - status = Cr.NS_BASE_STREAM_CLOSED; - - self._status = status; - - if (this._waiter) - this._notify(); - if (output._waiter) - output._notify(); - }, - - // - // see nsIBinaryInputStream.readByteArray - // - readByteArray: function readByteArray(count) { - dumpn("*** [" + this.name + "].readByteArray(" + count + ")"); - - if (self._data.length === 0) { - throw Components.isSuccessCode(self._status) - ? Cr.NS_BASE_STREAM_WOULD_BLOCK - : self._status; - } - - Assert.ok(this._readable <= self._data.length || - this._readable === Infinity, - "consistency check"); - - if (this._readable < count || self._data.length < count) - throw Cr.NS_BASE_STREAM_WOULD_BLOCK; - this._readable -= count; - return self._data.splice(0, count); - }, - - /** - * Makes the given number of additional bytes of data previously written - * to the pipe's output stream available for reading, triggering future - * notifications when required. - * - * @param count : uint - * the number of bytes of additional data to make available; must not be - * greater than the number of bytes already buffered but not made - * available by previous makeReadable calls - */ - makeReadable: function makeReadable(count) { - dumpn("*** [" + this.name + "].makeReadable(" + count + ")"); - - Assert.ok(Components.isSuccessCode(self._status), "errant call"); - Assert.ok(this._readable + count <= self._data.length || - this._readable === Infinity, - "increasing readable beyond written amount"); - - this._readable += count; - - dumpn("readable: " + this._readable + ", data: " + self._data); - - var waiter = this._waiter; - if (waiter !== null) { - if (waiter.requestedCount <= this._readable && !waiter.closureOnly) - this._notify(); - } - }, - - /** - * Disables the readability limit on this stream, meaning that as soon as - * *any* amount of data is written to output it becomes available from - * this stream and a stream-ready event is dispatched (if any stream-ready - * callback is currently set). - */ - disableReadabilityLimit: function disableReadabilityLimit() { - dumpn("*** [" + this.name + "].disableReadabilityLimit()"); - - this._readable = Infinity; - }, - - // - // see nsIInputStream.available - // - available: function available() { - dumpn("*** [" + this.name + "].available()"); - - if (self._data.length === 0 && !Components.isSuccessCode(self._status)) - throw self._status; - - return Math.min(this._readable, self._data.length); - }, - - /** - * Dispatches a pending stream-ready event ahead of schedule, rather than - * waiting for it to be dispatched in response to normal writes. This is - * useful when writing to the output has completed, and we need to have - * read all data written to this stream. If the output isn't closed and - * the reading of data from this races ahead of the last write to output, - * we need a notification to know when everything that's been written has - * been read. This ordinarily might be supplied by closing output, but - * in some cases it's not desirable to close output, so this supplies an - * alternative method to get notified when the last write has occurred. - */ - maybeNotifyFinally: function maybeNotifyFinally() { - dumpn("*** [" + this.name + "].maybeNotifyFinally()"); - - Assert.ok(this._waiter !== null, "must be waiting now"); - - if (self._data.length > 0) { - dumpn("*** data still pending, normal notifications will signal " + - "completion"); - return; - } - - // No data waiting to be written, so notify. We could just close the - // stream, but that's less faithful to the server's behavior (it doesn't - // close the stream, and we're pretending to impersonate the server as - // much as we can here), so instead we're going to notify when no data - // can be read. The CopyTest has already been flagged as complete, so - // the stream listener will detect that this is a wrap-it-up notify and - // invoke the next test. + if ( + !Components.isSuccessCode(self._status) || + (!closureOnly && + this._readable >= requestedCount && + self._data.length >= requestedCount) + ) { this._notify(); - }, + } + }, - /** - * Dispatches an event to call a previously-registered stream-ready - * callback. - */ - _notify: function _notify() { - dumpn("*** [" + this.name + "]._notify()"); + // + // see nsIAsyncInputStream.closeWithStatus + // + closeWithStatus: function closeWithStatus(status) { + dumpn("*** [" + this.name + "].closeWithStatus" + "(" + status + ")"); - var waiter = this._waiter; - Assert.ok(waiter !== null, "no waiter?"); + if (!Components.isSuccessCode(self._status)) { + dumpn( + "*** ignoring second closure of [input " + + this.name + + "] " + + "(status " + + self._status + + ")" + ); + return; + } - if (this._event === null) { - var event = this._event = - { - run: function run() { - input._waiter = null; - input._event = null; - try { - Assert.ok(!Components.isSuccessCode(self._status) || - input._readable >= waiter.requestedCount); - waiter.callback.onInputStreamReady(input); - } catch (e) { - do_throw("error calling onInputStreamReady: " + e); - } - }, - }; - waiter.eventTarget.dispatch(event, Ci.nsIThread.DISPATCH_NORMAL); + if (Components.isSuccessCode(status)) { + status = Cr.NS_BASE_STREAM_CLOSED; + } + + self._status = status; + + if (this._waiter) { + this._notify(); + } + if (output._waiter) { + output._notify(); + } + }, + + // + // see nsIBinaryInputStream.readByteArray + // + readByteArray: function readByteArray(count) { + dumpn("*** [" + this.name + "].readByteArray(" + count + ")"); + + if (self._data.length === 0) { + throw Components.isSuccessCode(self._status) + ? Cr.NS_BASE_STREAM_WOULD_BLOCK + : self._status; + } + + Assert.ok( + this._readable <= self._data.length || this._readable === Infinity, + "consistency check" + ); + + if (this._readable < count || self._data.length < count) { + throw Cr.NS_BASE_STREAM_WOULD_BLOCK; + } + this._readable -= count; + return self._data.splice(0, count); + }, + + /** + * Makes the given number of additional bytes of data previously written + * to the pipe's output stream available for reading, triggering future + * notifications when required. + * + * @param count : uint + * the number of bytes of additional data to make available; must not be + * greater than the number of bytes already buffered but not made + * available by previous makeReadable calls + */ + makeReadable: function makeReadable(count) { + dumpn("*** [" + this.name + "].makeReadable(" + count + ")"); + + Assert.ok(Components.isSuccessCode(self._status), "errant call"); + Assert.ok( + this._readable + count <= self._data.length || + this._readable === Infinity, + "increasing readable beyond written amount" + ); + + this._readable += count; + + dumpn("readable: " + this._readable + ", data: " + self._data); + + var waiter = this._waiter; + if (waiter !== null) { + if (waiter.requestedCount <= this._readable && !waiter.closureOnly) { + this._notify(); } - }, + } + }, - QueryInterface: ChromeUtils.generateQI(["nsIAsyncInputStream", "nsIInputStream"]), - }; + /** + * Disables the readability limit on this stream, meaning that as soon as + * *any* amount of data is written to output it becomes available from + * this stream and a stream-ready event is dispatched (if any stream-ready + * callback is currently set). + */ + disableReadabilityLimit: function disableReadabilityLimit() { + dumpn("*** [" + this.name + "].disableReadabilityLimit()"); + + this._readable = Infinity; + }, + + // + // see nsIInputStream.available + // + available: function available() { + dumpn("*** [" + this.name + "].available()"); + + if (self._data.length === 0 && !Components.isSuccessCode(self._status)) { + throw self._status; + } + + return Math.min(this._readable, self._data.length); + }, + + /** + * Dispatches a pending stream-ready event ahead of schedule, rather than + * waiting for it to be dispatched in response to normal writes. This is + * useful when writing to the output has completed, and we need to have + * read all data written to this stream. If the output isn't closed and + * the reading of data from this races ahead of the last write to output, + * we need a notification to know when everything that's been written has + * been read. This ordinarily might be supplied by closing output, but + * in some cases it's not desirable to close output, so this supplies an + * alternative method to get notified when the last write has occurred. + */ + maybeNotifyFinally: function maybeNotifyFinally() { + dumpn("*** [" + this.name + "].maybeNotifyFinally()"); + + Assert.ok(this._waiter !== null, "must be waiting now"); + + if (self._data.length > 0) { + dumpn( + "*** data still pending, normal notifications will signal " + + "completion" + ); + return; + } + + // No data waiting to be written, so notify. We could just close the + // stream, but that's less faithful to the server's behavior (it doesn't + // close the stream, and we're pretending to impersonate the server as + // much as we can here), so instead we're going to notify when no data + // can be read. The CopyTest has already been flagged as complete, so + // the stream listener will detect that this is a wrap-it-up notify and + // invoke the next test. + this._notify(); + }, + + /** + * Dispatches an event to call a previously-registered stream-ready + * callback. + */ + _notify: function _notify() { + dumpn("*** [" + this.name + "]._notify()"); + + var waiter = this._waiter; + Assert.ok(waiter !== null, "no waiter?"); + + if (this._event === null) { + var event = (this._event = { + run: function run() { + input._waiter = null; + input._event = null; + try { + Assert.ok( + !Components.isSuccessCode(self._status) || + input._readable >= waiter.requestedCount + ); + waiter.callback.onInputStreamReady(input); + } catch (e) { + do_throw("error calling onInputStreamReady: " + e); + } + }, + }); + waiter.eventTarget.dispatch(event, Ci.nsIThread.DISPATCH_NORMAL); + } + }, + + QueryInterface: ChromeUtils.generateQI([ + "nsIAsyncInputStream", + "nsIInputStream", + ]), + }); /** The output end of this pipe. */ - var output = this.outputStream = - { - /** A name for this stream, used in debugging output. */ - name: name + " output", + var output = (this.outputStream = { + /** A name for this stream, used in debugging output. */ + name: name + " output", - /** - * The number of bytes of data which may be written to this pipe without - * blocking. - */ - _writable: 0, + /** + * The number of bytes of data which may be written to this pipe without + * blocking. + */ + _writable: 0, - /** - * The increments in which pending data should be written, rather than - * simply defaulting to the amount requested (which, given that - * input.asyncWait precisely respects the requestedCount argument, will - * ordinarily always be writable in that amount), as an array whose - * elements from start to finish are the number of bytes to write each - * time write() or writeByteArray() is subsequently called. The sum of - * the values in this array, if this array is not empty, is always equal - * to this._writable. - */ - _writableAmounts: [], + /** + * The increments in which pending data should be written, rather than + * simply defaulting to the amount requested (which, given that + * input.asyncWait precisely respects the requestedCount argument, will + * ordinarily always be writable in that amount), as an array whose + * elements from start to finish are the number of bytes to write each + * time write() or writeByteArray() is subsequently called. The sum of + * the values in this array, if this array is not empty, is always equal + * to this._writable. + */ + _writableAmounts: [], - /** - * Data regarding a pending stream-ready callback on this, or null if no - * callback is currently waiting to be called. - */ - _waiter: null, + /** + * Data regarding a pending stream-ready callback on this, or null if no + * callback is currently waiting to be called. + */ + _waiter: null, - /** - * The event currently dispatched to make a stream-ready callback, if any - * such callback is currently ready to be made and not already in - * progress, or null when no callback is waiting to happen. - */ - _event: null, + /** + * The event currently dispatched to make a stream-ready callback, if any + * such callback is currently ready to be made and not already in + * progress, or null when no callback is waiting to happen. + */ + _event: null, - /** - * A stream-ready constructor to wrap an existing callback to intercept - * stream-ready notifications, or null if notifications shouldn't be - * wrapped at all. - */ - _streamReadyInterceptCreator: null, + /** + * A stream-ready constructor to wrap an existing callback to intercept + * stream-ready notifications, or null if notifications shouldn't be + * wrapped at all. + */ + _streamReadyInterceptCreator: null, - /** - * Registers a stream-ready wrapper creator function so that a - * stream-ready callback made in the future can be wrapped. - */ - interceptStreamReadyCallbacks(streamReadyInterceptCreator) { - dumpn("*** [" + this.name + "].interceptStreamReadyCallbacks"); + /** + * Registers a stream-ready wrapper creator function so that a + * stream-ready callback made in the future can be wrapped. + */ + interceptStreamReadyCallbacks(streamReadyInterceptCreator) { + dumpn("*** [" + this.name + "].interceptStreamReadyCallbacks"); - Assert.ok(this._streamReadyInterceptCreator !== null, - "intercepting onOutputStreamReady twice"); - this._streamReadyInterceptCreator = streamReadyInterceptCreator; - if (this._waiter) { - this._waiter.callback = - new streamReadyInterceptCreator(this._waiter.callback); - } - }, + Assert.ok( + this._streamReadyInterceptCreator !== null, + "intercepting onOutputStreamReady twice" + ); + this._streamReadyInterceptCreator = streamReadyInterceptCreator; + if (this._waiter) { + this._waiter.callback = new streamReadyInterceptCreator( + this._waiter.callback + ); + } + }, - /** - * Removes a previously-registered stream-ready wrapper creator function, - * also clearing any current wrapping. - */ - removeStreamReadyInterceptor() { - dumpn("*** [" + this.name + "].removeStreamReadyInterceptor()"); + /** + * Removes a previously-registered stream-ready wrapper creator function, + * also clearing any current wrapping. + */ + removeStreamReadyInterceptor() { + dumpn("*** [" + this.name + "].removeStreamReadyInterceptor()"); - Assert.ok(this._streamReadyInterceptCreator !== null, - "removing interceptor when none present?"); - this._streamReadyInterceptCreator = null; - if (this._waiter) - this._waiter.callback = this._waiter.callback.wrappedCallback; - }, + Assert.ok( + this._streamReadyInterceptCreator !== null, + "removing interceptor when none present?" + ); + this._streamReadyInterceptCreator = null; + if (this._waiter) { + this._waiter.callback = this._waiter.callback.wrappedCallback; + } + }, - // - // see nsIAsyncOutputStream.asyncWait - // - asyncWait: function asyncWait(callback, flags, requestedCount, target) { - dumpn("*** [" + this.name + "].asyncWait"); + // + // see nsIAsyncOutputStream.asyncWait + // + asyncWait: function asyncWait(callback, flags, requestedCount, target) { + dumpn("*** [" + this.name + "].asyncWait"); - Assert.ok(callback && typeof callback !== "function"); + Assert.ok(callback && typeof callback !== "function"); - var closureOnly = - (flags & Ci.nsIAsyncInputStream.WAIT_CLOSURE_ONLY) !== 0; + var closureOnly = + (flags & Ci.nsIAsyncInputStream.WAIT_CLOSURE_ONLY) !== 0; - Assert.ok(this._waiter === null || - (this._waiter.closureOnly && !closureOnly), - "asyncWait already called with a non-closure-only " + - "callback? unexpected!"); + Assert.ok( + this._waiter === null || (this._waiter.closureOnly && !closureOnly), + "asyncWait already called with a non-closure-only " + + "callback? unexpected!" + ); - this._waiter = - { - callback: - this._streamReadyInterceptCreator - ? new this._streamReadyInterceptCreator(callback) - : callback, - closureOnly, - requestedCount, - eventTarget: target, - toString: function toString() { - return "waiter(" + (closureOnly ? "closure only, " : "") + - "requestedCount: " + requestedCount + ", target: " + - target + ")"; - }, - }; + this._waiter = { + callback: this._streamReadyInterceptCreator + ? new this._streamReadyInterceptCreator(callback) + : callback, + closureOnly, + requestedCount, + eventTarget: target, + toString: function toString() { + return ( + "waiter(" + + (closureOnly ? "closure only, " : "") + + "requestedCount: " + + requestedCount + + ", target: " + + target + + ")" + ); + }, + }; - if ((!closureOnly && this._writable >= requestedCount) || - !Components.isSuccessCode(this.status)) { - this._notify(); - } - }, + if ( + (!closureOnly && this._writable >= requestedCount) || + !Components.isSuccessCode(this.status) + ) { + this._notify(); + } + }, - // - // see nsIAsyncOutputStream.closeWithStatus - // - closeWithStatus: function closeWithStatus(status) { - dumpn("*** [" + this.name + "].closeWithStatus(" + status + ")"); + // + // see nsIAsyncOutputStream.closeWithStatus + // + closeWithStatus: function closeWithStatus(status) { + dumpn("*** [" + this.name + "].closeWithStatus(" + status + ")"); - if (!Components.isSuccessCode(self._status)) { - dumpn("*** ignoring redundant closure of [input " + this.name + "] " + - "because it's already closed (status " + self._status + ")"); - return; - } + if (!Components.isSuccessCode(self._status)) { + dumpn( + "*** ignoring redundant closure of [input " + + this.name + + "] " + + "because it's already closed (status " + + self._status + + ")" + ); + return; + } - if (Components.isSuccessCode(status)) - status = Cr.NS_BASE_STREAM_CLOSED; + if (Components.isSuccessCode(status)) { + status = Cr.NS_BASE_STREAM_CLOSED; + } - self._status = status; + self._status = status; - if (input._waiter) - input._notify(); - if (this._waiter) - this._notify(); - }, + if (input._waiter) { + input._notify(); + } + if (this._waiter) { + this._notify(); + } + }, - // - // see nsIBinaryOutputStream.writeByteArray - // - writeByteArray: function writeByteArray(bytes, length) { - dumpn("*** [" + this.name + "].writeByteArray" + - "([" + bytes + "], " + length + ")"); + // + // see nsIBinaryOutputStream.writeByteArray + // + writeByteArray: function writeByteArray(bytes, length) { + dumpn( + "*** [" + + this.name + + "].writeByteArray" + + "([" + + bytes + + "], " + + length + + ")" + ); - Assert.equal(bytes.length, length, "sanity"); - if (!Components.isSuccessCode(self._status)) - throw self._status; + Assert.equal(bytes.length, length, "sanity"); + if (!Components.isSuccessCode(self._status)) { + throw self._status; + } - Assert.equal(this._writableAmounts.length, 0, - "writeByteArray can't support specified-length writes"); + Assert.equal( + this._writableAmounts.length, + 0, + "writeByteArray can't support specified-length writes" + ); - if (this._writable < length) - throw Cr.NS_BASE_STREAM_WOULD_BLOCK; + if (this._writable < length) { + throw Cr.NS_BASE_STREAM_WOULD_BLOCK; + } - self._data.push.apply(self._data, bytes); - this._writable -= length; + self._data.push.apply(self._data, bytes); + this._writable -= length; - if (input._readable === Infinity && input._waiter && - !input._waiter.closureOnly) { - input._notify(); - } - }, + if ( + input._readable === Infinity && + input._waiter && + !input._waiter.closureOnly + ) { + input._notify(); + } + }, - // - // see nsIOutputStream.write - // - write: function write(str, length) { - dumpn("*** [" + this.name + "].write"); + // + // see nsIOutputStream.write + // + write: function write(str, length) { + dumpn("*** [" + this.name + "].write"); - Assert.equal(str.length, length, "sanity"); - if (!Components.isSuccessCode(self._status)) - throw self._status; - if (this._writable === 0) - throw Cr.NS_BASE_STREAM_WOULD_BLOCK; + Assert.equal(str.length, length, "sanity"); + if (!Components.isSuccessCode(self._status)) { + throw self._status; + } + if (this._writable === 0) { + throw Cr.NS_BASE_STREAM_WOULD_BLOCK; + } - var actualWritten; - if (this._writableAmounts.length === 0) { - actualWritten = Math.min(this._writable, length); - } else { - Assert.ok(this._writable >= this._writableAmounts[0], - "writable amounts value greater than writable data?"); - Assert.equal(this._writable, sum(this._writableAmounts), - "total writable amount not equal to sum of writable " + - "increments"); - actualWritten = this._writableAmounts.shift(); - } + var actualWritten; + if (this._writableAmounts.length === 0) { + actualWritten = Math.min(this._writable, length); + } else { + Assert.ok( + this._writable >= this._writableAmounts[0], + "writable amounts value greater than writable data?" + ); + Assert.equal( + this._writable, + sum(this._writableAmounts), + "total writable amount not equal to sum of writable " + "increments" + ); + actualWritten = this._writableAmounts.shift(); + } - var bytes = str.substring(0, actualWritten) - .split("") - .map(function(v) { return v.charCodeAt(0); }); + var bytes = str + .substring(0, actualWritten) + .split("") + .map(function(v) { + return v.charCodeAt(0); + }); - self._data.push.apply(self._data, bytes); - this._writable -= actualWritten; + self._data.push.apply(self._data, bytes); + this._writable -= actualWritten; - if (input._readable === Infinity && input._waiter && - !input._waiter.closureOnly) { - input._notify(); - } + if ( + input._readable === Infinity && + input._waiter && + !input._waiter.closureOnly + ) { + input._notify(); + } - return actualWritten; - }, + return actualWritten; + }, - /** - * Increase the amount of data that can be written without blocking by the - * given number of bytes, triggering future notifications when required. - * - * @param count : uint - * the number of bytes of additional data to make writable - */ - makeWritable: function makeWritable(count) { - dumpn("*** [" + this.name + "].makeWritable(" + count + ")"); + /** + * Increase the amount of data that can be written without blocking by the + * given number of bytes, triggering future notifications when required. + * + * @param count : uint + * the number of bytes of additional data to make writable + */ + makeWritable: function makeWritable(count) { + dumpn("*** [" + this.name + "].makeWritable(" + count + ")"); - Assert.ok(Components.isSuccessCode(self._status)); + Assert.ok(Components.isSuccessCode(self._status)); - this._writable += count; + this._writable += count; - var waiter = this._waiter; - if (waiter && !waiter.closureOnly && - waiter.requestedCount <= this._writable) { - this._notify(); - } - }, + var waiter = this._waiter; + if ( + waiter && + !waiter.closureOnly && + waiter.requestedCount <= this._writable + ) { + this._notify(); + } + }, - /** - * Increase the amount of data that can be written without blocking, but - * do so by specifying a number of bytes that will be written each time - * a write occurs, even as asyncWait notifications are initially triggered - * as usual. Thus, rather than writes eagerly writing everything possible - * at each step, attempts to write out data by segment devolve into a - * partial segment write, then another, and so on until the amount of data - * specified as permitted to be written, has been written. - * - * Note that the writeByteArray method is incompatible with the previous - * calling of this method, in that, until all increments provided to this - * method have been consumed, writeByteArray cannot be called. Once all - * increments have been consumed, writeByteArray may again be called. - * - * @param increments : [uint] - * an array whose elements are positive numbers of bytes to permit to be - * written each time write() is subsequently called on this, ignoring - * the total amount of writable space specified by the sum of all - * increments - */ - makeWritableByIncrements: function makeWritableByIncrements(increments) { - dumpn("*** [" + this.name + "].makeWritableByIncrements" + - "([" + increments.join(", ") + "])"); + /** + * Increase the amount of data that can be written without blocking, but + * do so by specifying a number of bytes that will be written each time + * a write occurs, even as asyncWait notifications are initially triggered + * as usual. Thus, rather than writes eagerly writing everything possible + * at each step, attempts to write out data by segment devolve into a + * partial segment write, then another, and so on until the amount of data + * specified as permitted to be written, has been written. + * + * Note that the writeByteArray method is incompatible with the previous + * calling of this method, in that, until all increments provided to this + * method have been consumed, writeByteArray cannot be called. Once all + * increments have been consumed, writeByteArray may again be called. + * + * @param increments : [uint] + * an array whose elements are positive numbers of bytes to permit to be + * written each time write() is subsequently called on this, ignoring + * the total amount of writable space specified by the sum of all + * increments + */ + makeWritableByIncrements: function makeWritableByIncrements(increments) { + dumpn( + "*** [" + + this.name + + "].makeWritableByIncrements" + + "([" + + increments.join(", ") + + "])" + ); - Assert.ok(increments.length > 0, "bad increments"); - Assert.ok(increments.every(function(v) { return v > 0; }), - "zero increment?"); + Assert.ok(increments.length > 0, "bad increments"); + Assert.ok( + increments.every(function(v) { + return v > 0; + }), + "zero increment?" + ); - Assert.ok(Components.isSuccessCode(self._status)); + Assert.ok(Components.isSuccessCode(self._status)); - this._writable += sum(increments); - this._writableAmounts = increments; + this._writable += sum(increments); + this._writableAmounts = increments; - var waiter = this._waiter; - if (waiter && !waiter.closureOnly && - waiter.requestedCount <= this._writable) { - this._notify(); - } - }, + var waiter = this._waiter; + if ( + waiter && + !waiter.closureOnly && + waiter.requestedCount <= this._writable + ) { + this._notify(); + } + }, - /** - * Dispatches an event to call a previously-registered stream-ready - * callback. - */ - _notify: function _notify() { - dumpn("*** [" + this.name + "]._notify()"); + /** + * Dispatches an event to call a previously-registered stream-ready + * callback. + */ + _notify: function _notify() { + dumpn("*** [" + this.name + "]._notify()"); - var waiter = this._waiter; - Assert.ok(waiter !== null, "no waiter?"); + var waiter = this._waiter; + Assert.ok(waiter !== null, "no waiter?"); - if (this._event === null) { - var event = this._event = - { - run: function run() { - output._waiter = null; - output._event = null; + if (this._event === null) { + var event = (this._event = { + run: function run() { + output._waiter = null; + output._event = null; - try { - waiter.callback.onOutputStreamReady(output); - } catch (e) { - do_throw("error calling onOutputStreamReady: " + e); - } - }, - }; - waiter.eventTarget.dispatch(event, Ci.nsIThread.DISPATCH_NORMAL); - } - }, + try { + waiter.callback.onOutputStreamReady(output); + } catch (e) { + do_throw("error calling onOutputStreamReady: " + e); + } + }, + }); + waiter.eventTarget.dispatch(event, Ci.nsIThread.DISPATCH_NORMAL); + } + }, - QueryInterface: ChromeUtils.generateQI(["nsIAsyncOutputStream", "nsIOutputStream"]), - }; + QueryInterface: ChromeUtils.generateQI([ + "nsIAsyncOutputStream", + "nsIOutputStream", + ]), + }); } /** @@ -1042,14 +1143,12 @@ function CopyTest(name, next) { this._tasks = []; /** The copier used by this test. */ - this._copier = - new WriteThroughCopier(this._source, this._sink, this, null); + this._copier = new WriteThroughCopier(this._source, this._sink, this, null); // Start watching for data written by the copier to the sink. this._waitForWrittenData(); } -CopyTest.prototype = -{ +CopyTest.prototype = { /** * Adds the given array of bytes to data in the copier's source. * @@ -1098,23 +1197,30 @@ CopyTest.prototype = * @param dataQuantums : [[uint]] * array of byte arrays to expect to be written in sequence to the sink */ - makeSinkWritableAndWaitFor: - function makeSinkWritableAndWaitFor(bytes, dataQuantums) { + makeSinkWritableAndWaitFor: function makeSinkWritableAndWaitFor( + bytes, + dataQuantums + ) { var self = this; - Assert.equal(bytes, - dataQuantums.reduce(function(partial, current) { - return partial + current.length; - }, 0), - "bytes/quantums mismatch"); + Assert.equal( + bytes, + dataQuantums.reduce(function(partial, current) { + return partial + current.length; + }, 0), + "bytes/quantums mismatch" + ); function increaseSinkSpaceTask() { /* Now do the actual work to trigger the interceptor. */ self._sink.makeWritable(bytes); } - this._waitForHelper("increaseSinkSpaceTask", - dataQuantums, increaseSinkSpaceTask); + this._waitForHelper( + "increaseSinkSpaceTask", + dataQuantums, + increaseSinkSpaceTask + ); }, /** @@ -1128,11 +1234,15 @@ CopyTest.prototype = * @param dataQuantums : [[uint]] * array of byte arrays to expect to be written in sequence to the sink */ - makeSinkWritableByIncrementsAndWaitFor: - function makeSinkWritableByIncrementsAndWaitFor(bytes, dataQuantums) { + makeSinkWritableByIncrementsAndWaitFor: function makeSinkWritableByIncrementsAndWaitFor( + bytes, + dataQuantums + ) { var self = this; - var desiredAmounts = dataQuantums.map(function(v) { return v.length; }); + var desiredAmounts = dataQuantums.map(function(v) { + return v.length; + }); Assert.equal(bytes, sum(desiredAmounts), "bytes/quantums mismatch"); function increaseSinkSpaceByIncrementsTask() { @@ -1140,8 +1250,11 @@ CopyTest.prototype = self._sink.makeWritableByIncrements(desiredAmounts); } - this._waitForHelper("increaseSinkSpaceByIncrementsTask", - dataQuantums, increaseSinkSpaceByIncrementsTask); + this._waitForHelper( + "increaseSinkSpaceByIncrementsTask", + dataQuantums, + increaseSinkSpaceByIncrementsTask + ); }, /** @@ -1174,20 +1287,33 @@ CopyTest.prototype = * @param dataQuantums : [[uint]] * array of byte arrays to expect to be written in sequence to the sink */ - closeSourceAndWaitFor: - function closeSourceAndWaitFor(status, bytes, dataQuantums) { + closeSourceAndWaitFor: function closeSourceAndWaitFor( + status, + bytes, + dataQuantums + ) { var self = this; - Assert.equal(bytes, sum(dataQuantums.map(function(v) { return v.length; })), - "bytes/quantums mismatch"); + Assert.equal( + bytes, + sum( + dataQuantums.map(function(v) { + return v.length; + }) + ), + "bytes/quantums mismatch" + ); function closeSourceAndWaitForTask() { self._sink.makeWritable(bytes); self._copyableDataStream.closeWithStatus(status); } - this._waitForHelper("closeSourceAndWaitForTask", - dataQuantums, closeSourceAndWaitForTask); + this._waitForHelper( + "closeSourceAndWaitForTask", + dataQuantums, + closeSourceAndWaitForTask + ); }, /** @@ -1262,8 +1388,9 @@ CopyTest.prototype = expect: function expect(expectedStatus, receivedData) { this._expectedStatus = expectedStatus; this._expectedData = []; - for (var i = 0, sz = receivedData.length; i < sz; i++) + for (var i = 0, sz = receivedData.length; i < sz; i++) { this._expectedData.push.apply(this._expectedData, receivedData[i]); + } this._stageNextTask(); }, @@ -1295,40 +1422,54 @@ CopyTest.prototype = * Intercept all data-available notifications so we can continue when all * the ones we expect have been received. */ - var streamReadyCallback = - { - onInputStreamReady: function wrapperOnInputStreamReady(input) { - dumpn("*** streamReadyCallback.onInputStreamReady" + - "(" + input.name + ")"); + var streamReadyCallback = { + onInputStreamReady: function wrapperOnInputStreamReady(input) { + dumpn( + "*** streamReadyCallback.onInputStreamReady" + + "(" + + input.name + + ")" + ); - Assert.equal(this, streamReadyCallback, "sanity"); + Assert.equal(this, streamReadyCallback, "sanity"); - try { - if (quantumIndex < dataQuantums.length) { - var quantum = dataQuantums[quantumIndex++]; - var sz = quantum.length; - Assert.equal(self._lastQuantum.length, sz, - "different quantum lengths"); - for (var i = 0; i < sz; i++) { - Assert.equal(self._lastQuantum[i], quantum[i], - "bad data at " + i); - } - - dumpn("*** waiting to check remaining " + - (dataQuantums.length - quantumIndex) + " quantums..."); - } - } finally { - if (quantumIndex === dataQuantums.length) { - dumpn("*** data checks completed! next task..."); - self._copiedDataStream.removeStreamReadyInterceptor(); - self._stageNextTask(); + try { + if (quantumIndex < dataQuantums.length) { + var quantum = dataQuantums[quantumIndex++]; + var sz = quantum.length; + Assert.equal( + self._lastQuantum.length, + sz, + "different quantum lengths" + ); + for (var i = 0; i < sz; i++) { + Assert.equal( + self._lastQuantum[i], + quantum[i], + "bad data at " + i + ); } + + dumpn( + "*** waiting to check remaining " + + (dataQuantums.length - quantumIndex) + + " quantums..." + ); } - }, - }; + } finally { + if (quantumIndex === dataQuantums.length) { + dumpn("*** data checks completed! next task..."); + self._copiedDataStream.removeStreamReadyInterceptor(); + self._stageNextTask(); + } + } + }, + }; - var interceptor = - createStreamReadyInterceptor(streamReadyCallback, "onInputStreamReady"); + var interceptor = createStreamReadyInterceptor( + streamReadyCallback, + "onInputStreamReady" + ); self._copiedDataStream.interceptStreamReadyCallbacks(interceptor); /* Do the deed. */ @@ -1349,61 +1490,72 @@ CopyTest.prototype = dumpn("*** _waitForWrittenData (" + this.name + ")"); var self = this; - var outputWrittenWatcher = - { - onInputStreamReady: function onInputStreamReady(input) { - dumpn("*** outputWrittenWatcher.onInputStreamReady" + - "(" + input.name + ")"); + var outputWrittenWatcher = { + onInputStreamReady: function onInputStreamReady(input) { + dumpn( + "*** outputWrittenWatcher.onInputStreamReady" + "(" + input.name + ")" + ); - if (self._allDataWritten) { - do_throw("ruh-roh! why are we getting notified of more data " + - "after we should have received all of it?"); + if (self._allDataWritten) { + do_throw( + "ruh-roh! why are we getting notified of more data " + + "after we should have received all of it?" + ); + } + + self._waitingForData = false; + + try { + var avail = input.available(); + } catch (e) { + dumpn("*** available() threw! error: " + e); + if (self._completed) { + dumpn( + "*** NB: this isn't a problem, because we've copied " + + "completely now, and this notify may have been expedited " + + "by maybeNotifyFinally such that we're being called when " + + "we can *guarantee* nothing is available any more" + ); + } + avail = 0; + } + + if (avail > 0) { + var data = input.readByteArray(avail); + Assert.equal( + data.length, + avail, + "readByteArray returned wrong number of bytes?" + ); + self._lastQuantum = data; + self._receivedData.push.apply(self._receivedData, data); + } + + if (avail === 0) { + dumpn("*** all data received!"); + + self._allDataWritten = true; + + if (self._copyingFinished) { + dumpn("*** copying already finished, continuing to next test"); + self._testComplete(); + } else { + dumpn("*** copying not finished, waiting for that to happen"); } - self._waitingForData = false; + return; + } - try { - var avail = input.available(); - } catch (e) { - dumpn("*** available() threw! error: " + e); - if (self._completed) { - dumpn("*** NB: this isn't a problem, because we've copied " + - "completely now, and this notify may have been expedited " + - "by maybeNotifyFinally such that we're being called when " + - "we can *guarantee* nothing is available any more"); - } - avail = 0; - } + self._waitForWrittenData(); + }, + }; - if (avail > 0) { - var data = input.readByteArray(avail); - Assert.equal(data.length, avail, - "readByteArray returned wrong number of bytes?"); - self._lastQuantum = data; - self._receivedData.push.apply(self._receivedData, data); - } - - if (avail === 0) { - dumpn("*** all data received!"); - - self._allDataWritten = true; - - if (self._copyingFinished) { - dumpn("*** copying already finished, continuing to next test"); - self._testComplete(); - } else { - dumpn("*** copying not finished, waiting for that to happen"); - } - - return; - } - - self._waitForWrittenData(); - }, - }; - - this._copiedDataStream.asyncWait(outputWrittenWatcher, 0, 1, - gThreadManager.currentThread); + this._copiedDataStream.asyncWait( + outputWrittenWatcher, + 0, + 1, + gThreadManager.currentThread + ); this._waitingForData = true; }, @@ -1413,27 +1565,37 @@ CopyTest.prototype = * this test was first created. */ _testComplete: function _testComplete() { - dumpn("*** CopyTest(" + this.name + ") complete! " + - "On to the next test..."); + dumpn( + "*** CopyTest(" + this.name + ") complete! " + "On to the next test..." + ); try { Assert.ok(this._allDataWritten, "expect all data written now!"); Assert.ok(this._copyingFinished, "expect copying finished now!"); - Assert.equal(this._actualStatus, this._expectedStatus, - "wrong final status"); + Assert.equal( + this._actualStatus, + this._expectedStatus, + "wrong final status" + ); - var expected = this._expectedData, received = this._receivedData; + var expected = this._expectedData, + received = this._receivedData; dumpn("received: [" + received + "], expected: [" + expected + "]"); Assert.equal(received.length, expected.length, "wrong data"); - for (var i = 0, sz = expected.length; i < sz; i++) + for (var i = 0, sz = expected.length; i < sz; i++) { Assert.equal(received[i], expected[i], "bad data at " + i); + } } catch (e) { dumpn("!!! ERROR PERFORMING FINAL " + this.name + " CHECKS! " + e); throw e; } finally { - dumpn("*** CopyTest(" + this.name + ") complete! " + - "Invoking test-completion callback..."); + dumpn( + "*** CopyTest(" + + this.name + + ") complete! " + + "Invoking test-completion callback..." + ); this._done(); } }, @@ -1448,16 +1610,15 @@ CopyTest.prototype = } var task = this._tasks[this._currentTask++]; - var event = - { - run: function run() { - try { - task(); - } catch (e) { - do_throw("exception thrown running task: " + e); - } - }, - }; + var event = { + run: function run() { + try { + task(); + } catch (e) { + do_throw("exception thrown running task: " + e); + } + }, + }; gThreadManager.dispatchToMainThread(event); }, @@ -1508,8 +1669,9 @@ CopyTest.prototype = */ dumpn("*** not all data copied, waiting for that to happen..."); - if (!this._waitingForData) + if (!this._waitingForData) { this._waitForWrittenData(); + } this._copiedDataStream.maybeNotifyFinally(); } diff --git a/netwerk/test/httpserver/test/test_basic_functionality.js b/netwerk/test/httpserver/test/test_basic_functionality.js index bb212b4fbd26..c2a7243d2d28 100644 --- a/netwerk/test/httpserver/test/test_basic_functionality.js +++ b/netwerk/test/httpserver/test/test_basic_functionality.js @@ -14,14 +14,30 @@ XPCOMUtils.defineLazyGetter(this, "port", function() { XPCOMUtils.defineLazyGetter(this, "tests", function() { return [ - new Test("http://localhost:" + port + "/objHandler", - null, start_objHandler, null), - new Test("http://localhost:" + port + "/functionHandler", - null, start_functionHandler, null), - new Test("http://localhost:" + port + "/nonexistent-path", - null, start_non_existent_path, null), - new Test("http://localhost:" + port + "/lotsOfHeaders", - null, start_lots_of_headers, null), + new Test( + "http://localhost:" + port + "/objHandler", + null, + start_objHandler, + null + ), + new Test( + "http://localhost:" + port + "/functionHandler", + null, + start_functionHandler, + null + ), + new Test( + "http://localhost:" + port + "/nonexistent-path", + null, + start_non_existent_path, + null + ), + new Test( + "http://localhost:" + port + "/lotsOfHeaders", + null, + start_lots_of_headers, + null + ), ]; }); @@ -66,11 +82,13 @@ function start_objHandler(ch) { Assert.equal(ch.getResponseHeader("content-type"), "text/plain"); Assert.equal(ch.responseStatusText, "OK"); - var reqMin = {}, reqMaj = {}, respMin = {}, respMaj = {}; + var reqMin = {}, + reqMaj = {}, + respMin = {}, + respMaj = {}; ch.getRequestVersion(reqMaj, reqMin); ch.getResponseVersion(respMaj, respMin); - Assert.ok(reqMaj.value == respMaj.value && - reqMin.value == respMin.value); + Assert.ok(reqMaj.value == respMaj.value && reqMin.value == respMin.value); } function start_functionHandler(ch) { @@ -81,7 +99,10 @@ function start_functionHandler(ch) { Assert.equal(ch.getResponseHeader("foopy"), "quux-baz"); Assert.equal(ch.responseStatusText, "Page Not Found"); - var reqMin = {}, reqMaj = {}, respMin = {}, respMaj = {}; + var reqMin = {}, + reqMaj = {}, + respMin = {}, + respMaj = {}; ch.getRequestVersion(reqMaj, reqMin); ch.getResponseVersion(respMaj, respMin); Assert.ok(reqMaj.value == 1 && reqMin.value == 1); @@ -101,41 +122,41 @@ function start_lots_of_headers(ch) { Assert.equal(ch.responseStatus, 200); Assert.ok(ch.requestSucceeded); - for (var i = 0; i < HEADER_COUNT; i++) + for (var i = 0; i < HEADER_COUNT; i++) { Assert.equal(ch.getResponseHeader("X-Header-" + i), "value " + i); + } } // PATH HANDLERS // /objHandler -var objHandler = - { - handle(metadata, response) { - response.setStatusLine(metadata.httpVersion, 200, "OK"); - response.setHeader("Content-Type", "text/plain", false); +var objHandler = { + handle(metadata, response) { + response.setStatusLine(metadata.httpVersion, 200, "OK"); + response.setHeader("Content-Type", "text/plain", false); - var body = "Request (slightly reformatted):\n\n"; - body += metadata.method + " " + metadata.path; + var body = "Request (slightly reformatted):\n\n"; + body += metadata.method + " " + metadata.path; - Assert.equal(metadata.port, port); + Assert.equal(metadata.port, port); - if (metadata.queryString) - body += "?" + metadata.queryString; + if (metadata.queryString) { + body += "?" + metadata.queryString; + } - body += " HTTP/" + metadata.httpVersion + "\n"; + body += " HTTP/" + metadata.httpVersion + "\n"; - var headEnum = metadata.headers; - while (headEnum.hasMoreElements()) { - var fieldName = headEnum.getNext() - .QueryInterface(Ci.nsISupportsString) - .data; - body += fieldName + ": " + metadata.getHeader(fieldName) + "\n"; - } + var headEnum = metadata.headers; + while (headEnum.hasMoreElements()) { + var fieldName = headEnum.getNext().QueryInterface(Ci.nsISupportsString) + .data; + body += fieldName + ": " + metadata.getHeader(fieldName) + "\n"; + } - response.bodyOutputStream.write(body, body.length); - }, - QueryInterface: ChromeUtils.generateQI(["nsIHttpRequestHandler"]), - }; + response.bodyOutputStream.write(body, body.length); + }, + QueryInterface: ChromeUtils.generateQI(["nsIHttpRequestHandler"]), +}; // /functionHandler function functionHandler(metadata, response) { @@ -154,6 +175,7 @@ function functionHandler(metadata, response) { function lotsOfHeadersHandler(request, response) { response.setHeader("Content-Type", "text/plain", false); - for (var i = 0; i < HEADER_COUNT; i++) + for (var i = 0; i < HEADER_COUNT; i++) { response.setHeader("X-Header-" + i, "value " + i, false); + } } diff --git a/netwerk/test/httpserver/test/test_body_length.js b/netwerk/test/httpserver/test/test_body_length.js index 70f4c40580ae..2adbbeb27296 100644 --- a/netwerk/test/httpserver/test/test_body_length.js +++ b/netwerk/test/httpserver/test/test_body_length.js @@ -30,8 +30,9 @@ function contentLength(request, response) { var avail; var data = ""; - while ((avail = body.available()) > 0) + while ((avail = body.available()) > 0) { data += body.read(avail); + } Assert.equal(data, REQUEST_DATA); } @@ -42,18 +43,24 @@ function contentLength(request, response) { XPCOMUtils.defineLazyGetter(this, "tests", function() { return [ - new Test("http://localhost:" + srv.identity.primaryPort + "/content-length", - init_content_length), + new Test( + "http://localhost:" + srv.identity.primaryPort + "/content-length", + init_content_length + ), ]; }); function init_content_length(ch) { - var content = Cc["@mozilla.org/io/string-input-stream;1"] - .createInstance(Ci.nsIStringInputStream); + var content = Cc["@mozilla.org/io/string-input-stream;1"].createInstance( + Ci.nsIStringInputStream + ); content.data = REQUEST_DATA; - ch.QueryInterface(Ci.nsIUploadChannel) - .setUploadStream(content, "text/plain", REQUEST_DATA.length); + ch.QueryInterface(Ci.nsIUploadChannel).setUploadStream( + content, + "text/plain", + REQUEST_DATA.length + ); // Override the values implicitly set by setUploadStream above. ch.requestMethod = "POST"; diff --git a/netwerk/test/httpserver/test/test_byte_range.js b/netwerk/test/httpserver/test/test_byte_range.js index 0f264a8d6310..7505140edddd 100644 --- a/netwerk/test/httpserver/test/test_byte_range.js +++ b/netwerk/test/httpserver/test/test_byte_range.js @@ -14,35 +14,66 @@ XPCOMUtils.defineLazyGetter(this, "PREFIX", function() { XPCOMUtils.defineLazyGetter(this, "tests", function() { return [ - new Test(PREFIX + "/range.txt", - init_byterange, start_byterange, stop_byterange), - new Test(PREFIX + "/range.txt", - init_byterange2, start_byterange2), - new Test(PREFIX + "/range.txt", - init_byterange3, start_byterange3, stop_byterange3), - new Test(PREFIX + "/range.txt", - init_byterange4, start_byterange4), - new Test(PREFIX + "/range.txt", - init_byterange5, start_byterange5, stop_byterange5), - new Test(PREFIX + "/range.txt", - init_byterange6, start_byterange6, stop_byterange6), - new Test(PREFIX + "/range.txt", - init_byterange7, start_byterange7, stop_byterange7), - new Test(PREFIX + "/range.txt", - init_byterange8, start_byterange8, stop_byterange8), - new Test(PREFIX + "/range.txt", - init_byterange9, start_byterange9, stop_byterange9), - new Test(PREFIX + "/range.txt", - init_byterange10, start_byterange10), - new Test(PREFIX + "/range.txt", - init_byterange11, start_byterange11, stop_byterange11), - new Test(PREFIX + "/empty.txt", - null, start_byterange12, stop_byterange12), - new Test(PREFIX + "/headers.txt", - init_byterange13, start_byterange13, null), - new Test(PREFIX + "/range.txt", - null, start_normal, stop_normal), - ]; + new Test( + PREFIX + "/range.txt", + init_byterange, + start_byterange, + stop_byterange + ), + new Test(PREFIX + "/range.txt", init_byterange2, start_byterange2), + new Test( + PREFIX + "/range.txt", + init_byterange3, + start_byterange3, + stop_byterange3 + ), + new Test(PREFIX + "/range.txt", init_byterange4, start_byterange4), + new Test( + PREFIX + "/range.txt", + init_byterange5, + start_byterange5, + stop_byterange5 + ), + new Test( + PREFIX + "/range.txt", + init_byterange6, + start_byterange6, + stop_byterange6 + ), + new Test( + PREFIX + "/range.txt", + init_byterange7, + start_byterange7, + stop_byterange7 + ), + new Test( + PREFIX + "/range.txt", + init_byterange8, + start_byterange8, + stop_byterange8 + ), + new Test( + PREFIX + "/range.txt", + init_byterange9, + start_byterange9, + stop_byterange9 + ), + new Test(PREFIX + "/range.txt", init_byterange10, start_byterange10), + new Test( + PREFIX + "/range.txt", + init_byterange11, + start_byterange11, + stop_byterange11 + ), + new Test(PREFIX + "/empty.txt", null, start_byterange12, stop_byterange12), + new Test( + PREFIX + "/headers.txt", + init_byterange13, + start_byterange13, + null + ), + new Test(PREFIX + "/range.txt", null, start_normal, stop_normal), + ]; }); function run_test() { diff --git a/netwerk/test/httpserver/test/test_cern_meta.js b/netwerk/test/httpserver/test/test_cern_meta.js index b88414ac4ec8..3ff617289f18 100644 --- a/netwerk/test/httpserver/test/test_cern_meta.js +++ b/netwerk/test/httpserver/test/test_cern_meta.js @@ -13,16 +13,26 @@ XPCOMUtils.defineLazyGetter(this, "PREFIX", function() { XPCOMUtils.defineLazyGetter(this, "tests", function() { return [ - new Test(PREFIX + "/test_both.html", - null, start_testBoth, null), - new Test(PREFIX + "/test_ctype_override.txt", - null, start_test_ctype_override_txt, null), - new Test(PREFIX + "/test_status_override.html", - null, start_test_status_override_html, null), - new Test(PREFIX + "/test_status_override_nodesc.txt", - null, start_test_status_override_nodesc_txt, null), - new Test(PREFIX + "/caret_test.txt^", - null, start_caret_test_txt_, null), + new Test(PREFIX + "/test_both.html", null, start_testBoth, null), + new Test( + PREFIX + "/test_ctype_override.txt", + null, + start_test_ctype_override_txt, + null + ), + new Test( + PREFIX + "/test_status_override.html", + null, + start_test_status_override_html, + null + ), + new Test( + PREFIX + "/test_status_override_nodesc.txt", + null, + start_test_status_override_nodesc_txt, + null + ), + new Test(PREFIX + "/caret_test.txt^", null, start_caret_test_txt_, null), ]; }); @@ -37,7 +47,6 @@ function run_test() { runHttpTests(tests, testComplete(srv)); } - // TEST DATA function start_testBoth(ch) { diff --git a/netwerk/test/httpserver/test/test_default_index_handler.js b/netwerk/test/httpserver/test/test_default_index_handler.js index 8ca99ed0a77a..4f9bc8e2e1ae 100644 --- a/netwerk/test/httpserver/test/test_default_index_handler.js +++ b/netwerk/test/httpserver/test/test_default_index_handler.js @@ -28,7 +28,9 @@ function run_test() { function done() { do_test_pending(); destroyTestDirectory(); - srv.stop(function() { do_test_finished(); }); + srv.stop(function() { + do_test_finished(); + }); } runHttpTests(tests, done); @@ -77,7 +79,6 @@ function destroyTestDirectory() { dir.remove(true); } - /** *********** * UTILITIES * *************/ @@ -115,8 +116,10 @@ function hiddenDataCheck(bytes, uri, path) { var top = Services.io.newURI(uri); // N.B. No ERROR_IF_SEE_THIS.txt^ file! - var dirEntries = [{name: "file.txt", isDirectory: false}, - {name: "SHOULD_SEE_THIS.txt^", isDirectory: false}]; + var dirEntries = [ + { name: "file.txt", isDirectory: false }, + { name: "SHOULD_SEE_THIS.txt^", isDirectory: false }, + ]; for (var i = 0; i < items.length; i++) { var link = items[i].childNodes[0]; @@ -202,8 +205,10 @@ function makeFile(name, isDirectory, parentDir, lst) { try { file.append(name); file.create(type, 0o755); - lst.push({name, isDirectory}); - } catch (e) { /* OS probably doesn't like file name, skip */ } + lst.push({ name, isDirectory }); + } catch (e) { + /* OS probably doesn't like file name, skip */ + } } /** ******* @@ -214,7 +219,12 @@ XPCOMUtils.defineLazyGetter(this, "tests", function() { return [ new Test(BASE_URL, null, start, stopRootDirectory), new Test(BASE_URL + "foo/", null, start, stopFooDirectory), - new Test(BASE_URL + "bar/folder^/", null, start, stopTrailingCaretDirectory), + new Test( + BASE_URL + "bar/folder^/", + null, + start, + stopTrailingCaretDirectory + ), ]; }); diff --git a/netwerk/test/httpserver/test/test_empty_body.js b/netwerk/test/httpserver/test/test_empty_body.js index bf5ae0a0d7a5..97bed9aec33b 100644 --- a/netwerk/test/httpserver/test/test_empty_body.js +++ b/netwerk/test/httpserver/test/test_empty_body.js @@ -11,10 +11,18 @@ var srv; XPCOMUtils.defineLazyGetter(this, "tests", function() { return [ - new Test("http://localhost:" + srv.identity.primaryPort + "/empty-body-unwritten", - null, ensureEmpty, null), - new Test("http://localhost:" + srv.identity.primaryPort + "/empty-body-written", - null, ensureEmpty, null), + new Test( + "http://localhost:" + srv.identity.primaryPort + "/empty-body-unwritten", + null, + ensureEmpty, + null + ), + new Test( + "http://localhost:" + srv.identity.primaryPort + "/empty-body-written", + null, + ensureEmpty, + null + ), ]; }); diff --git a/netwerk/test/httpserver/test/test_errorhandler_exception.js b/netwerk/test/httpserver/test/test_errorhandler_exception.js index b461ff451194..ad366d7dae2e 100644 --- a/netwerk/test/httpserver/test/test_errorhandler_exception.js +++ b/netwerk/test/httpserver/test/test_errorhandler_exception.js @@ -9,14 +9,28 @@ XPCOMUtils.defineLazyGetter(this, "tests", function() { return [ - new Test("http://localhost:" + srv.identity.primaryPort + "/throws/exception", - null, start_throws_exception, succeeded), - new Test("http://localhost:" + srv.identity.primaryPort + - "/this/file/does/not/exist/and/404s", - null, start_nonexistent_404_fails_so_400, succeeded), - new Test("http://localhost:" + srv.identity.primaryPort + - "/attempts/404/fails/so/400/fails/so/500s", - register400Handler, start_multiple_exceptions_500, succeeded), + new Test( + "http://localhost:" + srv.identity.primaryPort + "/throws/exception", + null, + start_throws_exception, + succeeded + ), + new Test( + "http://localhost:" + + srv.identity.primaryPort + + "/this/file/does/not/exist/and/404s", + null, + start_nonexistent_404_fails_so_400, + succeeded + ), + new Test( + "http://localhost:" + + srv.identity.primaryPort + + "/attempts/404/fails/so/400/fails/so/500s", + register400Handler, + start_multiple_exceptions_500, + succeeded + ), ]; }); @@ -33,14 +47,20 @@ function run_test() { runHttpTests(tests, testComplete(srv)); } - // TEST DATA -function checkStatusLine(channel, httpMaxVer, httpMinVer, httpCode, statusText) { +function checkStatusLine( + channel, + httpMaxVer, + httpMinVer, + httpCode, + statusText +) { Assert.equal(channel.responseStatus, httpCode); Assert.equal(channel.responseStatusText, statusText); - var respMaj = {}, respMin = {}; + var respMaj = {}, + respMin = {}; channel.getResponseVersion(respMaj, respMin); Assert.equal(respMaj.value, httpMaxVer); Assert.equal(respMin.value, httpMinVer); @@ -66,7 +86,6 @@ function register400Handler(ch) { srv.registerErrorHandler(400, throwsException); } - // PATH HANDLERS // /throws/exception (and also a 404 and 400 error handler) diff --git a/netwerk/test/httpserver/test/test_header_array.js b/netwerk/test/httpserver/test/test_header_array.js index 7617a675ec81..7377be857b42 100644 --- a/netwerk/test/httpserver/test/test_header_array.js +++ b/netwerk/test/httpserver/test/test_header_array.js @@ -18,7 +18,6 @@ function run_test() { runHttpTests(tests, testComplete(srv)); } - /** ********** * HANDLERS * ************/ @@ -47,8 +46,11 @@ function pathHandler(request, response) { XPCOMUtils.defineLazyGetter(this, "tests", function() { return [ - new Test("http://localhost:" + srv.identity.primaryPort + "/path-handler", - null, check), + new Test( + "http://localhost:" + srv.identity.primaryPort + "/path-handler", + null, + check + ), ]; }); diff --git a/netwerk/test/httpserver/test/test_headers.js b/netwerk/test/httpserver/test/test_headers.js index e9f350754147..f3c2544d36d7 100644 --- a/netwerk/test/httpserver/test/test_headers.js +++ b/netwerk/test/httpserver/test/test_headers.js @@ -8,7 +8,6 @@ // structure and is not to be used directly outside of httpd.js itself except // for testing purposes - /** * Ensures that a fieldname-fieldvalue combination is a valid header. * @@ -40,14 +39,16 @@ function assertValidHeader(fieldName, fieldValue, headers) { function assertInvalidHeader(fieldName, fieldValue, headers) { try { headers.setHeader(fieldName, fieldValue, false); - throw new Error(`Setting (${fieldName}, ${fieldValue}) as header succeeded!`); + throw new Error( + `Setting (${fieldName}, ${fieldValue}) as header succeeded!` + ); } catch (e) { - if (e.result !== Cr.NS_ERROR_INVALID_ARG) + if (e.result !== Cr.NS_ERROR_INVALID_ARG) { do_throw("Unexpected exception thrown: " + e); + } } } - function run_test() { testHeaderValidity(); testGetHeader(); @@ -65,7 +66,7 @@ function testHeaderValidity() { assertInvalidHeader("@xml", "bar", headers); assertInvalidHeader("fiz(", "bar", headers); assertInvalidHeader("HTTP/1.1", "bar", headers); - assertInvalidHeader("b\"b", "bar", headers); + assertInvalidHeader('b"b', "bar", headers); assertInvalidHeader("ascsd\t", "bar", headers); assertInvalidHeader("{fds", "bar", headers); assertInvalidHeader("baz?", "bar", headers); @@ -106,31 +107,33 @@ function testGetHeader() { headers.getHeader(":"); throw new Error("Failed to throw for invalid header"); } catch (e) { - if (e.result !== Cr.NS_ERROR_INVALID_ARG) + if (e.result !== Cr.NS_ERROR_INVALID_ARG) { do_throw("headers.getHeader(':') must throw invalid arg"); + } } try { headers.getHeader("valid"); throw new Error("header doesn't exist"); } catch (e) { - if (e.result !== Cr.NS_ERROR_NOT_AVAILABLE) + if (e.result !== Cr.NS_ERROR_NOT_AVAILABLE) { do_throw("shouldn't be a header named 'valid' in headers!"); + } } } function testHeaderEnumerator() { var headers = new nsHttpHeaders(); - var heads = - { - "foo": "17", - "baz": "two six niner", - "decaf": "class Program { int .7; int main(){ .7 = 5; return 7 - .7; } }", - }; + var heads = { + foo: "17", + baz: "two six niner", + decaf: "class Program { int .7; int main(){ .7 = 5; return 7 - .7; } }", + }; - for (var i in heads) + for (var i in heads) { headers.setHeader(i, heads[i], false); + } var en = headers.enumerator; while (en.hasMoreElements()) { @@ -159,7 +162,8 @@ function testHasHeader() { headers.hasHeader(":"); throw new Error("failed to throw"); } catch (e) { - if (e.result !== Cr.NS_ERROR_INVALID_ARG) + if (e.result !== Cr.NS_ERROR_INVALID_ARG) { do_throw(".hasHeader for an invalid name should throw"); + } } } diff --git a/netwerk/test/httpserver/test/test_host.js b/netwerk/test/httpserver/test/test_host.js index 930d127a6057..47480a6ee69d 100644 --- a/netwerk/test/httpserver/test/test_host.js +++ b/netwerk/test/httpserver/test/test_host.js @@ -24,8 +24,10 @@ add_task(async function run_test1() { srv.registerPathHandler("/http/1.0-request", http10Request); srv.registerPathHandler("/http/1.1-good-host", http11goodHost); - srv.registerPathHandler("/http/1.1-good-host-wacky-port", - http11goodHostWackyPort); + srv.registerPathHandler( + "/http/1.1-good-host-wacky-port", + http11goodHostWackyPort + ); srv.registerPathHandler("/http/1.1-ip-host", http11ipHost); srv.start(FAKE_PORT_ONE); @@ -180,13 +182,14 @@ add_task(async function run_test_3() { // Okay, finally done with identity testing. Our primary location is the one // we want it to be, so we're off! - await new Promise(resolve => runRawTests(tests, resolve, (idx) => dump(`running test no ${idx}`))); + await new Promise(resolve => + runRawTests(tests, resolve, idx => dump(`running test no ${idx}`)) + ); // Finally shut down the server. await new Promise(resolve => srv.stop(resolve)); }); - /** ******************* * UTILITY FUNCTIONS * *********************/ @@ -235,7 +238,6 @@ function check400(aData) { Assert.equal(firstLine.substring(0, HTTP_400_LEADER_LENGTH), HTTP_400_LEADER); } - /** ************* * BEGIN TESTS * ***************/ @@ -252,8 +254,7 @@ function http10Request(request, response) { writeDetails(request, response); response.setStatusLine("1.0", 200, "TEST PASSED"); } -data = "GET /http/1.0-request HTTP/1.0\r\n" + - "\r\n"; +data = "GET /http/1.0-request HTTP/1.0\r\n" + "\r\n"; function check10(aData) { let iter = LineIterator(aData); @@ -263,94 +264,84 @@ function check10(aData) { skipHeaders(iter); // Okay, next line must be the data we expected to be written - let body = - [ - "Method: GET", - "Path: /http/1.0-request", - "Query: ", - "Version: 1.0", - "Scheme: http", - "Host: localhost", - "Port: 4444", - ]; + let body = [ + "Method: GET", + "Path: /http/1.0-request", + "Query: ", + "Version: 1.0", + "Scheme: http", + "Host: localhost", + "Port: 4444", + ]; expectLines(iter, body); } test = new RawTest("localhost", PORT, data, check10); tests.push(test); - // HTTP/1.1 request, no Host header, expect a 400 response -data = "GET /http/1.1-request HTTP/1.1\r\n" + - "\r\n"; +data = "GET /http/1.1-request HTTP/1.1\r\n" + "\r\n"; test = new RawTest("localhost", PORT, data, check400); tests.push(test); - // HTTP/1.1 request, wrong host, expect a 400 response -data = "GET /http/1.1-request HTTP/1.1\r\n" + - "Host: not-localhost\r\n" + - "\r\n"; +data = + "GET /http/1.1-request HTTP/1.1\r\n" + "Host: not-localhost\r\n" + "\r\n"; test = new RawTest("localhost", PORT, data, check400); tests.push(test); - // HTTP/1.1 request, wrong host/right port, expect a 400 response -data = "GET /http/1.1-request HTTP/1.1\r\n" + - "Host: not-localhost:4444\r\n" + - "\r\n"; +data = + "GET /http/1.1-request HTTP/1.1\r\n" + + "Host: not-localhost:4444\r\n" + + "\r\n"; test = new RawTest("localhost", PORT, data, check400); tests.push(test); - // HTTP/1.1 request, Host header has host but no port, expect a 400 response -data = "GET /http/1.1-request HTTP/1.1\r\n" + - "Host: 127.0.0.1\r\n" + - "\r\n"; +data = "GET /http/1.1-request HTTP/1.1\r\n" + "Host: 127.0.0.1\r\n" + "\r\n"; test = new RawTest("localhost", PORT, data, check400); tests.push(test); - // HTTP/1.1 request, Request-URI has wrong port, expect a 400 response -data = "GET http://127.0.0.1/http/1.1-request HTTP/1.1\r\n" + - "Host: 127.0.0.1\r\n" + - "\r\n"; +data = + "GET http://127.0.0.1/http/1.1-request HTTP/1.1\r\n" + + "Host: 127.0.0.1\r\n" + + "\r\n"; test = new RawTest("localhost", PORT, data, check400); tests.push(test); - // HTTP/1.1 request, Request-URI has wrong port, expect a 400 response -data = "GET http://localhost:31337/http/1.1-request HTTP/1.1\r\n" + - "Host: localhost:31337\r\n" + - "\r\n"; +data = + "GET http://localhost:31337/http/1.1-request HTTP/1.1\r\n" + + "Host: localhost:31337\r\n" + + "\r\n"; test = new RawTest("localhost", PORT, data, check400); tests.push(test); - // HTTP/1.1 request, Request-URI has wrong scheme, expect a 400 response -data = "GET https://localhost:4444/http/1.1-request HTTP/1.1\r\n" + - "Host: localhost:4444\r\n" + - "\r\n"; +data = + "GET https://localhost:4444/http/1.1-request HTTP/1.1\r\n" + + "Host: localhost:4444\r\n" + + "\r\n"; test = new RawTest("localhost", PORT, data, check400); tests.push(test); - // HTTP/1.1 request, correct Host header, expect handler's response function http11goodHost(request, response) { writeDetails(request, response); response.setStatusLine("1.1", 200, "TEST PASSED"); } -data = "GET /http/1.1-good-host HTTP/1.1\r\n" + - "Host: localhost:4444\r\n" + - "\r\n"; +data = + "GET /http/1.1-good-host HTTP/1.1\r\n" + "Host: localhost:4444\r\n" + "\r\n"; function check11goodHost(aData) { let iter = LineIterator(aData); @@ -360,32 +351,29 @@ function check11goodHost(aData) { skipHeaders(iter); // Okay, next line must be the data we expected to be written - let body = - [ - "Method: GET", - "Path: /http/1.1-good-host", - "Query: ", - "Version: 1.1", - "Scheme: http", - "Host: localhost", - "Port: 4444", - ]; + let body = [ + "Method: GET", + "Path: /http/1.1-good-host", + "Query: ", + "Version: 1.1", + "Scheme: http", + "Host: localhost", + "Port: 4444", + ]; expectLines(iter, body); } test = new RawTest("localhost", PORT, data, check11goodHost); tests.push(test); - // HTTP/1.1 request, Host header is secondary identity function http11ipHost(request, response) { writeDetails(request, response); response.setStatusLine("1.1", 200, "TEST PASSED"); } -data = "GET /http/1.1-ip-host HTTP/1.1\r\n" + - "Host: 127.0.0.1:4444\r\n" + - "\r\n"; +data = + "GET /http/1.1-ip-host HTTP/1.1\r\n" + "Host: 127.0.0.1:4444\r\n" + "\r\n"; function check11ipHost(aData) { let iter = LineIterator(aData); @@ -395,63 +383,62 @@ function check11ipHost(aData) { skipHeaders(iter); // Okay, next line must be the data we expected to be written - let body = - [ - "Method: GET", - "Path: /http/1.1-ip-host", - "Query: ", - "Version: 1.1", - "Scheme: http", - "Host: 127.0.0.1", - "Port: 4444", - ]; + let body = [ + "Method: GET", + "Path: /http/1.1-ip-host", + "Query: ", + "Version: 1.1", + "Scheme: http", + "Host: 127.0.0.1", + "Port: 4444", + ]; expectLines(iter, body); } test = new RawTest("localhost", PORT, data, check11ipHost); tests.push(test); - // HTTP/1.1 request, absolute path, accurate Host header // reusing previous request handler so not defining a new one -data = "GET http://localhost:4444/http/1.1-good-host HTTP/1.1\r\n" + - "Host: localhost:4444\r\n" + - "\r\n"; +data = + "GET http://localhost:4444/http/1.1-good-host HTTP/1.1\r\n" + + "Host: localhost:4444\r\n" + + "\r\n"; test = new RawTest("localhost", PORT, data, check11goodHost); tests.push(test); - // HTTP/1.1 request, absolute path, inaccurate Host header // reusing previous request handler so not defining a new one -data = "GET http://localhost:4444/http/1.1-good-host HTTP/1.1\r\n" + - "Host: localhost:1234\r\n" + - "\r\n"; +data = + "GET http://localhost:4444/http/1.1-good-host HTTP/1.1\r\n" + + "Host: localhost:1234\r\n" + + "\r\n"; test = new RawTest("localhost", PORT, data, check11goodHost); tests.push(test); - // HTTP/1.1 request, absolute path, different inaccurate Host header // reusing previous request handler so not defining a new one -data = "GET http://localhost:4444/http/1.1-good-host HTTP/1.1\r\n" + - "Host: not-localhost:4444\r\n" + - "\r\n"; +data = + "GET http://localhost:4444/http/1.1-good-host HTTP/1.1\r\n" + + "Host: not-localhost:4444\r\n" + + "\r\n"; test = new RawTest("localhost", PORT, data, check11goodHost); tests.push(test); - // HTTP/1.1 request, absolute path, yet another inaccurate Host header // reusing previous request handler so not defining a new one -data = "GET http://localhost:4444/http/1.1-good-host HTTP/1.1\r\n" + - "Host: yippity-skippity\r\n" + - "\r\n"; +data = + "GET http://localhost:4444/http/1.1-good-host HTTP/1.1\r\n" + + "Host: yippity-skippity\r\n" + + "\r\n"; function checkInaccurate(aData) { check11goodHost(aData); @@ -461,14 +448,14 @@ function checkInaccurate(aData) { test = new RawTest("localhost", PORT, data, checkInaccurate); tests.push(test); - // HTTP/1.0 request, absolute path, different inaccurate Host header // reusing previous request handler so not defining a new one -data = "GET /http/1.0-request HTTP/1.0\r\n" + - "Host: not-localhost:4444\r\n" + - "\r\n"; +data = + "GET /http/1.0-request HTTP/1.0\r\n" + + "Host: not-localhost:4444\r\n" + + "\r\n"; function check10ip(aData) { let iter = LineIterator(aData); @@ -478,32 +465,31 @@ function check10ip(aData) { skipHeaders(iter); // Okay, next line must be the data we expected to be written - let body = - [ - "Method: GET", - "Path: /http/1.0-request", - "Query: ", - "Version: 1.0", - "Scheme: http", - "Host: 127.0.0.1", - "Port: 4444", - ]; + let body = [ + "Method: GET", + "Path: /http/1.0-request", + "Query: ", + "Version: 1.0", + "Scheme: http", + "Host: 127.0.0.1", + "Port: 4444", + ]; expectLines(iter, body); } test = new RawTest("localhost", PORT, data, check10ip); tests.push(test); - // HTTP/1.1 request, Host header with implied port function http11goodHostWackyPort(request, response) { writeDetails(request, response); response.setStatusLine("1.1", 200, "TEST PASSED"); } -data = "GET /http/1.1-good-host-wacky-port HTTP/1.1\r\n" + - "Host: localhost\r\n" + - "\r\n"; +data = + "GET /http/1.1-good-host-wacky-port HTTP/1.1\r\n" + + "Host: localhost\r\n" + + "\r\n"; function check11goodHostWackyPort(aData) { let iter = LineIterator(aData); @@ -513,108 +499,104 @@ function check11goodHostWackyPort(aData) { skipHeaders(iter); // Okay, next line must be the data we expected to be written - let body = - [ - "Method: GET", - "Path: /http/1.1-good-host-wacky-port", - "Query: ", - "Version: 1.1", - "Scheme: http", - "Host: localhost", - "Port: 80", - ]; + let body = [ + "Method: GET", + "Path: /http/1.1-good-host-wacky-port", + "Query: ", + "Version: 1.1", + "Scheme: http", + "Host: localhost", + "Port: 80", + ]; expectLines(iter, body); } test = new RawTest("localhost", PORT, data, check11goodHostWackyPort); tests.push(test); - // HTTP/1.1 request, Host header with wacky implied port -data = "GET /http/1.1-good-host-wacky-port HTTP/1.1\r\n" + - "Host: localhost:\r\n" + - "\r\n"; +data = + "GET /http/1.1-good-host-wacky-port HTTP/1.1\r\n" + + "Host: localhost:\r\n" + + "\r\n"; test = new RawTest("localhost", PORT, data, check11goodHostWackyPort); tests.push(test); - // HTTP/1.1 request, absolute URI with implied port -data = "GET http://localhost/http/1.1-good-host-wacky-port HTTP/1.1\r\n" + - "Host: localhost\r\n" + - "\r\n"; +data = + "GET http://localhost/http/1.1-good-host-wacky-port HTTP/1.1\r\n" + + "Host: localhost\r\n" + + "\r\n"; test = new RawTest("localhost", PORT, data, check11goodHostWackyPort); tests.push(test); - // HTTP/1.1 request, absolute URI with wacky implied port -data = "GET http://localhost:/http/1.1-good-host-wacky-port HTTP/1.1\r\n" + - "Host: localhost\r\n" + - "\r\n"; +data = + "GET http://localhost:/http/1.1-good-host-wacky-port HTTP/1.1\r\n" + + "Host: localhost\r\n" + + "\r\n"; test = new RawTest("localhost", PORT, data, check11goodHostWackyPort); tests.push(test); - // HTTP/1.1 request, absolute URI with explicit implied port, ignored Host -data = "GET http://localhost:80/http/1.1-good-host-wacky-port HTTP/1.1\r\n" + - "Host: who-cares\r\n" + - "\r\n"; +data = + "GET http://localhost:80/http/1.1-good-host-wacky-port HTTP/1.1\r\n" + + "Host: who-cares\r\n" + + "\r\n"; test = new RawTest("localhost", PORT, data, check11goodHostWackyPort); tests.push(test); - // HTTP/1.1 request, a malformed Request-URI -data = "GET is-this-the-real-life-is-this-just-fantasy HTTP/1.1\r\n" + - "Host: localhost:4444\r\n" + - "\r\n"; +data = + "GET is-this-the-real-life-is-this-just-fantasy HTTP/1.1\r\n" + + "Host: localhost:4444\r\n" + + "\r\n"; test = new RawTest("localhost", PORT, data, check400); tests.push(test); - // HTTP/1.1 request, a malformed Host header -data = "GET /http/1.1-request HTTP/1.1\r\n" + - "Host: la la la\r\n" + - "\r\n"; +data = "GET /http/1.1-request HTTP/1.1\r\n" + "Host: la la la\r\n" + "\r\n"; test = new RawTest("localhost", PORT, data, check400); tests.push(test); - // HTTP/1.1 request, a malformed Host header but absolute URI, 5.2 sez fine -data = "GET http://localhost:4444/http/1.1-good-host HTTP/1.1\r\n" + - "Host: la la la\r\n" + - "\r\n"; +data = + "GET http://localhost:4444/http/1.1-good-host HTTP/1.1\r\n" + + "Host: la la la\r\n" + + "\r\n"; test = new RawTest("localhost", PORT, data, check11goodHost); tests.push(test); - // HTTP/1.0 request, absolute URI, but those aren't valid in HTTP/1.0 -data = "GET http://localhost:4444/http/1.1-request HTTP/1.0\r\n" + - "Host: localhost:4444\r\n" + - "\r\n"; +data = + "GET http://localhost:4444/http/1.1-request HTTP/1.0\r\n" + + "Host: localhost:4444\r\n" + + "\r\n"; test = new RawTest("localhost", PORT, data, check400); tests.push(test); - // HTTP/1.1 request, absolute URI with unrecognized host -data = "GET http://not-localhost:4444/http/1.1-request HTTP/1.1\r\n" + - "Host: not-localhost:4444\r\n" + - "\r\n"; +data = + "GET http://not-localhost:4444/http/1.1-request HTTP/1.1\r\n" + + "Host: not-localhost:4444\r\n" + + "\r\n"; test = new RawTest("localhost", PORT, data, check400); tests.push(test); - // HTTP/1.1 request, absolute URI with unrecognized host (but not in Host) -data = "GET http://not-localhost:4444/http/1.1-request HTTP/1.1\r\n" + - "Host: localhost:4444\r\n" + - "\r\n"; +data = + "GET http://not-localhost:4444/http/1.1-request HTTP/1.1\r\n" + + "Host: localhost:4444\r\n" + + "\r\n"; test = new RawTest("localhost", PORT, data, check400); tests.push(test); diff --git a/netwerk/test/httpserver/test/test_linedata.js b/netwerk/test/httpserver/test/test_linedata.js index 6543a2feccea..cdffb9995617 100644 --- a/netwerk/test/httpserver/test/test_linedata.js +++ b/netwerk/test/httpserver/test/test_linedata.js @@ -1,5 +1,5 @@ /* -*- indent-tabs-mode: nil; js-indent-level: 2 -*- -*/ + */ /* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ diff --git a/netwerk/test/httpserver/test/test_load_module.js b/netwerk/test/httpserver/test/test_load_module.js index f3c97f1085da..53718055e165 100644 --- a/netwerk/test/httpserver/test/test_load_module.js +++ b/netwerk/test/httpserver/test/test_load_module.js @@ -5,7 +5,9 @@ * Ensure httpd.js can be imported as a module and that a server starts. */ function run_test() { - const {HttpServer} = ChromeUtils.import("resource://testing-common/httpd.js"); + const { HttpServer } = ChromeUtils.import( + "resource://testing-common/httpd.js" + ); let server = new HttpServer(); server.start(-1); diff --git a/netwerk/test/httpserver/test/test_name_scheme.js b/netwerk/test/httpserver/test/test_name_scheme.js index fd354116804a..5014b1fa2a48 100644 --- a/netwerk/test/httpserver/test/test_name_scheme.js +++ b/netwerk/test/httpserver/test/test_name_scheme.js @@ -16,36 +16,43 @@ XPCOMUtils.defineLazyGetter(this, "PREFIX", function() { XPCOMUtils.defineLazyGetter(this, "tests", function() { return [ - new Test(PREFIX + "/bar.html^", - null, start_bar_html_, null), - new Test(PREFIX + "/foo.html^", - null, start_foo_html_, null), - new Test(PREFIX + "/normal-file.txt", - null, start_normal_file_txt, null), - new Test(PREFIX + "/folder^/file.txt", - null, start_folder__file_txt, null), + new Test(PREFIX + "/bar.html^", null, start_bar_html_, null), + new Test(PREFIX + "/foo.html^", null, start_foo_html_, null), + new Test(PREFIX + "/normal-file.txt", null, start_normal_file_txt, null), + new Test(PREFIX + "/folder^/file.txt", null, start_folder__file_txt, null), - new Test(PREFIX + "/foo/bar.html^", - null, start_bar_html_, null), - new Test(PREFIX + "/foo/foo.html^", - null, start_foo_html_, null), - new Test(PREFIX + "/foo/normal-file.txt", - null, start_normal_file_txt, null), - new Test(PREFIX + "/foo/folder^/file.txt", - null, start_folder__file_txt, null), + new Test(PREFIX + "/foo/bar.html^", null, start_bar_html_, null), + new Test(PREFIX + "/foo/foo.html^", null, start_foo_html_, null), + new Test( + PREFIX + "/foo/normal-file.txt", + null, + start_normal_file_txt, + null + ), + new Test( + PREFIX + "/foo/folder^/file.txt", + null, + start_folder__file_txt, + null + ), - new Test(PREFIX + "/end-caret^/bar.html^", - null, start_bar_html_, null), - new Test(PREFIX + "/end-caret^/foo.html^", - null, start_foo_html_, null), - new Test(PREFIX + "/end-caret^/normal-file.txt", - null, start_normal_file_txt, null), - new Test(PREFIX + "/end-caret^/folder^/file.txt", - null, start_folder__file_txt, null), - ]; + new Test(PREFIX + "/end-caret^/bar.html^", null, start_bar_html_, null), + new Test(PREFIX + "/end-caret^/foo.html^", null, start_foo_html_, null), + new Test( + PREFIX + "/end-caret^/normal-file.txt", + null, + start_normal_file_txt, + null + ), + new Test( + PREFIX + "/end-caret^/folder^/file.txt", + null, + start_folder__file_txt, + null + ), + ]; }); - function run_test() { srv = createServer(); @@ -61,7 +68,6 @@ function run_test() { runHttpTests(tests, testComplete(srv)); } - // TEST DATA function start_bar_html_(ch) { diff --git a/netwerk/test/httpserver/test/test_processasync.js b/netwerk/test/httpserver/test/test_processasync.js index 2aeeaaa0363f..3effd1ec1570 100644 --- a/netwerk/test/httpserver/test/test_processasync.js +++ b/netwerk/test/httpserver/test/test_processasync.js @@ -4,7 +4,6 @@ * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - /* * Tests for correct behavior of asynchronous responses. */ @@ -17,14 +16,14 @@ var srv; function run_test() { srv = createServer(); - for (var path in handlers) + for (var path in handlers) { srv.registerPathHandler(path, handlers[path]); + } srv.start(-1); runHttpTests(tests, testComplete(srv)); } - /** ************* * BEGIN TESTS * ***************/ @@ -32,12 +31,24 @@ function run_test() { XPCOMUtils.defineLazyGetter(this, "tests", function() { return [ new Test(PREPATH + "/handleSync", null, start_handleSync, null), - new Test(PREPATH + "/handleAsync1", null, start_handleAsync1, - stop_handleAsync1), - new Test(PREPATH + "/handleAsync2", init_handleAsync2, start_handleAsync2, - stop_handleAsync2), - new Test(PREPATH + "/handleAsyncOrdering", null, null, - stop_handleAsyncOrdering), + new Test( + PREPATH + "/handleAsync1", + null, + start_handleAsync1, + stop_handleAsync1 + ), + new Test( + PREPATH + "/handleAsync2", + init_handleAsync2, + start_handleAsync2, + stop_handleAsync2 + ), + new Test( + PREPATH + "/handleAsyncOrdering", + null, + null, + stop_handleAsyncOrdering + ), ]; }); @@ -171,14 +182,19 @@ handlers["/handleAsync2"] = handleAsync2; var startTime_handleAsync2; function init_handleAsync2(ch) { - var now = startTime_handleAsync2 = Date.now(); + var now = (startTime_handleAsync2 = Date.now()); dumpn("*** init_HandleAsync2: start time " + now); } function start_handleAsync2(ch) { var now = Date.now(); - dumpn("*** start_handleAsync2: onStartRequest time " + now + ", " + - (now - startTime_handleAsync2) + "ms after start time"); + dumpn( + "*** start_handleAsync2: onStartRequest time " + + now + + ", " + + (now - startTime_handleAsync2) + + "ms after start time" + ); Assert.ok(now >= startTime_handleAsync2 + startToHeaderDelay); Assert.equal(ch.responseStatus, 200); @@ -188,8 +204,13 @@ function start_handleAsync2(ch) { function stop_handleAsync2(ch, status, data) { var now = Date.now(); - dumpn("*** stop_handleAsync2: onStopRequest time " + now + ", " + - (now - startTime_handleAsync2) + "ms after header time"); + dumpn( + "*** stop_handleAsync2: onStopRequest time " + + now + + ", " + + (now - startTime_handleAsync2) + + "ms after header time" + ); Assert.ok(now >= startTime_handleAsync2 + startToFinishedDelay); Assert.equal(String.fromCharCode.apply(null, data), "BODY"); @@ -206,30 +227,30 @@ function handleAsyncOrdering(request, response) { var out = new BinaryOutputStream(response.bodyOutputStream); var data = []; - for (var i = 0; i < 65536; i++) + for (var i = 0; i < 65536; i++) { data[i] = 0; + } var count = 20; - var writeData = - { - run() { - if (count-- === 0) { - response.finish(); - return; - } + var writeData = { + run() { + if (count-- === 0) { + response.finish(); + return; + } + try { + out.writeByteArray(data, data.length); + step(); + } catch (e) { try { - out.writeByteArray(data, data.length); - step(); - } catch (e) { - try { - do_throw("error writing data: " + e); - } finally { - response.finish(); - } + do_throw("error writing data: " + e); + } finally { + response.finish(); } - }, - }; + } + }, + }; function step() { // Use gThreadManager here because it's expedient, *not* because it's // intended for public use! If you do this in client code, expect me to @@ -244,7 +265,8 @@ handlers["/handleAsyncOrdering"] = handleAsyncOrdering; function stop_handleAsyncOrdering(ch, status, data) { Assert.equal(data.length, 20 * 65536); data.forEach(function(v, index) { - if (v !== 0) + if (v !== 0) { do_throw("value " + v + " at index " + index + " should be zero"); + } }); } diff --git a/netwerk/test/httpserver/test/test_qi.js b/netwerk/test/httpserver/test/test_qi.js index c05916cb59fd..38ece5e4d110 100644 --- a/netwerk/test/httpserver/test/test_qi.js +++ b/netwerk/test/httpserver/test/test_qi.js @@ -13,10 +13,18 @@ XPCOMUtils.defineLazyGetter(this, "tests", function() { return [ - new Test("http://localhost:" + srv.identity.primaryPort + "/test", - null, start_test, null), - new Test("http://localhost:" + srv.identity.primaryPort + "/sjs/qi.sjs", - null, start_sjs_qi, null), + new Test( + "http://localhost:" + srv.identity.primaryPort + "/test", + null, + start_test, + null + ), + new Test( + "http://localhost:" + srv.identity.primaryPort + "/sjs/qi.sjs", + null, + start_sjs_qi, + null + ), ]; }); @@ -41,7 +49,6 @@ function run_test() { runHttpTests(tests, testComplete(srv)); } - // TEST DATA function start_test(ch) { @@ -54,7 +61,6 @@ function start_sjs_qi(ch) { Assert.equal(ch.responseStatus, 200); } - function testHandler(request, response) { var exstr; var qid; @@ -67,8 +73,11 @@ function testHandler(request, response) { passed = qid === request; } catch (e) { exstr = ("" + e).split(/[\x09\x20-\x7f\x81-\xff]+/)[0]; - response.setStatusLine(request.httpVersion, 500, - "request doesn't QI: " + exstr); + response.setStatusLine( + request.httpVersion, + 500, + "request doesn't QI: " + exstr + ); return; } if (!passed) { @@ -82,8 +91,11 @@ function testHandler(request, response) { passed = qid === response; } catch (e) { exstr = ("" + e).split(/[\x09\x20-\x7f\x81-\xff]+/)[0]; - response.setStatusLine(request.httpVersion, 500, - "response doesn't QI: " + exstr); + response.setStatusLine( + request.httpVersion, + 500, + "response doesn't QI: " + exstr + ); return; } if (!passed) { diff --git a/netwerk/test/httpserver/test/test_registerdirectory.js b/netwerk/test/httpserver/test/test_registerdirectory.js index 0e53f4a974f2..a5e530af0927 100644 --- a/netwerk/test/httpserver/test/test_registerdirectory.js +++ b/netwerk/test/httpserver/test/test_registerdirectory.js @@ -10,7 +10,6 @@ XPCOMUtils.defineLazyGetter(this, "BASE", function() { return "http://localhost:" + srv.identity.primaryPort; }); - function nocache(ch) { ch.loadFlags |= Ci.nsIRequest.LOAD_BYPASS_CACHE; // important! } @@ -38,186 +37,222 @@ function checkFile(ch, status, data) { var actualFile = serverBasePath.clone(); actualFile.append("test_registerdirectory.js"); - Assert.equal(ch.getResponseHeader("Content-Length"), - actualFile.fileSize.toString()); - Assert.equal(data.map(v => String.fromCharCode(v)).join(""), - fileContents(actualFile)); + Assert.equal( + ch.getResponseHeader("Content-Length"), + actualFile.fileSize.toString() + ); + Assert.equal( + data.map(v => String.fromCharCode(v)).join(""), + fileContents(actualFile) + ); } XPCOMUtils.defineLazyGetter(this, "tests", function() { return [ + /** ********************* + * without a base path * + ***********************/ + new Test(BASE + "/test_registerdirectory.js", nocache, notFound, null), -/** ********************* - * without a base path * - ***********************/ - new Test(BASE + "/test_registerdirectory.js", - nocache, notFound, null), + /** ****************** + * with a base path * + ********************/ + new Test( + BASE + "/test_registerdirectory.js", + function(ch) { + nocache(ch); + serverBasePath = testsDirectory.clone(); + srv.registerDirectory("/", serverBasePath); + }, + null, + checkFile + ), -/** ****************** - * with a base path * - ********************/ - new Test(BASE + "/test_registerdirectory.js", - function(ch) { - nocache(ch); - serverBasePath = testsDirectory.clone(); - srv.registerDirectory("/", serverBasePath); - }, - null, - checkFile), + /** *************************** + * without a base path again * + *****************************/ + new Test( + BASE + "/test_registerdirectory.js", + function(ch) { + nocache(ch); + serverBasePath = null; + srv.registerDirectory("/", serverBasePath); + }, + notFound, + null + ), -/** *************************** - * without a base path again * - *****************************/ - new Test(BASE + "/test_registerdirectory.js", - function(ch) { - nocache(ch); - serverBasePath = null; - srv.registerDirectory("/", serverBasePath); - }, - notFound, - null), + /** ************************* + * registered path handler * + ***************************/ + new Test( + BASE + "/test_registerdirectory.js", + function(ch) { + nocache(ch); + srv.registerPathHandler( + "/test_registerdirectory.js", + override_test_registerdirectory + ); + }, + checkOverride, + null + ), -/** ************************* - * registered path handler * - ***************************/ - new Test(BASE + "/test_registerdirectory.js", - function(ch) { - nocache(ch); - srv.registerPathHandler("/test_registerdirectory.js", - override_test_registerdirectory); - }, - checkOverride, - null), + /** ********************** + * removed path handler * + ************************/ + new Test( + BASE + "/test_registerdirectory.js", + function init_registerDirectory6(ch) { + nocache(ch); + srv.registerPathHandler("/test_registerdirectory.js", null); + }, + notFound, + null + ), -/** ********************** - * removed path handler * - ************************/ - new Test(BASE + "/test_registerdirectory.js", - function init_registerDirectory6(ch) { - nocache(ch); - srv.registerPathHandler("/test_registerdirectory.js", null); - }, - notFound, - null), + /** ****************** + * with a base path * + ********************/ + new Test( + BASE + "/test_registerdirectory.js", + function(ch) { + nocache(ch); -/** ****************** - * with a base path * - ********************/ - new Test(BASE + "/test_registerdirectory.js", - function(ch) { - nocache(ch); + // set the base path again + serverBasePath = testsDirectory.clone(); + srv.registerDirectory("/", serverBasePath); + }, + null, + checkFile + ), - // set the base path again - serverBasePath = testsDirectory.clone(); - srv.registerDirectory("/", serverBasePath); - }, - null, - checkFile), + /** *********************** + * ...and a path handler * + *************************/ + new Test( + BASE + "/test_registerdirectory.js", + function(ch) { + nocache(ch); + srv.registerPathHandler( + "/test_registerdirectory.js", + override_test_registerdirectory + ); + }, + checkOverride, + null + ), -/** *********************** - * ...and a path handler * - *************************/ - new Test(BASE + "/test_registerdirectory.js", - function(ch) { - nocache(ch); - srv.registerPathHandler("/test_registerdirectory.js", - override_test_registerdirectory); - }, - checkOverride, - null), + /** ********************** + * removed base handler * + ************************/ + new Test( + BASE + "/test_registerdirectory.js", + function(ch) { + nocache(ch); + serverBasePath = null; + srv.registerDirectory("/", serverBasePath); + }, + checkOverride, + null + ), -/** ********************** - * removed base handler * - ************************/ - new Test(BASE + "/test_registerdirectory.js", - function(ch) { - nocache(ch); - serverBasePath = null; - srv.registerDirectory("/", serverBasePath); - }, - checkOverride, - null), + /** ********************** + * removed path handler * + ************************/ + new Test( + BASE + "/test_registerdirectory.js", + function(ch) { + nocache(ch); + srv.registerPathHandler("/test_registerdirectory.js", null); + }, + notFound, + null + ), -/** ********************** - * removed path handler * - ************************/ - new Test(BASE + "/test_registerdirectory.js", - function(ch) { - nocache(ch); - srv.registerPathHandler("/test_registerdirectory.js", null); - }, - notFound, - null), + /** *********************** + * mapping set up, works * + *************************/ + new Test( + BASE + "/foo/test_registerdirectory.js", + function(ch) { + nocache(ch); + serverBasePath = testsDirectory.clone(); + srv.registerDirectory("/foo/", serverBasePath); + }, + check200, + null + ), -/** *********************** - * mapping set up, works * - *************************/ - new Test(BASE + "/foo/test_registerdirectory.js", - function(ch) { - nocache(ch); - serverBasePath = testsDirectory.clone(); - srv.registerDirectory("/foo/", serverBasePath); - }, - check200, - null), + /** ******************* + * no mapping, fails * + *********************/ + new Test( + BASE + "/foo/test_registerdirectory.js/test_registerdirectory.js", + nocache, + notFound, + null + ), -/** ******************* - * no mapping, fails * - *********************/ - new Test(BASE + "/foo/test_registerdirectory.js/test_registerdirectory.js", - nocache, - notFound, - null), + /** **************** + * mapping, works * + ******************/ + new Test( + BASE + "/foo/test_registerdirectory.js/test_registerdirectory.js", + function(ch) { + nocache(ch); + srv.registerDirectory( + "/foo/test_registerdirectory.js/", + serverBasePath + ); + }, + null, + checkFile + ), -/** **************** - * mapping, works * - ******************/ - new Test(BASE + "/foo/test_registerdirectory.js/test_registerdirectory.js", - function(ch) { - nocache(ch); - srv.registerDirectory("/foo/test_registerdirectory.js/", - serverBasePath); - }, - null, - checkFile), + /** ********************************** + * two mappings set up, still works * + ************************************/ + new Test(BASE + "/foo/test_registerdirectory.js", nocache, null, checkFile), -/** ********************************** - * two mappings set up, still works * - ************************************/ - new Test(BASE + "/foo/test_registerdirectory.js", - nocache, null, checkFile), + /** ************************ + * remove topmost mapping * + **************************/ + new Test( + BASE + "/foo/test_registerdirectory.js", + function(ch) { + nocache(ch); + srv.registerDirectory("/foo/", null); + }, + notFound, + null + ), -/** ************************ - * remove topmost mapping * - **************************/ - new Test(BASE + "/foo/test_registerdirectory.js", - function(ch) { - nocache(ch); - srv.registerDirectory("/foo/", null); - }, - notFound, - null), + /** ************************************ + * lower mapping still present, works * + **************************************/ + new Test( + BASE + "/foo/test_registerdirectory.js/test_registerdirectory.js", + nocache, + null, + checkFile + ), -/** ************************************ - * lower mapping still present, works * - **************************************/ - new Test(BASE + "/foo/test_registerdirectory.js/test_registerdirectory.js", - nocache, null, checkFile), - -/** ***************** - * mapping removed * - *******************/ - new Test(BASE + "/foo/test_registerdirectory.js/test_registerdirectory.js", - function(ch) { - nocache(ch); - srv.registerDirectory("/foo/test_registerdirectory.js/", null); - }, - notFound, - null), + /** ***************** + * mapping removed * + *******************/ + new Test( + BASE + "/foo/test_registerdirectory.js/test_registerdirectory.js", + function(ch) { + nocache(ch); + srv.registerDirectory("/foo/test_registerdirectory.js/", null); + }, + notFound, + null + ), ]; }); - var srv; var serverBasePath; var testsDirectory; @@ -231,7 +266,6 @@ function run_test() { runHttpTests(tests, testComplete(srv)); } - // PATH HANDLERS // override of /test_registerdirectory.js diff --git a/netwerk/test/httpserver/test/test_registerprefix.js b/netwerk/test/httpserver/test/test_registerprefix.js index a67f0f5e7fab..bbe1f8cf46df 100644 --- a/netwerk/test/httpserver/test/test_registerprefix.js +++ b/netwerk/test/httpserver/test/test_registerprefix.js @@ -20,25 +20,41 @@ function notFound(ch) { } function makeCheckOverride(magic) { - return (function checkOverride(ch) { + return function checkOverride(ch) { Assert.equal(ch.responseStatus, 200); Assert.equal(ch.responseStatusText, "OK"); Assert.ok(ch.requestSucceeded); Assert.equal(ch.getResponseHeader("Override-Succeeded"), magic); - }); + }; } XPCOMUtils.defineLazyGetter(this, "tests", function() { return [ - new Test(BASE + "/prefix/dummy", prefixHandler, null, - makeCheckOverride("prefix")), - new Test(BASE + "/prefix/dummy", pathHandler, null, - makeCheckOverride("path")), - new Test(BASE + "/prefix/subpath/dummy", longerPrefixHandler, null, - makeCheckOverride("subpath")), + new Test( + BASE + "/prefix/dummy", + prefixHandler, + null, + makeCheckOverride("prefix") + ), + new Test( + BASE + "/prefix/dummy", + pathHandler, + null, + makeCheckOverride("path") + ), + new Test( + BASE + "/prefix/subpath/dummy", + longerPrefixHandler, + null, + makeCheckOverride("subpath") + ), new Test(BASE + "/prefix/dummy", removeHandlers, null, notFound), - new Test(BASE + "/prefix/subpath/dummy", newPrefixHandler, null, - makeCheckOverride("subpath")), + new Test( + BASE + "/prefix/subpath/dummy", + newPrefixHandler, + null, + makeCheckOverride("subpath") + ), ]; }); @@ -105,11 +121,11 @@ function run_test() { // generate an override function makeOverride(magic) { - return (function override(metadata, response) { + return function override(metadata, response) { response.setStatusLine("1.1", 200, "OK"); response.setHeader("Override-Succeeded", magic, false); var body = "success!"; response.bodyOutputStream.write(body, body.length); - }); + }; } diff --git a/netwerk/test/httpserver/test/test_request_line_split_in_two_packets.js b/netwerk/test/httpserver/test/test_request_line_split_in_two_packets.js index cfb153d997db..65bb4ceda9f8 100644 --- a/netwerk/test/httpserver/test/test_request_line_split_in_two_packets.js +++ b/netwerk/test/httpserver/test/test_request_line_split_in_two_packets.js @@ -15,15 +15,15 @@ srv.start(-1); const PORT = srv.identity.primaryPort; function run_test() { - srv.registerPathHandler("/lots-of-leading-blank-lines", - lotsOfLeadingBlankLines); - srv.registerPathHandler("/very-long-request-line", - veryLongRequestLine); + srv.registerPathHandler( + "/lots-of-leading-blank-lines", + lotsOfLeadingBlankLines + ); + srv.registerPathHandler("/very-long-request-line", veryLongRequestLine); runRawTests(tests, testComplete(srv)); } - /** ************* * BEGIN TESTS * ***************/ @@ -31,7 +31,6 @@ function run_test() { var test, gData, str; var tests = []; - function veryLongRequestLine(request, response) { writeDetails(request, response); response.setStatusLine(request.httpVersion, 200, "TEST PASSED"); @@ -46,14 +45,21 @@ reallyLong = reallyLong + reallyLong + reallyLong + reallyLong; // 8192 reallyLong = reallyLong + reallyLong + reallyLong + reallyLong; // 32768 reallyLong = reallyLong + reallyLong + reallyLong + reallyLong; // 131072 reallyLong = reallyLong + reallyLong + reallyLong + reallyLong; // 524288 -if (reallyLong.length !== 524288) +if (reallyLong.length !== 524288) { throw new TypeError("generated length not as long as expected"); -str = "GET /very-long-request-line?" + reallyLong + " HTTP/1.1\r\n" + - "Host: localhost:" + PORT + "\r\n" + - "\r\n"; +} +str = + "GET /very-long-request-line?" + + reallyLong + + " HTTP/1.1\r\n" + + "Host: localhost:" + + PORT + + "\r\n" + + "\r\n"; gData = []; -for (let i = 0; i < str.length; i += 16384) +for (let i = 0; i < str.length; i += 16384) { gData.push(str.substr(i, 16384)); +} function checkVeryLongRequestLine(data) { var iter = LineIterator(data); @@ -67,38 +73,41 @@ function checkVeryLongRequestLine(data) { skipHeaders(iter); // Okay, next line must be the data we expected to be written - var body = - [ - "Method: GET", - "Path: /very-long-request-line", - "Query: " + reallyLong, - "Version: 1.1", - "Scheme: http", - "Host: localhost", - "Port: " + PORT, - ]; + var body = [ + "Method: GET", + "Path: /very-long-request-line", + "Query: " + reallyLong, + "Version: 1.1", + "Scheme: http", + "Host: localhost", + "Port: " + PORT, + ]; expectLines(iter, body); } test = new RawTest("localhost", PORT, gData, checkVeryLongRequestLine); tests.push(test); - function lotsOfLeadingBlankLines(request, response) { writeDetails(request, response); response.setStatusLine(request.httpVersion, 200, "TEST PASSED"); } var blankLines = "\r\n"; -for (let i = 0; i < 14; i++) +for (let i = 0; i < 14; i++) { blankLines += blankLines; -str = blankLines + - "GET /lots-of-leading-blank-lines HTTP/1.1\r\n" + - "Host: localhost:" + PORT + "\r\n" + - "\r\n"; +} +str = + blankLines + + "GET /lots-of-leading-blank-lines HTTP/1.1\r\n" + + "Host: localhost:" + + PORT + + "\r\n" + + "\r\n"; gData = []; -for (let i = 0; i < str.length; i += 100) +for (let i = 0; i < str.length; i += 100) { gData.push(str.substr(i, 100)); +} function checkLotsOfLeadingBlankLines(data) { var iter = LineIterator(data); @@ -112,16 +121,15 @@ function checkLotsOfLeadingBlankLines(data) { skipHeaders(iter); // Okay, next line must be the data we expected to be written - var body = - [ - "Method: GET", - "Path: /lots-of-leading-blank-lines", - "Query: ", - "Version: 1.1", - "Scheme: http", - "Host: localhost", - "Port: " + PORT, - ]; + var body = [ + "Method: GET", + "Path: /lots-of-leading-blank-lines", + "Query: ", + "Version: 1.1", + "Scheme: http", + "Host: localhost", + "Port: " + PORT, + ]; expectLines(iter, body); } diff --git a/netwerk/test/httpserver/test/test_response_write.js b/netwerk/test/httpserver/test/test_response_write.js index af40d8f8971d..fe0c4bd7ba6e 100644 --- a/netwerk/test/httpserver/test/test_response_write.js +++ b/netwerk/test/httpserver/test/test_response_write.js @@ -8,10 +8,18 @@ XPCOMUtils.defineLazyGetter(this, "tests", function() { return [ - new Test("http://localhost:" + srv.identity.primaryPort + "/writeString", - null, check_1234, succeeded), - new Test("http://localhost:" + srv.identity.primaryPort + "/writeInt", - null, check_1234, succeeded), + new Test( + "http://localhost:" + srv.identity.primaryPort + "/writeString", + null, + check_1234, + succeeded + ), + new Test( + "http://localhost:" + srv.identity.primaryPort + "/writeInt", + null, + check_1234, + succeeded + ), ]; }); @@ -27,7 +35,6 @@ function run_test() { runHttpTests(tests, testComplete(srv)); } - // TEST DATA function succeeded(ch, status, data) { diff --git a/netwerk/test/httpserver/test/test_seizepower.js b/netwerk/test/httpserver/test/test_seizepower.js index bf93b00fd134..ca67ab4e542b 100644 --- a/netwerk/test/httpserver/test/test_seizepower.js +++ b/netwerk/test/httpserver/test/test_seizepower.js @@ -28,13 +28,13 @@ function run_test() { runRawTests(tests, testComplete(srv)); } - function checkException(fun, err, msg) { try { fun(); } catch (e) { - if (e !== err && e.result !== err) + if (e !== err && e.result !== err) { do_throw(msg); + } return; } do_throw(msg); @@ -48,7 +48,6 @@ function callASAPLater(fun) { }); } - /** *************** * PATH HANDLERS * *****************/ @@ -65,33 +64,50 @@ function handleTooLate(request, response) { response.seizePower(); - if (response.bodyOutputStream !== output) + if (response.bodyOutputStream !== output) { response.write("bodyOutputStream changed!"); - else + } else { response.write("too-late passed"); + } response.finish(); } function handleExceptions(request, response) { response.seizePower(); - checkException(function() { response.setStatusLine("1.0", 500, "ISE"); }, - Cr.NS_ERROR_NOT_AVAILABLE, - "setStatusLine should throw not-available after seizePower"); - checkException(function() { response.setHeader("X-Fail", "FAIL", false); }, - Cr.NS_ERROR_NOT_AVAILABLE, - "setHeader should throw not-available after seizePower"); - checkException(function() { response.processAsync(); }, - Cr.NS_ERROR_NOT_AVAILABLE, - "processAsync should throw not-available after seizePower"); + checkException( + function() { + response.setStatusLine("1.0", 500, "ISE"); + }, + Cr.NS_ERROR_NOT_AVAILABLE, + "setStatusLine should throw not-available after seizePower" + ); + checkException( + function() { + response.setHeader("X-Fail", "FAIL", false); + }, + Cr.NS_ERROR_NOT_AVAILABLE, + "setHeader should throw not-available after seizePower" + ); + checkException( + function() { + response.processAsync(); + }, + Cr.NS_ERROR_NOT_AVAILABLE, + "processAsync should throw not-available after seizePower" + ); var out = response.bodyOutputStream; var data = "exceptions test passed"; out.write(data, data.length); response.seizePower(); // idempotency test of seizePower response.finish(); response.finish(); // idempotency test of finish after seizePower - checkException(function() { response.seizePower(); }, - Cr.NS_ERROR_UNEXPECTED, - "seizePower should throw unexpected after finish"); + checkException( + function() { + response.seizePower(); + }, + Cr.NS_ERROR_UNEXPECTED, + "seizePower should throw unexpected after finish" + ); } function handleAsyncSeizure(request, response) { @@ -108,15 +124,18 @@ function handleAsyncSeizure(request, response) { function handleSeizeAfterAsync(request, response) { response.setStatusLine(request.httpVersion, 200, "async seizure pass"); response.processAsync(); - checkException(function() { response.seizePower(); }, - Cr.NS_ERROR_NOT_AVAILABLE, - "seizePower should throw not-available after processAsync"); + checkException( + function() { + response.seizePower(); + }, + Cr.NS_ERROR_NOT_AVAILABLE, + "seizePower should throw not-available after processAsync" + ); callLater(1, function() { response.finish(); }); } - /** ************* * BEGIN TESTS * ***************/ @@ -131,32 +150,30 @@ XPCOMUtils.defineLazyGetter(this, "tests", function() { ]; }); -var data0 = "GET /raw-data HTTP/1.0\r\n" + - "\r\n"; +var data0 = "GET /raw-data HTTP/1.0\r\n" + "\r\n"; function checkRawData(data) { Assert.equal(data, "Raw data!"); } -var data1 = "GET /called-too-late HTTP/1.0\r\n" + - "\r\n"; +var data1 = "GET /called-too-late HTTP/1.0\r\n" + "\r\n"; function checkTooLate(data) { Assert.equal(LineIterator(data).next().value, "too-late passed"); } -var data2 = "GET /exceptions HTTP/1.0\r\n" + - "\r\n"; +var data2 = "GET /exceptions HTTP/1.0\r\n" + "\r\n"; function checkExceptions(data) { Assert.equal("exceptions test passed", data); } -var data3 = "GET /async-seizure HTTP/1.0\r\n" + - "\r\n"; +var data3 = "GET /async-seizure HTTP/1.0\r\n" + "\r\n"; function checkAsyncSeizure(data) { Assert.equal(data, "async seizure passed"); } -var data4 = "GET /seize-after-async HTTP/1.0\r\n" + - "\r\n"; +var data4 = "GET /seize-after-async HTTP/1.0\r\n" + "\r\n"; function checkSeizeAfterAsync(data) { - Assert.equal(LineIterator(data).next().value, "HTTP/1.0 200 async seizure pass"); + Assert.equal( + LineIterator(data).next().value, + "HTTP/1.0 200 async seizure pass" + ); } diff --git a/netwerk/test/httpserver/test/test_setstatusline.js b/netwerk/test/httpserver/test/test_setstatusline.js index b39caedbd772..b29634433814 100644 --- a/netwerk/test/httpserver/test/test_setstatusline.js +++ b/netwerk/test/httpserver/test/test_setstatusline.js @@ -30,22 +30,27 @@ function run_test() { runHttpTests(tests, testComplete(srv)); } - /** *********** * UTILITIES * *************/ -function checkStatusLine(channel, httpMaxVer, httpMinVer, httpCode, statusText) { +function checkStatusLine( + channel, + httpMaxVer, + httpMinVer, + httpCode, + statusText +) { Assert.equal(channel.responseStatus, httpCode); Assert.equal(channel.responseStatusText, statusText); - var respMaj = {}, respMin = {}; + var respMaj = {}, + respMin = {}; channel.getResponseVersion(respMaj, respMin); Assert.equal(respMaj.value, httpMaxVer); Assert.equal(respMin.value, httpMinVer); } - /** ******* * TESTS * *********/ @@ -63,10 +68,8 @@ XPCOMUtils.defineLazyGetter(this, "tests", function() { ]; }); - // /no/setstatusline -function noSetstatusline(metadata, response) { -} +function noSetstatusline(metadata, response) {} function startNoSetStatusLine(ch) { checkStatusLine(ch, 1, 1, 200, "OK"); } @@ -74,7 +77,6 @@ function stop(ch, status, data) { Assert.ok(Components.isSuccessCode(status)); } - // /http1_0 function http1_0(metadata, response) { response.setStatusLine("1.0", 200, "OK"); @@ -83,7 +85,6 @@ function startHttp1_0(ch) { checkStatusLine(ch, 1, 0, 200, "OK"); } - // /http1_1 function http1_1(metadata, response) { response.setStatusLine("1.1", 200, "OK"); @@ -92,7 +93,6 @@ function startHttp1_1(ch) { checkStatusLine(ch, 1, 1, 200, "OK"); } - // /invalidVersion function invalidVersion(metadata, response) { try { @@ -106,7 +106,6 @@ function startPassedTrue(ch) { Assert.equal(ch.getResponseHeader("Passed"), "true"); } - // /invalidStatus function invalidStatus(metadata, response) { try { @@ -116,7 +115,6 @@ function invalidStatus(metadata, response) { } } - // /invalidDescription function invalidDescription(metadata, response) { try { @@ -126,7 +124,6 @@ function invalidDescription(metadata, response) { } } - // /crazyCode function crazyCode(metadata, response) { response.setStatusLine("1.1", 617, "Crazy"); @@ -135,7 +132,6 @@ function startCrazy(ch) { checkStatusLine(ch, 1, 1, 617, "Crazy"); } - // /nullVersion function nullVersion(metadata, response) { response.setStatusLine(null, 255, "NULL"); diff --git a/netwerk/test/httpserver/test/test_sjs.js b/netwerk/test/httpserver/test/test_sjs.js index 18038aec339e..3b20d331a605 100644 --- a/netwerk/test/httpserver/test/test_sjs.js +++ b/netwerk/test/httpserver/test/test_sjs.js @@ -20,20 +20,22 @@ const BASE = "http://localhost:" + PORT; var test; var tests = []; - /** ******************* * UTILITY FUNCTIONS * *********************/ function bytesToString(bytes) { - return bytes.map(function(v) { return String.fromCharCode(v); }).join(""); + return bytes + .map(function(v) { + return String.fromCharCode(v); + }) + .join(""); } function skipCache(ch) { ch.loadFlags |= Ci.nsIRequest.LOAD_BYPASS_CACHE; } - /** ****************** * DEFINE THE TESTS * ********************/ @@ -61,7 +63,6 @@ function setupTests(throwing) { test = new Test(TEST_URL, setupFile, null, verifyRawText); tests.push(test); - // add mapping, => interpreted function addTypeMapping(ch) { @@ -79,14 +80,14 @@ function setupTests(throwing) { } function checkContents(ch, status, data) { - if (!throwing) + if (!throwing) { Assert.equal("PASS", bytesToString(data)); + } } test = new Test(TEST_URL, addTypeMapping, checkType, checkContents); tests.push(test); - // remove file/type mapping, map containing directory => raw text function setupDirectoryAndRemoveType(ch) { @@ -100,7 +101,6 @@ function setupTests(throwing) { test = new Test(TEST_URL, setupDirectoryAndRemoveType, null, verifyRawText); tests.push(test); - // add mapping, => interpreted function contentAndCleanup(ch, status, data) { @@ -119,7 +119,6 @@ function setupTests(throwing) { // after the two sets will almost certainly fail. } - /** *************** * ADD THE TESTS * *****************/ @@ -157,34 +156,54 @@ function rangeInit(expectedRangeHeader) { function checkRangeResult(ch) { try { var val = ch.getResponseHeader("Content-Range"); - } catch (e) { /* IDL doesn't specify a particular exception to require */ } + } catch (e) { + /* IDL doesn't specify a particular exception to require */ + } if (val !== undefined) { - do_throw("should not have gotten a Content-Range header, but got one " + - "with this value: " + val); + do_throw( + "should not have gotten a Content-Range header, but got one " + + "with this value: " + + val + ); } Assert.equal(200, ch.responseStatus); Assert.equal("OK", ch.responseStatusText); } -test = new Test(BASE + "/range-checker.sjs", - rangeInit("not-a-bytes-equals-specifier"), - checkRangeResult, null); +test = new Test( + BASE + "/range-checker.sjs", + rangeInit("not-a-bytes-equals-specifier"), + checkRangeResult, + null +); tests.push(test); -test = new Test(BASE + "/range-checker.sjs", - rangeInit("bytes=-"), - checkRangeResult, null); +test = new Test( + BASE + "/range-checker.sjs", + rangeInit("bytes=-"), + checkRangeResult, + null +); tests.push(test); -test = new Test(BASE + "/range-checker.sjs", - rangeInit("bytes=1000000-"), - checkRangeResult, null); +test = new Test( + BASE + "/range-checker.sjs", + rangeInit("bytes=1000000-"), + checkRangeResult, + null +); tests.push(test); -test = new Test(BASE + "/range-checker.sjs", - rangeInit("bytes=1-4"), - checkRangeResult, null); +test = new Test( + BASE + "/range-checker.sjs", + rangeInit("bytes=1-4"), + checkRangeResult, + null +); tests.push(test); -test = new Test(BASE + "/range-checker.sjs", - rangeInit("bytes=-4"), - checkRangeResult, null); +test = new Test( + BASE + "/range-checker.sjs", + rangeInit("bytes=-4"), + checkRangeResult, + null +); tests.push(test); // One last test: for file mappings, the content-type is determined by the @@ -206,7 +225,6 @@ function onStop(ch, status, data) { test = new Test(BASE + "/script.html", setupFileMapping, onStart, onStop); tests.push(test); - /** *************** * RUN THE TESTS * *****************/ @@ -215,7 +233,9 @@ function run_test() { // Test for a content-type which isn't a field-value try { srv.registerContentType("foo", "bar\nbaz"); - throw new Error("this server throws on content-types which aren't field-values"); + throw new Error( + "this server throws on content-types which aren't field-values" + ); } catch (e) { isException(e, Cr.NS_ERROR_INVALID_ARG); } diff --git a/netwerk/test/httpserver/test/test_sjs_object_state.js b/netwerk/test/httpserver/test/test_sjs_object_state.js index b72e68926031..c6dceceda4cb 100644 --- a/netwerk/test/httpserver/test/test_sjs_object_state.js +++ b/netwerk/test/httpserver/test/test_sjs_object_state.js @@ -8,7 +8,6 @@ * Tests that the object-state-preservation mechanism works correctly. */ - XPCOMUtils.defineLazyGetter(this, "PATH", function() { return "http://localhost:" + srv.identity.primaryPort + "/object-state.sjs"; }); @@ -60,32 +59,46 @@ var initialStarted = false; function initialStart(ch) { dumpn("*** initialStart"); - if (initialStarted) + if (initialStarted) { do_throw("initialStart: initialStarted is true?!?!"); + } initialStarted = true; - new HTTPTestLoader(PATH + "?state=intermediate", - intermediateStart, intermediateStop); + new HTTPTestLoader( + PATH + "?state=intermediate", + intermediateStart, + intermediateStop + ); } var initialStopped = false; function initialStop(ch, status, data) { dumpn("*** initialStop"); - Assert.equal(data.map(function(v) { return String.fromCharCode(v); }).join(""), - "done"); + Assert.equal( + data + .map(function(v) { + return String.fromCharCode(v); + }) + .join(""), + "done" + ); Assert.equal(srv.getObjectState("object-state-test"), null); - if (!initialStarted) + if (!initialStarted) { do_throw("initialStop: initialStarted is false?!?!"); - if (initialStopped) + } + if (initialStopped) { do_throw("initialStop: initialStopped is true?!?!"); - if (!intermediateStarted) + } + if (!intermediateStarted) { do_throw("initialStop: intermediateStarted is false?!?!"); - if (!intermediateStopped) + } + if (!intermediateStopped) { do_throw("initialStop: intermediateStopped is false?!?!"); + } initialStopped = true; @@ -98,10 +111,12 @@ function intermediateStart(ch) { Assert.notEqual(srv.getObjectState("object-state-test"), null); - if (!initialStarted) + if (!initialStarted) { do_throw("intermediateStart: initialStarted is false?!?!"); - if (intermediateStarted) + } + if (intermediateStarted) { do_throw("intermediateStart: intermediateStarted is true?!?!"); + } intermediateStarted = true; } @@ -110,36 +125,48 @@ var intermediateStopped = false; function intermediateStop(ch, status, data) { dumpn("*** intermediateStop"); - Assert.equal(data.map(function(v) { return String.fromCharCode(v); }).join(""), - "intermediate"); + Assert.equal( + data + .map(function(v) { + return String.fromCharCode(v); + }) + .join(""), + "intermediate" + ); Assert.notEqual(srv.getObjectState("object-state-test"), null); - if (!initialStarted) + if (!initialStarted) { do_throw("intermediateStop: initialStarted is false?!?!"); - if (!intermediateStarted) + } + if (!intermediateStarted) { do_throw("intermediateStop: intermediateStarted is false?!?!"); - if (intermediateStopped) + } + if (intermediateStopped) { do_throw("intermediateStop: intermediateStopped is true?!?!"); + } intermediateStopped = true; - new HTTPTestLoader(PATH + "?state=trigger", triggerStart, - triggerStop); + new HTTPTestLoader(PATH + "?state=trigger", triggerStart, triggerStop); } var triggerStarted = false; function triggerStart(ch) { dumpn("*** triggerStart"); - if (!initialStarted) + if (!initialStarted) { do_throw("triggerStart: initialStarted is false?!?!"); - if (!intermediateStarted) + } + if (!intermediateStarted) { do_throw("triggerStart: intermediateStarted is false?!?!"); - if (!intermediateStopped) + } + if (!intermediateStopped) { do_throw("triggerStart: intermediateStopped is false?!?!"); - if (triggerStarted) + } + if (triggerStarted) { do_throw("triggerStart: triggerStarted is true?!?!"); + } triggerStarted = true; } @@ -148,19 +175,30 @@ var triggerStopped = false; function triggerStop(ch, status, data) { dumpn("*** triggerStop"); - Assert.equal(data.map(function(v) { return String.fromCharCode(v); }).join(""), - "trigger"); + Assert.equal( + data + .map(function(v) { + return String.fromCharCode(v); + }) + .join(""), + "trigger" + ); - if (!initialStarted) + if (!initialStarted) { do_throw("triggerStop: initialStarted is false?!?!"); - if (!intermediateStarted) + } + if (!intermediateStarted) { do_throw("triggerStop: intermediateStarted is false?!?!"); - if (!intermediateStopped) + } + if (!intermediateStopped) { do_throw("triggerStop: intermediateStopped is false?!?!"); - if (!triggerStarted) + } + if (!triggerStarted) { do_throw("triggerStop: triggerStarted is false?!?!"); - if (triggerStopped) + } + if (triggerStopped) { do_throw("triggerStop: triggerStopped is false?!?!"); + } triggerStopped = true; @@ -183,21 +221,24 @@ function checkForFinish() { try { Assert.equal(srv.getObjectState("object-state-test"), null); - if (!initialStarted) + if (!initialStarted) { do_throw("checkForFinish: initialStarted is false?!?!"); - if (!intermediateStarted) + } + if (!intermediateStarted) { do_throw("checkForFinish: intermediateStarted is false?!?!"); - if (!intermediateStopped) + } + if (!intermediateStopped) { do_throw("checkForFinish: intermediateStopped is false?!?!"); - if (!triggerStarted) + } + if (!triggerStarted) { do_throw("checkForFinish: triggerStarted is false?!?!"); + } } finally { srv.stop(do_test_finished); } } } - /** ******************************* * UTILITY OBSERVABLE URL LOADER * *********************************/ @@ -219,38 +260,46 @@ function HTTPTestLoader(path, start, stop) { var channel = makeChannel(path); channel.asyncOpen(this); } -HTTPTestLoader.prototype = - { - onStartRequest(request) { - dumpn("*** HTTPTestLoader.onStartRequest for " + this._path); +HTTPTestLoader.prototype = { + onStartRequest(request) { + dumpn("*** HTTPTestLoader.onStartRequest for " + this._path); - var ch = request.QueryInterface(Ci.nsIHttpChannel) - .QueryInterface(Ci.nsIHttpChannelInternal); + var ch = request + .QueryInterface(Ci.nsIHttpChannel) + .QueryInterface(Ci.nsIHttpChannelInternal); + try { try { - try { - this._start(ch); - } catch (e) { - do_throw(this._path + ": error in onStartRequest: " + e); - } + this._start(ch); } catch (e) { - dumpn("!!! swallowing onStartRequest exception so onStopRequest is " + - "called..."); + do_throw(this._path + ": error in onStartRequest: " + e); } - }, - onDataAvailable(request, inputStream, offset, count) { - dumpn("*** HTTPTestLoader.onDataAvailable for " + this._path); + } catch (e) { + dumpn( + "!!! swallowing onStartRequest exception so onStopRequest is " + + "called..." + ); + } + }, + onDataAvailable(request, inputStream, offset, count) { + dumpn("*** HTTPTestLoader.onDataAvailable for " + this._path); - Array.prototype.push.apply(this._data, - makeBIS(inputStream).readByteArray(count)); - }, - onStopRequest(request, status) { - dumpn("*** HTTPTestLoader.onStopRequest for " + this._path); + Array.prototype.push.apply( + this._data, + makeBIS(inputStream).readByteArray(count) + ); + }, + onStopRequest(request, status) { + dumpn("*** HTTPTestLoader.onStopRequest for " + this._path); - var ch = request.QueryInterface(Ci.nsIHttpChannel) - .QueryInterface(Ci.nsIHttpChannelInternal); + var ch = request + .QueryInterface(Ci.nsIHttpChannel) + .QueryInterface(Ci.nsIHttpChannelInternal); - this._stop(ch, status, this._data); - }, - QueryInterface: ChromeUtils.generateQI(["nsIStreamListener", "nsIRequestObserver"]), - }; + this._stop(ch, status, this._data); + }, + QueryInterface: ChromeUtils.generateQI([ + "nsIStreamListener", + "nsIRequestObserver", + ]), +}; diff --git a/netwerk/test/httpserver/test/test_sjs_state.js b/netwerk/test/httpserver/test/test_sjs_state.js index 68ba47e169ae..e2e8b4bb32ba 100644 --- a/netwerk/test/httpserver/test/test_sjs_state.js +++ b/netwerk/test/httpserver/test/test_sjs_state.js @@ -22,20 +22,21 @@ function run_test() { function done() { Assert.equal(srv.getSharedState("shared-value"), "done!"); - Assert.equal(srv.getState("/path-handler", "private-value"), - "pathHandlerPrivate2"); - Assert.equal(srv.getState("/state1.sjs", "private-value"), - ""); - Assert.equal(srv.getState("/state2.sjs", "private-value"), - "newPrivate5"); + Assert.equal( + srv.getState("/path-handler", "private-value"), + "pathHandlerPrivate2" + ); + Assert.equal(srv.getState("/state1.sjs", "private-value"), ""); + Assert.equal(srv.getState("/state2.sjs", "private-value"), "newPrivate5"); do_test_pending(); - srv.stop(function() { do_test_finished(); }); + srv.stop(function() { + do_test_finished(); + }); } runHttpTests(tests, done); } - /** ********** * HANDLERS * ************/ @@ -45,10 +46,16 @@ var firstTime = true; function pathHandler(request, response) { response.setHeader("Cache-Control", "no-cache", false); - response.setHeader("X-Old-Shared-Value", srv.getSharedState("shared-value"), - false); - response.setHeader("X-Old-Private-Value", srv.getState("/path-handler", "private-value"), - false); + response.setHeader( + "X-Old-Shared-Value", + srv.getSharedState("shared-value"), + false + ); + response.setHeader( + "X-Old-Private-Value", + srv.getState("/path-handler", "private-value"), + false + ); var privateValue, sharedValue; if (firstTime) { @@ -67,38 +74,56 @@ function pathHandler(request, response) { response.setHeader("X-New-Shared-Value", sharedValue, false); } - /** ************* * BEGIN TESTS * ***************/ XPCOMUtils.defineLazyGetter(this, "tests", function() { return [ - new Test(URL + "/state1.sjs?" + - "newShared=newShared&newPrivate=newPrivate", - null, start_initial, null), - new Test(URL + "/state1.sjs?" + - "newShared=newShared2&newPrivate=newPrivate2", - null, start_overwrite, null), - new Test(URL + "/state1.sjs?" + - "newShared=&newPrivate=newPrivate3", - null, start_remove, null), - new Test(URL + "/path-handler", - null, start_handler, null), - new Test(URL + "/path-handler", - null, start_handler_again, null), - new Test(URL + "/state2.sjs?" + - "newShared=newShared4&newPrivate=newPrivate4", - null, start_other_initial, null), - new Test(URL + "/state2.sjs?" + - "newShared=", - null, start_other_remove_ignore, null), - new Test(URL + "/state2.sjs?" + - "newShared=newShared5&newPrivate=newPrivate5", - null, start_other_set_new, null), - new Test(URL + "/state1.sjs?" + - "newShared=done!&newPrivate=", - null, start_set_remove_original, null), + new Test( + URL + "/state1.sjs?" + "newShared=newShared&newPrivate=newPrivate", + null, + start_initial, + null + ), + new Test( + URL + "/state1.sjs?" + "newShared=newShared2&newPrivate=newPrivate2", + null, + start_overwrite, + null + ), + new Test( + URL + "/state1.sjs?" + "newShared=&newPrivate=newPrivate3", + null, + start_remove, + null + ), + new Test(URL + "/path-handler", null, start_handler, null), + new Test(URL + "/path-handler", null, start_handler_again, null), + new Test( + URL + "/state2.sjs?" + "newShared=newShared4&newPrivate=newPrivate4", + null, + start_other_initial, + null + ), + new Test( + URL + "/state2.sjs?" + "newShared=", + null, + start_other_remove_ignore, + null + ), + new Test( + URL + "/state2.sjs?" + "newShared=newShared5&newPrivate=newPrivate5", + null, + start_other_set_new, + null + ), + new Test( + URL + "/state1.sjs?" + "newShared=done!&newPrivate=", + null, + start_set_remove_original, + null + ), ]; }); @@ -108,8 +133,9 @@ function getHeaderFunction(ch) { try { return ch.getResponseHeader(name); } catch (e) { - if (e.result !== Cr.NS_ERROR_NOT_AVAILABLE) + if (e.result !== Cr.NS_ERROR_NOT_AVAILABLE) { throw e; + } } return ""; } @@ -127,7 +153,7 @@ function expectValues(ch, oldShared, newShared, oldPrivate, newPrivate) { } function start_initial(ch) { -dumpn("XXX start_initial"); + dumpn("XXX start_initial"); expectValues(ch, "", "newShared", "", "newPrivate"); } @@ -144,8 +170,13 @@ function start_handler(ch) { } function start_handler_again(ch) { - expectValues(ch, "pathHandlerShared", "", - "pathHandlerPrivate", "pathHandlerPrivate2"); + expectValues( + ch, + "pathHandlerShared", + "", + "pathHandlerPrivate", + "pathHandlerPrivate2" + ); } function start_other_initial(ch) { diff --git a/netwerk/test/httpserver/test/test_sjs_throwing_exceptions.js b/netwerk/test/httpserver/test/test_sjs_throwing_exceptions.js index 0738c6962bb0..a4c6bb161660 100644 --- a/netwerk/test/httpserver/test/test_sjs_throwing_exceptions.js +++ b/netwerk/test/httpserver/test/test_sjs_throwing_exceptions.js @@ -25,7 +25,9 @@ function run_test() { function done() { do_test_pending(); - srv.stop(function() { do_test_finished(); }); + srv.stop(function() { + do_test_finished(); + }); Assert.equal(gStartCount, TEST_RUNS); Assert.ok(lastPassed); } @@ -46,8 +48,9 @@ const TEST_RUNS = 250; XPCOMUtils.defineLazyGetter(this, "tests", function() { var _tests = new Array(TEST_RUNS + 1); var _test = new Test(URL + "/thrower.sjs?throw", null, start_thrower); - for (var i = 0; i < TEST_RUNS; i++) + for (var i = 0; i < TEST_RUNS; i++) { _tests[i] = _test; + } // ...and don't forget to stop! _tests[TEST_RUNS] = new Test(URL + "/thrower.sjs", null, start_last); return _tests; diff --git a/netwerk/test/httpserver/test/test_start_stop.js b/netwerk/test/httpserver/test/test_start_stop.js index ac99cfff81fc..2d03f1ec2cef 100644 --- a/netwerk/test/httpserver/test/test_start_stop.js +++ b/netwerk/test/httpserver/test/test_start_stop.js @@ -20,8 +20,10 @@ var srv, srv2; function run_test() { if (mozinfo.os == "win") { - dumpn("*** not running test_start_stop.js on Windows for now, because " + - "Windows is dumb"); + dumpn( + "*** not running test_start_stop.js on Windows for now, because " + + "Windows is dumb" + ); return; } @@ -65,15 +67,16 @@ function run_test_2() { do_test_pending(); try { - srv.stop({onStopped() { - try { - do_test_pending(); - run_test_3(); - } finally { - do_test_finished(); - } - }, - }); + srv.stop({ + onStopped() { + try { + do_test_pending(); + run_test_3(); + } finally { + do_test_finished(); + } + }, + }); } catch (e) { do_throw("error stopping with an object: " + e); } @@ -123,11 +126,11 @@ function run_test_5() { dumpn("*** run_test_5"); testsComplete = true; - if (stopped) + if (stopped) { do_test_finished(); + } } - const INTERVAL = 500; function handle(request, response) { @@ -157,6 +160,7 @@ var stopped = false; function serverStopped() { dumpn("*** server really, fully shut down now"); stopped = true; - if (testsComplete) + if (testsComplete) { do_test_finished(); + } } diff --git a/netwerk/test/mochitests/file_1331680.js b/netwerk/test/mochitests/file_1331680.js index 02d5094d9a55..3011ac9dab58 100644 --- a/netwerk/test/mochitests/file_1331680.js +++ b/netwerk/test/mochitests/file_1331680.js @@ -1,4 +1,4 @@ -const {Services} = ChromeUtils.import("resource://gre/modules/Services.jsm"); +const { Services } = ChromeUtils.import("resource://gre/modules/Services.jsm"); let cs = Cc["@mozilla.org/cookieService;1"].getService(Ci.nsICookieService); var observer = { @@ -8,15 +8,15 @@ var observer = { sendAsyncMessage("cookieName", cookie.name + "=" + cookie.value); sendAsyncMessage("cookieOperation", data); } - } + }, }; -addMessageListener("createObserver" , function(e) { +addMessageListener("createObserver", function(e) { Services.obs.addObserver(observer, "cookie-changed"); sendAsyncMessage("createObserver:return"); }); -addMessageListener("removeObserver" , function(e) { +addMessageListener("removeObserver", function(e) { Services.obs.removeObserver(observer, "cookie-changed"); sendAsyncMessage("removeObserver:return"); }); diff --git a/netwerk/test/mochitests/file_chromecommon.js b/netwerk/test/mochitests/file_chromecommon.js index 5b38ee0ffcf4..2315b2d341f1 100644 --- a/netwerk/test/mochitests/file_chromecommon.js +++ b/netwerk/test/mochitests/file_chromecommon.js @@ -1,10 +1,10 @@ -let cs = Cc["@mozilla.org/cookiemanager;1"] - .getService(Ci.nsICookieManager); +let cs = Cc["@mozilla.org/cookiemanager;1"].getService(Ci.nsICookieManager); addMessageListener("getCookieCountAndClear", () => { let count = 0; - for (let cookie of cs.enumerator) + for (let cookie of cs.enumerator) { ++count; + } cs.removeAll(); sendAsyncMessage("getCookieCountAndClear:return", { count }); diff --git a/netwerk/test/mochitests/file_documentcookie_maxage_chromescript.js b/netwerk/test/mochitests/file_documentcookie_maxage_chromescript.js index 59d518b8fc9c..b5e3785b4073 100644 --- a/netwerk/test/mochitests/file_documentcookie_maxage_chromescript.js +++ b/netwerk/test/mochitests/file_documentcookie_maxage_chromescript.js @@ -1,6 +1,5 @@ function getCookieService() { - return Cc["@mozilla.org/cookiemanager;1"] - .getService(Ci.nsICookieManager); + return Cc["@mozilla.org/cookiemanager;1"].getService(Ci.nsICookieManager); } function getCookies(cs) { diff --git a/netwerk/test/mochitests/file_testcommon.js b/netwerk/test/mochitests/file_testcommon.js index 6fe705df07c0..5925b29643eb 100644 --- a/netwerk/test/mochitests/file_testcommon.js +++ b/netwerk/test/mochitests/file_testcommon.js @@ -13,9 +13,10 @@ function setupTest(uri, cookies, loads) { SimpleTest.waitForExplicitFinish(); var prefSet = new Promise(resolve => { - SpecialPowers.pushPrefEnv({ set: [ - ["network.cookie.cookieBehavior", 1], - ]}, resolve); + SpecialPowers.pushPrefEnv( + { set: [["network.cookie.cookieBehavior", 1]] }, + resolve + ); }); gScript = SpecialPowers.loadChromeScript(SCRIPT_URL); @@ -28,7 +29,7 @@ function setupTest(uri, cookies, loads) { prefSet.then(() => { // load a window which contains an iframe; each will attempt to set // cookies from their respective domains. - gPopup = window.open(uri, 'hai', 'width=100,height=100'); + gPopup = window.open(uri, "hai", "width=100,height=100"); }); } diff --git a/netwerk/test/mochitests/file_testloadflags.js b/netwerk/test/mochitests/file_testloadflags.js index bd5d43969849..0a3ccaf81486 100644 --- a/netwerk/test/mochitests/file_testloadflags.js +++ b/netwerk/test/mochitests/file_testloadflags.js @@ -1,4 +1,6 @@ -const SCRIPT_URL = SimpleTest.getTestFileURL('file_testloadflags_chromescript.js'); +const SCRIPT_URL = SimpleTest.getTestFileURL( + "file_testloadflags_chromescript.js" +); var gExpectedCookies; var gExpectedHeaders; @@ -12,13 +14,26 @@ var gLoads = 0; // setupTest() is run from 'onload='. function setupTest(uri, domain, cookies, loads, headers) { - info("setupTest uri: " + uri + " domain: " + domain + " cookies: " + cookies + - " loads: " + loads + " headers: " + headers); + info( + "setupTest uri: " + + uri + + " domain: " + + domain + + " cookies: " + + cookies + + " loads: " + + loads + + " headers: " + + headers + ); SimpleTest.waitForExplicitFinish(); var prefSet = new Promise(resolve => { - SpecialPowers.pushPrefEnv({ set: [["network.cookie.cookieBehavior", 1]] }, resolve); + SpecialPowers.pushPrefEnv( + { set: [["network.cookie.cookieBehavior", 1]] }, + resolve + ); }); gExpectedCookies = cookies; @@ -29,8 +44,11 @@ function setupTest(uri, domain, cookies, loads, headers) { gScript.addMessageListener("info", ({ str }) => info(str)); gScript.addMessageListener("ok", ({ c, m }) => ok(c, m)); gScript.addMessageListener("observer:gotCookie", ({ cookie, uri }) => { - isnot(cookie.indexOf("oh=hai"), -1, - "cookie 'oh=hai' is in header for " + uri); + isnot( + cookie.indexOf("oh=hai"), + -1, + "cookie 'oh=hai' is in header for " + uri + ); ++gHeaders; }); @@ -42,15 +60,14 @@ function setupTest(uri, domain, cookies, loads, headers) { // Listen for MessageEvents. window.addEventListener("message", messageReceiver); - Promise.all([ prefSet, scriptReady ]).then(() => { + Promise.all([prefSet, scriptReady]).then(() => { // load a window which contains an iframe; each will attempt to set // cookies from their respective domains. - gPopup = window.open(uri, 'hai', 'width=100,height=100'); + gPopup = window.open(uri, "hai", "width=100,height=100"); }); } -function finishTest() -{ +function finishTest() { gScript.addMessageListener("shutdown:return", () => { gScript.destroy(); SimpleTest.finish(); @@ -60,10 +77,11 @@ function finishTest() /** Receives MessageEvents to this window. */ // Count and check loads. -function messageReceiver(evt) -{ - ok(evt.data == "f_lf_i msg data img" || evt.data == "f_lf_i msg data page", - "message data received from popup"); +function messageReceiver(evt) { + ok( + evt.data == "f_lf_i msg data img" || evt.data == "f_lf_i msg data page", + "message data received from popup" + ); if (evt.data == "f_lf_i msg data img") { info("message data received from popup for image"); } diff --git a/netwerk/test/mochitests/file_testloadflags_chromescript.js b/netwerk/test/mochitests/file_testloadflags_chromescript.js index d80f11cf37e1..05c8509ad652 100644 --- a/netwerk/test/mochitests/file_testloadflags_chromescript.js +++ b/netwerk/test/mochitests/file_testloadflags_chromescript.js @@ -16,8 +16,9 @@ function is(a, b, m) { function obs() { info("adding observer"); - this.os = Cc["@mozilla.org/observer-service;1"] - .getService(Ci.nsIObserverService); + this.os = Cc["@mozilla.org/observer-service;1"].getService( + Ci.nsIObserverService + ); this.os.addObserver(this, "http-on-modify-request"); } @@ -35,21 +36,26 @@ obs.prototype = { channel.visitRequestHeaders({ visitHeader(aHeader, aValue) { info(aHeader + ": " + aValue); - }}); + }, + }); } catch (err) { ok(false, "catch error " + err); } // Ignore notifications we don't care about (like favicons) - if (!channel.URI.spec.includes( - "http://example.org/tests/netwerk/test/mochitests/")) { + if ( + !channel.URI.spec.includes( + "http://example.org/tests/netwerk/test/mochitests/" + ) + ) { info("ignoring this one"); return; } - sendAsyncMessage("observer:gotCookie", - { cookie: channel.getRequestHeader("Cookie"), - uri: channel.URI.spec }); + sendAsyncMessage("observer:gotCookie", { + cookie: channel.getRequestHeader("Cookie"), + uri: channel.URI.spec, + }); }, remove() { @@ -57,15 +63,27 @@ obs.prototype = { this.os.removeObserver(this, "http-on-modify-request"); this.os = null; - } -} + }, +}; function getCookieCount(cs) { let count = 0; for (let cookie of cs.enumerator) { info("cookie: " + cookie); - info("cookie host " + cookie.host + " path " + cookie.path + " name " + cookie.name + - " value " + cookie.value + " isSecure " + cookie.isSecure + " expires " + cookie.expires); + info( + "cookie host " + + cookie.host + + " path " + + cookie.path + + " name " + + cookie.name + + " value " + + cookie.value + + " isSecure " + + cookie.isSecure + + " expires " + + cookie.expires + ); ++count; } @@ -73,8 +91,7 @@ function getCookieCount(cs) { } addMessageListener("init", ({ domain }) => { - let cs = Cc["@mozilla.org/cookiemanager;1"] - .getService(Ci.nsICookieManager); + let cs = Cc["@mozilla.org/cookiemanager;1"].getService(Ci.nsICookieManager); info("we are going to remove these cookies"); @@ -82,17 +99,30 @@ addMessageListener("init", ({ domain }) => { info(count + " cookies"); cs.removeAll(); - cs.add(domain, "", "oh", "hai", false, false, true, Math.pow(2, 62), {}, - Ci.nsICookie.SAMESITE_NONE); - is(cs.countCookiesFromHost(domain), 1, "number of cookies for domain " + domain); + cs.add( + domain, + "", + "oh", + "hai", + false, + false, + true, + Math.pow(2, 62), + {}, + Ci.nsICookie.SAMESITE_NONE + ); + is( + cs.countCookiesFromHost(domain), + 1, + "number of cookies for domain " + domain + ); gObs = new obs(); sendAsyncMessage("init:return"); }); addMessageListener("getCookieCount", () => { - let cs = Cc["@mozilla.org/cookiemanager;1"] - .getService(Ci.nsICookieManager); + let cs = Cc["@mozilla.org/cookiemanager;1"].getService(Ci.nsICookieManager); let count = getCookieCount(cs); cs.removeAll(); @@ -102,8 +132,7 @@ addMessageListener("getCookieCount", () => { addMessageListener("shutdown", () => { gObs.remove(); - let cs = Cc["@mozilla.org/cookiemanager;1"] - .getService(Ci.nsICookieManager); + let cs = Cc["@mozilla.org/cookiemanager;1"].getService(Ci.nsICookieManager); cs.removeAll(); sendAsyncMessage("shutdown:return"); }); diff --git a/netwerk/test/unit/client_cert_chooser.js b/netwerk/test/unit/client_cert_chooser.js index 06bfc736c53e..44d3e3e9625b 100644 --- a/netwerk/test/unit/client_cert_chooser.js +++ b/netwerk/test/unit/client_cert_chooser.js @@ -3,11 +3,13 @@ // License, v. 2.0. If a copy of the MPL was not distributed with this // file, You can obtain one at http://mozilla.org/MPL/2.0/. -const { XPCOMUtils } = ChromeUtils.import("resource://gre/modules/XPCOMUtils.jsm"); +const { XPCOMUtils } = ChromeUtils.import( + "resource://gre/modules/XPCOMUtils.jsm" +); var Prompter = { QueryInterface: ChromeUtils.generateQI([Ci.nsIPrompt]), - alert() {} // Do nothing when asked to show an alert + alert() {}, // Do nothing when asked to show an alert }; function WindowWatcherService() {} @@ -17,9 +19,7 @@ WindowWatcherService.prototype = { getNewPrompter() { return Prompter; - } + }, }; -this.NSGetFactory = XPCOMUtils.generateNSGetFactory([ - WindowWatcherService -]); +this.NSGetFactory = XPCOMUtils.generateNSGetFactory([WindowWatcherService]); diff --git a/netwerk/test/unit/head_cache.js b/netwerk/test/unit/head_cache.js index 1fdcf9a585d8..c3a4576f6d17 100644 --- a/netwerk/test/unit/head_cache.js +++ b/netwerk/test/unit/head_cache.js @@ -1,20 +1,23 @@ -var {XPCOMUtils} = ChromeUtils.import('resource://gre/modules/XPCOMUtils.jsm'); -var {Services} = ChromeUtils.import('resource://gre/modules/Services.jsm'); +var { XPCOMUtils } = ChromeUtils.import( + "resource://gre/modules/XPCOMUtils.jsm" +); +var { Services } = ChromeUtils.import("resource://gre/modules/Services.jsm"); var _CSvc; function get_cache_service() { - if (_CSvc) + if (_CSvc) { return _CSvc; + } - return _CSvc = Cc["@mozilla.org/netwerk/cache-storage-service;1"] - .getService(Ci.nsICacheStorageService); + return (_CSvc = Cc["@mozilla.org/netwerk/cache-storage-service;1"].getService( + Ci.nsICacheStorageService + )); } -function evict_cache_entries(where) -{ - var clearDisk = (!where || where == "disk" || where == "all"); - var clearMem = (!where || where == "memory" || where == "all"); - var clearAppCache = (where == "appcache"); +function evict_cache_entries(where) { + var clearDisk = !where || where == "disk" || where == "all"; + var clearMem = !where || where == "memory" || where == "all"; + var clearAppCache = where == "appcache"; var svc = get_cache_service(); var storage; @@ -35,72 +38,79 @@ function evict_cache_entries(where) } } -function createURI(urispec) -{ - var ioServ = Cc["@mozilla.org/network/io-service;1"] - .getService(Ci.nsIIOService); +function createURI(urispec) { + var ioServ = Cc["@mozilla.org/network/io-service;1"].getService( + Ci.nsIIOService + ); return ioServ.newURI(urispec); } -function getCacheStorage(where, lci, appcache) -{ - if (!lci) lci = Services.loadContextInfo.default; +function getCacheStorage(where, lci, appcache) { + if (!lci) { + lci = Services.loadContextInfo.default; + } var svc = get_cache_service(); switch (where) { - case "disk": return svc.diskCacheStorage(lci, false); - case "memory": return svc.memoryCacheStorage(lci); - case "appcache": return svc.appCacheStorage(lci, appcache); - case "pin": return svc.pinningCacheStorage(lci); + case "disk": + return svc.diskCacheStorage(lci, false); + case "memory": + return svc.memoryCacheStorage(lci); + case "appcache": + return svc.appCacheStorage(lci, appcache); + case "pin": + return svc.pinningCacheStorage(lci); } return null; } -function asyncOpenCacheEntry(key, where, flags, lci, callback, appcache) -{ +function asyncOpenCacheEntry(key, where, flags, lci, callback, appcache) { key = createURI(key); - function CacheListener() { } + function CacheListener() {} CacheListener.prototype = { _appCache: appcache, QueryInterface: ChromeUtils.generateQI(["nsICacheEntryOpenCallback"]), onCacheEntryCheck(entry, appCache) { - if (typeof callback === "object") + if (typeof callback === "object") { return callback.onCacheEntryCheck(entry, appCache); + } return Ci.nsICacheEntryOpenCallback.ENTRY_WANTED; }, - onCacheEntryAvailable (entry, isnew, appCache, status) { + onCacheEntryAvailable(entry, isnew, appCache, status) { if (typeof callback === "object") { // Root us at the callback callback.__cache_listener_root = this; callback.onCacheEntryAvailable(entry, isnew, appCache, status); - } - else + } else { callback(status, entry, appCache); + } }, - run () { + run() { var storage = getCacheStorage(where, lci, this._appCache); storage.asyncOpenURI(key, "", flags, this); - } + }, }; - (new CacheListener()).run(); + new CacheListener().run(); } -function syncWithCacheIOThread(callback, force) -{ +function syncWithCacheIOThread(callback, force) { if (force) { asyncOpenCacheEntry( - "http://nonexistententry/", "disk", Ci.nsICacheStorage.OPEN_READONLY, null, + "http://nonexistententry/", + "disk", + Ci.nsICacheStorage.OPEN_READONLY, + null, function(status, entry) { Assert.equal(status, Cr.NS_ERROR_CACHE_KEY_NOT_FOUND); callback(); - }); - } - else { + } + ); + } else { callback(); } } @@ -113,7 +123,7 @@ function get_device_entry_count(where, lci, continuation) { } var visitor = { - onCacheStorageInfo (entryCount, consumption) { + onCacheStorageInfo(entryCount, consumption) { executeSoon(function() { continuation(entryCount, consumption); }); @@ -124,19 +134,32 @@ function get_device_entry_count(where, lci, continuation) { storage.asyncVisitStorage(visitor, false); } -function asyncCheckCacheEntryPresence(key, where, shouldExist, continuation, appCache) -{ - asyncOpenCacheEntry(key, where, Ci.nsICacheStorage.OPEN_READONLY, null, +function asyncCheckCacheEntryPresence( + key, + where, + shouldExist, + continuation, + appCache +) { + asyncOpenCacheEntry( + key, + where, + Ci.nsICacheStorage.OPEN_READONLY, + null, function(status, entry) { if (shouldExist) { dump("TEST-INFO | checking cache key " + key + " exists @ " + where); Assert.equal(status, Cr.NS_OK); Assert.ok(!!entry); } else { - dump("TEST-INFO | checking cache key " + key + " doesn't exist @ " + where); + dump( + "TEST-INFO | checking cache key " + key + " doesn't exist @ " + where + ); Assert.equal(status, Cr.NS_ERROR_CACHE_KEY_NOT_FOUND); Assert.equal(null, entry); } continuation(); - }, appCache); + }, + appCache + ); } diff --git a/netwerk/test/unit/head_cache2.js b/netwerk/test/unit/head_cache2.js index cca116e1b339..0f6a89c7f6c0 100644 --- a/netwerk/test/unit/head_cache2.js +++ b/netwerk/test/unit/head_cache2.js @@ -1,91 +1,100 @@ var callbacks = new Array(); // Expect an existing entry -const NORMAL = 0; +const NORMAL = 0; // Expect a new entry -const NEW = 1 << 0; +const NEW = 1 << 0; // Return early from onCacheEntryCheck and set the callback to state it expects onCacheEntryCheck to happen -const NOTVALID = 1 << 1; +const NOTVALID = 1 << 1; // Throw from onCacheEntryAvailable -const THROWAVAIL = 1 << 2; +const THROWAVAIL = 1 << 2; // Open entry for reading-only -const READONLY = 1 << 3; +const READONLY = 1 << 3; // Expect the entry to not be found -const NOTFOUND = 1 << 4; +const NOTFOUND = 1 << 4; // Return ENTRY_NEEDS_REVALIDATION from onCacheEntryCheck -const REVAL = 1 << 5; +const REVAL = 1 << 5; // Return ENTRY_PARTIAL from onCacheEntryCheck, in combo with NEW or RECREATE bypasses check for emptiness of the entry -const PARTIAL = 1 << 6 +const PARTIAL = 1 << 6; // Expect the entry is doomed, i.e. the output stream should not be possible to open -const DOOMED = 1 << 7; +const DOOMED = 1 << 7; // Don't trigger the go-on callback until the entry is written -const WAITFORWRITE = 1 << 8; +const WAITFORWRITE = 1 << 8; // Don't write data (i.e. don't open output stream) -const METAONLY = 1 << 9; +const METAONLY = 1 << 9; // Do recreation of an existing cache entry -const RECREATE = 1 << 10; +const RECREATE = 1 << 10; // Do not give me the entry -const NOTWANTED = 1 << 11; +const NOTWANTED = 1 << 11; // Tell the cache to wait for the entry to be completely written first -const COMPLETE = 1 << 12; +const COMPLETE = 1 << 12; // Don't write meta/data and don't set valid in the callback, consumer will do it manually -const DONTFILL = 1 << 13; +const DONTFILL = 1 << 13; // Used in combination with METAONLY, don't call setValid() on the entry after metadata has been set -const DONTSETVALID = 1 << 14; +const DONTSETVALID = 1 << 14; // Notify before checking the data, useful for proper callback ordering checks const NOTIFYBEFOREREAD = 1 << 15; // It's allowed to not get an existing entry (result of opening is undetermined) -const MAYBE_NEW = 1 << 16; +const MAYBE_NEW = 1 << 16; var log_c2 = true; -function LOG_C2(o, m) -{ - if (!log_c2) return; - if (!m) +function LOG_C2(o, m) { + if (!log_c2) { + return; + } + if (!m) { dump("TEST-INFO | CACHE2: " + o + "\n"); - else - dump("TEST-INFO | CACHE2: callback #" + o.order + "(" + (o.workingData ? o.workingData.substr(0, 10) : "---") + ") " + m + "\n"); + } else { + dump( + "TEST-INFO | CACHE2: callback #" + + o.order + + "(" + + (o.workingData ? o.workingData.substr(0, 10) : "---") + + ") " + + m + + "\n" + ); + } } -function pumpReadStream(inputStream, goon) -{ +function pumpReadStream(inputStream, goon) { if (inputStream.isNonBlocking()) { // non-blocking stream, must read via pump - var pump = Cc["@mozilla.org/network/input-stream-pump;1"] - .createInstance(Ci.nsIInputStreamPump); + var pump = Cc["@mozilla.org/network/input-stream-pump;1"].createInstance( + Ci.nsIInputStreamPump + ); pump.init(inputStream, 0, 0, true); var data = ""; - pump.asyncRead({ - onStartRequest (aRequest) { }, - onDataAvailable (aRequest, aInputStream, aOffset, aCount) + pump.asyncRead( { - var wrapper = Cc["@mozilla.org/scriptableinputstream;1"]. - createInstance(Ci.nsIScriptableInputStream); - wrapper.init(aInputStream); - var str = wrapper.read(wrapper.available()); - LOG_C2("reading data '" + str.substring(0,5) + "'"); - data += str; + onStartRequest(aRequest) {}, + onDataAvailable(aRequest, aInputStream, aOffset, aCount) { + var wrapper = Cc[ + "@mozilla.org/scriptableinputstream;1" + ].createInstance(Ci.nsIScriptableInputStream); + wrapper.init(aInputStream); + var str = wrapper.read(wrapper.available()); + LOG_C2("reading data '" + str.substring(0, 5) + "'"); + data += str; + }, + onStopRequest(aRequest, aStatusCode) { + LOG_C2("done reading data: " + aStatusCode); + Assert.equal(aStatusCode, Cr.NS_OK); + goon(data); + }, }, - onStopRequest (aRequest, aStatusCode) - { - LOG_C2("done reading data: " + aStatusCode); - Assert.equal(aStatusCode, Cr.NS_OK); - goon(data); - }, - }, null); - } - else { + null + ); + } else { // blocking stream var data = read_stream(inputStream, inputStream.available()); goon(data); } } -OpenCallback.prototype = -{ +OpenCallback.prototype = { QueryInterface: ChromeUtils.generateQI(["nsICacheEntryOpenCallback"]), - onCacheEntryCheck(entry, appCache) - { + onCacheEntryCheck(entry, appCache) { LOG_C2(this, "onCacheEntryCheck"); Assert.ok(!this.onCheckPassed); this.onCheckPassed = true; @@ -103,15 +112,18 @@ OpenCallback.prototype = Assert.equal(entry.getMetaDataElement("meto"), this.workingMetadata); // check for sane flag combination - Assert.notEqual(this.behavior & (REVAL|PARTIAL), REVAL|PARTIAL); + Assert.notEqual(this.behavior & (REVAL | PARTIAL), REVAL | PARTIAL); - if (this.behavior & (REVAL|PARTIAL)) { + if (this.behavior & (REVAL | PARTIAL)) { LOG_C2(this, "onCacheEntryCheck DONE, return ENTRY_NEEDS_REVALIDATION"); return Ci.nsICacheEntryOpenCallback.ENTRY_NEEDS_REVALIDATION; } if (this.behavior & COMPLETE) { - LOG_C2(this, "onCacheEntryCheck DONE, return RECHECK_AFTER_WRITE_FINISHED"); + LOG_C2( + this, + "onCacheEntryCheck DONE, return RECHECK_AFTER_WRITE_FINISHED" + ); // Specific to the new backend because of concurrent read/write: // when a consumer returns RECHECK_AFTER_WRITE_FINISHED from onCacheEntryCheck // the cache calls this callback again after the entry write has finished. @@ -127,9 +139,8 @@ OpenCallback.prototype = LOG_C2(this, "onCacheEntryCheck DONE, return ENTRY_WANTED"); return Ci.nsICacheEntryOpenCallback.ENTRY_WANTED; }, - onCacheEntryAvailable(entry, isnew, appCache, status) - { - if ((this.behavior & MAYBE_NEW) && isnew) { + onCacheEntryAvailable(entry, isnew, appCache, status) { + if (this.behavior & MAYBE_NEW && isnew) { this.behavior |= NEW; } @@ -139,14 +150,14 @@ OpenCallback.prototype = Assert.equal(isnew, !!(this.behavior & NEW)); - if (this.behavior & (NOTFOUND|NOTWANTED)) { + if (this.behavior & (NOTFOUND | NOTWANTED)) { Assert.equal(status, Cr.NS_ERROR_CACHE_KEY_NOT_FOUND); Assert.ok(!entry); - if (this.behavior & THROWAVAIL) + if (this.behavior & THROWAVAIL) { this.throwAndNotify(entry); + } this.goon(entry); - } - else if (this.behavior & (NEW|RECREATE)) { + } else if (this.behavior & (NEW | RECREATE)) { Assert.ok(!!entry); if (this.behavior & RECREATE) { @@ -154,18 +165,19 @@ OpenCallback.prototype = Assert.ok(!!entry); } - if (this.behavior & THROWAVAIL) + if (this.behavior & THROWAVAIL) { this.throwAndNotify(entry); + } - if (!(this.behavior & WAITFORWRITE)) + if (!(this.behavior & WAITFORWRITE)) { this.goon(entry); + } if (!(this.behavior & PARTIAL)) { try { entry.getMetaDataElement("meto"); Assert.ok(false); - } - catch (ex) {} + } catch (ex) {} } if (this.behavior & DONTFILL) { @@ -174,21 +186,25 @@ OpenCallback.prototype = } var self = this; - executeSoon(function() { // emulate network latency + executeSoon(function() { + // emulate network latency entry.setMetaDataElement("meto", self.workingMetadata); entry.metaDataReady(); if (self.behavior & METAONLY) { // Since forcing GC/CC doesn't trigger OnWriterClosed, we have to set the entry valid manually :( - if (!(self.behavior & DONTSETVALID)) + if (!(self.behavior & DONTSETVALID)) { entry.setValid(); + } entry.close(); - if (self.behavior & WAITFORWRITE) + if (self.behavior & WAITFORWRITE) { self.goon(entry); + } return; } - executeSoon(function() { // emulate more network latency + executeSoon(function() { + // emulate more network latency if (self.behavior & DOOMED) { LOG_C2(self, "checking doom state"); try { @@ -200,37 +216,40 @@ OpenCallback.prototype = } catch (ex) { Assert.ok(true); } - if (self.behavior & WAITFORWRITE) + if (self.behavior & WAITFORWRITE) { self.goon(entry); + } return; } - var offset = (self.behavior & PARTIAL) - ? entry.dataSize - : 0; + var offset = self.behavior & PARTIAL ? entry.dataSize : 0; LOG_C2(self, "openOutputStream @ " + offset); var os = entry.openOutputStream(offset, -1); LOG_C2(self, "writing data"); var wrt = os.write(self.workingData, self.workingData.length); Assert.equal(wrt, self.workingData.length); os.close(); - if (self.behavior & WAITFORWRITE) + if (self.behavior & WAITFORWRITE) { self.goon(entry); + } entry.close(); - }) - }) - } - else { // NORMAL + }); + }); + } else { + // NORMAL Assert.ok(!!entry); Assert.equal(entry.getMetaDataElement("meto"), this.workingMetadata); - if (this.behavior & THROWAVAIL) + if (this.behavior & THROWAVAIL) { this.throwAndNotify(entry); - if (this.behavior & NOTIFYBEFOREREAD) + } + if (this.behavior & NOTIFYBEFOREREAD) { this.goon(entry, true); + } - var wrapper = Cc["@mozilla.org/scriptableinputstream;1"]. - createInstance(Ci.nsIScriptableInputStream); + var wrapper = Cc["@mozilla.org/scriptableinputstream;1"].createInstance( + Ci.nsIScriptableInputStream + ); var self = this; pumpReadStream(entry.openInputStream(0), function(data) { Assert.equal(data, self.workingData); @@ -241,16 +260,14 @@ OpenCallback.prototype = }); } }, - selfCheck() - { + selfCheck() { LOG_C2(this, "selfCheck"); - Assert.ok(this.onCheckPassed || (this.behavior & MAYBE_NEW)); + Assert.ok(this.onCheckPassed || this.behavior & MAYBE_NEW); Assert.ok(this.onAvailPassed); - Assert.ok(this.onDataCheckPassed || (this.behavior & MAYBE_NEW)); + Assert.ok(this.onDataCheckPassed || this.behavior & MAYBE_NEW); }, - throwAndNotify(entry) - { + throwAndNotify(entry) { LOG_C2(this, "Throwing"); var self = this; executeSoon(function() { @@ -258,47 +275,59 @@ OpenCallback.prototype = self.goon(entry); }); throw Cr.NS_ERROR_FAILURE; - } + }, }; -function OpenCallback(behavior, workingMetadata, workingData, goon) -{ +function OpenCallback(behavior, workingMetadata, workingData, goon) { this.behavior = behavior; this.workingMetadata = workingMetadata; this.workingData = workingData; this.goon = goon; - this.onCheckPassed = (!!(behavior & (NEW|RECREATE)) || !workingMetadata) && !(behavior & NOTVALID); + this.onCheckPassed = + (!!(behavior & (NEW | RECREATE)) || !workingMetadata) && + !(behavior & NOTVALID); this.onAvailPassed = false; - this.onDataCheckPassed = !!(behavior & (NEW|RECREATE|NOTWANTED)) || !workingMetadata; + this.onDataCheckPassed = + !!(behavior & (NEW | RECREATE | NOTWANTED)) || !workingMetadata; callbacks.push(this); this.order = callbacks.length; } -VisitCallback.prototype = -{ +VisitCallback.prototype = { QueryInterface: ChromeUtils.generateQI(["nsICacheStorageVisitor"]), - onCacheStorageInfo(num, consumption) - { + onCacheStorageInfo(num, consumption) { LOG_C2(this, "onCacheStorageInfo: num=" + num + ", size=" + consumption); Assert.equal(this.num, num); Assert.equal(this.consumption, consumption); - if (!this.entries) + if (!this.entries) { this.notify(); + } }, - onCacheEntryInfo(aURI, aIdEnhance, aDataSize, aFetchCount, aLastModifiedTime, aExpirationTime, - aPinned, aInfo) - { - var key = (aIdEnhance ? (aIdEnhance + ":") : "") + aURI.asciiSpec; + onCacheEntryInfo( + aURI, + aIdEnhance, + aDataSize, + aFetchCount, + aLastModifiedTime, + aExpirationTime, + aPinned, + aInfo + ) { + var key = (aIdEnhance ? aIdEnhance + ":" : "") + aURI.asciiSpec; LOG_C2(this, "onCacheEntryInfo: key=" + key); function findCacheIndex(element) { - if (typeof(element) === "string") { + if (typeof element === "string") { return element === key; - } else if (typeof(element) === "object") { - return element.uri === key && - element.lci.isAnonymous === aInfo.isAnonymous && - ChromeUtils.isOriginAttributesEqual(element.lci.originAttributes, - aInfo.originAttributes); + } else if (typeof element === "object") { + return ( + element.uri === key && + element.lci.isAnonymous === aInfo.isAnonymous && + ChromeUtils.isOriginAttributesEqual( + element.lci.originAttributes, + aInfo.originAttributes + ) + ); } return false; @@ -311,28 +340,25 @@ VisitCallback.prototype = this.entries.splice(index, 1); }, - onCacheEntryVisitCompleted() - { + onCacheEntryVisitCompleted() { LOG_C2(this, "onCacheEntryVisitCompleted"); - if (this.entries) + if (this.entries) { Assert.equal(this.entries.length, 0); + } this.notify(); }, - notify() - { + notify() { Assert.ok(!!this.goon); var goon = this.goon; this.goon = null; executeSoon(goon); }, - selfCheck() - { + selfCheck() { Assert.ok(!this.entries || !this.entries.length); - } + }, }; -function VisitCallback(num, consumption, entries, goon) -{ +function VisitCallback(num, consumption, entries, goon) { this.num = num; this.consumption = consumption; this.entries = entries; @@ -341,64 +367,61 @@ function VisitCallback(num, consumption, entries, goon) this.order = callbacks.length; } -EvictionCallback.prototype = -{ +EvictionCallback.prototype = { QueryInterface: ChromeUtils.generateQI(["nsICacheEntryDoomCallback"]), - onCacheEntryDoomed(result) - { + onCacheEntryDoomed(result) { Assert.equal(this.expectedSuccess, result == Cr.NS_OK); this.goon(); }, - selfCheck() {} -} + selfCheck() {}, +}; -function EvictionCallback(success, goon) -{ +function EvictionCallback(success, goon) { this.expectedSuccess = success; this.goon = goon; callbacks.push(this); this.order = callbacks.length; } -MultipleCallbacks.prototype = -{ - fired() - { - if (--this.pending == 0) - { +MultipleCallbacks.prototype = { + fired() { + if (--this.pending == 0) { var self = this; - if (this.delayed) - executeSoon(function() { self.goon(); }); - else + if (this.delayed) { + executeSoon(function() { + self.goon(); + }); + } else { this.goon(); + } } }, - add() - { + add() { ++this.pending; - } -} + }, +}; -function MultipleCallbacks(number, goon, delayed) -{ +function MultipleCallbacks(number, goon, delayed) { this.pending = number; this.goon = goon; this.delayed = delayed; } -function wait_for_cache_index(continue_func) -{ +function wait_for_cache_index(continue_func) { // This callback will not fire before the index is in the ready state. nsICacheStorage.exists() will // no longer throw after this point. get_cache_service().asyncGetDiskConsumption({ - onNetworkCacheDiskConsumption() { continue_func(); }, + onNetworkCacheDiskConsumption() { + continue_func(); + }, // eslint-disable-next-line mozilla/use-chromeutils-generateqi - QueryInterface() { return this; } + QueryInterface() { + return this; + }, }); } -function finish_cache2_test() -{ +function finish_cache2_test() { callbacks.forEach(function(callback, index) { callback.selfCheck(); }); diff --git a/netwerk/test/unit/head_channels.js b/netwerk/test/unit/head_channels.js index f4c3924cacd3..ce8c861f65b2 100644 --- a/netwerk/test/unit/head_channels.js +++ b/netwerk/test/unit/head_channels.js @@ -3,9 +3,9 @@ */ function read_stream(stream, count) { /* assume stream has non-ASCII data */ - var wrapper = - Cc["@mozilla.org/binaryinputstream;1"] - .createInstance(Ci.nsIBinaryInputStream); + var wrapper = Cc["@mozilla.org/binaryinputstream;1"].createInstance( + Ci.nsIBinaryInputStream + ); wrapper.setInputStream(stream); /* JS methods can be called with a maximum of 65535 arguments, and input streams don't have to return all the data they make .available() when @@ -15,10 +15,11 @@ function read_stream(stream, count) { var bytes = wrapper.readByteArray(Math.min(65535, count)); data.push(String.fromCharCode.apply(null, bytes)); count -= bytes.length; - if (bytes.length == 0) + if (bytes.length == 0) { do_throw("Nothing read from input stream!"); + } } - return data.join(''); + return data.join(""); } const CL_EXPECT_FAILURE = 0x1; @@ -64,50 +65,64 @@ ChannelListener.prototype = { _contentLen: -1, _lastEvent: 0, - QueryInterface: ChromeUtils.generateQI(["nsIStreamListener", "nsIRequestObserver"]), + QueryInterface: ChromeUtils.generateQI([ + "nsIStreamListener", + "nsIRequestObserver", + ]), onStartRequest(request) { try { - if (this._got_onstartrequest) + if (this._got_onstartrequest) { do_throw("Got second onStartRequest event!"); + } this._got_onstartrequest = true; this._lastEvent = Date.now(); try { - this._isFromCache = request.QueryInterface(Ci.nsICacheInfoChannel).isFromCache(); + this._isFromCache = request + .QueryInterface(Ci.nsICacheInfoChannel) + .isFromCache(); } catch (e) {} var thrown = false; try { - this._cacheEntryId = request.QueryInterface(Ci.nsICacheInfoChannel).getCacheEntryId(); + this._cacheEntryId = request + .QueryInterface(Ci.nsICacheInfoChannel) + .getCacheEntryId(); } catch (e) { thrown = true; } - if (this._isFromCache && thrown) + if (this._isFromCache && thrown) { do_throw("Should get a CacheEntryId"); - else if (!this._isFromCache && !thrown) + } else if (!this._isFromCache && !thrown) { do_throw("Shouldn't get a CacheEntryId"); + } request.QueryInterface(Ci.nsIChannel); try { this._contentLen = request.contentLength; - } - catch (ex) { - if (!(this._flags & (CL_EXPECT_FAILURE | CL_ALLOW_UNKNOWN_CL))) + } catch (ex) { + if (!(this._flags & (CL_EXPECT_FAILURE | CL_ALLOW_UNKNOWN_CL))) { do_throw("Could not get contentLength"); + } } - if (!request.isPending()) + if (!request.isPending()) { do_throw("request reports itself as not pending from onStartRequest!"); - if (this._contentLen == -1 && !(this._flags & (CL_EXPECT_FAILURE | CL_ALLOW_UNKNOWN_CL))) + } + if ( + this._contentLen == -1 && + !(this._flags & (CL_EXPECT_FAILURE | CL_ALLOW_UNKNOWN_CL)) + ) { do_throw("Content length is unknown in onStartRequest!"); + } - if ((this._flags & CL_FROM_CACHE)) { + if (this._flags & CL_FROM_CACHE) { request.QueryInterface(Ci.nsICachingChannel); if (!request.isFromCache()) { do_throw("Response is not from the cache (CL_FROM_CACHE)"); } } - if ((this._flags & CL_NOT_FROM_CACHE)) { + if (this._flags & CL_NOT_FROM_CACHE) { request.QueryInterface(Ci.nsICachingChannel); if (request.isFromCache()) { do_throw("Response is from the cache (CL_NOT_FROM_CACHE)"); @@ -116,7 +131,9 @@ ChannelListener.prototype = { if (this._flags & CL_SUSPEND) { request.suspend(); - do_timeout(SUSPEND_DELAY, function() { request.resume(); }); + do_timeout(SUSPEND_DELAY, function() { + request.resume(); + }); } } catch (ex) { do_throw("Error in onStartRequest: " + ex); @@ -127,24 +144,35 @@ ChannelListener.prototype = { try { let current = Date.now(); - if (!this._got_onstartrequest) + if (!this._got_onstartrequest) { do_throw("onDataAvailable without onStartRequest event!"); - if (this._got_onstoprequest) + } + if (this._got_onstoprequest) { do_throw("onDataAvailable after onStopRequest event!"); - if (!request.isPending()) + } + if (!request.isPending()) { do_throw("request reports itself as not pending from onDataAvailable!"); - if (this._flags & CL_EXPECT_FAILURE) + } + if (this._flags & CL_EXPECT_FAILURE) { do_throw("Got data despite expecting a failure"); + } - if (current - this._lastEvent >= SUSPEND_DELAY && - !(this._flags & CL_EXPECT_3S_DELAY)) - do_throw("Data received after significant unexpected delay"); - else if (current - this._lastEvent < SUSPEND_DELAY && - this._flags & CL_EXPECT_3S_DELAY) + if ( + current - this._lastEvent >= SUSPEND_DELAY && + !(this._flags & CL_EXPECT_3S_DELAY) + ) { + do_throw("Data received after significant unexpected delay"); + } else if ( + current - this._lastEvent < SUSPEND_DELAY && + this._flags & CL_EXPECT_3S_DELAY + ) { do_throw("Data received sooner than expected"); - else if (current - this._lastEvent >= SUSPEND_DELAY && - this._flags & CL_EXPECT_3S_DELAY) - this._flags &= ~CL_EXPECT_3S_DELAY; // No more delays expected + } else if ( + current - this._lastEvent >= SUSPEND_DELAY && + this._flags & CL_EXPECT_3S_DELAY + ) { + this._flags &= ~CL_EXPECT_3S_DELAY; + } // No more delays expected this._buffer = this._buffer.concat(read_stream(stream, count)); this._lastEvent = current; @@ -156,43 +184,65 @@ ChannelListener.prototype = { onStopRequest(request, status) { try { var success = Components.isSuccessCode(status); - if (!this._got_onstartrequest) + if (!this._got_onstartrequest) { do_throw("onStopRequest without onStartRequest event!"); - if (this._got_onstoprequest) + } + if (this._got_onstoprequest) { do_throw("Got second onStopRequest event!"); + } this._got_onstoprequest = true; - if ((this._flags & (CL_EXPECT_FAILURE | CL_EXPECT_LATE_FAILURE)) && success) - do_throw("Should have failed to load URL (status is " + status.toString(16) + ")"); - else if (!(this._flags & (CL_EXPECT_FAILURE | CL_EXPECT_LATE_FAILURE)) && !success) + if ( + this._flags & (CL_EXPECT_FAILURE | CL_EXPECT_LATE_FAILURE) && + success + ) { + do_throw( + "Should have failed to load URL (status is " + + status.toString(16) + + ")" + ); + } else if ( + !(this._flags & (CL_EXPECT_FAILURE | CL_EXPECT_LATE_FAILURE)) && + !success + ) { do_throw("Failed to load URL: " + status.toString(16)); - if (status != request.status) + } + if (status != request.status) { do_throw("request.status does not match status arg to onStopRequest!"); - if (request.isPending()) + } + if (request.isPending()) { do_throw("request reports itself as pending from onStopRequest!"); - if (!(this._flags & (CL_EXPECT_FAILURE | CL_EXPECT_LATE_FAILURE | CL_IGNORE_CL)) && - !(this._flags & CL_EXPECT_GZIP) && - this._contentLen != -1) - Assert.equal(this._buffer.length, this._contentLen) + } + if ( + !( + this._flags & + (CL_EXPECT_FAILURE | CL_EXPECT_LATE_FAILURE | CL_IGNORE_CL) + ) && + !(this._flags & CL_EXPECT_GZIP) && + this._contentLen != -1 + ) { + Assert.equal(this._buffer.length, this._contentLen); + } } catch (ex) { do_throw("Error in onStopRequest: " + ex); } try { - this._closure(request, - this._buffer, - this._closurectx, - this._isFromCache, - this._cacheEntryId); + this._closure( + request, + this._buffer, + this._closurectx, + this._isFromCache, + this._cacheEntryId + ); this._closurectx = null; } catch (ex) { do_throw("Error in closure function: " + ex); } - } + }, }; var ES_ABORT_REDIRECT = 0x01; -function ChannelEventSink(flags) -{ +function ChannelEventSink(flags) { this._flags = flags; } @@ -200,17 +250,19 @@ ChannelEventSink.prototype = { QueryInterface: ChromeUtils.generateQI(["nsIInterfaceRequestor"]), getInterface(iid) { - if (iid.equals(Ci.nsIChannelEventSink)) + if (iid.equals(Ci.nsIChannelEventSink)) { return this; + } throw Cr.NS_ERROR_NO_INTERFACE; }, asyncOnChannelRedirect(oldChannel, newChannel, flags, callback) { - if (this._flags & ES_ABORT_REDIRECT) + if (this._flags & ES_ABORT_REDIRECT) { throw Cr.NS_BINDING_ABORTED; + } callback.onRedirectVerifyCallback(Cr.NS_OK); - } + }, }; /** @@ -222,12 +274,13 @@ function OriginAttributes(inIsolatedMozBrowser, privateId) { } OriginAttributes.prototype = { inIsolatedMozBrowser: false, - privateBrowsingId: 0 + privateBrowsingId: 0, }; function readFile(file) { - let fstream = Cc["@mozilla.org/network/file-input-stream;1"] - .createInstance(Ci.nsIFileInputStream); + let fstream = Cc["@mozilla.org/network/file-input-stream;1"].createInstance( + Ci.nsIFileInputStream + ); fstream.init(file, -1, 0, 0); let data = NetUtil.readInputStreamToString(fstream, fstream.available()); fstream.close(); @@ -237,9 +290,8 @@ function readFile(file) { function addCertFromFile(certdb, filename, trustString) { let certFile = do_get_file(filename, false); let pem = readFile(certFile) - .replace(/-----BEGIN CERTIFICATE-----/, "") - .replace(/-----END CERTIFICATE-----/, "") - .replace(/[\r\n]/g, ""); + .replace(/-----BEGIN CERTIFICATE-----/, "") + .replace(/-----END CERTIFICATE-----/, "") + .replace(/[\r\n]/g, ""); certdb.addCertFromBase64(pem, trustString); } - diff --git a/netwerk/test/unit/head_cookies.js b/netwerk/test/unit/head_cookies.js index c9fe143a49f3..27664aeaa944 100644 --- a/netwerk/test/unit/head_cookies.js +++ b/netwerk/test/unit/head_cookies.js @@ -2,37 +2,46 @@ * http://creativecommons.org/publicdomain/zero/1.0/ */ -const {NetUtil} = ChromeUtils.import("resource://gre/modules/NetUtil.jsm"); +const { NetUtil } = ChromeUtils.import("resource://gre/modules/NetUtil.jsm"); -XPCOMUtils.defineLazyServiceGetter(Services, "cookies", - "@mozilla.org/cookieService;1", - "nsICookieService"); -XPCOMUtils.defineLazyServiceGetter(Services, "cookiemgr", - "@mozilla.org/cookiemanager;1", - "nsICookieManager"); +XPCOMUtils.defineLazyServiceGetter( + Services, + "cookies", + "@mozilla.org/cookieService;1", + "nsICookieService" +); +XPCOMUtils.defineLazyServiceGetter( + Services, + "cookiemgr", + "@mozilla.org/cookiemanager;1", + "nsICookieManager" +); -XPCOMUtils.defineLazyServiceGetter(Services, "etld", - "@mozilla.org/network/effective-tld-service;1", - "nsIEffectiveTLDService"); +XPCOMUtils.defineLazyServiceGetter( + Services, + "etld", + "@mozilla.org/network/effective-tld-service;1", + "nsIEffectiveTLDService" +); -function do_check_throws(f, result, stack) -{ - if (!stack) +function do_check_throws(f, result, stack) { + if (!stack) { stack = Components.stack.caller; + } try { f(); } catch (exc) { - if (exc.result == result) + if (exc.result == result) { return; + } do_throw("expected result " + result + ", caught " + exc, stack); } do_throw("expected result " + result + ", none thrown", stack); } // Helper to step a generator function and catch a StopIteration exception. -function do_run_generator(generator) -{ +function do_run_generator(generator) { try { generator.next(); } catch (e) { @@ -41,8 +50,7 @@ function do_run_generator(generator) } // Helper to finish a generator function test. -function do_finish_generator_test(generator) -{ +function do_finish_generator_test(generator) { executeSoon(function() { generator.return(); do_test_finished(); @@ -57,19 +65,20 @@ function _observer(generator, topic) { } _observer.prototype = { - observe (subject, topic, data) { + observe(subject, topic, data) { Assert.equal(this.topic, topic); Services.obs.removeObserver(this, this.topic); // Continue executing the generator function. - if (this.generator) + if (this.generator) { do_run_generator(this.generator); + } this.generator = null; this.topic = null; - } -} + }, +}; // Close the cookie database. If a generator is supplied, it will be invoked // once the close is complete. @@ -96,7 +105,14 @@ function do_load_profile(generator) { // Set a single session cookie using http and test the cookie count // against 'expected' function do_set_single_http_cookie(uri, channel, expected) { - Services.cookies.setCookieStringFromHttp(uri, null, null, "foo=bar", null, channel); + Services.cookies.setCookieStringFromHttp( + uri, + null, + null, + "foo=bar", + null, + channel + ); Assert.equal(Services.cookiemgr.countCookiesFromHost(uri.host), expected); } @@ -112,10 +128,24 @@ function do_set_cookies(uri, channel, session, expected) { Services.cookies.setCookieString(uri, null, "can=has" + suffix, channel); Assert.equal(Services.cookiemgr.countCookiesFromHost(uri.host), expected[1]); // without channel, from http - Services.cookies.setCookieStringFromHttp(uri, null, null, "cheez=burger" + suffix, null, null); + Services.cookies.setCookieStringFromHttp( + uri, + null, + null, + "cheez=burger" + suffix, + null, + null + ); Assert.equal(Services.cookiemgr.countCookiesFromHost(uri.host), expected[2]); // with channel, from http - Services.cookies.setCookieStringFromHttp(uri, null, null, "hot=dog" + suffix, null, channel); + Services.cookies.setCookieStringFromHttp( + uri, + null, + null, + "hot=dog" + suffix, + null, + channel + ); Assert.equal(Services.cookiemgr.countCookiesFromHost(uri.host), expected[3]); } @@ -133,17 +163,18 @@ function do_count_cookies() { } // Helper object to store cookie data. -function Cookie(name, - value, - host, - path, - expiry, - lastAccessed, - creationTime, - isSession, - isSecure, - isHttpOnly) -{ +function Cookie( + name, + value, + host, + path, + expiry, + lastAccessed, + creationTime, + isSession, + isSecure, + isHttpOnly +) { this.name = name; this.value = value; this.host = host; @@ -155,33 +186,35 @@ function Cookie(name, this.isSecure = isSecure; this.isHttpOnly = isHttpOnly; - let strippedHost = host.charAt(0) == '.' ? host.slice(1) : host; + let strippedHost = host.charAt(0) == "." ? host.slice(1) : host; try { this.baseDomain = Services.etld.getBaseDomainFromHost(strippedHost); } catch (e) { - if (e.result == Cr.NS_ERROR_HOST_IS_IP_ADDRESS || - e.result == Cr.NS_ERROR_INSUFFICIENT_DOMAIN_LEVELS) + if ( + e.result == Cr.NS_ERROR_HOST_IS_IP_ADDRESS || + e.result == Cr.NS_ERROR_INSUFFICIENT_DOMAIN_LEVELS + ) { this.baseDomain = strippedHost; + } } } // Object representing a database connection and associated statements. The // implementation varies depending on schema version. -function CookieDatabaseConnection(file, schema) -{ +function CookieDatabaseConnection(file, schema) { // Manually generate a cookies.sqlite file with appropriate rows, columns, // and schema version. If it already exists, just set up our statements. let exists = file.exists(); this.db = Services.storage.openDatabase(file); this.schema = schema; - if (!exists) + if (!exists) { this.db.schemaVersion = schema; + } switch (schema) { - case 1: - { + case 1: { if (!exists) { this.db.executeSimpleSQL( "CREATE TABLE moz_cookies ( \ @@ -192,7 +225,8 @@ function CookieDatabaseConnection(file, schema) path TEXT, \ expiry INTEGER, \ isSecure INTEGER, \ - isHttpOnly INTEGER)"); + isHttpOnly INTEGER)" + ); } this.stmtInsert = this.db.createStatement( @@ -213,16 +247,17 @@ function CookieDatabaseConnection(file, schema) :path, \ :expiry, \ :isSecure, \ - :isHttpOnly)"); + :isHttpOnly)" + ); this.stmtDelete = this.db.createStatement( - "DELETE FROM moz_cookies WHERE id = :id"); + "DELETE FROM moz_cookies WHERE id = :id" + ); break; } - case 2: - { + case 2: { if (!exists) { this.db.executeSimpleSQL( "CREATE TABLE moz_cookies ( \ @@ -234,7 +269,8 @@ function CookieDatabaseConnection(file, schema) expiry INTEGER, \ lastAccessed INTEGER, \ isSecure INTEGER, \ - isHttpOnly INTEGER)"); + isHttpOnly INTEGER)" + ); } this.stmtInsert = this.db.createStatement( @@ -257,19 +293,21 @@ function CookieDatabaseConnection(file, schema) :expiry, \ :lastAccessed, \ :isSecure, \ - :isHttpOnly)"); + :isHttpOnly)" + ); this.stmtDelete = this.db.createStatement( - "DELETE FROM moz_cookies WHERE id = :id"); + "DELETE FROM moz_cookies WHERE id = :id" + ); this.stmtUpdate = this.db.createStatement( - "UPDATE moz_cookies SET lastAccessed = :lastAccessed WHERE id = :id"); + "UPDATE moz_cookies SET lastAccessed = :lastAccessed WHERE id = :id" + ); break; } - case 3: - { + case 3: { if (!exists) { this.db.executeSimpleSQL( "CREATE TABLE moz_cookies ( \ @@ -282,10 +320,12 @@ function CookieDatabaseConnection(file, schema) expiry INTEGER, \ lastAccessed INTEGER, \ isSecure INTEGER, \ - isHttpOnly INTEGER)"); + isHttpOnly INTEGER)" + ); this.db.executeSimpleSQL( - "CREATE INDEX moz_basedomain ON moz_cookies (baseDomain)"); + "CREATE INDEX moz_basedomain ON moz_cookies (baseDomain)" + ); } this.stmtInsert = this.db.createStatement( @@ -310,19 +350,21 @@ function CookieDatabaseConnection(file, schema) :expiry, \ :lastAccessed, \ :isSecure, \ - :isHttpOnly)"); + :isHttpOnly)" + ); this.stmtDelete = this.db.createStatement( - "DELETE FROM moz_cookies WHERE id = :id"); + "DELETE FROM moz_cookies WHERE id = :id" + ); this.stmtUpdate = this.db.createStatement( - "UPDATE moz_cookies SET lastAccessed = :lastAccessed WHERE id = :id"); + "UPDATE moz_cookies SET lastAccessed = :lastAccessed WHERE id = :id" + ); break; } - case 4: - { + case 4: { if (!exists) { this.db.executeSimpleSQL( "CREATE TABLE moz_cookies ( \ @@ -337,13 +379,14 @@ function CookieDatabaseConnection(file, schema) creationTime INTEGER, \ isSecure INTEGER, \ isHttpOnly INTEGER \ - CONSTRAINT moz_uniqueid UNIQUE (name, host, path))"); + CONSTRAINT moz_uniqueid UNIQUE (name, host, path))" + ); this.db.executeSimpleSQL( - "CREATE INDEX moz_basedomain ON moz_cookies (baseDomain)"); + "CREATE INDEX moz_basedomain ON moz_cookies (baseDomain)" + ); - this.db.executeSimpleSQL( - "PRAGMA journal_mode = WAL"); + this.db.executeSimpleSQL("PRAGMA journal_mode = WAL"); } this.stmtInsert = this.db.createStatement( @@ -368,162 +411,160 @@ function CookieDatabaseConnection(file, schema) :lastAccessed, \ :creationTime, \ :isSecure, \ - :isHttpOnly)"); + :isHttpOnly)" + ); this.stmtDelete = this.db.createStatement( "DELETE FROM moz_cookies \ - WHERE name = :name AND host = :host AND path = :path"); + WHERE name = :name AND host = :host AND path = :path" + ); this.stmtUpdate = this.db.createStatement( "UPDATE moz_cookies SET lastAccessed = :lastAccessed \ - WHERE name = :name AND host = :host AND path = :path"); + WHERE name = :name AND host = :host AND path = :path" + ); break; } - default: - do_throw("unrecognized schemaVersion!"); + default: + do_throw("unrecognized schemaVersion!"); } } -CookieDatabaseConnection.prototype = -{ - insertCookie(cookie) - { - if (!(cookie instanceof Cookie)) +CookieDatabaseConnection.prototype = { + insertCookie(cookie) { + if (!(cookie instanceof Cookie)) { do_throw("not a cookie"); + } - switch (this.schema) - { - case 1: - this.stmtInsert.bindByName("id", cookie.creationTime); - this.stmtInsert.bindByName("name", cookie.name); - this.stmtInsert.bindByName("value", cookie.value); - this.stmtInsert.bindByName("host", cookie.host); - this.stmtInsert.bindByName("path", cookie.path); - this.stmtInsert.bindByName("expiry", cookie.expiry); - this.stmtInsert.bindByName("isSecure", cookie.isSecure); - this.stmtInsert.bindByName("isHttpOnly", cookie.isHttpOnly); - break; + switch (this.schema) { + case 1: + this.stmtInsert.bindByName("id", cookie.creationTime); + this.stmtInsert.bindByName("name", cookie.name); + this.stmtInsert.bindByName("value", cookie.value); + this.stmtInsert.bindByName("host", cookie.host); + this.stmtInsert.bindByName("path", cookie.path); + this.stmtInsert.bindByName("expiry", cookie.expiry); + this.stmtInsert.bindByName("isSecure", cookie.isSecure); + this.stmtInsert.bindByName("isHttpOnly", cookie.isHttpOnly); + break; - case 2: - this.stmtInsert.bindByName("id", cookie.creationTime); - this.stmtInsert.bindByName("name", cookie.name); - this.stmtInsert.bindByName("value", cookie.value); - this.stmtInsert.bindByName("host", cookie.host); - this.stmtInsert.bindByName("path", cookie.path); - this.stmtInsert.bindByName("expiry", cookie.expiry); - this.stmtInsert.bindByName("lastAccessed", cookie.lastAccessed); - this.stmtInsert.bindByName("isSecure", cookie.isSecure); - this.stmtInsert.bindByName("isHttpOnly", cookie.isHttpOnly); - break; + case 2: + this.stmtInsert.bindByName("id", cookie.creationTime); + this.stmtInsert.bindByName("name", cookie.name); + this.stmtInsert.bindByName("value", cookie.value); + this.stmtInsert.bindByName("host", cookie.host); + this.stmtInsert.bindByName("path", cookie.path); + this.stmtInsert.bindByName("expiry", cookie.expiry); + this.stmtInsert.bindByName("lastAccessed", cookie.lastAccessed); + this.stmtInsert.bindByName("isSecure", cookie.isSecure); + this.stmtInsert.bindByName("isHttpOnly", cookie.isHttpOnly); + break; - case 3: - this.stmtInsert.bindByName("id", cookie.creationTime); - this.stmtInsert.bindByName("baseDomain", cookie.baseDomain); - this.stmtInsert.bindByName("name", cookie.name); - this.stmtInsert.bindByName("value", cookie.value); - this.stmtInsert.bindByName("host", cookie.host); - this.stmtInsert.bindByName("path", cookie.path); - this.stmtInsert.bindByName("expiry", cookie.expiry); - this.stmtInsert.bindByName("lastAccessed", cookie.lastAccessed); - this.stmtInsert.bindByName("isSecure", cookie.isSecure); - this.stmtInsert.bindByName("isHttpOnly", cookie.isHttpOnly); - break; + case 3: + this.stmtInsert.bindByName("id", cookie.creationTime); + this.stmtInsert.bindByName("baseDomain", cookie.baseDomain); + this.stmtInsert.bindByName("name", cookie.name); + this.stmtInsert.bindByName("value", cookie.value); + this.stmtInsert.bindByName("host", cookie.host); + this.stmtInsert.bindByName("path", cookie.path); + this.stmtInsert.bindByName("expiry", cookie.expiry); + this.stmtInsert.bindByName("lastAccessed", cookie.lastAccessed); + this.stmtInsert.bindByName("isSecure", cookie.isSecure); + this.stmtInsert.bindByName("isHttpOnly", cookie.isHttpOnly); + break; - case 4: - this.stmtInsert.bindByName("baseDomain", cookie.baseDomain); - this.stmtInsert.bindByName("name", cookie.name); - this.stmtInsert.bindByName("value", cookie.value); - this.stmtInsert.bindByName("host", cookie.host); - this.stmtInsert.bindByName("path", cookie.path); - this.stmtInsert.bindByName("expiry", cookie.expiry); - this.stmtInsert.bindByName("lastAccessed", cookie.lastAccessed); - this.stmtInsert.bindByName("creationTime", cookie.creationTime); - this.stmtInsert.bindByName("isSecure", cookie.isSecure); - this.stmtInsert.bindByName("isHttpOnly", cookie.isHttpOnly); - break; + case 4: + this.stmtInsert.bindByName("baseDomain", cookie.baseDomain); + this.stmtInsert.bindByName("name", cookie.name); + this.stmtInsert.bindByName("value", cookie.value); + this.stmtInsert.bindByName("host", cookie.host); + this.stmtInsert.bindByName("path", cookie.path); + this.stmtInsert.bindByName("expiry", cookie.expiry); + this.stmtInsert.bindByName("lastAccessed", cookie.lastAccessed); + this.stmtInsert.bindByName("creationTime", cookie.creationTime); + this.stmtInsert.bindByName("isSecure", cookie.isSecure); + this.stmtInsert.bindByName("isHttpOnly", cookie.isHttpOnly); + break; - default: - do_throw("unrecognized schemaVersion!"); + default: + do_throw("unrecognized schemaVersion!"); } do_execute_stmt(this.stmtInsert); }, - deleteCookie(cookie) - { - if (!(cookie instanceof Cookie)) + deleteCookie(cookie) { + if (!(cookie instanceof Cookie)) { do_throw("not a cookie"); + } - switch (this.db.schemaVersion) - { - case 1: - case 2: - case 3: - this.stmtDelete.bindByName("id", cookie.creationTime); - break; + switch (this.db.schemaVersion) { + case 1: + case 2: + case 3: + this.stmtDelete.bindByName("id", cookie.creationTime); + break; - case 4: - this.stmtDelete.bindByName("name", cookie.name); - this.stmtDelete.bindByName("host", cookie.host); - this.stmtDelete.bindByName("path", cookie.path); - break; + case 4: + this.stmtDelete.bindByName("name", cookie.name); + this.stmtDelete.bindByName("host", cookie.host); + this.stmtDelete.bindByName("path", cookie.path); + break; - default: - do_throw("unrecognized schemaVersion!"); + default: + do_throw("unrecognized schemaVersion!"); } do_execute_stmt(this.stmtDelete); }, - updateCookie(cookie) - { - if (!(cookie instanceof Cookie)) + updateCookie(cookie) { + if (!(cookie instanceof Cookie)) { do_throw("not a cookie"); + } - switch (this.db.schemaVersion) - { - case 1: - do_throw("can't update a schema 1 cookie!"); + switch (this.db.schemaVersion) { + case 1: + do_throw("can't update a schema 1 cookie!"); - case 2: - case 3: - this.stmtUpdate.bindByName("id", cookie.creationTime); - this.stmtUpdate.bindByName("lastAccessed", cookie.lastAccessed); - break; + case 2: + case 3: + this.stmtUpdate.bindByName("id", cookie.creationTime); + this.stmtUpdate.bindByName("lastAccessed", cookie.lastAccessed); + break; - case 4: - this.stmtDelete.bindByName("name", cookie.name); - this.stmtDelete.bindByName("host", cookie.host); - this.stmtDelete.bindByName("path", cookie.path); - this.stmtUpdate.bindByName("lastAccessed", cookie.lastAccessed); - break; + case 4: + this.stmtDelete.bindByName("name", cookie.name); + this.stmtDelete.bindByName("host", cookie.host); + this.stmtDelete.bindByName("path", cookie.path); + this.stmtUpdate.bindByName("lastAccessed", cookie.lastAccessed); + break; - default: - do_throw("unrecognized schemaVersion!"); + default: + do_throw("unrecognized schemaVersion!"); } do_execute_stmt(this.stmtUpdate); }, - close() - { + close() { this.stmtInsert.finalize(); this.stmtDelete.finalize(); - if (this.stmtUpdate) + if (this.stmtUpdate) { this.stmtUpdate.finalize(); + } this.db.close(); this.stmtInsert = null; this.stmtDelete = null; this.stmtUpdate = null; this.db = null; - } -} + }, +}; -function do_get_cookie_file(profile) -{ +function do_get_cookie_file(profile) { let file = profile.clone(); file.append("cookies.sqlite"); return file; @@ -531,16 +572,15 @@ function do_get_cookie_file(profile) // Count the cookies from 'host' in a database. If 'host' is null, count all // cookies. -function do_count_cookies_in_db(connection, host) -{ +function do_count_cookies_in_db(connection, host) { let select = null; if (host) { select = connection.createStatement( - "SELECT COUNT(1) FROM moz_cookies WHERE host = :host"); + "SELECT COUNT(1) FROM moz_cookies WHERE host = :host" + ); select.bindByName("host", host); } else { - select = connection.createStatement( - "SELECT COUNT(1) FROM moz_cookies"); + select = connection.createStatement("SELECT COUNT(1) FROM moz_cookies"); } select.executeStep(); @@ -551,8 +591,7 @@ function do_count_cookies_in_db(connection, host) } // Execute 'stmt', ensuring that we reset it if it throws. -function do_execute_stmt(stmt) -{ +function do_execute_stmt(stmt) { try { stmt.executeStep(); stmt.reset(); diff --git a/netwerk/test/unit/socks_client_subprocess.js b/netwerk/test/unit/socks_client_subprocess.js index c9a6d49c0d98..c1e6a5dcaab1 100644 --- a/netwerk/test/unit/socks_client_subprocess.js +++ b/netwerk/test/unit/socks_client_subprocess.js @@ -1,40 +1,58 @@ var CC = Components.Constructor; -const BinaryInputStream = CC("@mozilla.org/binaryinputstream;1", - "nsIBinaryInputStream", - "setInputStream"); -const ProtocolProxyService = CC("@mozilla.org/network/protocol-proxy-service;1", - "nsIProtocolProxyService"); -var sts = Cc["@mozilla.org/network/socket-transport-service;1"] - .getService(Ci.nsISocketTransportService); +const BinaryInputStream = CC( + "@mozilla.org/binaryinputstream;1", + "nsIBinaryInputStream", + "setInputStream" +); +const ProtocolProxyService = CC( + "@mozilla.org/network/protocol-proxy-service;1", + "nsIProtocolProxyService" +); +var sts = Cc["@mozilla.org/network/socket-transport-service;1"].getService( + Ci.nsISocketTransportService +); -function launchConnection(socks_vers, socks_port, dest_host, dest_port, dns) -{ +function launchConnection(socks_vers, socks_port, dest_host, dest_port, dns) { var pi_flags = 0; - if (dns == 'remote') + if (dns == "remote") { pi_flags = Ci.nsIProxyInfo.TRANSPARENT_PROXY_RESOLVES_HOST; - + } + var pps = new ProtocolProxyService(); - var pi = pps.newProxyInfo(socks_vers, 'localhost', socks_port, '', '', - pi_flags, -1, null); + var pi = pps.newProxyInfo( + socks_vers, + "localhost", + socks_port, + "", + "", + pi_flags, + -1, + null + ); var trans = sts.createTransport([], dest_host, dest_port, pi); - var input = trans.openInputStream(Ci.nsITransport.OPEN_BLOCKING,0,0); - var output = trans.openOutputStream(Ci.nsITransport.OPEN_BLOCKING,0,0); + var input = trans.openInputStream(Ci.nsITransport.OPEN_BLOCKING, 0, 0); + var output = trans.openOutputStream(Ci.nsITransport.OPEN_BLOCKING, 0, 0); var bin = new BinaryInputStream(input); var data = bin.readBytes(5); - if (data == 'PING!') { - print('client: got ping, sending pong.'); - output.write('PONG!', 5); + if (data == "PING!") { + print("client: got ping, sending pong."); + output.write("PONG!", 5); } else { - print('client: wrong data from server:', data); - output.write('Error: wrong data received.', 27); + print("client: wrong data from server:", data); + output.write("Error: wrong data received.", 27); } output.close(); } for (var arg of arguments) { - print('client: running test', arg); - test = arg.split('|'); - launchConnection(test[0], parseInt(test[1]), test[2], - parseInt(test[3]), test[4]); + print("client: running test", arg); + test = arg.split("|"); + launchConnection( + test[0], + parseInt(test[1]), + test[2], + parseInt(test[3]), + test[4] + ); } diff --git a/netwerk/test/unit/test_1073747.js b/netwerk/test/unit/test_1073747.js index 20cb20e014c1..64afb7e7a505 100644 --- a/netwerk/test/unit/test_1073747.js +++ b/netwerk/test/unit/test_1073747.js @@ -1,30 +1,42 @@ // Test based on submitted one from Peter B Shalimoff -var test = function(s, funcName){ - function Arg(){}; - Arg.prototype.toString = function(){ - info("Testing " + funcName + " with null args"); - return this.value; - }; - // create a generic arg lits of null, -1, and 10 nulls - var args = [s, -1]; - for (var i = 0; i < 10; ++i) { - args.push(new Arg()); - } - var up = Cc["@mozilla.org/network/url-parser;1?auth=maybe"].getService(Ci.nsIURLParser); - try { - up[funcName].apply(up, args); - return args; - } catch (x) { - Assert.ok(true); // make sure it throws an exception instead of crashing - return x; - } - // should always have an exception to catch - Assert.ok(false); +var test = function(s, funcName) { + function Arg() {} + Arg.prototype.toString = function() { + info("Testing " + funcName + " with null args"); + return this.value; + }; + // create a generic arg lits of null, -1, and 10 nulls + var args = [s, -1]; + for (var i = 0; i < 10; ++i) { + args.push(new Arg()); + } + var up = Cc["@mozilla.org/network/url-parser;1?auth=maybe"].getService( + Ci.nsIURLParser + ); + try { + up[funcName].apply(up, args); + return args; + } catch (x) { + Assert.ok(true); // make sure it throws an exception instead of crashing + return x; + } + // should always have an exception to catch + Assert.ok(false); }; var s = null; -var funcs = ["parseAuthority", "parseFileName", "parseFilePath", "parsePath", "parseServerInfo", "parseURL", "parseUserInfo"]; +var funcs = [ + "parseAuthority", + "parseFileName", + "parseFilePath", + "parsePath", + "parseServerInfo", + "parseURL", + "parseUserInfo", +]; function run_test() { - funcs.forEach(function(f){test(s, f);}); + funcs.forEach(function(f) { + test(s, f); + }); } diff --git a/netwerk/test/unit/test_304_responses.js b/netwerk/test/unit/test_304_responses.js index 6004193183e4..56ebd1183221 100644 --- a/netwerk/test/unit/test_304_responses.js +++ b/netwerk/test/unit/test_304_responses.js @@ -1,7 +1,7 @@ "use strict"; // https://bugzilla.mozilla.org/show_bug.cgi?id=761228 -const {HttpServer} = ChromeUtils.import("resource://testing-common/httpd.js"); +const { HttpServer } = ChromeUtils.import("resource://testing-common/httpd.js"); XPCOMUtils.defineLazyGetter(this, "URL", function() { return "http://localhost:" + httpServer.identity.primaryPort; @@ -19,20 +19,22 @@ const unexpected304 = "unexpected304"; const existingCached304 = "existingCached304"; function make_uri(url) { - var ios = Cc["@mozilla.org/network/io-service;1"]. - getService(Ci.nsIIOService); + var ios = Cc["@mozilla.org/network/io-service;1"].getService(Ci.nsIIOService); return ios.newURI(url); } function make_channel(url) { - return NetUtil.newChannel({uri: url, loadUsingSystemPrincipal: true}) - .QueryInterface(Ci.nsIHttpChannel); + return NetUtil.newChannel({ + uri: url, + loadUsingSystemPrincipal: true, + }).QueryInterface(Ci.nsIHttpChannel); } function clearCache() { - var service = Cc["@mozilla.org/netwerk/cache-storage-service;1"] - .getService(Ci.nsICacheStorageService); - service.clear(); + var service = Cc["@mozilla.org/netwerk/cache-storage-service;1"].getService( + Ci.nsICacheStorageService + ); + service.clear(); } function alwaysReturn304Handler(metadata, response) { @@ -44,10 +46,14 @@ function run_test() { evict_cache_entries(); httpServer = new HttpServer(); - httpServer.registerPathHandler(basePath + unexpected304, - alwaysReturn304Handler); - httpServer.registerPathHandler(basePath + existingCached304, - alwaysReturn304Handler); + httpServer.registerPathHandler( + basePath + unexpected304, + alwaysReturn304Handler + ); + httpServer.registerPathHandler( + basePath + existingCached304, + alwaysReturn304Handler + ); httpServer.start(-1); run_next_test(); } @@ -74,12 +80,16 @@ add_test(function test_unexpected_304() { // the cache. add_test(function test_304_stored_in_cache() { asyncOpenCacheEntry( - baseURI + existingCached304, "disk", Ci.nsICacheStorage.OPEN_NORMALLY, null, - function (entryStatus, cacheEntry) { + baseURI + existingCached304, + "disk", + Ci.nsICacheStorage.OPEN_NORMALLY, + null, + function(entryStatus, cacheEntry) { cacheEntry.setMetaDataElement("request-method", "GET"); - cacheEntry.setMetaDataElement("response-head", - "HTTP/1.1 304 Not Modified\r\n" + - "\r\n"); + cacheEntry.setMetaDataElement( + "response-head", + "HTTP/1.1 304 Not Modified\r\n" + "\r\n" + ); cacheEntry.metaDataReady(); cacheEntry.close(); @@ -90,5 +100,6 @@ add_test(function test_304_stored_in_cache() { chan.setRequestHeader("If-None-Match", '"foo"', false); chan.asyncOpen(new ChannelListener(consume304, null)); - }); + } + ); }); diff --git a/netwerk/test/unit/test_307_redirect.js b/netwerk/test/unit/test_307_redirect.js index 791ff67e746a..0d1c85c46a1c 100644 --- a/netwerk/test/unit/test_307_redirect.js +++ b/netwerk/test/unit/test_307_redirect.js @@ -1,4 +1,4 @@ -const {HttpServer} = ChromeUtils.import("resource://testing-common/httpd.js"); +const { HttpServer } = ChromeUtils.import("resource://testing-common/httpd.js"); XPCOMUtils.defineLazyGetter(this, "URL", function() { return "http://localhost:" + httpserver.identity.primaryPort; @@ -15,75 +15,80 @@ XPCOMUtils.defineLazyGetter(this, "noRedirectURI", function() { var httpserver = null; function make_channel(url) { - return NetUtil.newChannel({uri: url, loadUsingSystemPrincipal: true}); + return NetUtil.newChannel({ uri: url, loadUsingSystemPrincipal: true }); } const requestBody = "request body"; -function redirectHandler(metadata, response) -{ +function redirectHandler(metadata, response) { response.setStatusLine(metadata.httpVersion, 307, "Moved Temporarily"); response.setHeader("Location", noRedirectURI, false); } -function contentHandler(metadata, response) -{ +function contentHandler(metadata, response) { response.setHeader("Content-Type", "text/plain"); - response.bodyOutputStream.writeFrom(metadata.bodyInputStream, - metadata.bodyInputStream.available()); + response.bodyOutputStream.writeFrom( + metadata.bodyInputStream, + metadata.bodyInputStream.available() + ); } -function noRedirectStreamObserver(request, buffer) -{ +function noRedirectStreamObserver(request, buffer) { Assert.equal(buffer, requestBody); var chan = make_channel(uri); - var uploadStream = Cc["@mozilla.org/io/string-input-stream;1"] - .createInstance(Ci.nsIStringInputStream); + var uploadStream = Cc["@mozilla.org/io/string-input-stream;1"].createInstance( + Ci.nsIStringInputStream + ); uploadStream.setData(requestBody, requestBody.length); - chan.QueryInterface(Ci.nsIUploadChannel).setUploadStream(uploadStream, - "text/plain", - -1); + chan + .QueryInterface(Ci.nsIUploadChannel) + .setUploadStream(uploadStream, "text/plain", -1); chan.asyncOpen(new ChannelListener(noHeaderStreamObserver, null)); } -function noHeaderStreamObserver(request, buffer) -{ +function noHeaderStreamObserver(request, buffer) { Assert.equal(buffer, requestBody); var chan = make_channel(uri); - var uploadStream = Cc["@mozilla.org/io/string-input-stream;1"] - .createInstance(Ci.nsIStringInputStream); - var streamBody = "Content-Type: text/plain\r\n" + - "Content-Length: " + requestBody.length + "\r\n\r\n" + - requestBody; + var uploadStream = Cc["@mozilla.org/io/string-input-stream;1"].createInstance( + Ci.nsIStringInputStream + ); + var streamBody = + "Content-Type: text/plain\r\n" + + "Content-Length: " + + requestBody.length + + "\r\n\r\n" + + requestBody; uploadStream.setData(streamBody, streamBody.length); - chan.QueryInterface(Ci.nsIUploadChannel).setUploadStream(uploadStream, "", -1); + chan + .QueryInterface(Ci.nsIUploadChannel) + .setUploadStream(uploadStream, "", -1); chan.asyncOpen(new ChannelListener(headerStreamObserver, null)); } -function headerStreamObserver(request, buffer) -{ +function headerStreamObserver(request, buffer) { Assert.equal(buffer, requestBody); httpserver.stop(do_test_finished); } -function run_test() -{ +function run_test() { httpserver = new HttpServer(); httpserver.registerPathHandler("/redirect", redirectHandler); httpserver.registerPathHandler("/content", contentHandler); httpserver.start(-1); - var prefs = Cc["@mozilla.org/preferences-service;1"] - .getService(Ci.nsIPrefBranch); + var prefs = Cc["@mozilla.org/preferences-service;1"].getService( + Ci.nsIPrefBranch + ); prefs.setBoolPref("network.http.prompt-temp-redirect", false); var chan = make_channel(noRedirectURI); - var uploadStream = Cc["@mozilla.org/io/string-input-stream;1"] - .createInstance(Ci.nsIStringInputStream); + var uploadStream = Cc["@mozilla.org/io/string-input-stream;1"].createInstance( + Ci.nsIStringInputStream + ); uploadStream.setData(requestBody, requestBody.length); - chan.QueryInterface(Ci.nsIUploadChannel).setUploadStream(uploadStream, - "text/plain", - -1); + chan + .QueryInterface(Ci.nsIUploadChannel) + .setUploadStream(uploadStream, "text/plain", -1); chan.asyncOpen(new ChannelListener(noRedirectStreamObserver, null)); do_test_pending(); } diff --git a/netwerk/test/unit/test_421.js b/netwerk/test/unit/test_421.js index c5690640cd4c..cf9842ac208c 100644 --- a/netwerk/test/unit/test_421.js +++ b/netwerk/test/unit/test_421.js @@ -1,4 +1,4 @@ -const {HttpServer} = ChromeUtils.import("resource://testing-common/httpd.js"); +const { HttpServer } = ChromeUtils.import("resource://testing-common/httpd.js"); XPCOMUtils.defineLazyGetter(this, "URL", function() { return "http://localhost:" + httpserver.identity.primaryPort; @@ -25,7 +25,10 @@ function setup_test() { } function setupChannel(path) { - var chan = NetUtil.newChannel({uri: URL + path, loadUsingSystemPrincipal: true}); + var chan = NetUtil.newChannel({ + uri: URL + path, + loadUsingSystemPrincipal: true, + }); chan.QueryInterface(Ci.nsIHttpChannel); chan.requestMethod = "GET"; return chan; diff --git a/netwerk/test/unit/test_MIME_params.js b/netwerk/test/unit/test_MIME_params.js index 81e49ddb44df..34698a3c7cf0 100644 --- a/netwerk/test/unit/test_MIME_params.js +++ b/netwerk/test/unit/test_MIME_params.js @@ -5,8 +5,8 @@ * See also https://bugzilla.mozilla.org/show_bug.cgi?id=609667 */ -var BS = '\\'; -var DQUOTE = '"'; +var BS = "\\"; +var DQUOTE = '"'; // Test array: // - element 0: "Content-Disposition" header to test @@ -17,329 +17,431 @@ var DQUOTE = '"'; // (currently supports continuations; expected results without continuations // are commented out for now) // - element 3: correct value returned for disposition-type (empty param name) -// - element 4: correct value for filename returned +// - element 4: correct value for filename returned // // 3 and 4 may be left out if they are identical var tests = [ // No filename parameter: return nothing - ["attachment;", - "attachment", Cr.NS_ERROR_INVALID_ARG], + ["attachment;", "attachment", Cr.NS_ERROR_INVALID_ARG], // basic - ["attachment; filename=basic", - "attachment", "basic"], + ["attachment; filename=basic", "attachment", "basic"], // extended - ["attachment; filename*=UTF-8''extended", - "attachment", "extended"], + ["attachment; filename*=UTF-8''extended", "attachment", "extended"], // prefer extended to basic (bug 588781) - ["attachment; filename=basic; filename*=UTF-8''extended", - "attachment", "extended"], + [ + "attachment; filename=basic; filename*=UTF-8''extended", + "attachment", + "extended", + ], // prefer extended to basic (bug 588781) - ["attachment; filename*=UTF-8''extended; filename=basic", - "attachment", "extended"], + [ + "attachment; filename*=UTF-8''extended; filename=basic", + "attachment", + "extended", + ], // use first basic value (invalid; error recovery) - ["attachment; filename=first; filename=wrong", - "attachment", "first"], + ["attachment; filename=first; filename=wrong", "attachment", "first"], // old school bad HTTP servers: missing 'attachment' or 'inline' // (invalid; error recovery) - ["filename=old", - "filename=old", "old"], + ["filename=old", "filename=old", "old"], - ["attachment; filename*=UTF-8''extended", - "attachment", "extended"], + ["attachment; filename*=UTF-8''extended", "attachment", "extended"], // continuations not part of RFC 5987 (bug 610054) - ["attachment; filename*0=foo; filename*1=bar", - "attachment", "foobar", - /* "attachment", Cr.NS_ERROR_INVALID_ARG */], + [ + "attachment; filename*0=foo; filename*1=bar", + "attachment", + "foobar", + /* "attachment", Cr.NS_ERROR_INVALID_ARG */ + ], // Return first continuation (invalid; error recovery) - ["attachment; filename*0=first; filename*0=wrong; filename=basic", - "attachment", "first", - /* "attachment", "basic" */], + [ + "attachment; filename*0=first; filename*0=wrong; filename=basic", + "attachment", + "first", + /* "attachment", "basic" */ + ], // Only use correctly ordered continuations (invalid; error recovery) - ["attachment; filename*0=first; filename*1=second; filename*0=wrong", - "attachment", "firstsecond", - /* "attachment", Cr.NS_ERROR_INVALID_ARG */], + [ + "attachment; filename*0=first; filename*1=second; filename*0=wrong", + "attachment", + "firstsecond", + /* "attachment", Cr.NS_ERROR_INVALID_ARG */ + ], // prefer continuation to basic (unless RFC 5987) - ["attachment; filename=basic; filename*0=foo; filename*1=bar", - "attachment", "foobar", - /* "attachment", "basic" */], + [ + "attachment; filename=basic; filename*0=foo; filename*1=bar", + "attachment", + "foobar", + /* "attachment", "basic" */ + ], // Prefer extended to basic and/or (broken or not) continuation // (invalid; error recovery) - ["attachment; filename=basic; filename*0=first; filename*0=wrong; filename*=UTF-8''extended", - "attachment", "extended"], + [ + "attachment; filename=basic; filename*0=first; filename*0=wrong; filename*=UTF-8''extended", + "attachment", + "extended", + ], // RFC 2231 not clear on correct outcome: we prefer non-continued extended // (invalid; error recovery) - ["attachment; filename=basic; filename*=UTF-8''extended; filename*0=foo; filename*1=bar", - "attachment", "extended"], + [ + "attachment; filename=basic; filename*=UTF-8''extended; filename*0=foo; filename*1=bar", + "attachment", + "extended", + ], // Gaps should result in returning only value until gap hit // (invalid; error recovery) - ["attachment; filename*0=foo; filename*2=bar", - "attachment", "foo", - /* "attachment", Cr.NS_ERROR_INVALID_ARG */], + [ + "attachment; filename*0=foo; filename*2=bar", + "attachment", + "foo", + /* "attachment", Cr.NS_ERROR_INVALID_ARG */ + ], // Don't allow leading 0's (*01) (invalid; error recovery) - ["attachment; filename*0=foo; filename*01=bar", - "attachment", "foo", - /* "attachment", Cr.NS_ERROR_INVALID_ARG */], + [ + "attachment; filename*0=foo; filename*01=bar", + "attachment", + "foo", + /* "attachment", Cr.NS_ERROR_INVALID_ARG */ + ], // continuations should prevail over non-extended (unless RFC 5987) - ["attachment; filename=basic; filename*0*=UTF-8''multi;\r\n" - + " filename*1=line;\r\n" - + " filename*2*=%20extended", - "attachment", "multiline extended", - /* "attachment", "basic" */], + [ + "attachment; filename=basic; filename*0*=UTF-8''multi;\r\n" + + " filename*1=line;\r\n" + + " filename*2*=%20extended", + "attachment", + "multiline extended", + /* "attachment", "basic" */ + ], // Gaps should result in returning only value until gap hit // (invalid; error recovery) - ["attachment; filename=basic; filename*0*=UTF-8''multi;\r\n" - + " filename*1=line;\r\n" - + " filename*3*=%20extended", - "attachment", "multiline", - /* "attachment", "basic" */], + [ + "attachment; filename=basic; filename*0*=UTF-8''multi;\r\n" + + " filename*1=line;\r\n" + + " filename*3*=%20extended", + "attachment", + "multiline", + /* "attachment", "basic" */ + ], // First series, only please, and don't slurp up higher elements (*2 in this // case) from later series into earlier one (invalid; error recovery) - ["attachment; filename=basic; filename*0*=UTF-8''multi;\r\n" - + " filename*1=line;\r\n" - + " filename*0*=UTF-8''wrong;\r\n" - + " filename*1=bad;\r\n" - + " filename*2=evil", - "attachment", "multiline", - /* "attachment", "basic" */], + [ + "attachment; filename=basic; filename*0*=UTF-8''multi;\r\n" + + " filename*1=line;\r\n" + + " filename*0*=UTF-8''wrong;\r\n" + + " filename*1=bad;\r\n" + + " filename*2=evil", + "attachment", + "multiline", + /* "attachment", "basic" */ + ], // RFC 2231 not clear on correct outcome: we prefer non-continued extended // (invalid; error recovery) - ["attachment; filename=basic; filename*0=UTF-8''multi\r\n;" - + " filename*=UTF-8''extended;\r\n" - + " filename*1=line;\r\n" - + " filename*2*=%20extended", - "attachment", "extended"], + [ + "attachment; filename=basic; filename*0=UTF-8''multi\r\n;" + + " filename*=UTF-8''extended;\r\n" + + " filename*1=line;\r\n" + + " filename*2*=%20extended", + "attachment", + "extended", + ], // sneaky: if unescaped, make sure we leave UTF-8'' in value - ["attachment; filename*0=UTF-8''unescaped;\r\n" - + " filename*1*=%20so%20includes%20UTF-8''%20in%20value", - "attachment", "UTF-8''unescaped so includes UTF-8'' in value", - /* "attachment", Cr.NS_ERROR_INVALID_ARG */], + [ + "attachment; filename*0=UTF-8''unescaped;\r\n" + + " filename*1*=%20so%20includes%20UTF-8''%20in%20value", + "attachment", + "UTF-8''unescaped so includes UTF-8'' in value", + /* "attachment", Cr.NS_ERROR_INVALID_ARG */ + ], // sneaky: if unescaped, make sure we leave UTF-8'' in value - ["attachment; filename=basic; filename*0=UTF-8''unescaped;\r\n" - + " filename*1*=%20so%20includes%20UTF-8''%20in%20value", - "attachment", "UTF-8''unescaped so includes UTF-8'' in value", - /* "attachment", "basic" */], + [ + "attachment; filename=basic; filename*0=UTF-8''unescaped;\r\n" + + " filename*1*=%20so%20includes%20UTF-8''%20in%20value", + "attachment", + "UTF-8''unescaped so includes UTF-8'' in value", + /* "attachment", "basic" */ + ], // Prefer basic over invalid continuation // (invalid; error recovery) - ["attachment; filename=basic; filename*1=multi;\r\n" - + " filename*2=line;\r\n" - + " filename*3*=%20extended", - "attachment", "basic"], + [ + "attachment; filename=basic; filename*1=multi;\r\n" + + " filename*2=line;\r\n" + + " filename*3*=%20extended", + "attachment", + "basic", + ], // support digits over 10 - ["attachment; filename=basic; filename*0*=UTF-8''0;\r\n" - + " filename*1=1; filename*2=2;filename*3=3;filename*4=4;filename*5=5;\r\n" - + " filename*6=6; filename*7=7;filename*8=8;filename*9=9;filename*10=a;\r\n" - + " filename*11=b; filename*12=c;filename*13=d;filename*14=e;filename*15=f\r\n", - "attachment", "0123456789abcdef", - /* "attachment", "basic" */], + [ + "attachment; filename=basic; filename*0*=UTF-8''0;\r\n" + + " filename*1=1; filename*2=2;filename*3=3;filename*4=4;filename*5=5;\r\n" + + " filename*6=6; filename*7=7;filename*8=8;filename*9=9;filename*10=a;\r\n" + + " filename*11=b; filename*12=c;filename*13=d;filename*14=e;filename*15=f\r\n", + "attachment", + "0123456789abcdef", + /* "attachment", "basic" */ + ], // support digits over 10 (detect gaps) - ["attachment; filename=basic; filename*0*=UTF-8''0;\r\n" - + " filename*1=1; filename*2=2;filename*3=3;filename*4=4;filename*5=5;\r\n" - + " filename*6=6; filename*7=7;filename*8=8;filename*9=9;filename*10=a;\r\n" - + " filename*11=b; filename*12=c;filename*14=e\r\n", - "attachment", "0123456789abc", - /* "attachment", "basic" */], + [ + "attachment; filename=basic; filename*0*=UTF-8''0;\r\n" + + " filename*1=1; filename*2=2;filename*3=3;filename*4=4;filename*5=5;\r\n" + + " filename*6=6; filename*7=7;filename*8=8;filename*9=9;filename*10=a;\r\n" + + " filename*11=b; filename*12=c;filename*14=e\r\n", + "attachment", + "0123456789abc", + /* "attachment", "basic" */ + ], // return nothing: invalid // (invalid; error recovery) - ["attachment; filename*1=multi;\r\n" - + " filename*2=line;\r\n" - + " filename*3*=%20extended", - "attachment", Cr.NS_ERROR_INVALID_ARG], - - // Bug 272541: Empty disposition type treated as "attachment" + [ + "attachment; filename*1=multi;\r\n" + + " filename*2=line;\r\n" + + " filename*3*=%20extended", + "attachment", + Cr.NS_ERROR_INVALID_ARG, + ], + + // Bug 272541: Empty disposition type treated as "attachment" // sanity check - ["attachment; filename=foo.html", - "attachment", "foo.html", - "attachment", "foo.html"], + [ + "attachment; filename=foo.html", + "attachment", + "foo.html", + "attachment", + "foo.html", + ], // the actual bug - ["; filename=foo.html", - Cr.NS_ERROR_FIRST_HEADER_FIELD_COMPONENT_EMPTY, "foo.html", - Cr.NS_ERROR_FIRST_HEADER_FIELD_COMPONENT_EMPTY, "foo.html"], - + [ + "; filename=foo.html", + Cr.NS_ERROR_FIRST_HEADER_FIELD_COMPONENT_EMPTY, + "foo.html", + Cr.NS_ERROR_FIRST_HEADER_FIELD_COMPONENT_EMPTY, + "foo.html", + ], + // regression check, but see bug 671204 - ["filename=foo.html", - "filename=foo.html", "foo.html", - "filename=foo.html", "foo.html"], - + [ + "filename=foo.html", + "filename=foo.html", + "foo.html", + "filename=foo.html", + "foo.html", + ], + // Bug 384571: RFC 2231 parameters not decoded when appearing in reversed order // check ordering - ["attachment; filename=basic; filename*0*=UTF-8''0;\r\n" - + " filename*1=1; filename*2=2;filename*3=3;filename*4=4;filename*5=5;\r\n" - + " filename*6=6; filename*7=7;filename*8=8;filename*9=9;filename*10=a;\r\n" - + " filename*11=b; filename*12=c;filename*13=d;filename*15=f;filename*14=e;\r\n", - "attachment", "0123456789abcdef", - /* "attachment", "basic" */], + [ + "attachment; filename=basic; filename*0*=UTF-8''0;\r\n" + + " filename*1=1; filename*2=2;filename*3=3;filename*4=4;filename*5=5;\r\n" + + " filename*6=6; filename*7=7;filename*8=8;filename*9=9;filename*10=a;\r\n" + + " filename*11=b; filename*12=c;filename*13=d;filename*15=f;filename*14=e;\r\n", + "attachment", + "0123456789abcdef", + /* "attachment", "basic" */ + ], // check non-digits in sequence numbers - ["attachment; filename=basic; filename*0*=UTF-8''0;\r\n" - + " filename*1a=1\r\n", - "attachment", "0", - /* "attachment", "basic" */], + [ + "attachment; filename=basic; filename*0*=UTF-8''0;\r\n" + + " filename*1a=1\r\n", + "attachment", + "0", + /* "attachment", "basic" */ + ], // check duplicate sequence numbers - ["attachment; filename=basic; filename*0*=UTF-8''0;\r\n" - + " filename*0=bad; filename*1=1;\r\n", - "attachment", "0", - /* "attachment", "basic" */], + [ + "attachment; filename=basic; filename*0*=UTF-8''0;\r\n" + + " filename*0=bad; filename*1=1;\r\n", + "attachment", + "0", + /* "attachment", "basic" */ + ], // check overflow - ["attachment; filename=basic; filename*0*=UTF-8''0;\r\n" - + " filename*11111111111111111111111111111111111111111111111111111111111=1", - "attachment", "0", - /* "attachment", "basic" */], + [ + "attachment; filename=basic; filename*0*=UTF-8''0;\r\n" + + " filename*11111111111111111111111111111111111111111111111111111111111=1", + "attachment", + "0", + /* "attachment", "basic" */ + ], // check underflow - ["attachment; filename=basic; filename*0*=UTF-8''0;\r\n" - + " filename*-1=1", - "attachment", "0", - /* "attachment", "basic" */], + [ + "attachment; filename=basic; filename*0*=UTF-8''0;\r\n" + " filename*-1=1", + "attachment", + "0", + /* "attachment", "basic" */ + ], // check mixed token/quoted-string - ["attachment; filename=basic; filename*0=\"0\";\r\n" - + " filename*1=1;\r\n" - + " filename*2*=%32", - "attachment", "012", - /* "attachment", "basic" */], + [ + 'attachment; filename=basic; filename*0="0";\r\n' + + " filename*1=1;\r\n" + + " filename*2*=%32", + "attachment", + "012", + /* "attachment", "basic" */ + ], // check empty sequence number - ["attachment; filename=basic; filename**=UTF-8''0\r\n", - "attachment", "basic", - "attachment", "basic"], - + [ + "attachment; filename=basic; filename**=UTF-8''0\r\n", + "attachment", + "basic", + "attachment", + "basic", + ], // Bug 419157: ensure that a MIME parameter with no charset information // fallbacks to Latin-1 - ["attachment;filename=IT839\x04\xB5(m8)2.pdf;", - "attachment", "IT839\u0004\u00b5(m8)2.pdf"], + [ + "attachment;filename=IT839\x04\xB5(m8)2.pdf;", + "attachment", + "IT839\u0004\u00b5(m8)2.pdf", + ], // Bug 588389: unescaping backslashes in quoted string parameters - - // '\"', should be parsed as '"' - ["attachment; filename=" + DQUOTE + (BS + DQUOTE) + DQUOTE, - "attachment", DQUOTE], - + + // '\"', should be parsed as '"' + [ + "attachment; filename=" + DQUOTE + (BS + DQUOTE) + DQUOTE, + "attachment", + DQUOTE, + ], + // 'a\"b', should be parsed as 'a"b' - ["attachment; filename=" + DQUOTE + 'a' + (BS + DQUOTE) + 'b' + DQUOTE, - "attachment", "a" + DQUOTE + "b"], - + [ + "attachment; filename=" + DQUOTE + "a" + (BS + DQUOTE) + "b" + DQUOTE, + "attachment", + "a" + DQUOTE + "b", + ], + // '\x', should be parsed as 'x' - ["attachment; filename=" + DQUOTE + (BS + "x") + DQUOTE, - "attachment", "x"], - + ["attachment; filename=" + DQUOTE + (BS + "x") + DQUOTE, "attachment", "x"], + // test empty param (quoted-string) - ["attachment; filename=" + DQUOTE + DQUOTE, - "attachment", ""], - - // test empty param - ["attachment; filename=", - "attachment", ""], + ["attachment; filename=" + DQUOTE + DQUOTE, "attachment", ""], + + // test empty param + ["attachment; filename=", "attachment", ""], // Bug 601933: RFC 2047 does not apply to parameters (at least in HTTP) - ["attachment; filename==?ISO-8859-1?Q?foo-=E4.html?=", - "attachment", "foo-\u00e4.html", - /* "attachment", "=?ISO-8859-1?Q?foo-=E4.html?=" */], + [ + "attachment; filename==?ISO-8859-1?Q?foo-=E4.html?=", + "attachment", + "foo-\u00e4.html", + /* "attachment", "=?ISO-8859-1?Q?foo-=E4.html?=" */ + ], - ["attachment; filename=\"=?ISO-8859-1?Q?foo-=E4.html?=\"", - "attachment", "foo-\u00e4.html", - /* "attachment", "=?ISO-8859-1?Q?foo-=E4.html?=" */], + [ + 'attachment; filename="=?ISO-8859-1?Q?foo-=E4.html?="', + "attachment", + "foo-\u00e4.html", + /* "attachment", "=?ISO-8859-1?Q?foo-=E4.html?=" */ + ], // format sent by GMail as of 2012-07-23 (5987 overrides 2047) - ["attachment; filename=\"=?ISO-8859-1?Q?foo-=E4.html?=\"; filename*=UTF-8''5987", - "attachment", "5987"], + [ + "attachment; filename=\"=?ISO-8859-1?Q?foo-=E4.html?=\"; filename*=UTF-8''5987", + "attachment", + "5987", + ], // Bug 651185: double quotes around 2231/5987 encoded param // Change reverted to backwards compat issues with various web services, // such as OWA (Bug 703015), plus similar problems in Thunderbird. If this // is tried again in the future, email probably needs to be special-cased. - - // sanity check - ["attachment; filename*=utf-8''%41", - "attachment", "A"], - // the actual bug - ["attachment; filename*=" + DQUOTE + "utf-8''%41" + DQUOTE, - "attachment", "A"], + // sanity check + ["attachment; filename*=utf-8''%41", "attachment", "A"], + + // the actual bug + [ + "attachment; filename*=" + DQUOTE + "utf-8''%41" + DQUOTE, + "attachment", + "A", + ], // previously with the fix for 651185: // "attachment", Cr.NS_ERROR_INVALID_ARG], // Bug 670333: Content-Disposition parser does not require presence of "=" // in params - + // sanity check - ["attachment; filename*=UTF-8''foo-%41.html", - "attachment", "foo-A.html"], + ["attachment; filename*=UTF-8''foo-%41.html", "attachment", "foo-A.html"], // the actual bug - ["attachment; filename *=UTF-8''foo-%41.html", - "attachment", Cr.NS_ERROR_INVALID_ARG], - + [ + "attachment; filename *=UTF-8''foo-%41.html", + "attachment", + Cr.NS_ERROR_INVALID_ARG, + ], + // the actual bug, without 2231/5987 encoding - ["attachment; filename X", - "attachment", Cr.NS_ERROR_INVALID_ARG], + ["attachment; filename X", "attachment", Cr.NS_ERROR_INVALID_ARG], // sanity check with WS on both sides - ["attachment; filename = foo-A.html", - "attachment", "foo-A.html"], + ["attachment; filename = foo-A.html", "attachment", "foo-A.html"], // Bug 685192: in RFC2231/5987 encoding, a missing charset field should be - // treated as error + // treated as error // the actual bug - ["attachment; filename*=''foo", - "attachment", "foo"], + ["attachment; filename*=''foo", "attachment", "foo"], // previously with the fix for 692574: - // "attachment", Cr.NS_ERROR_INVALID_ARG], + // "attachment", Cr.NS_ERROR_INVALID_ARG], // sanity check - ["attachment; filename*=a''foo", - "attachment", "foo"], + ["attachment; filename*=a''foo", "attachment", "foo"], // Bug 692574: RFC2231/5987 decoding should not tolerate missing single // quotes // one missing - ["attachment; filename*=UTF-8'foo-%41.html", - "attachment", "foo-A.html"], + ["attachment; filename*=UTF-8'foo-%41.html", "attachment", "foo-A.html"], // previously with the fix for 692574: // "attachment", Cr.NS_ERROR_INVALID_ARG], // both missing - ["attachment; filename*=foo-%41.html", - "attachment","foo-A.html"], + ["attachment; filename*=foo-%41.html", "attachment", "foo-A.html"], // previously with the fix for 692574: // "attachment", Cr.NS_ERROR_INVALID_ARG], // make sure fallback works - ["attachment; filename*=UTF-8'foo-%41.html; filename=bar.html", - "attachment", "foo-A.html"], + [ + "attachment; filename*=UTF-8'foo-%41.html; filename=bar.html", + "attachment", + "foo-A.html", + ], // previously with the fix for 692574: // "attachment", "bar.html"], @@ -347,184 +449,273 @@ var tests = [ // as authoritative // UTF-8 labeled ISO-8859-1 - ["attachment; filename*=ISO-8859-1''%c3%a4", - "attachment", "\u00c3\u00a4"], + ["attachment; filename*=ISO-8859-1''%c3%a4", "attachment", "\u00c3\u00a4"], // UTF-8 labeled ISO-8859-1, but with octets not allowed in ISO-8859-1 // accepts x82, understands it as Win1252, maps it to Unicode \u20a1 - ["attachment; filename*=ISO-8859-1''%e2%82%ac", - "attachment", "\u00e2\u201a\u00ac"], + [ + "attachment; filename*=ISO-8859-1''%e2%82%ac", + "attachment", + "\u00e2\u201a\u00ac", + ], // defective UTF-8 - ["attachment; filename*=UTF-8''A%e4B", - "attachment", Cr.NS_ERROR_INVALID_ARG], + ["attachment; filename*=UTF-8''A%e4B", "attachment", Cr.NS_ERROR_INVALID_ARG], // defective UTF-8, with fallback - ["attachment; filename*=UTF-8''A%e4B; filename=fallback", - "attachment", "fallback"], + [ + "attachment; filename*=UTF-8''A%e4B; filename=fallback", + "attachment", + "fallback", + ], // defective UTF-8 (continuations), with fallback - ["attachment; filename*0*=UTF-8''A%e4B; filename=fallback", - "attachment", "fallback"], + [ + "attachment; filename*0*=UTF-8''A%e4B; filename=fallback", + "attachment", + "fallback", + ], // check that charsets aren't mixed up - ["attachment; filename*0*=ISO-8859-15''euro-sign%3d%a4; filename*=ISO-8859-1''currency-sign%3d%a4", - "attachment", "currency-sign=\u00a4"], + [ + "attachment; filename*0*=ISO-8859-15''euro-sign%3d%a4; filename*=ISO-8859-1''currency-sign%3d%a4", + "attachment", + "currency-sign=\u00a4", + ], // same as above, except reversed - ["attachment; filename*=ISO-8859-1''currency-sign%3d%a4; filename*0*=ISO-8859-15''euro-sign%3d%a4", - "attachment", "currency-sign=\u00a4"], + [ + "attachment; filename*=ISO-8859-1''currency-sign%3d%a4; filename*0*=ISO-8859-15''euro-sign%3d%a4", + "attachment", + "currency-sign=\u00a4", + ], // Bug 704989: add workaround for broken Outlook Web App (OWA) // attachment handling - ["attachment; filename*=\"a%20b\"", - "attachment", "a b"], + ['attachment; filename*="a%20b"', "attachment", "a b"], // Bug 717121: crash nsMIMEHeaderParamImpl::DoParameterInternal - ["attachment; filename=\"", - "attachment", ""], + ['attachment; filename="', "attachment", ""], // We used to read past string if last param w/o = and ; // Note: was only detected on windows PGO builds - ["attachment; filename=foo; trouble", - "attachment", "foo"], + ["attachment; filename=foo; trouble", "attachment", "foo"], // Same, followed by space, hits another case - ["attachment; filename=foo; trouble ", - "attachment", "foo"], + ["attachment; filename=foo; trouble ", "attachment", "foo"], - ["attachment", - "attachment", Cr.NS_ERROR_INVALID_ARG], + ["attachment", "attachment", Cr.NS_ERROR_INVALID_ARG], // Bug 730574: quoted-string in RFC2231-continuations not handled - ['attachment; filename=basic; filename*0="foo"; filename*1="\\b\\a\\r.html"', - "attachment", "foobar.html", - /* "attachment", "basic" */], + [ + 'attachment; filename=basic; filename*0="foo"; filename*1="\\b\\a\\r.html"', + "attachment", + "foobar.html", + /* "attachment", "basic" */ + ], // unmatched escape char - ['attachment; filename=basic; filename*0="foo"; filename*1="\\b\\a\\', - "attachment", "fooba\\", - /* "attachment", "basic" */], + [ + 'attachment; filename=basic; filename*0="foo"; filename*1="\\b\\a\\', + "attachment", + "fooba\\", + /* "attachment", "basic" */ + ], // Bug 732369: Content-Disposition parser does not require presence of ";" between params - // optimally, this would not even return the disposition type "attachment" + // optimally, this would not even return the disposition type "attachment" - ["attachment; extension=bla filename=foo", - "attachment", Cr.NS_ERROR_INVALID_ARG], + [ + "attachment; extension=bla filename=foo", + "attachment", + Cr.NS_ERROR_INVALID_ARG, + ], - ["attachment; filename=foo extension=bla", - "attachment", "foo"], + ["attachment; filename=foo extension=bla", "attachment", "foo"], - ["attachment filename=foo", - "attachment", Cr.NS_ERROR_INVALID_ARG], + ["attachment filename=foo", "attachment", Cr.NS_ERROR_INVALID_ARG], // Bug 777687: handling of broken %escapes - ["attachment; filename*=UTF-8''f%oo; filename=bar", - "attachment", "bar"], + ["attachment; filename*=UTF-8''f%oo; filename=bar", "attachment", "bar"], - ["attachment; filename*=UTF-8''foo%; filename=bar", - "attachment", "bar"], + ["attachment; filename*=UTF-8''foo%; filename=bar", "attachment", "bar"], // Bug 783502 - xpcshell test netwerk/test/unit/test_MIME_params.js fails on AddressSanitizer - ['attachment; filename="\\b\\a\\', - "attachment", "ba\\"], + ['attachment; filename="\\b\\a\\', "attachment", "ba\\"], // Bug 1412213 - do continue to parse, behind an empty parameter - ['attachment; ; filename=foo', - "attachment", "foo"], + ["attachment; ; filename=foo", "attachment", "foo"], // Bug 1412213 - do continue to parse, behind a parameter w/o = - ['attachment; badparameter; filename=foo', - "attachment", "foo"], + ["attachment; badparameter; filename=foo", "attachment", "foo"], ]; var rfc5987paramtests = [ - [ // basic test - "UTF-8'language'value", "value", "language", Cr.NS_OK ], - [ // percent decoding - "UTF-8''1%202", "1 2", "", Cr.NS_OK ], - [ // UTF-8 - "UTF-8''%c2%a3%20and%20%e2%82%ac%20rates", "\u00a3 and \u20ac rates", "", Cr.NS_OK ], - [ // missing charset - "''abc", "", "", Cr.NS_ERROR_INVALID_ARG ], - [ // ISO-8859-1: unsupported - "ISO-8859-1''%A3%20rates", "", "", Cr.NS_ERROR_INVALID_ARG ], - [ // unknown charset - "foo''abc", "", "", Cr.NS_ERROR_INVALID_ARG ], - [ // missing component - "abc", "", "", Cr.NS_ERROR_INVALID_ARG ], - [ // missing component - "'abc", "", "", Cr.NS_ERROR_INVALID_ARG ], - [ // illegal chars - "UTF-8''a b", "", "", Cr.NS_ERROR_INVALID_ARG ], - [ // broken % escapes - "UTF-8''a%zz", "", "", Cr.NS_ERROR_INVALID_ARG ], - [ // broken % escapes - "UTF-8''a%b", "", "", Cr.NS_ERROR_INVALID_ARG ], - [ // broken % escapes - "UTF-8''a%", "", "", Cr.NS_ERROR_INVALID_ARG ], - [ // broken UTF-8 - "UTF-8''%A3%20rates", "", "", 0x8050000E /* NS_ERROR_UDEC_ILLEGALINPUT */ ], + [ + // basic test + "UTF-8'language'value", + "value", + "language", + Cr.NS_OK, + ], + [ + // percent decoding + "UTF-8''1%202", + "1 2", + "", + Cr.NS_OK, + ], + [ + // UTF-8 + "UTF-8''%c2%a3%20and%20%e2%82%ac%20rates", + "\u00a3 and \u20ac rates", + "", + Cr.NS_OK, + ], + [ + // missing charset + "''abc", + "", + "", + Cr.NS_ERROR_INVALID_ARG, + ], + [ + // ISO-8859-1: unsupported + "ISO-8859-1''%A3%20rates", + "", + "", + Cr.NS_ERROR_INVALID_ARG, + ], + [ + // unknown charset + "foo''abc", + "", + "", + Cr.NS_ERROR_INVALID_ARG, + ], + [ + // missing component + "abc", + "", + "", + Cr.NS_ERROR_INVALID_ARG, + ], + [ + // missing component + "'abc", + "", + "", + Cr.NS_ERROR_INVALID_ARG, + ], + [ + // illegal chars + "UTF-8''a b", + "", + "", + Cr.NS_ERROR_INVALID_ARG, + ], + [ + // broken % escapes + "UTF-8''a%zz", + "", + "", + Cr.NS_ERROR_INVALID_ARG, + ], + [ + // broken % escapes + "UTF-8''a%b", + "", + "", + Cr.NS_ERROR_INVALID_ARG, + ], + [ + // broken % escapes + "UTF-8''a%", + "", + "", + Cr.NS_ERROR_INVALID_ARG, + ], + [ + // broken UTF-8 + "UTF-8''%A3%20rates", + "", + "", + 0x8050000e /* NS_ERROR_UDEC_ILLEGALINPUT */, + ], ]; -function do_tests(whichRFC) -{ - var mhp = Cc["@mozilla.org/network/mime-hdrparam;1"] - .getService(Ci.nsIMIMEHeaderParam); +function do_tests(whichRFC) { + var mhp = Cc["@mozilla.org/network/mime-hdrparam;1"].getService( + Ci.nsIMIMEHeaderParam + ); - var unused = { value : null }; + var unused = { value: null }; for (var i = 0; i < tests.length; ++i) { dump("Testing #" + i + ": " + tests[i] + "\n"); // check disposition type - var expectedDt = tests[i].length == 3 || whichRFC == 0 ? tests[i][1] : tests[i][3]; + var expectedDt = + tests[i].length == 3 || whichRFC == 0 ? tests[i][1] : tests[i][3]; try { var result; - - if (whichRFC == 0) + + if (whichRFC == 0) { result = mhp.getParameter(tests[i][0], "", "UTF-8", true, unused); - else + } else { result = mhp.getParameterHTTP(tests[i][0], "", "UTF-8", true, unused); + } Assert.equal(result, expectedDt); - } - catch (e) { + } catch (e) { // Tests can also succeed by expecting to fail with given error code if (e.result) { // Allow following tests to run by catching exception from do_check_eq() - try { - Assert.equal(e.result, expectedDt); - } catch(e) {} + try { + Assert.equal(e.result, expectedDt); + } catch (e) {} } continue; } // check filename parameter - var expectedFn = tests[i].length == 3 || whichRFC == 0 ? tests[i][2] : tests[i][4]; + var expectedFn = + tests[i].length == 3 || whichRFC == 0 ? tests[i][2] : tests[i][4]; try { var result; - - if (whichRFC == 0) - result = mhp.getParameter(tests[i][0], "filename", "UTF-8", true, unused); - else - result = mhp.getParameterHTTP(tests[i][0], "filename", "UTF-8", true, unused); + + if (whichRFC == 0) { + result = mhp.getParameter( + tests[i][0], + "filename", + "UTF-8", + true, + unused + ); + } else { + result = mhp.getParameterHTTP( + tests[i][0], + "filename", + "UTF-8", + true, + unused + ); + } Assert.equal(result, expectedFn); - } - catch (e) { + } catch (e) { // Tests can also succeed by expecting to fail with given error code if (e.result) { // Allow following tests to run by catching exception from do_check_eq() - try { - Assert.equal(e.result, expectedFn); - } catch(e) {} + try { + Assert.equal(e.result, expectedFn); + } catch (e) {} } continue; } @@ -532,8 +723,9 @@ function do_tests(whichRFC) } function test_decode5987Param() { - var mhp = Cc["@mozilla.org/network/mime-hdrparam;1"] - .getService(Ci.nsIMIMEHeaderParam); + var mhp = Cc["@mozilla.org/network/mime-hdrparam;1"].getService( + Ci.nsIMIMEHeaderParam + ); for (var i = 0; i < rfc5987paramtests.length; ++i) { dump("Testing #" + i + ": " + rfc5987paramtests[i] + "\n"); @@ -544,19 +736,16 @@ function test_decode5987Param() { if (rfc5987paramtests[i][3] == Cr.NS_OK) { Assert.equal(rfc5987paramtests[i][1], decoded); Assert.equal(rfc5987paramtests[i][2], lang.value); - } - else { + } else { Assert.equal(rfc5987paramtests[i][3], "instead got: " + decoded); } - } - catch (e) { + } catch (e) { Assert.equal(rfc5987paramtests[i][3], e.result); } } } function run_test() { - // Test RFC 2231 (complete header field values) do_tests(0); diff --git a/netwerk/test/unit/test_NetUtil.js b/netwerk/test/unit/test_NetUtil.js index 7fc940beaa65..044fd04b564a 100644 --- a/netwerk/test/unit/test_NetUtil.js +++ b/netwerk/test/unit/test_NetUtil.js @@ -8,15 +8,15 @@ * This file tests the methods on NetUtil.jsm. */ -const {HttpServer} = ChromeUtils.import("resource://testing-common/httpd.js"); - +const { HttpServer } = ChromeUtils.import("resource://testing-common/httpd.js"); // We need the profile directory so the test harness will clean up our test // files. do_get_profile(); const OUTPUT_STREAM_CONTRACT_ID = "@mozilla.org/network/file-output-stream;1"; -const SAFE_OUTPUT_STREAM_CONTRACT_ID = "@mozilla.org/network/safe-file-output-stream;1"; +const SAFE_OUTPUT_STREAM_CONTRACT_ID = + "@mozilla.org/network/safe-file-output-stream;1"; //////////////////////////////////////////////////////////////////////////////// //// Helper Methods @@ -28,25 +28,25 @@ const SAFE_OUTPUT_STREAM_CONTRACT_ID = "@mozilla.org/network/safe-file-output-st * The file to return from. * @return the contents of the file in the form of a string. */ -function getFileContents(aFile) -{ +function getFileContents(aFile) { "use strict"; - let fstream = Cc["@mozilla.org/network/file-input-stream;1"]. - createInstance(Ci.nsIFileInputStream); + let fstream = Cc["@mozilla.org/network/file-input-stream;1"].createInstance( + Ci.nsIFileInputStream + ); fstream.init(aFile, -1, 0, 0); - let cstream = Cc["@mozilla.org/intl/converter-input-stream;1"]. - createInstance(Ci.nsIConverterInputStream); + let cstream = Cc["@mozilla.org/intl/converter-input-stream;1"].createInstance( + Ci.nsIConverterInputStream + ); cstream.init(fstream, "UTF-8", 0, 0); - let string = {}; + let string = {}; cstream.readString(-1, string); cstream.close(); return string.value; } - /** * Tests asynchronously writing a file using NetUtil.asyncCopy. * @@ -55,25 +55,30 @@ function getFileContents(aFile) * @param aDeferOpen * Whether to use DEFER_OPEN in the output stream. */ -function async_write_file(aContractId, aDeferOpen) -{ +function async_write_file(aContractId, aDeferOpen) { do_test_pending(); // First, we need an output file to write to. - let file = Cc["@mozilla.org/file/directory_service;1"]. - getService(Ci.nsIProperties). - get("ProfD", Ci.nsIFile); + let file = Cc["@mozilla.org/file/directory_service;1"] + .getService(Ci.nsIProperties) + .get("ProfD", Ci.nsIFile); file.append("NetUtil-async-test-file.tmp"); file.createUnique(Ci.nsIFile.NORMAL_FILE_TYPE, 0o666); // Then, we need an output stream to our output file. let ostream = Cc[aContractId].createInstance(Ci.nsIFileOutputStream); - ostream.init(file, -1, -1, aDeferOpen ? Ci.nsIFileOutputStream.DEFER_OPEN : 0); + ostream.init( + file, + -1, + -1, + aDeferOpen ? Ci.nsIFileOutputStream.DEFER_OPEN : 0 + ); // Finally, we need an input stream to take data from. const TEST_DATA = "this is a test string"; - let istream = Cc["@mozilla.org/io/string-input-stream;1"]. - createInstance(Ci.nsIStringInputStream); + let istream = Cc["@mozilla.org/io/string-input-stream;1"].createInstance( + Ci.nsIStringInputStream + ); istream.setData(TEST_DATA, TEST_DATA.length); NetUtil.asyncCopy(istream, ostream, function(aResult) { @@ -93,8 +98,7 @@ function async_write_file(aContractId, aDeferOpen) //// Tests // Test NetUtil.asyncCopy for all possible buffering scenarios -function test_async_copy() -{ +function test_async_copy() { // Create a data sample function make_sample(text) { let data = []; @@ -108,27 +112,30 @@ function test_async_copy() function make_input(isBuffered, data) { if (isBuffered) { // String input streams are buffered - let istream = Cc["@mozilla.org/io/string-input-stream;1"]. - createInstance(Ci.nsIStringInputStream); + let istream = Cc["@mozilla.org/io/string-input-stream;1"].createInstance( + Ci.nsIStringInputStream + ); istream.setData(data, data.length); return istream; } // File input streams are not buffered, so let's create a file - let file = Cc["@mozilla.org/file/directory_service;1"]. - getService(Ci.nsIProperties). - get("ProfD", Ci.nsIFile); + let file = Cc["@mozilla.org/file/directory_service;1"] + .getService(Ci.nsIProperties) + .get("ProfD", Ci.nsIFile); file.append("NetUtil-asyncFetch-test-file.tmp"); file.createUnique(Ci.nsIFile.NORMAL_FILE_TYPE, 0o666); - let ostream = Cc["@mozilla.org/network/file-output-stream;1"]. - createInstance(Ci.nsIFileOutputStream); + let ostream = Cc[ + "@mozilla.org/network/file-output-stream;1" + ].createInstance(Ci.nsIFileOutputStream); ostream.init(file, -1, -1, 0); ostream.write(data, data.length); ostream.close(); - let istream = Cc["@mozilla.org/network/file-input-stream;1"]. - createInstance(Ci.nsIFileInputStream); + let istream = Cc["@mozilla.org/network/file-input-stream;1"].createInstance( + Ci.nsIFileInputStream + ); istream.init(file, -1, 0, 0); return istream; @@ -136,37 +143,40 @@ function test_async_copy() // Create an output buffer holding some data function make_output(isBuffered) { - let file = Cc["@mozilla.org/file/directory_service;1"]. - getService(Ci.nsIProperties). - get("ProfD", Ci.nsIFile); + let file = Cc["@mozilla.org/file/directory_service;1"] + .getService(Ci.nsIProperties) + .get("ProfD", Ci.nsIFile); file.append("NetUtil-asyncFetch-test-file.tmp"); file.createUnique(Ci.nsIFile.NORMAL_FILE_TYPE, 0o666); - let ostream = Cc["@mozilla.org/network/file-output-stream;1"]. - createInstance(Ci.nsIFileOutputStream); + let ostream = Cc[ + "@mozilla.org/network/file-output-stream;1" + ].createInstance(Ci.nsIFileOutputStream); ostream.init(file, -1, -1, 0); if (!isBuffered) { - return {file, sink: ostream}; + return { file, sink: ostream }; } - let bstream = Cc["@mozilla.org/network/buffered-output-stream;1"]. - createInstance(Ci.nsIBufferedOutputStream); + let bstream = Cc[ + "@mozilla.org/network/buffered-output-stream;1" + ].createInstance(Ci.nsIBufferedOutputStream); bstream.init(ostream, 256); - return {file, sink: bstream}; + return { file, sink: bstream }; } (async function() { do_test_pending(); for (let bufferedInput of [true, false]) { for (let bufferedOutput of [true, false]) { - let text = "test_async_copy with " - + (bufferedInput?"buffered input":"unbuffered input") - + ", " - + (bufferedOutput?"buffered output":"unbuffered output"); + let text = + "test_async_copy with " + + (bufferedInput ? "buffered input" : "unbuffered input") + + ", " + + (bufferedOutput ? "buffered output" : "unbuffered output"); info(text); let TEST_DATA = "[" + make_sample(text) + "]"; let source = make_input(bufferedInput, TEST_DATA); - let {file, sink} = make_output(bufferedOutput); + let { file, sink } = make_output(bufferedOutput); let result = await new Promise(resolve => { NetUtil.asyncCopy(source, sink, resolve); }); @@ -202,21 +212,18 @@ function test_async_write_file_safe_deferred() { async_write_file(SAFE_OUTPUT_STREAM_CONTRACT_ID, true); } -function test_newURI_no_spec_throws() -{ +function test_newURI_no_spec_throws() { try { NetUtil.newURI(); do_throw("should throw!"); - } - catch (e) { + } catch (e) { Assert.equal(e.result, Cr.NS_ERROR_INVALID_ARG); } run_next_test(); } -function test_newURI() -{ +function test_newURI() { let ios = Cc["@mozilla.org/network/io-service;1"].getService(Ci.nsIIOService); // Check that we get the same URI back from the IO service and the utility @@ -229,14 +236,13 @@ function test_newURI() run_next_test(); } -function test_newURI_takes_nsIFile() -{ +function test_newURI_takes_nsIFile() { let ios = Cc["@mozilla.org/network/io-service;1"].getService(Ci.nsIIOService); // Create a test file that we can pass into NetUtil.newURI - let file = Cc["@mozilla.org/file/directory_service;1"]. - getService(Ci.nsIProperties). - get("ProfD", Ci.nsIFile); + let file = Cc["@mozilla.org/file/directory_service;1"] + .getService(Ci.nsIProperties) + .get("ProfD", Ci.nsIFile); file.append("NetUtil-test-file.tmp"); // Check that we get the same URI back from the IO service and the utility @@ -248,34 +254,29 @@ function test_newURI_takes_nsIFile() run_next_test(); } -function test_asyncFetch_no_channel() -{ +function test_asyncFetch_no_channel() { try { - NetUtil.asyncFetch(null, function() { }); + NetUtil.asyncFetch(null, function() {}); do_throw("should throw!"); - } - catch (e) { + } catch (e) { Assert.equal(e.result, Cr.NS_ERROR_INVALID_ARG); } run_next_test(); } -function test_asyncFetch_no_callback() -{ +function test_asyncFetch_no_callback() { try { - NetUtil.asyncFetch({ }); + NetUtil.asyncFetch({}); do_throw("should throw!"); - } - catch (e) { + } catch (e) { Assert.equal(e.result, Cr.NS_ERROR_INVALID_ARG); } run_next_test(); } -function test_asyncFetch_with_nsIChannel() -{ +function test_asyncFetch_with_nsIChannel() { const TEST_DATA = "this is a test string"; // Start the http server, and register our handler. @@ -300,8 +301,9 @@ function test_asyncFetch_with_nsIChannel() // Check that we got the right data. Assert.equal(aInputStream.available(), TEST_DATA.length); - let is = Cc["@mozilla.org/scriptableinputstream;1"]. - createInstance(Ci.nsIScriptableInputStream); + let is = Cc["@mozilla.org/scriptableinputstream;1"].createInstance( + Ci.nsIScriptableInputStream + ); is.init(aInputStream); let result = is.read(TEST_DATA.length); Assert.equal(TEST_DATA, result); @@ -310,8 +312,7 @@ function test_asyncFetch_with_nsIChannel() }); } -function test_asyncFetch_with_nsIURI() -{ +function test_asyncFetch_with_nsIURI() { const TEST_DATA = "this is a test string"; // Start the http server, and register our handler. @@ -324,36 +325,40 @@ function test_asyncFetch_with_nsIURI() server.start(-1); // Create our URI. - let uri = NetUtil.newURI("http://localhost:" + - server.identity.primaryPort + "/test"); + let uri = NetUtil.newURI( + "http://localhost:" + server.identity.primaryPort + "/test" + ); // Open our URI asynchronously. - NetUtil.asyncFetch({ - uri, - loadUsingSystemPrincipal: true, - }, function(aInputStream, aResult) { - // Check that we had success. - Assert.ok(Components.isSuccessCode(aResult)); + NetUtil.asyncFetch( + { + uri, + loadUsingSystemPrincipal: true, + }, + function(aInputStream, aResult) { + // Check that we had success. + Assert.ok(Components.isSuccessCode(aResult)); - // Check that we got the right data. - Assert.equal(aInputStream.available(), TEST_DATA.length); - let is = Cc["@mozilla.org/scriptableinputstream;1"]. - createInstance(Ci.nsIScriptableInputStream); - is.init(aInputStream); - let result = is.read(TEST_DATA.length); - Assert.equal(TEST_DATA, result); + // Check that we got the right data. + Assert.equal(aInputStream.available(), TEST_DATA.length); + let is = Cc["@mozilla.org/scriptableinputstream;1"].createInstance( + Ci.nsIScriptableInputStream + ); + is.init(aInputStream); + let result = is.read(TEST_DATA.length); + Assert.equal(TEST_DATA, result); - server.stop(run_next_test); - }, - null, // aLoadingNode - Services.scriptSecurityManager.getSystemPrincipal(), - null, // aTriggeringPrincipal - Ci.nsILoadInfo.SEC_ALLOW_CROSS_ORIGIN_DATA_IS_NULL, - Ci.nsIContentPolicy.TYPE_OTHER); + server.stop(run_next_test); + }, + null, // aLoadingNode + Services.scriptSecurityManager.getSystemPrincipal(), + null, // aTriggeringPrincipal + Ci.nsILoadInfo.SEC_ALLOW_CROSS_ORIGIN_DATA_IS_NULL, + Ci.nsIContentPolicy.TYPE_OTHER + ); } -function test_asyncFetch_with_string() -{ +function test_asyncFetch_with_string() { const TEST_DATA = "this is a test string"; // Start the http server, and register our handler. @@ -366,44 +371,48 @@ function test_asyncFetch_with_string() server.start(-1); // Open our location asynchronously. - NetUtil.asyncFetch({ - uri: "http://localhost:" + server.identity.primaryPort + "/test", - loadUsingSystemPrincipal: true, - }, function(aInputStream, aResult) { - // Check that we had success. - Assert.ok(Components.isSuccessCode(aResult)); + NetUtil.asyncFetch( + { + uri: "http://localhost:" + server.identity.primaryPort + "/test", + loadUsingSystemPrincipal: true, + }, + function(aInputStream, aResult) { + // Check that we had success. + Assert.ok(Components.isSuccessCode(aResult)); - // Check that we got the right data. - Assert.equal(aInputStream.available(), TEST_DATA.length); - let is = Cc["@mozilla.org/scriptableinputstream;1"]. - createInstance(Ci.nsIScriptableInputStream); - is.init(aInputStream); - let result = is.read(TEST_DATA.length); - Assert.equal(TEST_DATA, result); + // Check that we got the right data. + Assert.equal(aInputStream.available(), TEST_DATA.length); + let is = Cc["@mozilla.org/scriptableinputstream;1"].createInstance( + Ci.nsIScriptableInputStream + ); + is.init(aInputStream); + let result = is.read(TEST_DATA.length); + Assert.equal(TEST_DATA, result); - server.stop(run_next_test); - }, - null, // aLoadingNode - Services.scriptSecurityManager.getSystemPrincipal(), - null, // aTriggeringPrincipal - Ci.nsILoadInfo.SEC_ALLOW_CROSS_ORIGIN_DATA_IS_NULL, - Ci.nsIContentPolicy.TYPE_OTHER); + server.stop(run_next_test); + }, + null, // aLoadingNode + Services.scriptSecurityManager.getSystemPrincipal(), + null, // aTriggeringPrincipal + Ci.nsILoadInfo.SEC_ALLOW_CROSS_ORIGIN_DATA_IS_NULL, + Ci.nsIContentPolicy.TYPE_OTHER + ); } -function test_asyncFetch_with_nsIFile() -{ +function test_asyncFetch_with_nsIFile() { const TEST_DATA = "this is a test string"; // First we need a file to read from. - let file = Cc["@mozilla.org/file/directory_service;1"]. - getService(Ci.nsIProperties). - get("ProfD", Ci.nsIFile); + let file = Cc["@mozilla.org/file/directory_service;1"] + .getService(Ci.nsIProperties) + .get("ProfD", Ci.nsIFile); file.append("NetUtil-asyncFetch-test-file.tmp"); file.createUnique(Ci.nsIFile.NORMAL_FILE_TYPE, 0o666); // Write the test data to the file. - let ostream = Cc["@mozilla.org/network/file-output-stream;1"]. - createInstance(Ci.nsIFileOutputStream); + let ostream = Cc["@mozilla.org/network/file-output-stream;1"].createInstance( + Ci.nsIFileOutputStream + ); ostream.init(file, -1, -1, 0); ostream.write(TEST_DATA, TEST_DATA.length); @@ -412,58 +421,66 @@ function test_asyncFetch_with_nsIFile() // Open our file asynchronously. // Note that this causes main-tread I/O and should be avoided in production. - NetUtil.asyncFetch({ - uri: NetUtil.newURI(file), - loadUsingSystemPrincipal: true, - }, function(aInputStream, aResult) { - // Check that we had success. - Assert.ok(Components.isSuccessCode(aResult)); + NetUtil.asyncFetch( + { + uri: NetUtil.newURI(file), + loadUsingSystemPrincipal: true, + }, + function(aInputStream, aResult) { + // Check that we had success. + Assert.ok(Components.isSuccessCode(aResult)); - // Check that we got the right data. - Assert.equal(aInputStream.available(), TEST_DATA.length); - let is = Cc["@mozilla.org/scriptableinputstream;1"]. - createInstance(Ci.nsIScriptableInputStream); - is.init(aInputStream); - let result = is.read(TEST_DATA.length); - Assert.equal(TEST_DATA, result); + // Check that we got the right data. + Assert.equal(aInputStream.available(), TEST_DATA.length); + let is = Cc["@mozilla.org/scriptableinputstream;1"].createInstance( + Ci.nsIScriptableInputStream + ); + is.init(aInputStream); + let result = is.read(TEST_DATA.length); + Assert.equal(TEST_DATA, result); - run_next_test(); - }, - null, // aLoadingNode - Services.scriptSecurityManager.getSystemPrincipal(), - null, // aTriggeringPrincipal - Ci.nsILoadInfo.SEC_ALLOW_CROSS_ORIGIN_DATA_IS_NULL, - Ci.nsIContentPolicy.TYPE_OTHER); + run_next_test(); + }, + null, // aLoadingNode + Services.scriptSecurityManager.getSystemPrincipal(), + null, // aTriggeringPrincipal + Ci.nsILoadInfo.SEC_ALLOW_CROSS_ORIGIN_DATA_IS_NULL, + Ci.nsIContentPolicy.TYPE_OTHER + ); } -function test_asyncFetch_with_nsIInputString() -{ +function test_asyncFetch_with_nsIInputString() { const TEST_DATA = "this is a test string"; - let istream = Cc["@mozilla.org/io/string-input-stream;1"]. - createInstance(Ci.nsIStringInputStream); + let istream = Cc["@mozilla.org/io/string-input-stream;1"].createInstance( + Ci.nsIStringInputStream + ); istream.setData(TEST_DATA, TEST_DATA.length); // Read the input stream asynchronously. - NetUtil.asyncFetch(istream, function(aInputStream, aResult) { - // Check that we had success. - Assert.ok(Components.isSuccessCode(aResult)); + NetUtil.asyncFetch( + istream, + function(aInputStream, aResult) { + // Check that we had success. + Assert.ok(Components.isSuccessCode(aResult)); - // Check that we got the right data. - Assert.equal(aInputStream.available(), TEST_DATA.length); - Assert.equal(NetUtil.readInputStreamToString(aInputStream, TEST_DATA.length), - TEST_DATA); + // Check that we got the right data. + Assert.equal(aInputStream.available(), TEST_DATA.length); + Assert.equal( + NetUtil.readInputStreamToString(aInputStream, TEST_DATA.length), + TEST_DATA + ); - run_next_test(); - }, - null, // aLoadingNode - Services.scriptSecurityManager.getSystemPrincipal(), - null, // aTriggeringPrincipal - Ci.nsILoadInfo.SEC_ALLOW_CROSS_ORIGIN_DATA_IS_NULL, - Ci.nsIContentPolicy.TYPE_OTHER); + run_next_test(); + }, + null, // aLoadingNode + Services.scriptSecurityManager.getSystemPrincipal(), + null, // aTriggeringPrincipal + Ci.nsILoadInfo.SEC_ALLOW_CROSS_ORIGIN_DATA_IS_NULL, + Ci.nsIContentPolicy.TYPE_OTHER + ); } -function test_asyncFetch_does_not_block() -{ +function test_asyncFetch_does_not_block() { // Create our channel that has no data. let channel = NetUtil.newChannel({ uri: "data:text/plain,", @@ -477,14 +494,14 @@ function test_asyncFetch_does_not_block() // Check that reading a byte throws that the stream was closed (as opposed // saying it would block). - let is = Cc["@mozilla.org/scriptableinputstream;1"]. - createInstance(Ci.nsIScriptableInputStream); + let is = Cc["@mozilla.org/scriptableinputstream;1"].createInstance( + Ci.nsIScriptableInputStream + ); is.init(aInputStream); try { is.read(1); do_throw("should throw!"); - } - catch (e) { + } catch (e) { Assert.equal(e.result, Cr.NS_BASE_STREAM_CLOSED); } @@ -492,97 +509,101 @@ function test_asyncFetch_does_not_block() }); } -function test_newChannel_no_specifier() -{ +function test_newChannel_no_specifier() { try { NetUtil.newChannel(); do_throw("should throw!"); - } - catch (e) { + } catch (e) { Assert.equal(e.result, Cr.NS_ERROR_INVALID_ARG); } run_next_test(); } -function test_newChannel_with_string() -{ +function test_newChannel_with_string() { const TEST_SPEC = "http://mozilla.org"; // Check that we get the same URI back from channel the IO service creates and // the channel the utility method creates. - let ios = Services.io - let iosChannel = ios.newChannel(TEST_SPEC, - null, - null, - null, // aLoadingNode - Services.scriptSecurityManager.getSystemPrincipal(), - null, // aTriggeringPrincipal - Ci.nsILoadInfo.SEC_ALLOW_CROSS_ORIGIN_DATA_IS_NULL, - Ci.nsIContentPolicy.TYPE_OTHER); + let ios = Services.io; + let iosChannel = ios.newChannel( + TEST_SPEC, + null, + null, + null, // aLoadingNode + Services.scriptSecurityManager.getSystemPrincipal(), + null, // aTriggeringPrincipal + Ci.nsILoadInfo.SEC_ALLOW_CROSS_ORIGIN_DATA_IS_NULL, + Ci.nsIContentPolicy.TYPE_OTHER + ); let NetUtilChannel = NetUtil.newChannel({ uri: TEST_SPEC, - loadUsingSystemPrincipal: true + loadUsingSystemPrincipal: true, }); Assert.ok(iosChannel.URI.equals(NetUtilChannel.URI)); run_next_test(); } -function test_newChannel_with_nsIURI() -{ +function test_newChannel_with_nsIURI() { const TEST_SPEC = "http://mozilla.org"; // Check that we get the same URI back from channel the IO service creates and // the channel the utility method creates. let uri = NetUtil.newURI(TEST_SPEC); - let iosChannel = Services.io.newChannelFromURI(uri, - null, // aLoadingNode - Services.scriptSecurityManager.getSystemPrincipal(), - null, // aTriggeringPrincipal - Ci.nsILoadInfo.SEC_ALLOW_CROSS_ORIGIN_DATA_IS_NULL, - Ci.nsIContentPolicy.TYPE_OTHER); + let iosChannel = Services.io.newChannelFromURI( + uri, + null, // aLoadingNode + Services.scriptSecurityManager.getSystemPrincipal(), + null, // aTriggeringPrincipal + Ci.nsILoadInfo.SEC_ALLOW_CROSS_ORIGIN_DATA_IS_NULL, + Ci.nsIContentPolicy.TYPE_OTHER + ); let NetUtilChannel = NetUtil.newChannel({ uri, - loadUsingSystemPrincipal: true + loadUsingSystemPrincipal: true, }); Assert.ok(iosChannel.URI.equals(NetUtilChannel.URI)); run_next_test(); } -function test_newChannel_with_options() -{ +function test_newChannel_with_options() { let uri = "data:text/plain,"; - let iosChannel = Services.io.newChannelFromURI(NetUtil.newURI(uri), - null, // aLoadingNode - Services.scriptSecurityManager.getSystemPrincipal(), - null, // aTriggeringPrincipal - Ci.nsILoadInfo.SEC_ALLOW_CROSS_ORIGIN_DATA_IS_NULL, - Ci.nsIContentPolicy.TYPE_OTHER); + let iosChannel = Services.io.newChannelFromURI( + NetUtil.newURI(uri), + null, // aLoadingNode + Services.scriptSecurityManager.getSystemPrincipal(), + null, // aTriggeringPrincipal + Ci.nsILoadInfo.SEC_ALLOW_CROSS_ORIGIN_DATA_IS_NULL, + Ci.nsIContentPolicy.TYPE_OTHER + ); function checkEqualToIOSChannel(channel) { - Assert.ok(iosChannel.URI.equals(channel.URI)); + Assert.ok(iosChannel.URI.equals(channel.URI)); } - checkEqualToIOSChannel(NetUtil.newChannel({ - uri, - loadingPrincipal: Services.scriptSecurityManager.getSystemPrincipal(), - securityFlags: Ci.nsILoadInfo.SEC_ALLOW_CROSS_ORIGIN_DATA_IS_NULL, - contentPolicyType: Ci.nsIContentPolicy.TYPE_OTHER, - })); + checkEqualToIOSChannel( + NetUtil.newChannel({ + uri, + loadingPrincipal: Services.scriptSecurityManager.getSystemPrincipal(), + securityFlags: Ci.nsILoadInfo.SEC_ALLOW_CROSS_ORIGIN_DATA_IS_NULL, + contentPolicyType: Ci.nsIContentPolicy.TYPE_OTHER, + }) + ); - checkEqualToIOSChannel(NetUtil.newChannel({ - uri, - loadUsingSystemPrincipal: true, - })); + checkEqualToIOSChannel( + NetUtil.newChannel({ + uri, + loadUsingSystemPrincipal: true, + }) + ); run_next_test(); } -function test_newChannel_with_wrong_options() -{ +function test_newChannel_with_wrong_options() { let uri = "data:text/plain,"; let systemPrincipal = Services.scriptSecurityManager.getSystemPrincipal(); @@ -628,136 +649,137 @@ function test_newChannel_with_wrong_options() run_next_test(); } -function test_readInputStreamToString() -{ +function test_readInputStreamToString() { const TEST_DATA = "this is a test string\0 with an embedded null"; - let istream = Cc["@mozilla.org/io/string-input-stream;1"]. - createInstance(Ci.nsISupportsCString); + let istream = Cc["@mozilla.org/io/string-input-stream;1"].createInstance( + Ci.nsISupportsCString + ); istream.data = TEST_DATA; - Assert.equal(NetUtil.readInputStreamToString(istream, TEST_DATA.length), - TEST_DATA); + Assert.equal( + NetUtil.readInputStreamToString(istream, TEST_DATA.length), + TEST_DATA + ); run_next_test(); } -function test_readInputStreamToString_no_input_stream() -{ +function test_readInputStreamToString_no_input_stream() { try { NetUtil.readInputStreamToString("hi", 2); do_throw("should throw!"); - } - catch (e) { + } catch (e) { Assert.equal(e.result, Cr.NS_ERROR_INVALID_ARG); } run_next_test(); } -function test_readInputStreamToString_no_bytes_arg() -{ +function test_readInputStreamToString_no_bytes_arg() { const TEST_DATA = "this is a test string"; - let istream = Cc["@mozilla.org/io/string-input-stream;1"]. - createInstance(Ci.nsIStringInputStream); + let istream = Cc["@mozilla.org/io/string-input-stream;1"].createInstance( + Ci.nsIStringInputStream + ); istream.setData(TEST_DATA, TEST_DATA.length); try { NetUtil.readInputStreamToString(istream); do_throw("should throw!"); - } - catch (e) { + } catch (e) { Assert.equal(e.result, Cr.NS_ERROR_INVALID_ARG); } run_next_test(); } -function test_readInputStreamToString_blocking_stream() -{ +function test_readInputStreamToString_blocking_stream() { let pipe = Cc["@mozilla.org/pipe;1"].createInstance(Ci.nsIPipe); pipe.init(true, true, 0, 0, null); try { NetUtil.readInputStreamToString(pipe.inputStream, 10); do_throw("should throw!"); - } - catch (e) { + } catch (e) { Assert.equal(e.result, Cr.NS_BASE_STREAM_WOULD_BLOCK); } run_next_test(); } -function test_readInputStreamToString_too_many_bytes() -{ +function test_readInputStreamToString_too_many_bytes() { const TEST_DATA = "this is a test string"; - let istream = Cc["@mozilla.org/io/string-input-stream;1"]. - createInstance(Ci.nsIStringInputStream); + let istream = Cc["@mozilla.org/io/string-input-stream;1"].createInstance( + Ci.nsIStringInputStream + ); istream.setData(TEST_DATA, TEST_DATA.length); try { NetUtil.readInputStreamToString(istream, TEST_DATA.length + 10); do_throw("should throw!"); - } - catch (e) { + } catch (e) { Assert.equal(e.result, Cr.NS_ERROR_FAILURE); } run_next_test(); } -function test_readInputStreamToString_with_charset() -{ +function test_readInputStreamToString_with_charset() { const TEST_DATA = "\uff10\uff11\uff12\uff13"; const TEST_DATA_UTF8 = "\xef\xbc\x90\xef\xbc\x91\xef\xbc\x92\xef\xbc\x93"; const TEST_DATA_SJIS = "\x82\x4f\x82\x50\x82\x51\x82\x52"; - let istream = Cc["@mozilla.org/io/string-input-stream;1"]. - createInstance(Ci.nsIStringInputStream); + let istream = Cc["@mozilla.org/io/string-input-stream;1"].createInstance( + Ci.nsIStringInputStream + ); istream.setData(TEST_DATA_UTF8, TEST_DATA_UTF8.length); - Assert.equal(NetUtil.readInputStreamToString(istream, - TEST_DATA_UTF8.length, - { charset: "UTF-8"}), - TEST_DATA); + Assert.equal( + NetUtil.readInputStreamToString(istream, TEST_DATA_UTF8.length, { + charset: "UTF-8", + }), + TEST_DATA + ); istream.setData(TEST_DATA_SJIS, TEST_DATA_SJIS.length); - Assert.equal(NetUtil.readInputStreamToString(istream, - TEST_DATA_SJIS.length, - { charset: "Shift_JIS"}), - TEST_DATA); + Assert.equal( + NetUtil.readInputStreamToString(istream, TEST_DATA_SJIS.length, { + charset: "Shift_JIS", + }), + TEST_DATA + ); run_next_test(); } -function test_readInputStreamToString_invalid_sequence() -{ +function test_readInputStreamToString_invalid_sequence() { const TEST_DATA = "\ufffd\ufffd\ufffd\ufffd"; const TEST_DATA_UTF8 = "\xaa\xaa\xaa\xaa"; - let istream = Cc["@mozilla.org/io/string-input-stream;1"]. - createInstance(Ci.nsIStringInputStream); + let istream = Cc["@mozilla.org/io/string-input-stream;1"].createInstance( + Ci.nsIStringInputStream + ); istream.setData(TEST_DATA_UTF8, TEST_DATA_UTF8.length); try { - NetUtil.readInputStreamToString(istream, - TEST_DATA_UTF8.length, - { charset: "UTF-8" }); + NetUtil.readInputStreamToString(istream, TEST_DATA_UTF8.length, { + charset: "UTF-8", + }); do_throw("should throw!"); } catch (e) { Assert.equal(e.result, Cr.NS_ERROR_ILLEGAL_INPUT); } istream.setData(TEST_DATA_UTF8, TEST_DATA_UTF8.length); - Assert.equal(NetUtil.readInputStreamToString(istream, - TEST_DATA_UTF8.length, { - charset: "UTF-8", - replacement: Ci.nsIConverterInputStream.DEFAULT_REPLACEMENT_CHARACTER}), - TEST_DATA); + Assert.equal( + NetUtil.readInputStreamToString(istream, TEST_DATA_UTF8.length, { + charset: "UTF-8", + replacement: Ci.nsIConverterInputStream.DEFAULT_REPLACEMENT_CHARACTER, + }), + TEST_DATA + ); run_next_test(); } - //////////////////////////////////////////////////////////////////////////////// //// Test Runner @@ -792,4 +814,3 @@ function test_readInputStreamToString_invalid_sequence() test_readInputStreamToString_invalid_sequence, ].forEach(f => add_test(f)); var index = 0; - diff --git a/netwerk/test/unit/test_URIs.js b/netwerk/test/unit/test_URIs.js index e61e168730db..50f016e1e457 100644 --- a/netwerk/test/unit/test_URIs.js +++ b/netwerk/test/unit/test_URIs.js @@ -5,12 +5,11 @@ "use strict"; +var gIoService = Cc["@mozilla.org/network/io-service;1"].getService( + Ci.nsIIOService +); -var gIoService = Cc["@mozilla.org/network/io-service;1"] - .getService(Ci.nsIIOService); - - -// Run by: cd objdir; make -C netwerk/test/ xpcshell-tests +// Run by: cd objdir; make -C netwerk/test/ xpcshell-tests // or: cd objdir; make SOLO_FILE="test_URIs.js" -C netwerk/test/ check-one // See also test_URIs2.js. @@ -22,238 +21,339 @@ var gIoService = Cc["@mozilla.org/network/io-service;1"] // TEST DATA // --------- var gTests = [ - { spec: "about:blank", - scheme: "about", + { + spec: "about:blank", + scheme: "about", prePath: "about:", pathQueryRef: "blank", - ref: "", - nsIURL: false, nsINestedURI: true, immutable: true }, - { spec: "about:foobar", - scheme: "about", + ref: "", + nsIURL: false, + nsINestedURI: true, + immutable: true, + }, + { + spec: "about:foobar", + scheme: "about", prePath: "about:", pathQueryRef: "foobar", - ref: "", - nsIURL: false, nsINestedURI: false, immutable: true }, - { spec: "chrome://foobar/somedir/somefile.xml", - scheme: "chrome", + ref: "", + nsIURL: false, + nsINestedURI: false, + immutable: true, + }, + { + spec: "chrome://foobar/somedir/somefile.xml", + scheme: "chrome", prePath: "chrome://foobar", pathQueryRef: "/somedir/somefile.xml", - ref: "", - nsIURL: true, nsINestedURI: false, immutable: true }, - { spec: "data:text/html;charset=utf-8,", - scheme: "data", + ref: "", + nsIURL: true, + nsINestedURI: false, + immutable: true, + }, + { + spec: "data:text/html;charset=utf-8,", + scheme: "data", prePath: "data:", pathQueryRef: "text/html;charset=utf-8,", - ref: "", - nsIURL: false, nsINestedURI: false }, - { spec: "data:text/html;charset=utf-8,\r\n\t", - scheme: "data", + ref: "", + nsIURL: false, + nsINestedURI: false, + }, + { + spec: "data:text/html;charset=utf-8,\r\n\t", + scheme: "data", prePath: "data:", pathQueryRef: "text/html;charset=utf-8,", - ref: "", - nsIURL: false, nsINestedURI: false }, - { spec: "data:text/plain,hello%20world", - scheme: "data", + ref: "", + nsIURL: false, + nsINestedURI: false, + }, + { + spec: "data:text/plain,hello%20world", + scheme: "data", prePath: "data:", pathQueryRef: "text/plain,hello%20world", - ref: "", - nsIURL: false, nsINestedURI: false }, - { spec: "data:text/plain,hello world", - scheme: "data", + ref: "", + nsIURL: false, + nsINestedURI: false, + }, + { + spec: "data:text/plain,hello world", + scheme: "data", prePath: "data:", pathQueryRef: "text/plain,hello world", - ref: "", - nsIURL: false, nsINestedURI: false }, - { spec: "file:///dir/afile", - scheme: "data", + ref: "", + nsIURL: false, + nsINestedURI: false, + }, + { + spec: "file:///dir/afile", + scheme: "data", prePath: "data:", pathQueryRef: "text/plain,2", - ref: "", + ref: "", relativeURI: "data:te\nxt/plain,2", - nsIURL: false, nsINestedURI: false }, - { spec: "file://", - scheme: "file", + nsIURL: false, + nsINestedURI: false, + }, + { + spec: "file://", + scheme: "file", prePath: "file://", pathQueryRef: "/", - ref: "", - nsIURL: true, nsINestedURI: false }, - { spec: "file:///", - scheme: "file", + ref: "", + nsIURL: true, + nsINestedURI: false, + }, + { + spec: "file:///", + scheme: "file", prePath: "file://", pathQueryRef: "/", - ref: "", - nsIURL: true, nsINestedURI: false }, - { spec: "file:///myFile.html", - scheme: "file", + ref: "", + nsIURL: true, + nsINestedURI: false, + }, + { + spec: "file:///myFile.html", + scheme: "file", prePath: "file://", pathQueryRef: "/myFile.html", - ref: "", - nsIURL: true, nsINestedURI: false }, - { spec: "file:///dir/afile", - scheme: "file", + ref: "", + nsIURL: true, + nsINestedURI: false, + }, + { + spec: "file:///dir/afile", + scheme: "file", prePath: "file://", pathQueryRef: "/dir/data/text/plain,2", - ref: "", + ref: "", relativeURI: "data/text/plain,2", - nsIURL: true, nsINestedURI: false }, - { spec: "file:///dir/dir2/", - scheme: "file", + nsIURL: true, + nsINestedURI: false, + }, + { + spec: "file:///dir/dir2/", + scheme: "file", prePath: "file://", pathQueryRef: "/dir/dir2/data/text/plain,2", - ref: "", + ref: "", relativeURI: "data/text/plain,2", - nsIURL: true, nsINestedURI: false }, - { spec: "ftp://ftp.mozilla.org/pub/mozilla.org/README", - scheme: "ftp", + nsIURL: true, + nsINestedURI: false, + }, + { + spec: "ftp://ftp.mozilla.org/pub/mozilla.org/README", + scheme: "ftp", prePath: "ftp://ftp.mozilla.org", pathQueryRef: "/pub/mozilla.org/README", - ref: "", - nsIURL: true, nsINestedURI: false }, - { spec: "ftp://foo:bar@ftp.mozilla.org:100/pub/mozilla.org/README", - scheme: "ftp", + ref: "", + nsIURL: true, + nsINestedURI: false, + }, + { + spec: "ftp://foo:bar@ftp.mozilla.org:100/pub/mozilla.org/README", + scheme: "ftp", prePath: "ftp://foo:bar@ftp.mozilla.org:100", - port: 100, + port: 100, username: "foo", password: "bar", pathQueryRef: "/pub/mozilla.org/README", - ref: "", - nsIURL: true, nsINestedURI: false }, - { spec: "ftp://foo:@ftp.mozilla.org:100/pub/mozilla.org/README", - scheme: "ftp", + ref: "", + nsIURL: true, + nsINestedURI: false, + }, + { + spec: "ftp://foo:@ftp.mozilla.org:100/pub/mozilla.org/README", + scheme: "ftp", prePath: "ftp://foo@ftp.mozilla.org:100", - port: 100, + port: 100, username: "foo", password: "", pathQueryRef: "/pub/mozilla.org/README", - ref: "", - nsIURL: true, nsINestedURI: false }, + ref: "", + nsIURL: true, + nsINestedURI: false, + }, //Bug 706249 - { spec: "gopher://mozilla.org/", - scheme: "gopher", + { + spec: "gopher://mozilla.org/", + scheme: "gopher", prePath: "gopher:", pathQueryRef: "//mozilla.org/", - ref: "", - nsIURL: false, nsINestedURI: false }, - { spec: "http://www.example.com/", - scheme: "http", + ref: "", + nsIURL: false, + nsINestedURI: false, + }, + { + spec: "http://www.example.com/", + scheme: "http", prePath: "http://www.example.com", pathQueryRef: "/", - ref: "", - nsIURL: true, nsINestedURI: false }, - { spec: "http://www.exa\nmple.com/", - scheme: "http", + ref: "", + nsIURL: true, + nsINestedURI: false, + }, + { + spec: "http://www.exa\nmple.com/", + scheme: "http", prePath: "http://www.example.com", pathQueryRef: "/", - ref: "", - nsIURL: true, nsINestedURI: false }, - { spec: "http://10.32.4.239/", - scheme: "http", + ref: "", + nsIURL: true, + nsINestedURI: false, + }, + { + spec: "http://10.32.4.239/", + scheme: "http", prePath: "http://10.32.4.239", - host: "10.32.4.239", + host: "10.32.4.239", pathQueryRef: "/", - ref: "", - nsIURL: true, nsINestedURI: false }, - { spec: "http://[::192.9.5.5]/ipng", - scheme: "http", + ref: "", + nsIURL: true, + nsINestedURI: false, + }, + { + spec: "http://[::192.9.5.5]/ipng", + scheme: "http", prePath: "http://[::c009:505]", - host: "::c009:505", + host: "::c009:505", pathQueryRef: "/ipng", - ref: "", - nsIURL: true, nsINestedURI: false }, - { spec: "http://[FEDC:BA98:7654:3210:FEDC:BA98:7654:3210]:8888/index.html", - scheme: "http", + ref: "", + nsIURL: true, + nsINestedURI: false, + }, + { + spec: "http://[FEDC:BA98:7654:3210:FEDC:BA98:7654:3210]:8888/index.html", + scheme: "http", prePath: "http://[fedc:ba98:7654:3210:fedc:ba98:7654:3210]:8888", - host: "fedc:ba98:7654:3210:fedc:ba98:7654:3210", - port: 8888, + host: "fedc:ba98:7654:3210:fedc:ba98:7654:3210", + port: 8888, pathQueryRef: "/index.html", - ref: "", - nsIURL: true, nsINestedURI: false }, - { spec: "http://bar:foo@www.mozilla.org:8080/pub/mozilla.org/README.html", - scheme: "http", + ref: "", + nsIURL: true, + nsINestedURI: false, + }, + { + spec: "http://bar:foo@www.mozilla.org:8080/pub/mozilla.org/README.html", + scheme: "http", prePath: "http://bar:foo@www.mozilla.org:8080", - port: 8080, + port: 8080, username: "bar", password: "foo", - host: "www.mozilla.org", + host: "www.mozilla.org", pathQueryRef: "/pub/mozilla.org/README.html", - ref: "", - nsIURL: true, nsINestedURI: false }, - { spec: "jar:resource://!/", - scheme: "jar", + ref: "", + nsIURL: true, + nsINestedURI: false, + }, + { + spec: "jar:resource://!/", + scheme: "jar", prePath: "jar:", pathQueryRef: "resource:///!/", - ref: "", - nsIURL: true, nsINestedURI: true }, - { spec: "jar:resource://gre/chrome.toolkit.jar!/", - scheme: "jar", + ref: "", + nsIURL: true, + nsINestedURI: true, + }, + { + spec: "jar:resource://gre/chrome.toolkit.jar!/", + scheme: "jar", prePath: "jar:", pathQueryRef: "resource://gre/chrome.toolkit.jar!/", - ref: "", - nsIURL: true, nsINestedURI: true }, - { spec: "mailto:webmaster@mozilla.com", - scheme: "mailto", + ref: "", + nsIURL: true, + nsINestedURI: true, + }, + { + spec: "mailto:webmaster@mozilla.com", + scheme: "mailto", prePath: "mailto:", pathQueryRef: "webmaster@mozilla.com", - ref: "", - nsIURL: false, nsINestedURI: false }, - { spec: "javascript:new Date()", - scheme: "javascript", + ref: "", + nsIURL: false, + nsINestedURI: false, + }, + { + spec: "javascript:new Date()", + scheme: "javascript", prePath: "javascript:", pathQueryRef: "new Date()", - ref: "", - nsIURL: false, nsINestedURI: false }, - { spec: "blob:123456", - scheme: "blob", + ref: "", + nsIURL: false, + nsINestedURI: false, + }, + { + spec: "blob:123456", + scheme: "blob", prePath: "blob:", pathQueryRef: "123456", - ref: "", - nsIURL: false, nsINestedURI: false, immutable: true }, - { spec: "place:sort=8&maxResults=10", - scheme: "place", + ref: "", + nsIURL: false, + nsINestedURI: false, + immutable: true, + }, + { + spec: "place:sort=8&maxResults=10", + scheme: "place", prePath: "place:", pathQueryRef: "sort=8&maxResults=10", - ref: "", - nsIURL: false, nsINestedURI: false }, - { spec: "resource://gre/", - scheme: "resource", + ref: "", + nsIURL: false, + nsINestedURI: false, + }, + { + spec: "resource://gre/", + scheme: "resource", prePath: "resource://gre", pathQueryRef: "/", - ref: "", - nsIURL: true, nsINestedURI: false }, - { spec: "resource://gre/components/", - scheme: "resource", + ref: "", + nsIURL: true, + nsINestedURI: false, + }, + { + spec: "resource://gre/components/", + scheme: "resource", prePath: "resource://gre", pathQueryRef: "/components/", - ref: "", - nsIURL: true, nsINestedURI: false }, + ref: "", + nsIURL: true, + nsINestedURI: false, + }, - // Adding more? Consider adding to test_URIs2.js instead, so that neither - // test runs for *too* long, risking timeouts on slow platforms. + // Adding more? Consider adding to test_URIs2.js instead, so that neither + // test runs for *too* long, risking timeouts on slow platforms. ]; -var gHashSuffixes = [ - "#", - "#myRef", - "#myRef?a=b", - "#myRef#", - "#myRef#x:yz" -]; +var gHashSuffixes = ["#", "#myRef", "#myRef?a=b", "#myRef#", "#myRef#x:yz"]; // TEST HELPER FUNCTIONS // --------------------- function do_info(text, stack) { - if (!stack) + if (!stack) { stack = Components.stack.caller; + } - dump( "\n" + - "TEST-INFO | " + stack.filename + " | [" + stack.name + " : " + - stack.lineNumber + "] " + text + "\n"); + dump( + "\n" + + "TEST-INFO | " + + stack.filename + + " | [" + + stack.name + + " : " + + stack.lineNumber + + "] " + + text + + "\n" + ); } // Checks that the URIs satisfy equals(), in both possible orderings. // Also checks URI.equalsExceptRef(), because equal URIs should also be equal // when we ignore the ref. -// +// // The third argument is optional. If the client passes a third argument // (e.g. todo_check_true), we'll use that in lieu of ok. function do_check_uri_eq(aURI1, aURI2, aCheckTrueFunc = ok) { @@ -275,11 +375,13 @@ function do_check_uri_eq(aURI1, aURI2, aCheckTrueFunc = ok) { // The third argument is optional. If the client passes a third argument // (e.g. todo_check_true), we'll use that in lieu of ok. function do_check_uri_eqExceptRef(aURI1, aURI2, aCheckTrueFunc = ok) { - do_info("(uri equalsExceptRef check: '" + - aURI1.spec + "' == '" + aURI2.spec + "')"); + do_info( + "(uri equalsExceptRef check: '" + aURI1.spec + "' == '" + aURI2.spec + "')" + ); aCheckTrueFunc(aURI1.equalsExceptRef(aURI2)); - do_info("(uri equalsExceptRef check: '" + - aURI2.spec + "' == '" + aURI1.spec + "')"); + do_info( + "(uri equalsExceptRef check: '" + aURI2.spec + "' == '" + aURI1.spec + "')" + ); aCheckTrueFunc(aURI2.equalsExceptRef(aURI1)); } @@ -288,13 +390,20 @@ function do_check_uri_eqExceptRef(aURI1, aURI2, aCheckTrueFunc = ok) { // if aTestFunctor is passed in). function do_check_property(aTest, aURI, aPropertyName, aTestFunctor) { if (aTest[aPropertyName]) { - var expectedVal = aTestFunctor ? - aTestFunctor(aTest[aPropertyName]) : - aTest[aPropertyName]; + var expectedVal = aTestFunctor + ? aTestFunctor(aTest[aPropertyName]) + : aTest[aPropertyName]; - do_info("testing " + aPropertyName + " of " + - (aTestFunctor ? "modified '" : "'" ) + aTest.spec + - "' is '" + expectedVal + "'"); + do_info( + "testing " + + aPropertyName + + " of " + + (aTestFunctor ? "modified '" : "'") + + aTest.spec + + "' is '" + + expectedVal + + "'" + ); Assert.equal(aURI[aPropertyName], expectedVal); } } @@ -303,12 +412,16 @@ function do_check_property(aTest, aURI, aPropertyName, aTestFunctor) { function do_test_uri_basic(aTest) { var URI; - do_info("Basic tests for " + aTest.spec + - " relative URI: " + (aTest.relativeURI === undefined ? "(none)" : aTest.relativeURI) ); + do_info( + "Basic tests for " + + aTest.spec + + " relative URI: " + + (aTest.relativeURI === undefined ? "(none)" : aTest.relativeURI) + ); try { URI = NetUtil.newURI(aTest.spec); - } catch(e) { + } catch (e) { do_info("Caught error on parse of" + aTest.spec + " Error: " + e.result); if (aTest.fail) { Assert.equal(e.result, aTest.result); @@ -323,14 +436,26 @@ function do_test_uri_basic(aTest) { try { relURI = gIoService.newURI(aTest.relativeURI, null, URI); } catch (e) { - do_info("Caught error on Relative parse of " + aTest.spec + " + " + aTest.relativeURI +" Error: " + e.result); + do_info( + "Caught error on Relative parse of " + + aTest.spec + + " + " + + aTest.relativeURI + + " Error: " + + e.result + ); if (aTest.relativeFail) { Assert.equal(e.result, aTest.relativeFail); return; } do_throw(e.result); } - do_info("relURI.pathQueryRef = " + relURI.pathQueryRef + ", was " + URI.pathQueryRef); + do_info( + "relURI.pathQueryRef = " + + relURI.pathQueryRef + + ", was " + + URI.pathQueryRef + ); URI = relURI; do_info("URI.pathQueryRef now = " + URI.pathQueryRef); } @@ -338,27 +463,34 @@ function do_test_uri_basic(aTest) { // Sanity-check do_info("testing " + aTest.spec + " equals a clone of itself"); do_check_uri_eq(URI, URI.mutate().finalize()); - do_check_uri_eqExceptRef(URI, URI.mutate().setRef("").finalize()); + do_check_uri_eqExceptRef( + URI, + URI.mutate() + .setRef("") + .finalize() + ); do_info("testing " + aTest.spec + " instanceof nsIURL"); Assert.equal(URI instanceof Ci.nsIURL, aTest.nsIURL); do_info("testing " + aTest.spec + " instanceof nsINestedURI"); - Assert.equal(URI instanceof Ci.nsINestedURI, - aTest.nsINestedURI); + Assert.equal(URI instanceof Ci.nsINestedURI, aTest.nsINestedURI); - do_info("testing that " + aTest.spec + " throws or returns false " + - "from equals(null)"); + do_info( + "testing that " + + aTest.spec + + " throws or returns false " + + "from equals(null)" + ); // XXXdholbert At some point it'd probably be worth making this behavior // (throwing vs. returning false) consistent across URI implementations. var threw = false; var isEqualToNull; try { isEqualToNull = URI.equals(null); - } catch(e) { + } catch (e) { threw = true; } Assert.ok(threw || !isEqualToNull); - // Check the various components do_check_property(aTest, URI, "scheme"); do_check_property(aTest, URI, "prePath"); @@ -388,54 +520,104 @@ function do_test_uri_with_hash_suffix(aTest, aSuffix) { try { origURI = gIoService.newURI(aTest.relativeURI, null, origURI); } catch (e) { - do_info("Caught error on Relative parse of " + aTest.spec + " + " + aTest.relativeURI +" Error: " + e.result); + do_info( + "Caught error on Relative parse of " + + aTest.spec + + " + " + + aTest.relativeURI + + " Error: " + + e.result + ); return; } try { testURI = gIoService.newURI(aSuffix, null, origURI); } catch (e) { - do_info("Caught error adding suffix to " + aTest.spec + " + " + aTest.relativeURI + ", suffix " + aSuffix + " Error: " + e.result); + do_info( + "Caught error adding suffix to " + + aTest.spec + + " + " + + aTest.relativeURI + + ", suffix " + + aSuffix + + " Error: " + + e.result + ); return; } } else { testURI = NetUtil.newURI(aTest.spec + aSuffix); } - do_info("testing " + aTest.spec + " with '" + aSuffix + "' appended " + - "equals a clone of itself"); + do_info( + "testing " + + aTest.spec + + " with '" + + aSuffix + + "' appended " + + "equals a clone of itself" + ); do_check_uri_eq(testURI, testURI.mutate().finalize()); - do_info("testing " + aTest.spec + - " doesn't equal self with '" + aSuffix + "' appended"); + do_info( + "testing " + + aTest.spec + + " doesn't equal self with '" + + aSuffix + + "' appended" + ); Assert.ok(!origURI.equals(testURI)); - do_info("testing " + aTest.spec + - " is equalExceptRef to self with '" + aSuffix + "' appended"); + do_info( + "testing " + + aTest.spec + + " is equalExceptRef to self with '" + + aSuffix + + "' appended" + ); do_check_uri_eqExceptRef(origURI, testURI); Assert.equal(testURI.hasRef, true); if (!origURI.ref) { // These tests fail if origURI has a ref - do_info("testing setRef('') on " + testURI.spec + - " is equal to no-ref version but not equal to ref version"); - var cloneNoRef = testURI.mutate().setRef("").finalize(); // we used to clone here. + do_info( + "testing setRef('') on " + + testURI.spec + + " is equal to no-ref version but not equal to ref version" + ); + var cloneNoRef = testURI + .mutate() + .setRef("") + .finalize(); // we used to clone here. do_info("cloneNoRef: " + cloneNoRef.spec + " hasRef: " + cloneNoRef.hasRef); do_info("testURI: " + testURI.spec + " hasRef: " + testURI.hasRef); do_check_uri_eq(cloneNoRef, origURI); Assert.ok(!cloneNoRef.equals(testURI)); - do_info("testing cloneWithNewRef on " + testURI.spec + - " with an empty ref is equal to no-ref version but not equal to ref version"); - var cloneNewRef = testURI.mutate().setRef("").finalize(); + do_info( + "testing cloneWithNewRef on " + + testURI.spec + + " with an empty ref is equal to no-ref version but not equal to ref version" + ); + var cloneNewRef = testURI + .mutate() + .setRef("") + .finalize(); do_check_uri_eq(cloneNewRef, origURI); do_check_uri_eq(cloneNewRef, cloneNoRef); Assert.ok(!cloneNewRef.equals(testURI)); - do_info("testing cloneWithNewRef on " + origURI.spec + - " with the same new ref is equal to ref version and not equal to no-ref version"); - cloneNewRef = origURI.mutate().setRef(aSuffix).finalize(); + do_info( + "testing cloneWithNewRef on " + + origURI.spec + + " with the same new ref is equal to ref version and not equal to no-ref version" + ); + cloneNewRef = origURI + .mutate() + .setRef(aSuffix) + .finalize(); do_check_uri_eq(cloneNewRef, testURI); Assert.ok(cloneNewRef.equals(testURI)); } @@ -444,10 +626,12 @@ function do_test_uri_with_hash_suffix(aTest, aSuffix) { do_check_property(aTest, testURI, "prePath"); if (!origURI.ref) { // These don't work if it's a ref already because '+' doesn't give the right result - do_check_property(aTest, testURI, "pathQueryRef", - function(aStr) { return aStr + aSuffix; }); - do_check_property(aTest, testURI, "ref", - function(aStr) { return aSuffix.substr(1); }); + do_check_property(aTest, testURI, "pathQueryRef", function(aStr) { + return aStr + aSuffix; + }); + do_check_property(aTest, testURI, "ref", function(aStr) { + return aSuffix.substr(1); + }); } } @@ -456,32 +640,53 @@ function do_test_mutate_ref(aTest, aSuffix) { do_info("making sure caller is using suffix that starts with '#'"); Assert.equal(aSuffix[0], "#"); - var refURIWithSuffix = NetUtil.newURI(aTest.spec + aSuffix); + var refURIWithSuffix = NetUtil.newURI(aTest.spec + aSuffix); var refURIWithoutSuffix = NetUtil.newURI(aTest.spec); - var testURI = NetUtil.newURI(aTest.spec); + var testURI = NetUtil.newURI(aTest.spec); // First: Try setting .ref to our suffix - do_info("testing that setting .ref on " + aTest.spec + - " to '" + aSuffix + "' does what we expect"); - testURI = testURI.mutate().setRef(aSuffix).finalize(); + do_info( + "testing that setting .ref on " + + aTest.spec + + " to '" + + aSuffix + + "' does what we expect" + ); + testURI = testURI + .mutate() + .setRef(aSuffix) + .finalize(); do_check_uri_eq(testURI, refURIWithSuffix); do_check_uri_eqExceptRef(testURI, refURIWithoutSuffix); // Now try setting .ref but leave off the initial hash (expect same result) var suffixLackingHash = aSuffix.substr(1); - if (suffixLackingHash) { // (skip this our suffix was *just* a #) - do_info("testing that setting .ref on " + aTest.spec + - " to '" + suffixLackingHash + "' does what we expect"); - testURI = testURI.mutate().setRef(suffixLackingHash).finalize(); + if (suffixLackingHash) { + // (skip this our suffix was *just* a #) + do_info( + "testing that setting .ref on " + + aTest.spec + + " to '" + + suffixLackingHash + + "' does what we expect" + ); + testURI = testURI + .mutate() + .setRef(suffixLackingHash) + .finalize(); do_check_uri_eq(testURI, refURIWithSuffix); do_check_uri_eqExceptRef(testURI, refURIWithoutSuffix); } // Now, clear .ref (should get us back the original spec) - do_info("testing that clearing .ref on " + testURI.spec + - " does what we expect"); - testURI = testURI.mutate().setRef("").finalize(); + do_info( + "testing that clearing .ref on " + testURI.spec + " does what we expect" + ); + testURI = testURI + .mutate() + .setRef("") + .finalize(); do_check_uri_eq(testURI, refURIWithoutSuffix); do_check_uri_eqExceptRef(testURI, refURIWithSuffix); @@ -490,13 +695,17 @@ function do_test_mutate_ref(aTest, aSuffix) { // Now try setting .spec directly (including suffix) and then clearing .ref var specWithSuffix = aTest.spec + aSuffix; - do_info("testing that setting spec to " + - specWithSuffix + " and then clearing ref does what we expect"); + do_info( + "testing that setting spec to " + + specWithSuffix + + " and then clearing ref does what we expect" + ); - testURI = testURI.mutate() - .setSpec(specWithSuffix) - .setRef("") - .finalize(); + testURI = testURI + .mutate() + .setSpec(specWithSuffix) + .setRef("") + .finalize(); do_check_uri_eq(testURI, refURIWithoutSuffix); do_check_uri_eqExceptRef(testURI, refURIWithSuffix); @@ -507,96 +716,161 @@ function do_test_mutate_ref(aTest, aSuffix) { testURI = NetUtil.newURI(aTest.spec); var pathWithSuffix = aTest.pathQueryRef + aSuffix; - do_info("testing that setting path to " + - pathWithSuffix + " and then clearing ref does what we expect"); - testURI = testURI.mutate() - .setPathQueryRef(pathWithSuffix) - .setRef("") - .finalize(); + do_info( + "testing that setting path to " + + pathWithSuffix + + " and then clearing ref does what we expect" + ); + testURI = testURI + .mutate() + .setPathQueryRef(pathWithSuffix) + .setRef("") + .finalize(); do_check_uri_eq(testURI, refURIWithoutSuffix); do_check_uri_eqExceptRef(testURI, refURIWithSuffix); // Also: make sure that clearing .pathQueryRef also clears .ref - testURI = testURI.mutate().setPathQueryRef(pathWithSuffix).finalize(); - do_info("testing that clearing path from " + - pathWithSuffix + " also clears .ref"); - testURI = testURI.mutate().setPathQueryRef("").finalize(); + testURI = testURI + .mutate() + .setPathQueryRef(pathWithSuffix) + .finalize(); + do_info( + "testing that clearing path from " + + pathWithSuffix + + " also clears .ref" + ); + testURI = testURI + .mutate() + .setPathQueryRef("") + .finalize(); Assert.equal(testURI.ref, ""); } } } // Check that changing nested/about URIs works correctly. -function check_nested_mutations() -{ +function check_nested_mutations() { // nsNestedAboutURI let uri1 = gIoService.newURI("about:blank#"); let uri2 = gIoService.newURI("about:blank"); - let uri3 = uri1.mutate().setRef("").finalize(); + let uri3 = uri1 + .mutate() + .setRef("") + .finalize(); do_check_uri_eq(uri3, uri2); - uri3 = uri2.mutate().setRef("#").finalize(); + uri3 = uri2 + .mutate() + .setRef("#") + .finalize(); do_check_uri_eq(uri3, uri1); uri1 = gIoService.newURI("about:blank?something"); uri2 = gIoService.newURI("about:blank"); - uri3 = uri1.mutate().setQuery("").finalize(); + uri3 = uri1 + .mutate() + .setQuery("") + .finalize(); do_check_uri_eq(uri3, uri2); - uri3 = uri2.mutate().setQuery("something").finalize(); + uri3 = uri2 + .mutate() + .setQuery("something") + .finalize(); do_check_uri_eq(uri3, uri1); uri1 = gIoService.newURI("about:blank?query#ref"); uri2 = gIoService.newURI("about:blank"); - uri3 = uri1.mutate().setPathQueryRef("blank").finalize(); + uri3 = uri1 + .mutate() + .setPathQueryRef("blank") + .finalize(); do_check_uri_eq(uri3, uri2); - uri3 = uri2.mutate().setPathQueryRef("blank?query#ref").finalize(); + uri3 = uri2 + .mutate() + .setPathQueryRef("blank?query#ref") + .finalize(); do_check_uri_eq(uri3, uri1); // nsSimpleNestedURI uri1 = gIoService.newURI("view-source:http://example.com/path#"); uri2 = gIoService.newURI("view-source:http://example.com/path"); - uri3 = uri1.mutate().setRef("").finalize(); + uri3 = uri1 + .mutate() + .setRef("") + .finalize(); do_check_uri_eq(uri3, uri2); - uri3 = uri2.mutate().setRef("#").finalize(); + uri3 = uri2 + .mutate() + .setRef("#") + .finalize(); do_check_uri_eq(uri3, uri1); uri1 = gIoService.newURI("view-source:http://example.com/path?something"); uri2 = gIoService.newURI("view-source:http://example.com/path"); - uri3 = uri1.mutate().setQuery("").finalize(); + uri3 = uri1 + .mutate() + .setQuery("") + .finalize(); do_check_uri_eq(uri3, uri2); - uri3 = uri2.mutate().setQuery("something").finalize(); + uri3 = uri2 + .mutate() + .setQuery("something") + .finalize(); do_check_uri_eq(uri3, uri1); uri1 = gIoService.newURI("view-source:http://example.com/path?query#ref"); uri2 = gIoService.newURI("view-source:http://example.com/path"); - uri3 = uri1.mutate().setPathQueryRef("path").finalize(); + uri3 = uri1 + .mutate() + .setPathQueryRef("path") + .finalize(); do_check_uri_eq(uri3, uri2); - uri3 = uri2.mutate().setPathQueryRef("path?query#ref").finalize(); + uri3 = uri2 + .mutate() + .setPathQueryRef("path?query#ref") + .finalize(); do_check_uri_eq(uri3, uri1); uri1 = gIoService.newURI("view-source:about:blank#"); uri2 = gIoService.newURI("view-source:about:blank"); - uri3 = uri1.mutate().setRef("").finalize(); + uri3 = uri1 + .mutate() + .setRef("") + .finalize(); do_check_uri_eq(uri3, uri2); - uri3 = uri2.mutate().setRef("#").finalize(); + uri3 = uri2 + .mutate() + .setRef("#") + .finalize(); do_check_uri_eq(uri3, uri1); uri1 = gIoService.newURI("view-source:about:blank?something"); uri2 = gIoService.newURI("view-source:about:blank"); - uri3 = uri1.mutate().setQuery("").finalize(); + uri3 = uri1 + .mutate() + .setQuery("") + .finalize(); do_check_uri_eq(uri3, uri2); - uri3 = uri2.mutate().setQuery("something").finalize(); + uri3 = uri2 + .mutate() + .setQuery("something") + .finalize(); do_check_uri_eq(uri3, uri1); uri1 = gIoService.newURI("view-source:about:blank?query#ref"); uri2 = gIoService.newURI("view-source:about:blank"); - uri3 = uri1.mutate().setPathQueryRef("blank").finalize(); + uri3 = uri1 + .mutate() + .setPathQueryRef("blank") + .finalize(); do_check_uri_eq(uri3, uri2); - uri3 = uri2.mutate().setPathQueryRef("blank?query#ref").finalize(); + uri3 = uri2 + .mutate() + .setPathQueryRef("blank?query#ref") + .finalize(); do_check_uri_eq(uri3, uri1); } -function check_space_escaping() -{ +function check_space_escaping() { let uri = gIoService.newURI("data:text/plain,hello%20world#space hash"); Assert.equal(uri.spec, "data:text/plain,hello%20world#space%20hash"); uri = gIoService.newURI("data:text/plain,hello%20world#space%20hash"); @@ -609,8 +883,7 @@ function check_space_escaping() uri = gIoService.newURI("http://example.com/test%20path#test%20path"); } -function check_schemeIsNull() -{ +function check_schemeIsNull() { let uri = gIoService.newURI("data:text/plain,aaa"); Assert.ok(!uri.schemeIs(null)); uri = gIoService.newURI("http://example.com"); @@ -625,11 +898,21 @@ function check_schemeIsNull() // Check that characters in the query of moz-extension aren't improperly unescaped (Bug 1547882) function check_mozextension_query() { - let uri = gIoService.newURI("moz-extension://a7d1572e-3beb-4d93-a920-c408fa09e8ea/_source/holding.html"); - uri = uri.mutate().setQuery("u=https%3A%2F%2Fnews.ycombinator.com%2F").finalize(); + let uri = gIoService.newURI( + "moz-extension://a7d1572e-3beb-4d93-a920-c408fa09e8ea/_source/holding.html" + ); + uri = uri + .mutate() + .setQuery("u=https%3A%2F%2Fnews.ycombinator.com%2F") + .finalize(); Assert.equal(uri.query, "u=https%3A%2F%2Fnews.ycombinator.com%2F"); - uri = gIoService.newURI("moz-extension://a7d1572e-3beb-4d93-a920-c408fa09e8ea/_source/holding.html?u=https%3A%2F%2Fnews.ycombinator.com%2F"); - Assert.equal(uri.spec, "moz-extension://a7d1572e-3beb-4d93-a920-c408fa09e8ea/_source/holding.html?u=https%3A%2F%2Fnews.ycombinator.com%2F"); + uri = gIoService.newURI( + "moz-extension://a7d1572e-3beb-4d93-a920-c408fa09e8ea/_source/holding.html?u=https%3A%2F%2Fnews.ycombinator.com%2F" + ); + Assert.equal( + uri.spec, + "moz-extension://a7d1572e-3beb-4d93-a920-c408fa09e8ea/_source/holding.html?u=https%3A%2F%2Fnews.ycombinator.com%2F" + ); Assert.equal(uri.query, "u=https%3A%2F%2Fnews.ycombinator.com%2F"); } @@ -642,16 +925,20 @@ function check_resolve() { function test_extra_protocols() { let url = gIoService.newURI("dweb://example.com/test"); Assert.equal(url.host, "example.com"); - url = gIoService.newURI("dat://41f8a987cfeba80a037e51cc8357d513b62514de36f2f9b3d3eeec7a8fb3b5a5/"); - Assert.equal(url.host, "41f8a987cfeba80a037e51cc8357d513b62514de36f2f9b3d3eeec7a8fb3b5a5"); + url = gIoService.newURI( + "dat://41f8a987cfeba80a037e51cc8357d513b62514de36f2f9b3d3eeec7a8fb3b5a5/" + ); + Assert.equal( + url.host, + "41f8a987cfeba80a037e51cc8357d513b62514de36f2f9b3d3eeec7a8fb3b5a5" + ); url = gIoService.newURI("dat://example.com/test"); Assert.equal(url.host, "example.com"); } // TEST MAIN FUNCTION // ------------------ -function run_test() -{ +function run_test() { check_nested_mutations(); check_space_escaping(); check_schemeIsNull(); @@ -664,7 +951,9 @@ function run_test() let base = gIoService.newURI("http://example.org/xenia?"); let resolved = gIoService.newURI("?x", null, base); let expected = gIoService.newURI("http://example.org/xenia?x"); - do_info("Bug 662981: ACSII - comparing " + resolved.spec + " and " + expected.spec); + do_info( + "Bug 662981: ACSII - comparing " + resolved.spec + " and " + expected.spec + ); Assert.ok(resolved.equals(expected)); // UTF-8 character "è" @@ -672,7 +961,9 @@ function run_test() base = gIoService.newURI("http://example.org/xènia?"); resolved = gIoService.newURI("?x", null, base); expected = gIoService.newURI("http://example.org/xènia?x"); - do_info("Bug 662981: UTF8 - comparing " + resolved.spec + " and " + expected.spec); + do_info( + "Bug 662981: UTF8 - comparing " + resolved.spec + " and " + expected.spec + ); Assert.ok(resolved.equals(expected)); gTests.forEach(function(aTest) { @@ -682,11 +973,11 @@ function run_test() if (!aTest.fail) { // Try adding various #-prefixed strings to the ends of the URIs gHashSuffixes.forEach(function(aSuffix) { - do_test_uri_with_hash_suffix(aTest, aSuffix); - if (!aTest.immutable) { - do_test_mutate_ref(aTest, aSuffix); - } - }); + do_test_uri_with_hash_suffix(aTest, aSuffix); + if (!aTest.immutable) { + do_test_mutate_ref(aTest, aSuffix); + } + }); // For URIs that we couldn't mutate above due to them being immutable: // Now we check that they're actually immutable. diff --git a/netwerk/test/unit/test_URIs2.js b/netwerk/test/unit/test_URIs2.js index 8d5e86df7a77..99e90a6d14d1 100644 --- a/netwerk/test/unit/test_URIs2.js +++ b/netwerk/test/unit/test_URIs2.js @@ -1,15 +1,15 @@ /* -*- indent-tabs-mode: nil; js-indent-level: 2 -*- */ -var gIoService = Cc["@mozilla.org/network/io-service;1"] - .getService(Ci.nsIIOService); +var gIoService = Cc["@mozilla.org/network/io-service;1"].getService( + Ci.nsIIOService +); - -// Run by: cd objdir; make -C netwerk/test/ xpcshell-tests +// Run by: cd objdir; make -C netwerk/test/ xpcshell-tests // or: cd objdir; make SOLO_FILE="test_URIs2.js" -C netwerk/test/ check-one // This is a clone of test_URIs.js, with a different set of test data in gTests. // The original test data in test_URIs.js was split between test_URIs and test_URIs2.js -// because test_URIs.js was running for too long on slow platforms, causing +// because test_URIs.js was running for too long on slow platforms, causing // intermittent timeouts. // Relevant RFCs: 1738, 1808, 2396, 3986 (newer than the code) @@ -19,112 +19,159 @@ var gIoService = Cc["@mozilla.org/network/io-service;1"] // TEST DATA // --------- var gTests = [ - { spec: "view-source:about:blank", - scheme: "view-source", + { + spec: "view-source:about:blank", + scheme: "view-source", prePath: "view-source:", pathQueryRef: "about:blank", - ref: "", - nsIURL: false, nsINestedURI: true, immutable: true }, - { spec: "view-source:http://www.mozilla.org/", - scheme: "view-source", + ref: "", + nsIURL: false, + nsINestedURI: true, + immutable: true, + }, + { + spec: "view-source:http://www.mozilla.org/", + scheme: "view-source", prePath: "view-source:", pathQueryRef: "http://www.mozilla.org/", - ref: "", - nsIURL: false, nsINestedURI: true, immutable: true }, - { spec: "x-external:", - scheme: "x-external", + ref: "", + nsIURL: false, + nsINestedURI: true, + immutable: true, + }, + { + spec: "x-external:", + scheme: "x-external", prePath: "x-external:", pathQueryRef: "", - ref: "", - nsIURL: false, nsINestedURI: false }, - { spec: "x-external:abc", - scheme: "x-external", + ref: "", + nsIURL: false, + nsINestedURI: false, + }, + { + spec: "x-external:abc", + scheme: "x-external", prePath: "x-external:", pathQueryRef: "abc", - ref: "", - nsIURL: false, nsINestedURI: false }, - { spec: "http://www2.example.com/", + ref: "", + nsIURL: false, + nsINestedURI: false, + }, + { + spec: "http://www2.example.com/", relativeURI: "a/b/c/d", - scheme: "http", + scheme: "http", prePath: "http://www2.example.com", pathQueryRef: "/a/b/c/d", - ref: "", - nsIURL: true, nsINestedURI: false }, + ref: "", + nsIURL: true, + nsINestedURI: false, + }, // relative URL testcases from http://greenbytes.de/tech/webdav/rfc3986.html#rfc.section.5.4 - { spec: "http://a/b/c/d;p?q", + { + spec: "http://a/b/c/d;p?q", relativeURI: "g:h", - scheme: "g", + scheme: "g", prePath: "g:", pathQueryRef: "h", - ref: "", - nsIURL: false, nsINestedURI: false }, - { spec: "http://a/b/c/d;p?q", + ref: "", + nsIURL: false, + nsINestedURI: false, + }, + { + spec: "http://a/b/c/d;p?q", relativeURI: "g", - scheme: "http", + scheme: "http", prePath: "http://a", pathQueryRef: "/b/c/g", - ref: "", - nsIURL: true, nsINestedURI: false }, - { spec: "http://a/b/c/d;p?q", + ref: "", + nsIURL: true, + nsINestedURI: false, + }, + { + spec: "http://a/b/c/d;p?q", relativeURI: "./g", - scheme: "http", + scheme: "http", prePath: "http://a", pathQueryRef: "/b/c/g", - ref: "", - nsIURL: true, nsINestedURI: false }, - { spec: "http://a/b/c/d;p?q", + ref: "", + nsIURL: true, + nsINestedURI: false, + }, + { + spec: "http://a/b/c/d;p?q", relativeURI: "g/", - scheme: "http", + scheme: "http", prePath: "http://a", pathQueryRef: "/b/c/g/", - ref: "", - nsIURL: true, nsINestedURI: false }, - { spec: "http://a/b/c/d;p?q", + ref: "", + nsIURL: true, + nsINestedURI: false, + }, + { + spec: "http://a/b/c/d;p?q", relativeURI: "/g", - scheme: "http", + scheme: "http", prePath: "http://a", pathQueryRef: "/g", - ref: "", - nsIURL: true, nsINestedURI: false }, - { spec: "http://a/b/c/d;p?q", + ref: "", + nsIURL: true, + nsINestedURI: false, + }, + { + spec: "http://a/b/c/d;p?q", relativeURI: "?y", - scheme: "http", + scheme: "http", prePath: "http://a", pathQueryRef: "/b/c/d;p?y", - ref: "",// fix - nsIURL: true, nsINestedURI: false }, - { spec: "http://a/b/c/d;p?q", + ref: "", // fix + nsIURL: true, + nsINestedURI: false, + }, + { + spec: "http://a/b/c/d;p?q", relativeURI: "g?y", - scheme: "http", + scheme: "http", prePath: "http://a", pathQueryRef: "/b/c/g?y", - ref: "",// fix + ref: "", // fix specIgnoringRef: "http://a/b/c/g?y", - hasRef: false, - nsIURL: true, nsINestedURI: false }, - { spec: "http://a/b/c/d;p?q", + hasRef: false, + nsIURL: true, + nsINestedURI: false, + }, + { + spec: "http://a/b/c/d;p?q", relativeURI: "#s", - scheme: "http", + scheme: "http", prePath: "http://a", pathQueryRef: "/b/c/d;p?q#s", - ref: "s",// fix + ref: "s", // fix specIgnoringRef: "http://a/b/c/d;p?q", - hasRef: true, - nsIURL: true, nsINestedURI: false }, - { spec: "http://a/b/c/d;p?q", + hasRef: true, + nsIURL: true, + nsINestedURI: false, + }, + { + spec: "http://a/b/c/d;p?q", relativeURI: "g#s", - scheme: "http", + scheme: "http", prePath: "http://a", pathQueryRef: "/b/c/g#s", - ref: "s", - nsIURL: true, nsINestedURI: false }, - { spec: "http://a/b/c/d;p?q", + ref: "s", + nsIURL: true, + nsINestedURI: false, + }, + { + spec: "http://a/b/c/d;p?q", relativeURI: "g?y#s", - scheme: "http", + scheme: "http", prePath: "http://a", pathQueryRef: "/b/c/g?y#s", - ref: "s", - nsIURL: true, nsINestedURI: false }, + ref: "s", + nsIURL: true, + nsINestedURI: false, + }, /* Bug xxxxxx - we return a path of b/c/;x { spec: "http://a/b/c/d;p?q", @@ -135,20 +182,26 @@ var gTests = [ ref: "", nsIURL: true, nsINestedURI: false }, */ - { spec: "http://a/b/c/d;p?q", + { + spec: "http://a/b/c/d;p?q", relativeURI: "g;x", - scheme: "http", + scheme: "http", prePath: "http://a", pathQueryRef: "/b/c/g;x", - ref: "", - nsIURL: true, nsINestedURI: false }, - { spec: "http://a/b/c/d;p?q", + ref: "", + nsIURL: true, + nsINestedURI: false, + }, + { + spec: "http://a/b/c/d;p?q", relativeURI: "g;x?y#s", - scheme: "http", + scheme: "http", prePath: "http://a", pathQueryRef: "/b/c/g;x?y#s", - ref: "s", - nsIURL: true, nsINestedURI: false }, + ref: "s", + nsIURL: true, + nsINestedURI: false, + }, /* Can't easily specify a relative URI of "" to the test code { spec: "http://a/b/c/d;p?q", @@ -159,211 +212,290 @@ var gTests = [ ref: "", nsIURL: true, nsINestedURI: false }, */ - { spec: "http://a/b/c/d;p?q", + { + spec: "http://a/b/c/d;p?q", relativeURI: ".", - scheme: "http", + scheme: "http", prePath: "http://a", pathQueryRef: "/b/c/", - ref: "", - nsIURL: true, nsINestedURI: false }, - { spec: "http://a/b/c/d;p?q", + ref: "", + nsIURL: true, + nsINestedURI: false, + }, + { + spec: "http://a/b/c/d;p?q", relativeURI: "./", - scheme: "http", + scheme: "http", prePath: "http://a", pathQueryRef: "/b/c/", - ref: "", - nsIURL: true, nsINestedURI: false }, - { spec: "http://a/b/c/d;p?q", + ref: "", + nsIURL: true, + nsINestedURI: false, + }, + { + spec: "http://a/b/c/d;p?q", relativeURI: "..", - scheme: "http", + scheme: "http", prePath: "http://a", pathQueryRef: "/b/", - ref: "", - nsIURL: true, nsINestedURI: false }, - { spec: "http://a/b/c/d;p?q", + ref: "", + nsIURL: true, + nsINestedURI: false, + }, + { + spec: "http://a/b/c/d;p?q", relativeURI: "../", - scheme: "http", + scheme: "http", prePath: "http://a", pathQueryRef: "/b/", - ref: "", - nsIURL: true, nsINestedURI: false }, - { spec: "http://a/b/c/d;p?q", + ref: "", + nsIURL: true, + nsINestedURI: false, + }, + { + spec: "http://a/b/c/d;p?q", relativeURI: "../g", - scheme: "http", + scheme: "http", prePath: "http://a", pathQueryRef: "/b/g", - ref: "", - nsIURL: true, nsINestedURI: false }, - { spec: "http://a/b/c/d;p?q", + ref: "", + nsIURL: true, + nsINestedURI: false, + }, + { + spec: "http://a/b/c/d;p?q", relativeURI: "../..", - scheme: "http", + scheme: "http", prePath: "http://a", pathQueryRef: "/", - ref: "", - nsIURL: true, nsINestedURI: false }, - { spec: "http://a/b/c/d;p?q", + ref: "", + nsIURL: true, + nsINestedURI: false, + }, + { + spec: "http://a/b/c/d;p?q", relativeURI: "../../", - scheme: "http", + scheme: "http", prePath: "http://a", pathQueryRef: "/", - ref: "", - nsIURL: true, nsINestedURI: false }, - { spec: "http://a/b/c/d;p?q", + ref: "", + nsIURL: true, + nsINestedURI: false, + }, + { + spec: "http://a/b/c/d;p?q", relativeURI: "../../g", - scheme: "http", + scheme: "http", prePath: "http://a", pathQueryRef: "/g", - ref: "", - nsIURL: true, nsINestedURI: false }, + ref: "", + nsIURL: true, + nsINestedURI: false, + }, // abnormal examples - { spec: "http://a/b/c/d;p?q", + { + spec: "http://a/b/c/d;p?q", relativeURI: "../../../g", - scheme: "http", + scheme: "http", prePath: "http://a", pathQueryRef: "/g", - ref: "", - nsIURL: true, nsINestedURI: false }, - { spec: "http://a/b/c/d;p?q", + ref: "", + nsIURL: true, + nsINestedURI: false, + }, + { + spec: "http://a/b/c/d;p?q", relativeURI: "../../../../g", - scheme: "http", + scheme: "http", prePath: "http://a", pathQueryRef: "/g", - ref: "", - nsIURL: true, nsINestedURI: false }, + ref: "", + nsIURL: true, + nsINestedURI: false, + }, - // coalesce - { spec: "http://a/b/c/d;p?q", + // coalesce + { + spec: "http://a/b/c/d;p?q", relativeURI: "/./g", - scheme: "http", + scheme: "http", prePath: "http://a", pathQueryRef: "/g", - ref: "", - nsIURL: true, nsINestedURI: false }, - { spec: "http://a/b/c/d;p?q", + ref: "", + nsIURL: true, + nsINestedURI: false, + }, + { + spec: "http://a/b/c/d;p?q", relativeURI: "/../g", - scheme: "http", + scheme: "http", prePath: "http://a", pathQueryRef: "/g", - ref: "", - nsIURL: true, nsINestedURI: false }, - { spec: "http://a/b/c/d;p?q", + ref: "", + nsIURL: true, + nsINestedURI: false, + }, + { + spec: "http://a/b/c/d;p?q", relativeURI: "g.", - scheme: "http", + scheme: "http", prePath: "http://a", pathQueryRef: "/b/c/g.", - ref: "", - nsIURL: true, nsINestedURI: false }, - { spec: "http://a/b/c/d;p?q", + ref: "", + nsIURL: true, + nsINestedURI: false, + }, + { + spec: "http://a/b/c/d;p?q", relativeURI: ".g", - scheme: "http", + scheme: "http", prePath: "http://a", pathQueryRef: "/b/c/.g", - ref: "", - nsIURL: true, nsINestedURI: false }, - { spec: "http://a/b/c/d;p?q", + ref: "", + nsIURL: true, + nsINestedURI: false, + }, + { + spec: "http://a/b/c/d;p?q", relativeURI: "g..", - scheme: "http", + scheme: "http", prePath: "http://a", pathQueryRef: "/b/c/g..", - ref: "", - nsIURL: true, nsINestedURI: false }, - { spec: "http://a/b/c/d;p?q", + ref: "", + nsIURL: true, + nsINestedURI: false, + }, + { + spec: "http://a/b/c/d;p?q", relativeURI: "..g", - scheme: "http", + scheme: "http", prePath: "http://a", pathQueryRef: "/b/c/..g", - ref: "", - nsIURL: true, nsINestedURI: false }, - { spec: "http://a/b/c/d;p?q", + ref: "", + nsIURL: true, + nsINestedURI: false, + }, + { + spec: "http://a/b/c/d;p?q", relativeURI: ".", - scheme: "http", + scheme: "http", prePath: "http://a", pathQueryRef: "/b/c/", - ref: "", - nsIURL: true, nsINestedURI: false }, - { spec: "http://a/b/c/d;p?q", + ref: "", + nsIURL: true, + nsINestedURI: false, + }, + { + spec: "http://a/b/c/d;p?q", relativeURI: "./../g", - scheme: "http", + scheme: "http", prePath: "http://a", pathQueryRef: "/b/g", - ref: "", - nsIURL: true, nsINestedURI: false }, - { spec: "http://a/b/c/d;p?q", + ref: "", + nsIURL: true, + nsINestedURI: false, + }, + { + spec: "http://a/b/c/d;p?q", relativeURI: "./g/.", - scheme: "http", + scheme: "http", prePath: "http://a", pathQueryRef: "/b/c/g/", - ref: "", - nsIURL: true, nsINestedURI: false }, - { spec: "http://a/b/c/d;p?q", + ref: "", + nsIURL: true, + nsINestedURI: false, + }, + { + spec: "http://a/b/c/d;p?q", relativeURI: "g/./h", - scheme: "http", + scheme: "http", prePath: "http://a", pathQueryRef: "/b/c/g/h", - ref: "", - nsIURL: true, nsINestedURI: false }, - { spec: "http://a/b/c/d;p?q", + ref: "", + nsIURL: true, + nsINestedURI: false, + }, + { + spec: "http://a/b/c/d;p?q", relativeURI: "g/../h", - scheme: "http", + scheme: "http", prePath: "http://a", pathQueryRef: "/b/c/h", - ref: "",// fix - nsIURL: true, nsINestedURI: false }, - { spec: "http://a/b/c/d;p?q", + ref: "", // fix + nsIURL: true, + nsINestedURI: false, + }, + { + spec: "http://a/b/c/d;p?q", relativeURI: "g;x=1/./y", - scheme: "http", + scheme: "http", prePath: "http://a", pathQueryRef: "/b/c/g;x=1/y", - ref: "", - nsIURL: true, nsINestedURI: false }, - { spec: "http://a/b/c/d;p?q", + ref: "", + nsIURL: true, + nsINestedURI: false, + }, + { + spec: "http://a/b/c/d;p?q", relativeURI: "g;x=1/../y", - scheme: "http", + scheme: "http", prePath: "http://a", pathQueryRef: "/b/c/y", - ref: "", - nsIURL: true, nsINestedURI: false }, + ref: "", + nsIURL: true, + nsINestedURI: false, + }, // protocol-relative http://tools.ietf.org/html/rfc3986#section-4.2 - { spec: "http://www2.example.com/", + { + spec: "http://www2.example.com/", relativeURI: "//www3.example2.com/bar", - scheme: "http", + scheme: "http", prePath: "http://www3.example2.com", pathQueryRef: "/bar", - ref: "", - nsIURL: true, nsINestedURI: false }, - { spec: "https://www2.example.com/", + ref: "", + nsIURL: true, + nsINestedURI: false, + }, + { + spec: "https://www2.example.com/", relativeURI: "//www3.example2.com/bar", - scheme: "https", + scheme: "https", prePath: "https://www3.example2.com", pathQueryRef: "/bar", - ref: "", - nsIURL: true, nsINestedURI: false }, + ref: "", + nsIURL: true, + nsINestedURI: false, + }, ]; -var gHashSuffixes = [ - "#", - "#myRef", - "#myRef?a=b", - "#myRef#", - "#myRef#x:yz" -]; +var gHashSuffixes = ["#", "#myRef", "#myRef?a=b", "#myRef#", "#myRef#x:yz"]; // TEST HELPER FUNCTIONS // --------------------- function do_info(text, stack) { - if (!stack) + if (!stack) { stack = Components.stack.caller; + } - dump( "\n" + - "TEST-INFO | " + stack.filename + " | [" + stack.name + " : " + - stack.lineNumber + "] " + text + "\n"); + dump( + "\n" + + "TEST-INFO | " + + stack.filename + + " | [" + + stack.name + + " : " + + stack.lineNumber + + "] " + + text + + "\n" + ); } // Checks that the URIs satisfy equals(), in both possible orderings. // Also checks URI.equalsExceptRef(), because equal URIs should also be equal // when we ignore the ref. -// +// // The third argument is optional. If the client passes a third argument // (e.g. todo_check_true), we'll use that in lieu of ok. function do_check_uri_eq(aURI1, aURI2, aCheckTrueFunc = ok) { @@ -385,11 +517,13 @@ function do_check_uri_eq(aURI1, aURI2, aCheckTrueFunc = ok) { // The third argument is optional. If the client passes a third argument // (e.g. todo_check_true), we'll use that in lieu of ok. function do_check_uri_eqExceptRef(aURI1, aURI2, aCheckTrueFunc = ok) { - do_info("(uri equalsExceptRef check: '" + - aURI1.spec + "' == '" + aURI2.spec + "')"); + do_info( + "(uri equalsExceptRef check: '" + aURI1.spec + "' == '" + aURI2.spec + "')" + ); aCheckTrueFunc(aURI1.equalsExceptRef(aURI2)); - do_info("(uri equalsExceptRef check: '" + - aURI2.spec + "' == '" + aURI1.spec + "')"); + do_info( + "(uri equalsExceptRef check: '" + aURI2.spec + "' == '" + aURI1.spec + "')" + ); aCheckTrueFunc(aURI2.equalsExceptRef(aURI1)); } @@ -398,13 +532,20 @@ function do_check_uri_eqExceptRef(aURI1, aURI2, aCheckTrueFunc = ok) { // if aTestFunctor is passed in). function do_check_property(aTest, aURI, aPropertyName, aTestFunctor) { if (aTest[aPropertyName]) { - var expectedVal = aTestFunctor ? - aTestFunctor(aTest[aPropertyName]) : - aTest[aPropertyName]; + var expectedVal = aTestFunctor + ? aTestFunctor(aTest[aPropertyName]) + : aTest[aPropertyName]; - do_info("testing " + aPropertyName + " of " + - (aTestFunctor ? "modified '" : "'" ) + aTest.spec + - "' is '" + expectedVal + "'"); + do_info( + "testing " + + aPropertyName + + " of " + + (aTestFunctor ? "modified '" : "'") + + aTest.spec + + "' is '" + + expectedVal + + "'" + ); Assert.equal(aURI[aPropertyName], expectedVal); } } @@ -413,11 +554,13 @@ function do_check_property(aTest, aURI, aPropertyName, aTestFunctor) { function do_test_uri_basic(aTest) { var URI; - do_info("Basic tests for " + aTest.spec + " relative URI: " + aTest.relativeURI); + do_info( + "Basic tests for " + aTest.spec + " relative URI: " + aTest.relativeURI + ); try { URI = NetUtil.newURI(aTest.spec); - } catch(e) { + } catch (e) { do_info("Caught error on parse of" + aTest.spec + " Error: " + e.result); if (aTest.fail) { Assert.equal(e.result, aTest.result); @@ -432,14 +575,26 @@ function do_test_uri_basic(aTest) { try { relURI = gIoService.newURI(aTest.relativeURI, null, URI); } catch (e) { - do_info("Caught error on Relative parse of " + aTest.spec + " + " + aTest.relativeURI +" Error: " + e.result); + do_info( + "Caught error on Relative parse of " + + aTest.spec + + " + " + + aTest.relativeURI + + " Error: " + + e.result + ); if (aTest.relativeFail) { Assert.equal(e.result, aTest.relativeFail); return; } do_throw(e.result); } - do_info("relURI.pathQueryRef = " + relURI.pathQueryRef + ", was " + URI.pathQueryRef); + do_info( + "relURI.pathQueryRef = " + + relURI.pathQueryRef + + ", was " + + URI.pathQueryRef + ); URI = relURI; do_info("URI.pathQueryRef now = " + URI.pathQueryRef); } @@ -447,27 +602,34 @@ function do_test_uri_basic(aTest) { // Sanity-check do_info("testing " + aTest.spec + " equals a clone of itself"); do_check_uri_eq(URI, URI.mutate().finalize()); - do_check_uri_eqExceptRef(URI, URI.mutate().setRef("").finalize()); + do_check_uri_eqExceptRef( + URI, + URI.mutate() + .setRef("") + .finalize() + ); do_info("testing " + aTest.spec + " instanceof nsIURL"); Assert.equal(URI instanceof Ci.nsIURL, aTest.nsIURL); do_info("testing " + aTest.spec + " instanceof nsINestedURI"); - Assert.equal(URI instanceof Ci.nsINestedURI, - aTest.nsINestedURI); + Assert.equal(URI instanceof Ci.nsINestedURI, aTest.nsINestedURI); - do_info("testing that " + aTest.spec + " throws or returns false " + - "from equals(null)"); + do_info( + "testing that " + + aTest.spec + + " throws or returns false " + + "from equals(null)" + ); // XXXdholbert At some point it'd probably be worth making this behavior // (throwing vs. returning false) consistent across URI implementations. var threw = false; var isEqualToNull; try { isEqualToNull = URI.equals(null); - } catch(e) { + } catch (e) { threw = true; } Assert.ok(threw || !isEqualToNull); - // Check the various components do_check_property(aTest, URI, "scheme"); do_check_property(aTest, URI, "prePath"); @@ -497,39 +659,77 @@ function do_test_uri_with_hash_suffix(aTest, aSuffix) { try { origURI = gIoService.newURI(aTest.relativeURI, null, origURI); } catch (e) { - do_info("Caught error on Relative parse of " + aTest.spec + " + " + aTest.relativeURI +" Error: " + e.result); + do_info( + "Caught error on Relative parse of " + + aTest.spec + + " + " + + aTest.relativeURI + + " Error: " + + e.result + ); return; } try { testURI = gIoService.newURI(aSuffix, null, origURI); } catch (e) { - do_info("Caught error adding suffix to " + aTest.spec + " + " + aTest.relativeURI + ", suffix " + aSuffix + " Error: " + e.result); + do_info( + "Caught error adding suffix to " + + aTest.spec + + " + " + + aTest.relativeURI + + ", suffix " + + aSuffix + + " Error: " + + e.result + ); return; } } else { testURI = NetUtil.newURI(aTest.spec + aSuffix); } - do_info("testing " + aTest.spec + " with '" + aSuffix + "' appended " + - "equals a clone of itself"); + do_info( + "testing " + + aTest.spec + + " with '" + + aSuffix + + "' appended " + + "equals a clone of itself" + ); do_check_uri_eq(testURI, testURI.mutate().finalize()); - do_info("testing " + aTest.spec + - " doesn't equal self with '" + aSuffix + "' appended"); + do_info( + "testing " + + aTest.spec + + " doesn't equal self with '" + + aSuffix + + "' appended" + ); Assert.ok(!origURI.equals(testURI)); - do_info("testing " + aTest.spec + - " is equalExceptRef to self with '" + aSuffix + "' appended"); + do_info( + "testing " + + aTest.spec + + " is equalExceptRef to self with '" + + aSuffix + + "' appended" + ); do_check_uri_eqExceptRef(origURI, testURI); Assert.equal(testURI.hasRef, true); if (!origURI.ref) { // These tests fail if origURI has a ref - do_info("testing cloneIgnoringRef on " + testURI.spec + - " is equal to no-ref version but not equal to ref version"); - var cloneNoRef = testURI.mutate().setRef("").finalize(); + do_info( + "testing cloneIgnoringRef on " + + testURI.spec + + " is equal to no-ref version but not equal to ref version" + ); + var cloneNoRef = testURI + .mutate() + .setRef("") + .finalize(); do_check_uri_eq(cloneNoRef, origURI); Assert.ok(!cloneNoRef.equals(testURI)); } @@ -538,10 +738,12 @@ function do_test_uri_with_hash_suffix(aTest, aSuffix) { do_check_property(aTest, testURI, "prePath"); if (!origURI.ref) { // These don't work if it's a ref already because '+' doesn't give the right result - do_check_property(aTest, testURI, "pathQueryRef", - function(aStr) { return aStr + aSuffix; }); - do_check_property(aTest, testURI, "ref", - function(aStr) { return aSuffix.substr(1); }); + do_check_property(aTest, testURI, "pathQueryRef", function(aStr) { + return aStr + aSuffix; + }); + do_check_property(aTest, testURI, "ref", function(aStr) { + return aSuffix.substr(1); + }); } } @@ -550,32 +752,53 @@ function do_test_mutate_ref(aTest, aSuffix) { do_info("making sure caller is using suffix that starts with '#'"); Assert.equal(aSuffix[0], "#"); - var refURIWithSuffix = NetUtil.newURI(aTest.spec + aSuffix); + var refURIWithSuffix = NetUtil.newURI(aTest.spec + aSuffix); var refURIWithoutSuffix = NetUtil.newURI(aTest.spec); - var testURI = NetUtil.newURI(aTest.spec); + var testURI = NetUtil.newURI(aTest.spec); // First: Try setting .ref to our suffix - do_info("testing that setting .ref on " + aTest.spec + - " to '" + aSuffix + "' does what we expect"); - testURI = testURI.mutate().setRef(aSuffix).finalize(); + do_info( + "testing that setting .ref on " + + aTest.spec + + " to '" + + aSuffix + + "' does what we expect" + ); + testURI = testURI + .mutate() + .setRef(aSuffix) + .finalize(); do_check_uri_eq(testURI, refURIWithSuffix); do_check_uri_eqExceptRef(testURI, refURIWithoutSuffix); // Now try setting .ref but leave off the initial hash (expect same result) var suffixLackingHash = aSuffix.substr(1); - if (suffixLackingHash) { // (skip this our suffix was *just* a #) - do_info("testing that setting .ref on " + aTest.spec + - " to '" + suffixLackingHash + "' does what we expect"); - testURI = testURI.mutate().setRef(suffixLackingHash).finalize(); + if (suffixLackingHash) { + // (skip this our suffix was *just* a #) + do_info( + "testing that setting .ref on " + + aTest.spec + + " to '" + + suffixLackingHash + + "' does what we expect" + ); + testURI = testURI + .mutate() + .setRef(suffixLackingHash) + .finalize(); do_check_uri_eq(testURI, refURIWithSuffix); do_check_uri_eqExceptRef(testURI, refURIWithoutSuffix); } // Now, clear .ref (should get us back the original spec) - do_info("testing that clearing .ref on " + testURI.spec + - " does what we expect"); - testURI = testURI.mutate().setRef("").finalize(); + do_info( + "testing that clearing .ref on " + testURI.spec + " does what we expect" + ); + testURI = testURI + .mutate() + .setRef("") + .finalize(); do_check_uri_eq(testURI, refURIWithoutSuffix); do_check_uri_eqExceptRef(testURI, refURIWithSuffix); @@ -584,12 +807,16 @@ function do_test_mutate_ref(aTest, aSuffix) { // Now try setting .spec directly (including suffix) and then clearing .ref var specWithSuffix = aTest.spec + aSuffix; - do_info("testing that setting spec to " + - specWithSuffix + " and then clearing ref does what we expect"); - testURI = testURI.mutate() - .setSpec(specWithSuffix) - .setRef("") - .finalize(); + do_info( + "testing that setting spec to " + + specWithSuffix + + " and then clearing ref does what we expect" + ); + testURI = testURI + .mutate() + .setSpec(specWithSuffix) + .setRef("") + .finalize(); do_check_uri_eq(testURI, refURIWithoutSuffix); do_check_uri_eqExceptRef(testURI, refURIWithSuffix); @@ -600,20 +827,33 @@ function do_test_mutate_ref(aTest, aSuffix) { testURI = NetUtil.newURI(aTest.spec); var pathWithSuffix = aTest.pathQueryRef + aSuffix; - do_info("testing that setting path to " + - pathWithSuffix + " and then clearing ref does what we expect"); - testURI = testURI.mutate() - .setPathQueryRef(pathWithSuffix) - .setRef("") - .finalize(); + do_info( + "testing that setting path to " + + pathWithSuffix + + " and then clearing ref does what we expect" + ); + testURI = testURI + .mutate() + .setPathQueryRef(pathWithSuffix) + .setRef("") + .finalize(); do_check_uri_eq(testURI, refURIWithoutSuffix); do_check_uri_eqExceptRef(testURI, refURIWithSuffix); // Also: make sure that clearing .pathQueryRef also clears .ref - testURI = testURI.mutate().setPathQueryRef(pathWithSuffix).finalize(); - do_info("testing that clearing path from " + - pathWithSuffix + " also clears .ref"); - testURI = testURI.mutate().setPathQueryRef("").finalize(); + testURI = testURI + .mutate() + .setPathQueryRef(pathWithSuffix) + .finalize(); + do_info( + "testing that clearing path from " + + pathWithSuffix + + " also clears .ref" + ); + testURI = testURI + .mutate() + .setPathQueryRef("") + .finalize(); Assert.equal(testURI.ref, ""); } } @@ -621,14 +861,15 @@ function do_test_mutate_ref(aTest, aSuffix) { // TEST MAIN FUNCTION // ------------------ -function run_test() -{ +function run_test() { // UTF-8 check - From bug 622981 // ASCII let base = gIoService.newURI("http://example.org/xenia?"); let resolved = gIoService.newURI("?x", null, base); let expected = gIoService.newURI("http://example.org/xenia?x"); - do_info("Bug 662981: ACSII - comparing " + resolved.spec + " and " + expected.spec); + do_info( + "Bug 662981: ACSII - comparing " + resolved.spec + " and " + expected.spec + ); Assert.ok(resolved.equals(expected)); // UTF-8 character "è" @@ -636,7 +877,9 @@ function run_test() base = gIoService.newURI("http://example.org/xènia?"); resolved = gIoService.newURI("?x", null, base); expected = gIoService.newURI("http://example.org/xènia?x"); - do_info("Bug 662981: UTF8 - comparing " + resolved.spec + " and " + expected.spec); + do_info( + "Bug 662981: UTF8 - comparing " + resolved.spec + " and " + expected.spec + ); Assert.ok(resolved.equals(expected)); gTests.forEach(function(aTest) { @@ -646,11 +889,11 @@ function run_test() if (!aTest.fail) { // Try adding various #-prefixed strings to the ends of the URIs gHashSuffixes.forEach(function(aSuffix) { - do_test_uri_with_hash_suffix(aTest, aSuffix); - if (!aTest.immutable) { - do_test_mutate_ref(aTest, aSuffix); - } - }); + do_test_uri_with_hash_suffix(aTest, aSuffix); + if (!aTest.immutable) { + do_test_mutate_ref(aTest, aSuffix); + } + }); // For URIs that we couldn't mutate above due to them being immutable: // Now we check that they're actually immutable. diff --git a/netwerk/test/unit/test_XHR_redirects.js b/netwerk/test/unit/test_XHR_redirects.js index e91730859250..50fd2edd33ed 100644 --- a/netwerk/test/unit/test_XHR_redirects.js +++ b/netwerk/test/unit/test_XHR_redirects.js @@ -4,8 +4,10 @@ // etc--see HttpBaseChannel::IsSafeMethod). Since no prompting is possible // in xpcshell, we get an error for prompts, and the request fails. -const {HttpServer} = ChromeUtils.import("resource://testing-common/httpd.js"); -const {Preferences} = ChromeUtils.import("resource://gre/modules/Preferences.jsm"); +const { HttpServer } = ChromeUtils.import("resource://testing-common/httpd.js"); +const { Preferences } = ChromeUtils.import( + "resource://gre/modules/Preferences.jsm" +); Cu.importGlobalProperties(["XMLHttpRequest"]); @@ -23,15 +25,13 @@ XPCOMUtils.defineLazyGetter(this, "pOther", function() { return sOther.identity.primaryPort; }); -function createXHR(async, method, path) -{ +function createXHR(async, method, path) { var xhr = new XMLHttpRequest(); xhr.open(method, "http://localhost:" + pSame + path, async); return xhr; } -function checkResults(xhr, method, status, unsafe) -{ +function checkResults(xhr, method, status, unsafe) { if (unsafe) { if (sRedirectPromptPref) { // The method is null if we prompt for unsafe redirects @@ -42,8 +42,9 @@ function checkResults(xhr, method, status, unsafe) } } - if (xhr.readyState != 4) + if (xhr.readyState != 4) { return false; + } Assert.equal(xhr.status, status); if (status == 200) { @@ -59,18 +60,48 @@ function run_test() { sSame = new HttpServer(); // same-origin redirects - sSame.registerPathHandler("/bug" + BUGID + "-redirect301", bug676059redirect301); - sSame.registerPathHandler("/bug" + BUGID + "-redirect302", bug676059redirect302); - sSame.registerPathHandler("/bug" + BUGID + "-redirect303", bug676059redirect303); - sSame.registerPathHandler("/bug" + BUGID + "-redirect307", bug676059redirect307); - sSame.registerPathHandler("/bug" + BUGID + "-redirect308", bug676059redirect308); + sSame.registerPathHandler( + "/bug" + BUGID + "-redirect301", + bug676059redirect301 + ); + sSame.registerPathHandler( + "/bug" + BUGID + "-redirect302", + bug676059redirect302 + ); + sSame.registerPathHandler( + "/bug" + BUGID + "-redirect303", + bug676059redirect303 + ); + sSame.registerPathHandler( + "/bug" + BUGID + "-redirect307", + bug676059redirect307 + ); + sSame.registerPathHandler( + "/bug" + BUGID + "-redirect308", + bug676059redirect308 + ); // cross-origin redirects - sSame.registerPathHandler("/bug" + OTHERBUGID + "-redirect301", bug696849redirect301); - sSame.registerPathHandler("/bug" + OTHERBUGID + "-redirect302", bug696849redirect302); - sSame.registerPathHandler("/bug" + OTHERBUGID + "-redirect303", bug696849redirect303); - sSame.registerPathHandler("/bug" + OTHERBUGID + "-redirect307", bug696849redirect307); - sSame.registerPathHandler("/bug" + OTHERBUGID + "-redirect308", bug696849redirect308); + sSame.registerPathHandler( + "/bug" + OTHERBUGID + "-redirect301", + bug696849redirect301 + ); + sSame.registerPathHandler( + "/bug" + OTHERBUGID + "-redirect302", + bug696849redirect302 + ); + sSame.registerPathHandler( + "/bug" + OTHERBUGID + "-redirect303", + bug696849redirect303 + ); + sSame.registerPathHandler( + "/bug" + OTHERBUGID + "-redirect307", + bug696849redirect307 + ); + sSame.registerPathHandler( + "/bug" + OTHERBUGID + "-redirect308", + bug696849redirect308 + ); // same-origin target sSame.registerPathHandler("/bug" + BUGID + "-target", echoMethod); @@ -86,10 +117,10 @@ function run_test() { // methodToSend is the HTTP method to send // redirectedMethod is the method to use for the redirect, if any // finalStatus is 200 when the redirect takes place, redirectType otherwise - + // Note that unsafe methods should not follow the redirect automatically // Of the methods below, DELETE, POST and PUT are unsafe - + sRedirectPromptPref = Preferences.get("network.http.prompt-temp-redirect"); // Following Bug 677754 we don't prompt for unsafe redirects @@ -136,49 +167,56 @@ function run_test() { var othertests = tests; // for now these have identical results var xhr; - + for (var i = 0; i < tests.length; ++i) { dump("Testing " + tests[i] + "\n"); - xhr = createXHR(false, tests[i][1], "/bug" + BUGID + "-redirect" + tests[i][0]); + xhr = createXHR( + false, + tests[i][1], + "/bug" + BUGID + "-redirect" + tests[i][0] + ); xhr.send(null); checkResults(xhr, tests[i][2], tests[i][3], tests[i][4]); - } + } for (var i = 0; i < othertests.length; ++i) { dump("Testing " + othertests[i] + " (cross-origin)\n"); - xhr = createXHR(false, othertests[i][1], "/bug" + OTHERBUGID + "-redirect" + othertests[i][0]); + xhr = createXHR( + false, + othertests[i][1], + "/bug" + OTHERBUGID + "-redirect" + othertests[i][0] + ); xhr.send(null); checkResults(xhr, othertests[i][2], tests[i][3], tests[i][4]); - } + } sSame.stop(do_test_finished); sOther.stop(do_test_finished); } - + function redirect(metadata, response, status, port, bugid) { // set a proper reason string to avoid confusion when looking at the // HTTP messages var reason; if (status == 301) { reason = "Moved Permanently"; - } - else if (status == 302) { + } else if (status == 302) { reason = "Found"; - } - else if (status == 303) { + } else if (status == 303) { reason = "See Other"; - } - else if (status == 307) { + } else if (status == 307) { reason = "Temporary Redirect"; - } - else if (status == 308) { + } else if (status == 308) { reason = "Permanent Redirect"; } - + response.setStatusLine(metadata.httpVersion, status, reason); - response.setHeader("Location", "http://localhost:" + port + "/bug" + bugid + "-target"); -} - + response.setHeader( + "Location", + "http://localhost:" + port + "/bug" + bugid + "-target" + ); +} + // PATH HANDLER FOR /bug676059-redirect301 function bug676059redirect301(metadata, response) { redirect(metadata, response, 301, pSame, BUGID); diff --git a/netwerk/test/unit/test_about_networking.js b/netwerk/test/unit/test_about_networking.js index 27b7a149e0a4..c89b8227f9f8 100644 --- a/netwerk/test/unit/test_about_networking.js +++ b/netwerk/test/unit/test_about_networking.js @@ -3,13 +3,15 @@ * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ -const {HttpServer} = ChromeUtils.import("resource://testing-common/httpd.js"); +const { HttpServer } = ChromeUtils.import("resource://testing-common/httpd.js"); -const gDashboard = Cc['@mozilla.org/network/dashboard;1'] - .getService(Ci.nsIDashboard); +const gDashboard = Cc["@mozilla.org/network/dashboard;1"].getService( + Ci.nsIDashboard +); -const gServerSocket = Cc["@mozilla.org/network/server-socket;1"] - .createInstance(Ci.nsIServerSocket); +const gServerSocket = Cc["@mozilla.org/network/server-socket;1"].createInstance( + Ci.nsIServerSocket +); const gHttpServer = new HttpServer(); add_test(function test_http() { @@ -46,12 +48,17 @@ add_test(function test_dns() { }); add_test(function test_sockets() { - let sts = Cc["@mozilla.org/network/socket-transport-service;1"] - .getService(Ci.nsISocketTransportService); + let sts = Cc["@mozilla.org/network/socket-transport-service;1"].getService( + Ci.nsISocketTransportService + ); let threadManager = Cc["@mozilla.org/thread-manager;1"].getService(); - let transport = sts.createTransport([], "127.0.0.1", - gServerSocket.port, null); + let transport = sts.createTransport( + [], + "127.0.0.1", + gServerSocket.port, + null + ); let listener = { onTransportStatus(aTransport, aStatus, aProgress, aProgressMax) { if (aStatus == Ci.nsISocketTransport.STATUS_CONNECTED_TO) { @@ -69,7 +76,7 @@ add_test(function test_sockets() { run_next_test(); }); } - } + }, }; transport.setEventSink(listener, threadManager.currentThread); @@ -77,15 +84,21 @@ add_test(function test_sockets() { }); function run_test() { - Services.prefs.setBoolPref("network.cookieSettings.unblocked_for_testing", true); + Services.prefs.setBoolPref( + "network.cookieSettings.unblocked_for_testing", + true + ); - let ioService = Cc["@mozilla.org/network/io-service;1"] - .getService(Ci.nsIIOService); + let ioService = Cc["@mozilla.org/network/io-service;1"].getService( + Ci.nsIIOService + ); gHttpServer.start(-1); - let uri = ioService.newURI("http://localhost:" + gHttpServer.identity.primaryPort); - let channel = NetUtil.newChannel({uri, loadUsingSystemPrincipal: true}); + let uri = ioService.newURI( + "http://localhost:" + gHttpServer.identity.primaryPort + ); + let channel = NetUtil.newChannel({ uri, loadUsingSystemPrincipal: true }); channel.open(); @@ -93,4 +106,3 @@ function run_test() { run_next_test(); } - diff --git a/netwerk/test/unit/test_about_protocol.js b/netwerk/test/unit/test_about_protocol.js index 9a743928233b..ac65fca2f6b1 100644 --- a/netwerk/test/unit/test_about_protocol.js +++ b/netwerk/test/unit/test_about_protocol.js @@ -2,43 +2,54 @@ * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - var unsafeAboutModule = { QueryInterface: ChromeUtils.generateQI([Ci.nsIAboutModule]), - newChannel (aURI, aLoadInfo) { + newChannel(aURI, aLoadInfo) { var uri = Services.io.newURI("about:blank"); let chan = Services.io.newChannelFromURIWithLoadInfo(uri, aLoadInfo); chan.owner = Services.scriptSecurityManager.getSystemPrincipal(); return chan; }, - getURIFlags (aURI) { + getURIFlags(aURI) { return Ci.nsIAboutModule.URI_SAFE_FOR_UNTRUSTED_CONTENT; - } + }, }; var factory = { createInstance(aOuter, aIID) { - if (aOuter) + if (aOuter) { throw Cr.NS_ERROR_NO_AGGREGATION; + } return unsafeAboutModule.QueryInterface(aIID); }, lockFactory(aLock) { throw Cr.NS_ERROR_NOT_IMPLEMENTED; }, - QueryInterface: ChromeUtils.generateQI([Ci.nsIFactory]) + QueryInterface: ChromeUtils.generateQI([Ci.nsIFactory]), }; function run_test() { let registrar = Components.manager.QueryInterface(Ci.nsIComponentRegistrar); - let classID = Cc["@mozilla.org/uuid-generator;1"].getService(Ci.nsIUUIDGenerator).generateUUID(); - registrar.registerFactory(classID, "", "@mozilla.org/network/protocol/about;1?what=unsafe", factory); + let classID = Cc["@mozilla.org/uuid-generator;1"] + .getService(Ci.nsIUUIDGenerator) + .generateUUID(); + registrar.registerFactory( + classID, + "", + "@mozilla.org/network/protocol/about;1?what=unsafe", + factory + ); let aboutUnsafeChan = NetUtil.newChannel({ uri: "about:unsafe", - loadUsingSystemPrincipal: true + loadUsingSystemPrincipal: true, }); - Assert.equal(null, aboutUnsafeChan.owner, "URI_SAFE_FOR_UNTRUSTED_CONTENT channel has no owner"); + Assert.equal( + null, + aboutUnsafeChan.owner, + "URI_SAFE_FOR_UNTRUSTED_CONTENT channel has no owner" + ); registrar.unregisterFactory(classID, factory); } diff --git a/netwerk/test/unit/test_aboutblank.js b/netwerk/test/unit/test_aboutblank.js index 5d1a4bc06af3..cf51b8adedfc 100644 --- a/netwerk/test/unit/test_aboutblank.js +++ b/netwerk/test/unit/test_aboutblank.js @@ -1,4 +1,3 @@ - function run_test() { var base = NetUtil.newURI("http://www.example.com"); var about1 = NetUtil.newURI("about:blank"); @@ -6,19 +5,18 @@ function run_test() { var chan1 = NetUtil.newChannel({ uri: about1, - loadUsingSystemPrincipal: true + loadUsingSystemPrincipal: true, }).QueryInterface(Ci.nsIPropertyBag2); var chan2 = NetUtil.newChannel({ uri: about2, - loadUsingSystemPrincipal: true + loadUsingSystemPrincipal: true, }).QueryInterface(Ci.nsIPropertyBag2); var haveProp = false; var propVal = null; try { - propVal = chan1.getPropertyAsInterface("baseURI", - Ci.nsIURI); + propVal = chan1.getPropertyAsInterface("baseURI", Ci.nsIURI); haveProp = true; } catch (e) { if (e.result != Cr.NS_ERROR_NOT_AVAILABLE) { @@ -28,7 +26,5 @@ function run_test() { } Assert.equal(propVal, null); Assert.equal(haveProp, false); - Assert.equal(chan2.getPropertyAsInterface("baseURI", - Ci.nsIURI), - base); + Assert.equal(chan2.getPropertyAsInterface("baseURI", Ci.nsIURI), base); } diff --git a/netwerk/test/unit/test_addr_in_use_error.js b/netwerk/test/unit/test_addr_in_use_error.js index 0cba50719e76..f5f4a214b3cd 100644 --- a/netwerk/test/unit/test_addr_in_use_error.js +++ b/netwerk/test/unit/test_addr_in_use_error.js @@ -4,12 +4,13 @@ var CC = Components.Constructor; -const ServerSocket = CC("@mozilla.org/network/server-socket;1", - "nsIServerSocket", - "init"); +const ServerSocket = CC( + "@mozilla.org/network/server-socket;1", + "nsIServerSocket", + "init" +); -function testAddrInUse() -{ +function testAddrInUse() { // Windows lets us have as many sockets listening on the same address as // we like, evidently. if (mozinfo.os == "win") { @@ -22,11 +23,12 @@ function testAddrInUse() Assert.ok(listener instanceof Ci.nsIServerSocket); // Try to create another listening socket on the same port, whatever that was. - do_check_throws_nsIException(() => ServerSocket(listener.port, true, -1), - "NS_ERROR_SOCKET_ADDRESS_IN_USE"); + do_check_throws_nsIException( + () => ServerSocket(listener.port, true, -1), + "NS_ERROR_SOCKET_ADDRESS_IN_USE" + ); } -function run_test() -{ +function run_test() { testAddrInUse(); } diff --git a/netwerk/test/unit/test_alt-data_closeWithStatus.js b/netwerk/test/unit/test_alt-data_closeWithStatus.js index e5cfc14cecf9..f8245e4f726f 100644 --- a/netwerk/test/unit/test_alt-data_closeWithStatus.js +++ b/netwerk/test/unit/test_alt-data_closeWithStatus.js @@ -10,7 +10,7 @@ * - again we receive the data from the server. */ -const {HttpServer} = ChromeUtils.import("resource://testing-common/httpd.js"); +const { HttpServer } = ChromeUtils.import("resource://testing-common/httpd.js"); XPCOMUtils.defineLazyGetter(this, "URL", function() { return "http://localhost:" + httpServer.identity.primaryPort + "/content"; @@ -19,21 +19,24 @@ XPCOMUtils.defineLazyGetter(this, "URL", function() { var httpServer = null; // needs to be rooted -var cacheFlushObserver = cacheFlushObserver = { observe() { - cacheFlushObserver = null; - readServerContentAgain(); -}}; +var cacheFlushObserver = (cacheFlushObserver = { + observe() { + cacheFlushObserver = null; + readServerContentAgain(); + }, +}); var currentThread = null; function make_channel(url, callback, ctx) { - return NetUtil.newChannel({uri: url, loadUsingSystemPrincipal: true}); + return NetUtil.newChannel({ uri: url, loadUsingSystemPrincipal: true }); } function inChildProcess() { - return Cc["@mozilla.org/xre/app-info;1"] - .getService(Ci.nsIXULRuntime) - .processType != Ci.nsIXULRuntime.PROCESS_TYPE_DEFAULT; + return ( + Cc["@mozilla.org/xre/app-info;1"].getService(Ci.nsIXULRuntime) + .processType != Ci.nsIXULRuntime.PROCESS_TYPE_DEFAULT + ); } const responseContent = "response body"; @@ -46,15 +49,14 @@ var shouldPassRevalidation = true; var cache_storage = null; -function contentHandler(metadata, response) -{ +function contentHandler(metadata, response) { response.setHeader("Content-Type", "text/plain"); response.setHeader("Cache-Control", "no-cache"); response.setHeader("ETag", "test-etag1"); try { var etag = metadata.getHeader("If-None-Match"); - } catch(ex) { + } catch (ex) { var etag = ""; } @@ -67,8 +69,7 @@ function contentHandler(metadata, response) } } -function check_has_alt_data_in_index(aHasAltData) -{ +function check_has_alt_data_in_index(aHasAltData) { if (inChildProcess()) { return; } @@ -77,8 +78,7 @@ function check_has_alt_data_in_index(aHasAltData) Assert.equal(hasAltData.value, aHasAltData); } -function run_test() -{ +function run_test() { do_get_profile(); httpServer = new HttpServer(); httpServer.registerPathHandler("/content", contentHandler); @@ -86,15 +86,14 @@ function run_test() do_test_pending(); if (!inChildProcess()) { - cache_storage = getCacheStorage("disk") ; + cache_storage = getCacheStorage("disk"); wait_for_cache_index(asyncOpen); } else { asyncOpen(); } } -function asyncOpen() -{ +function asyncOpen() { var chan = make_channel(URL); var cc = chan.QueryInterface(Ci.nsICacheInfoChannel); @@ -103,8 +102,7 @@ function asyncOpen() chan.asyncOpen(new ChannelListener(readServerContent, null)); } -function readServerContent(request, buffer) -{ +function readServerContent(request, buffer) { var cc = request.QueryInterface(Ci.nsICacheInfoChannel); Assert.equal(buffer, responseContent); @@ -119,23 +117,29 @@ function readServerContent(request, buffer) var os = cc.openAlternativeOutputStream(altContentType, altContent.length); var aos = os.QueryInterface(Ci.nsIAsyncOutputStream); - aos.asyncWait(_ => { - os.write(altContent, altContent.length); - aos.closeWithStatus(Cr.NS_ERROR_FAILURE); - executeSoon(flushAndReadServerContentAgain); - }, 0, 0, currentThread); + aos.asyncWait( + _ => { + os.write(altContent, altContent.length); + aos.closeWithStatus(Cr.NS_ERROR_FAILURE); + executeSoon(flushAndReadServerContentAgain); + }, + 0, + 0, + currentThread + ); }); } -function flushAndReadServerContentAgain() -{ +function flushAndReadServerContentAgain() { // We need to do a GC pass to ensure the cache entry has been freed. gc(); if (!inChildProcess()) { - Services.cache2.QueryInterface(Ci.nsICacheTesting).flush(cacheFlushObserver); + Services.cache2 + .QueryInterface(Ci.nsICacheTesting) + .flush(cacheFlushObserver); } else { - do_send_remote_message('flush'); - do_await_remote_message('flushed').then(() => { + do_send_remote_message("flush"); + do_await_remote_message("flushed").then(() => { readServerContentAgain(); }); } @@ -151,8 +155,7 @@ function readServerContentAgain() { chan.asyncOpen(new ChannelListener(readServerContentAgainCB, null)); } -function readServerContentAgainCB(request, buffer) -{ +function readServerContentAgainCB(request, buffer) { var cc = request.QueryInterface(Ci.nsICacheInfoChannel); Assert.equal(buffer, responseContent); diff --git a/netwerk/test/unit/test_alt-data_cross_process.js b/netwerk/test/unit/test_alt-data_cross_process.js index 928f539fd93a..03ceee924205 100644 --- a/netwerk/test/unit/test_alt-data_cross_process.js +++ b/netwerk/test/unit/test_alt-data_cross_process.js @@ -9,7 +9,7 @@ * - this time the alt data must arive */ -const {HttpServer} = ChromeUtils.import("resource://testing-common/httpd.js"); +const { HttpServer } = ChromeUtils.import("resource://testing-common/httpd.js"); XPCOMUtils.defineLazyGetter(this, "URL", function() { return "http://localhost:" + httpServer.identity.primaryPort + "/content"; @@ -18,13 +18,14 @@ XPCOMUtils.defineLazyGetter(this, "URL", function() { var httpServer = null; function make_channel(url, callback, ctx) { - return NetUtil.newChannel({uri: url, loadUsingSystemPrincipal: true}); + return NetUtil.newChannel({ uri: url, loadUsingSystemPrincipal: true }); } function inChildProcess() { - return Cc["@mozilla.org/xre/app-info;1"] - .getService(Ci.nsIXULRuntime) - .processType != Ci.nsIXULRuntime.PROCESS_TYPE_DEFAULT; + return ( + Cc["@mozilla.org/xre/app-info;1"].getService(Ci.nsIXULRuntime) + .processType != Ci.nsIXULRuntime.PROCESS_TYPE_DEFAULT + ); } const responseContent = "response body"; @@ -37,15 +38,14 @@ var shouldPassRevalidation = true; var cache_storage = null; -function contentHandler(metadata, response) -{ +function contentHandler(metadata, response) { response.setHeader("Content-Type", "text/plain"); response.setHeader("Cache-Control", "no-cache"); response.setHeader("ETag", "test-etag1"); try { var etag = metadata.getHeader("If-None-Match"); - } catch(ex) { + } catch (ex) { var etag = ""; } @@ -58,8 +58,7 @@ function contentHandler(metadata, response) } } -function check_has_alt_data_in_index(aHasAltData) -{ +function check_has_alt_data_in_index(aHasAltData) { if (inChildProcess()) { return; } @@ -68,8 +67,7 @@ function check_has_alt_data_in_index(aHasAltData) Assert.equal(hasAltData.value, aHasAltData); } -function run_test() -{ +function run_test() { httpServer = new HttpServer(); httpServer.registerPathHandler("/content", contentHandler); httpServer.start(-1); @@ -78,8 +76,7 @@ function run_test() asyncOpen(); } -function asyncOpen() -{ +function asyncOpen() { var chan = make_channel(URL); var cc = chan.QueryInterface(Ci.nsICacheInfoChannel); @@ -88,8 +85,7 @@ function asyncOpen() chan.asyncOpen(new ChannelListener(readServerContent, null)); } -function readServerContent(request, buffer) -{ +function readServerContent(request, buffer) { var cc = request.QueryInterface(Ci.nsICacheInfoChannel); Assert.equal(buffer, responseContent); @@ -105,12 +101,11 @@ function readServerContent(request, buffer) }); } -function flushAndOpenAltChannel() -{ +function flushAndOpenAltChannel() { // We need to do a GC pass to ensure the cache entry has been freed. gc(); - do_send_remote_message('flush'); - do_await_remote_message('flushed').then(() => { + do_send_remote_message("flush"); + do_await_remote_message("flushed").then(() => { openAltChannel(); }); } @@ -123,8 +118,7 @@ function openAltChannel() { chan.asyncOpen(new ChannelListener(readAltContent, null)); } -function readAltContent(request, buffer) -{ +function readAltContent(request, buffer) { var cc = request.QueryInterface(Ci.nsICacheInfoChannel); Assert.equal(servedNotModified, true); @@ -132,8 +126,8 @@ function readAltContent(request, buffer) Assert.equal(buffer, altContent); // FINISH - do_send_remote_message('done'); - do_await_remote_message('finish').then(() => { + do_send_remote_message("done"); + do_await_remote_message("finish").then(() => { httpServer.stop(do_test_finished); }); } diff --git a/netwerk/test/unit/test_alt-data_overwrite.js b/netwerk/test/unit/test_alt-data_overwrite.js index c022fb81abcc..0f6a83b66c01 100644 --- a/netwerk/test/unit/test_alt-data_overwrite.js +++ b/netwerk/test/unit/test_alt-data_overwrite.js @@ -12,7 +12,7 @@ * - readAltContent3 checks that it gets back the newly saved alt-data */ -const {HttpServer} = ChromeUtils.import("resource://testing-common/httpd.js"); +const { HttpServer } = ChromeUtils.import("resource://testing-common/httpd.js"); XPCOMUtils.defineLazyGetter(this, "URL", function() { return "http://localhost:" + httpServer.identity.primaryPort + "/content"; @@ -21,7 +21,7 @@ XPCOMUtils.defineLazyGetter(this, "URL", function() { let httpServer = null; function make_and_open_channel(url, altContentType, callback) { - let chan = NetUtil.newChannel({uri: url, loadUsingSystemPrincipal: true}); + let chan = NetUtil.newChannel({ uri: url, loadUsingSystemPrincipal: true }); if (altContentType) { let cc = chan.QueryInterface(Ci.nsICacheInfoChannel); cc.preferAlternativeDataType(altContentType, "", true); @@ -37,15 +37,14 @@ const altContentType2 = "text/binary2"; let servedNotModified = false; -function contentHandler(metadata, response) -{ +function contentHandler(metadata, response) { response.setHeader("Content-Type", "text/plain"); response.setHeader("Cache-Control", "no-cache"); response.setHeader("ETag", "test-etag1"); - let etag = "" + let etag = ""; try { etag = metadata.getHeader("If-None-Match"); - } catch(ex) { + } catch (ex) { etag = ""; } @@ -58,8 +57,7 @@ function contentHandler(metadata, response) } } -function run_test() -{ +function run_test() { do_get_profile(); httpServer = new HttpServer(); httpServer.registerPathHandler("/content", contentHandler); @@ -69,8 +67,7 @@ function run_test() make_and_open_channel(URL, altContentType, readServerContent); } -function readServerContent(request, buffer) -{ +function readServerContent(request, buffer) { let cc = request.QueryInterface(Ci.nsICacheInfoChannel); Assert.equal(buffer, responseContent); @@ -85,26 +82,26 @@ function readServerContent(request, buffer) }); } -function flushAndOpenAltChannel() -{ +function flushAndOpenAltChannel() { // We need to do a GC pass to ensure the cache entry has been freed. Cu.forceShrinkingGC(); Services.cache2.QueryInterface(Ci.nsICacheTesting).flush(cacheFlushObserver); } // needs to be rooted -let cacheFlushObserver = { observe() { - if (!cacheFlushObserver) { - info("ignoring cacheFlushObserver\n"); - return; - } - cacheFlushObserver = null; - Cu.forceShrinkingGC(); - make_and_open_channel(URL, altContentType, readAltContent); -}}; +let cacheFlushObserver = { + observe() { + if (!cacheFlushObserver) { + info("ignoring cacheFlushObserver\n"); + return; + } + cacheFlushObserver = null; + Cu.forceShrinkingGC(); + make_and_open_channel(URL, altContentType, readAltContent); + }, +}; -function readAltContent(request, buffer, closure, fromCache) -{ +function readAltContent(request, buffer, closure, fromCache) { Cu.forceShrinkingGC(); let cc = request.QueryInterface(Ci.nsICacheInfoChannel); @@ -115,8 +112,7 @@ function readAltContent(request, buffer, closure, fromCache) make_and_open_channel(URL, "dummy/null", readServerContent2); } -function readServerContent2(request, buffer, closure, fromCache) -{ +function readServerContent2(request, buffer, closure, fromCache) { Cu.forceShrinkingGC(); let cc = request.QueryInterface(Ci.nsICacheInfoChannel); @@ -133,26 +129,26 @@ function readServerContent2(request, buffer, closure, fromCache) }); } -function flushAndOpenAltChannel2() -{ +function flushAndOpenAltChannel2() { // We need to do a GC pass to ensure the cache entry has been freed. Cu.forceShrinkingGC(); Services.cache2.QueryInterface(Ci.nsICacheTesting).flush(cacheFlushObserver2); } // needs to be rooted -let cacheFlushObserver2 = { observe() { - if (!cacheFlushObserver2) { - info("ignoring cacheFlushObserver2\n"); - return; - } - cacheFlushObserver2 = null; - Cu.forceShrinkingGC(); - make_and_open_channel(URL, altContentType, readAltContent2); -}}; +let cacheFlushObserver2 = { + observe() { + if (!cacheFlushObserver2) { + info("ignoring cacheFlushObserver2\n"); + return; + } + cacheFlushObserver2 = null; + Cu.forceShrinkingGC(); + make_and_open_channel(URL, altContentType, readAltContent2); + }, +}; -function readAltContent2(request, buffer, closure, fromCache) -{ +function readAltContent2(request, buffer, closure, fromCache) { Cu.forceShrinkingGC(); let cc = request.QueryInterface(Ci.nsICacheInfoChannel); @@ -163,7 +159,10 @@ function readAltContent2(request, buffer, closure, fromCache) executeSoon(() => { Cu.forceShrinkingGC(); info("writing other content\n"); - let os = cc.openAlternativeOutputStream(altContentType2, altContent2.length); + let os = cc.openAlternativeOutputStream( + altContentType2, + altContent2.length + ); os.write(altContent2, altContent2.length); os.close(); @@ -171,28 +170,27 @@ function readAltContent2(request, buffer, closure, fromCache) }); } -function flushAndOpenAltChannel3() -{ +function flushAndOpenAltChannel3() { // We need to do a GC pass to ensure the cache entry has been freed. Cu.forceShrinkingGC(); Services.cache2.QueryInterface(Ci.nsICacheTesting).flush(cacheFlushObserver3); } // needs to be rooted -let cacheFlushObserver3 = { observe() { - if (!cacheFlushObserver3) { - info("ignoring cacheFlushObserver3\n"); - return; - } +let cacheFlushObserver3 = { + observe() { + if (!cacheFlushObserver3) { + info("ignoring cacheFlushObserver3\n"); + return; + } - cacheFlushObserver3 = null; - Cu.forceShrinkingGC(); - make_and_open_channel(URL, altContentType2, readAltContent3); -}}; + cacheFlushObserver3 = null; + Cu.forceShrinkingGC(); + make_and_open_channel(URL, altContentType2, readAltContent3); + }, +}; - -function readAltContent3(request, buffer, closure, fromCache) -{ +function readAltContent3(request, buffer, closure, fromCache) { let cc = request.QueryInterface(Ci.nsICacheInfoChannel); Assert.equal(servedNotModified || fromCache, true); diff --git a/netwerk/test/unit/test_alt-data_simple.js b/netwerk/test/unit/test_alt-data_simple.js index 2e5cbf51eee0..0d2788203188 100644 --- a/netwerk/test/unit/test_alt-data_simple.js +++ b/netwerk/test/unit/test_alt-data_simple.js @@ -9,7 +9,7 @@ * - this time the alt data must arive */ -const {HttpServer} = ChromeUtils.import("resource://testing-common/httpd.js"); +const { HttpServer } = ChromeUtils.import("resource://testing-common/httpd.js"); XPCOMUtils.defineLazyGetter(this, "URL", function() { return "http://localhost:" + httpServer.identity.primaryPort + "/content"; @@ -18,13 +18,14 @@ XPCOMUtils.defineLazyGetter(this, "URL", function() { var httpServer = null; function make_channel(url, callback, ctx) { - return NetUtil.newChannel({uri: url, loadUsingSystemPrincipal: true}); + return NetUtil.newChannel({ uri: url, loadUsingSystemPrincipal: true }); } function inChildProcess() { - return Cc["@mozilla.org/xre/app-info;1"] - .getService(Ci.nsIXULRuntime) - .processType != Ci.nsIXULRuntime.PROCESS_TYPE_DEFAULT; + return ( + Cc["@mozilla.org/xre/app-info;1"].getService(Ci.nsIXULRuntime) + .processType != Ci.nsIXULRuntime.PROCESS_TYPE_DEFAULT + ); } const responseContent = "response body"; @@ -37,15 +38,14 @@ var shouldPassRevalidation = true; var cache_storage = null; -function contentHandler(metadata, response) -{ +function contentHandler(metadata, response) { response.setHeader("Content-Type", "text/plain"); response.setHeader("Cache-Control", "no-cache"); response.setHeader("ETag", "test-etag1"); try { var etag = metadata.getHeader("If-None-Match"); - } catch(ex) { + } catch (ex) { var etag = ""; } @@ -58,8 +58,7 @@ function contentHandler(metadata, response) } } -function check_has_alt_data_in_index(aHasAltData) -{ +function check_has_alt_data_in_index(aHasAltData) { if (inChildProcess()) { return; } @@ -68,8 +67,7 @@ function check_has_alt_data_in_index(aHasAltData) Assert.equal(hasAltData.value, aHasAltData); } -function run_test() -{ +function run_test() { do_get_profile(); httpServer = new HttpServer(); httpServer.registerPathHandler("/content", contentHandler); @@ -77,15 +75,14 @@ function run_test() do_test_pending(); if (!inChildProcess()) { - cache_storage = getCacheStorage("disk") ; + cache_storage = getCacheStorage("disk"); wait_for_cache_index(asyncOpen); } else { asyncOpen(); } } -function asyncOpen() -{ +function asyncOpen() { var chan = make_channel(URL); var cc = chan.QueryInterface(Ci.nsICacheInfoChannel); @@ -94,8 +91,7 @@ function asyncOpen() chan.asyncOpen(new ChannelListener(readServerContent, null)); } -function readServerContent(request, buffer) -{ +function readServerContent(request, buffer) { var cc = request.QueryInterface(Ci.nsICacheInfoChannel); Assert.equal(buffer, responseContent); @@ -112,20 +108,23 @@ function readServerContent(request, buffer) } // needs to be rooted -var cacheFlushObserver = cacheFlushObserver = { observe() { - cacheFlushObserver = null; - openAltChannel(); -}}; +var cacheFlushObserver = (cacheFlushObserver = { + observe() { + cacheFlushObserver = null; + openAltChannel(); + }, +}); -function flushAndOpenAltChannel() -{ +function flushAndOpenAltChannel() { // We need to do a GC pass to ensure the cache entry has been freed. gc(); if (!inChildProcess()) { - Services.cache2.QueryInterface(Ci.nsICacheTesting).flush(cacheFlushObserver); + Services.cache2 + .QueryInterface(Ci.nsICacheTesting) + .flush(cacheFlushObserver); } else { - do_send_remote_message('flush'); - do_await_remote_message('flushed').then(() => { + do_send_remote_message("flush"); + do_await_remote_message("flushed").then(() => { openAltChannel(); }); } @@ -141,8 +140,7 @@ function openAltChannel() { chan.asyncOpen(new ChannelListener(readAltContent, null)); } -function readAltContent(request, buffer) -{ +function readAltContent(request, buffer) { var cc = request.QueryInterface(Ci.nsICacheInfoChannel); Assert.equal(servedNotModified, true); @@ -153,12 +151,11 @@ function readAltContent(request, buffer) cc.getOriginalInputStream({ onInputStreamReady(aInputStream) { executeSoon(() => readOriginalInputStream(aInputStream)); - } + }, }); } -function readOriginalInputStream(aInputStream) -{ +function readOriginalInputStream(aInputStream) { // We expect the async stream length to match the expected content. // If the test times out, it's probably because of this. try { @@ -171,8 +168,7 @@ function readOriginalInputStream(aInputStream) } } -function requestAgain() -{ +function requestAgain() { shouldPassRevalidation = false; var chan = make_channel(URL); var cc = chan.QueryInterface(Ci.nsICacheInfoChannel); @@ -180,8 +176,7 @@ function requestAgain() chan.asyncOpen(new ChannelListener(readEmptyAltContent, null)); } -function readEmptyAltContent(request, buffer) -{ +function readEmptyAltContent(request, buffer) { var cc = request.QueryInterface(Ci.nsICacheInfoChannel); // the cache is overwrite and the alt-data is reset diff --git a/netwerk/test/unit/test_alt-data_stream.js b/netwerk/test/unit/test_alt-data_stream.js index b921301c4c67..5efea7e692f7 100644 --- a/netwerk/test/unit/test_alt-data_stream.js +++ b/netwerk/test/unit/test_alt-data_stream.js @@ -11,7 +11,7 @@ * */ -const {HttpServer} = ChromeUtils.import("resource://testing-common/httpd.js"); +const { HttpServer } = ChromeUtils.import("resource://testing-common/httpd.js"); XPCOMUtils.defineLazyGetter(this, "URL", function() { return "http://localhost:" + httpServer.identity.primaryPort + "/content"; @@ -20,36 +20,35 @@ XPCOMUtils.defineLazyGetter(this, "URL", function() { var httpServer = null; function make_channel(url) { - return NetUtil.newChannel({uri: url, loadUsingSystemPrincipal: true}); + return NetUtil.newChannel({ uri: url, loadUsingSystemPrincipal: true }); } const responseContent = "response body"; // We need a large content in order to make sure that the IPDL stream is cut // into several different chunks. // We fill each chunk with a different character for easy debugging. -const altContent = "a".repeat(128*1024) + - "b".repeat(128*1024) + - "c".repeat(128*1024) + - "d".repeat(128*1024) + - "e".repeat(128*1024) + - "f".repeat(128*1024) + - "g".repeat(128*1024) + - "h".repeat(128*1024) + - "i".repeat(13); // Just so the chunk size doesn't match exactly. +const altContent = + "a".repeat(128 * 1024) + + "b".repeat(128 * 1024) + + "c".repeat(128 * 1024) + + "d".repeat(128 * 1024) + + "e".repeat(128 * 1024) + + "f".repeat(128 * 1024) + + "g".repeat(128 * 1024) + + "h".repeat(128 * 1024) + + "i".repeat(13); // Just so the chunk size doesn't match exactly. const firstChunkSize = Math.floor(altContent.length / 4); const altContentType = "text/binary"; -function contentHandler(metadata, response) -{ +function contentHandler(metadata, response) { response.setHeader("Content-Type", "text/plain"); response.setHeader("Cache-Control", "max-age=86400"); response.bodyOutputStream.write(responseContent, responseContent.length); } -function run_test() -{ +function run_test() { do_get_profile(); httpServer = new HttpServer(); httpServer.registerPathHandler("/content", contentHandler); @@ -67,8 +66,7 @@ function run_test() // Output stream used to write alt-data to the cache entry. var os; -function readServerContent(request, buffer) -{ +function readServerContent(request, buffer) { var cc = request.QueryInterface(Ci.nsICacheInfoChannel); Assert.equal(buffer, responseContent); @@ -83,8 +81,7 @@ function readServerContent(request, buffer) }); } -function openAltChannel() -{ +function openAltChannel() { var chan = make_channel(URL); var cc = chan.QueryInterface(Ci.nsICacheInfoChannel); cc.preferAlternativeDataType(altContentType, "", true); @@ -94,7 +91,7 @@ function openAltChannel() var altDataListener = { buffer: "", - onStartRequest(request) { }, + onStartRequest(request) {}, onDataAvailable(request, stream, offset, count) { let string = NetUtil.readInputStreamToString(stream, count); this.buffer += string; @@ -104,7 +101,10 @@ var altDataListener = { // data in the first chunk. if (this.buffer.length == firstChunkSize) { // write the rest of the content - os.write(altContent.substring(firstChunkSize, altContent.length), altContent.length - firstChunkSize); + os.write( + altContent.substring(firstChunkSize, altContent.length), + altContent.length - firstChunkSize + ); os.close(); } }, @@ -117,8 +117,7 @@ var altDataListener = { }, }; -function openAltChannelWithOriginalContent() -{ +function openAltChannelWithOriginalContent() { var chan = make_channel(URL); var cc = chan.QueryInterface(Ci.nsICacheInfoChannel); cc.preferAlternativeDataType(altContentType, "", false); @@ -128,7 +127,7 @@ function openAltChannelWithOriginalContent() var originalListener = { buffer: "", - onStartRequest(request) { }, + onStartRequest(request) {}, onDataAvailable(request, stream, offset, count) { let string = NetUtil.readInputStreamToString(stream, count); this.buffer += string; @@ -142,12 +141,11 @@ var originalListener = { }, }; -function testAltDataStream(cc) -{ +function testAltDataStream(cc) { cc.getAltDataInputStream(altContentType, { onInputStreamReady(aInputStream) { Assert.ok(!!aInputStream); httpServer.stop(do_test_finished); - } + }, }); } diff --git a/netwerk/test/unit/test_alt-data_too_big.js b/netwerk/test/unit/test_alt-data_too_big.js index 695362fc3eed..bb02a988e30b 100644 --- a/netwerk/test/unit/test_alt-data_too_big.js +++ b/netwerk/test/unit/test_alt-data_too_big.js @@ -10,10 +10,9 @@ */ var data = "data "; -var altData = "alt-data" +var altData = "alt-data"; -function run_test() -{ +function run_test() { do_get_profile(); // Expand both data to 1MB @@ -30,22 +29,26 @@ function run_test() do_test_pending(); } -function write_data() -{ - asyncOpenCacheEntry("http://data/", "disk", Ci.nsICacheStorage.OPEN_NORMALLY, null, function (status, entry) { - Assert.equal(status, Cr.NS_OK); +function write_data() { + asyncOpenCacheEntry( + "http://data/", + "disk", + Ci.nsICacheStorage.OPEN_NORMALLY, + null, + function(status, entry) { + Assert.equal(status, Cr.NS_OK); - var os = entry.openOutputStream(0, -1); - var written = os.write(data, data.length); - Assert.equal(written, data.length); - os.close(); + var os = entry.openOutputStream(0, -1); + var written = os.write(data, data.length); + Assert.equal(written, data.length); + os.close(); - open_big_altdata_output(entry); - }); + open_big_altdata_output(entry); + } + ); } -function open_big_altdata_output(entry) -{ +function open_big_altdata_output(entry) { try { var os = entry.openAlternativeOutputStream("text/binary", altData.length); } catch (e) { @@ -56,43 +59,53 @@ function open_big_altdata_output(entry) check_entry(write_big_altdata); } -function write_big_altdata() -{ - asyncOpenCacheEntry("http://data/", "disk", Ci.nsICacheStorage.OPEN_NORMALLY, null, function (status, entry) { - Assert.equal(status, Cr.NS_OK); +function write_big_altdata() { + asyncOpenCacheEntry( + "http://data/", + "disk", + Ci.nsICacheStorage.OPEN_NORMALLY, + null, + function(status, entry) { + Assert.equal(status, Cr.NS_OK); - var os = entry.openAlternativeOutputStream("text/binary", -1); - try { - os.write(altData, altData.length); - } catch (e) { - Assert.equal(e.result, Cr.NS_ERROR_FILE_TOO_BIG); - } - os.close(); - entry.close(); - - check_entry(do_test_finished); - }); -} - -function check_entry(cb) -{ - asyncOpenCacheEntry("http://data/", "disk", Ci.nsICacheStorage.OPEN_NORMALLY, null, function (status, entry) { - Assert.equal(status, Cr.NS_OK); - - var is = null; - try { - is = entry.openAlternativeInputStream("text/binary"); - } catch (e) { - Assert.equal(e.result, Cr.NS_ERROR_NOT_AVAILABLE); - } - - is = entry.openInputStream(0); - pumpReadStream(is, function(read) { - Assert.equal(read.length, data.length); - is.close(); + var os = entry.openAlternativeOutputStream("text/binary", -1); + try { + os.write(altData, altData.length); + } catch (e) { + Assert.equal(e.result, Cr.NS_ERROR_FILE_TOO_BIG); + } + os.close(); entry.close(); - executeSoon(cb); - }); - }); + check_entry(do_test_finished); + } + ); +} + +function check_entry(cb) { + asyncOpenCacheEntry( + "http://data/", + "disk", + Ci.nsICacheStorage.OPEN_NORMALLY, + null, + function(status, entry) { + Assert.equal(status, Cr.NS_OK); + + var is = null; + try { + is = entry.openAlternativeInputStream("text/binary"); + } catch (e) { + Assert.equal(e.result, Cr.NS_ERROR_NOT_AVAILABLE); + } + + is = entry.openInputStream(0); + pumpReadStream(is, function(read) { + Assert.equal(read.length, data.length); + is.close(); + entry.close(); + + executeSoon(cb); + }); + } + ); } diff --git a/netwerk/test/unit/test_altsvc.js b/netwerk/test/unit/test_altsvc.js index 3feb69e4f338..5f77a47ae8f1 100644 --- a/netwerk/test/unit/test_altsvc.js +++ b/netwerk/test/unit/test_altsvc.js @@ -1,4 +1,4 @@ -const {HttpServer} = ChromeUtils.import("resource://testing-common/httpd.js"); +const { HttpServer } = ChromeUtils.import("resource://testing-common/httpd.js"); var h2Port; var prefs; @@ -16,14 +16,16 @@ var otherServer; // server socket listening for other connection. var h2FooRoute; // foo.example.com:H2PORT var h2BarRoute; // bar.example.com:H2PORT -var h2Route; // :H2PORT +var h2Route; // :H2PORT var httpFooOrigin; // http://foo.exmaple.com:PORT/ var httpsFooOrigin; // https://foo.exmaple.com:PORT/ var httpBarOrigin; // http://bar.example.com:PORT/ var httpsBarOrigin; // https://bar.example.com:PORT/ function run_test() { - var env = Cc["@mozilla.org/process/environment;1"].getService(Ci.nsIEnvironment); + var env = Cc["@mozilla.org/process/environment;1"].getService( + Ci.nsIEnvironment + ); h2Port = env.get("MOZHTTP2_PORT"); Assert.notEqual(h2Port, null); Assert.notEqual(h2Port, ""); @@ -41,26 +43,38 @@ function run_test() { prefs.setBoolPref("network.http.spdy.enabled.http2", true); prefs.setBoolPref("network.http.altsvc.enabled", true); prefs.setBoolPref("network.http.altsvc.oe", true); - prefs.setCharPref("network.dns.localDomains", "foo.example.com, bar.example.com"); + prefs.setCharPref( + "network.dns.localDomains", + "foo.example.com, bar.example.com" + ); // The moz-http2 cert is for foo.example.com and is signed by http2-ca.pem // so add that cert to the trust list as a signing cert. The same cert is used // for both h2FooRoute and h2BarRoute though it is only valid for // the foo.example.com domain name. - let certdb = Cc["@mozilla.org/security/x509certdb;1"] - .getService(Ci.nsIX509CertDB); + let certdb = Cc["@mozilla.org/security/x509certdb;1"].getService( + Ci.nsIX509CertDB + ); addCertFromFile(certdb, "http2-ca.pem", "CTu,u,u"); h1Foo = new HttpServer(); h1Foo.registerPathHandler("/altsvc-test", h1Server); h1Foo.registerPathHandler("/.well-known/http-opportunistic", h1ServerWK); h1Foo.start(-1); - h1Foo.identity.setPrimary("http", "foo.example.com", h1Foo.identity.primaryPort); + h1Foo.identity.setPrimary( + "http", + "foo.example.com", + h1Foo.identity.primaryPort + ); h1Bar = new HttpServer(); h1Bar.registerPathHandler("/altsvc-test", h1Server); h1Bar.start(-1); - h1Bar.identity.setPrimary("http", "bar.example.com", h1Bar.identity.primaryPort); + h1Bar.identity.setPrimary( + "http", + "bar.example.com", + h1Bar.identity.primaryPort + ); h2FooRoute = "foo.example.com:" + h2Port; h2BarRoute = "bar.example.com:" + h2Port; @@ -70,10 +84,20 @@ function run_test() { httpsFooOrigin = "https://" + h2FooRoute + "/"; httpBarOrigin = "http://bar.example.com:" + h1Bar.identity.primaryPort + "/"; httpsBarOrigin = "https://" + h2BarRoute + "/"; - dump ("http foo - " + httpFooOrigin + "\n" + - "https foo - " + httpsFooOrigin + "\n" + - "http bar - " + httpBarOrigin + "\n" + - "https bar - " + httpsBarOrigin + "\n"); + dump( + "http foo - " + + httpFooOrigin + + "\n" + + "https foo - " + + httpsFooOrigin + + "\n" + + "http bar - " + + httpBarOrigin + + "\n" + + "https bar - " + + httpsBarOrigin + + "\n" + ); doTest1(); } @@ -121,7 +145,7 @@ function resetPrefs() { function makeChan(origin) { return NetUtil.newChannel({ uri: origin + "altsvc-test", - loadUsingSystemPrincipal: true + loadUsingSystemPrincipal: true, }).QueryInterface(Ci.nsIHttpChannel); } @@ -141,7 +165,9 @@ Listener.prototype = { if (expectPass) { if (!Components.isSuccessCode(request.status)) { - do_throw("Channel should have a success code! (" + request.status + ")"); + do_throw( + "Channel should have a success code! (" + request.status + ")" + ); } Assert.equal(request.responseStatus, 200); } else { @@ -175,18 +201,17 @@ Listener.prototype = { Assert.equal(routed, xaltsvc); // always true, but a useful log nextTest(); } else { - dump ("poll later for alt svc mapping\n"); + dump("poll later for alt svc mapping\n"); do_test_pending(); loadWithoutClearingMappings = true; do_timeout(500, doTest); } do_test_finished(); - } + }, }; -function testsDone() -{ +function testsDone() { dump("testDone\n"); resetPrefs(); do_test_pending(); @@ -197,8 +222,7 @@ function testsDone() h1Bar.stop(do_test_finished); } -function doTest() -{ +function doTest() { dump("execute doTest " + origin + "\n"); var chan = makeChan(origin); var listener = new Listener(); @@ -208,8 +232,9 @@ function doTest() if (loadWithoutClearingMappings) { chan.loadFlags = Ci.nsIChannel.LOAD_INITIAL_DOCUMENT_URI; } else { - chan.loadFlags = Ci.nsIRequest.LOAD_FRESH_CONNECTION | - Ci.nsIChannel.LOAD_INITIAL_DOCUMENT_URI; + chan.loadFlags = + Ci.nsIRequest.LOAD_FRESH_CONNECTION | + Ci.nsIChannel.LOAD_INITIAL_DOCUMENT_URI; } loadWithoutClearingMappings = false; chan.loadInfo.originAttributes = originAttributes; @@ -223,10 +248,9 @@ function doTest() // When xaltsvc is set to h2Route (i.e. :port with the implied hostname) it doesn't match the alt-used, // which is always explicit, so it needs to be changed after the channel is created but before the // listener is invoked - + // http://foo served from h2=:port -function doTest1() -{ +function doTest1() { dump("doTest1()\n"); origin = httpFooOrigin; xaltsvc = h2Route; @@ -237,8 +261,7 @@ function doTest1() } // http://foo served from h2=foo:port -function doTest2() -{ +function doTest2() { dump("doTest2()\n"); origin = httpFooOrigin; xaltsvc = h2FooRoute; @@ -249,8 +272,7 @@ function doTest2() // http://foo served from h2=bar:port // requires cert for foo -function doTest3() -{ +function doTest3() { dump("doTest3()\n"); origin = httpFooOrigin; xaltsvc = h2BarRoute; @@ -260,11 +282,10 @@ function doTest3() } // https://bar should fail because host bar has cert for foo -function doTest4() -{ +function doTest4() { dump("doTest4()\n"); origin = httpsBarOrigin; - xaltsvc = ''; + xaltsvc = ""; expectPass = false; nextTest = doTest5; do_test_pending(); @@ -272,11 +293,10 @@ function doTest4() } // https://foo no alt-svc (just check cert setup) -function doTest5() -{ +function doTest5() { dump("doTest5()\n"); origin = httpsFooOrigin; - xaltsvc = 'NA'; + xaltsvc = "NA"; expectPass = true; nextTest = doTest6; do_test_pending(); @@ -284,8 +304,7 @@ function doTest5() } // https://foo via bar (bar has cert for foo) -function doTest6() -{ +function doTest6() { dump("doTest6()\n"); origin = httpsFooOrigin; xaltsvc = h2BarRoute; @@ -295,11 +314,10 @@ function doTest6() } // check again https://bar should fail because host bar has cert for foo -function doTest7() -{ +function doTest7() { dump("doTest7()\n"); origin = httpsBarOrigin; - xaltsvc = ''; + xaltsvc = ""; expectPass = false; nextTest = doTest8; do_test_pending(); @@ -310,8 +328,7 @@ function doTest7() // should not use TLS/h2 because h2BarRoute is not auth'd for bar // however the test ought to PASS (i.e. get a 200) because fallback // to plaintext happens.. thus the timeout -function doTest8() -{ +function doTest8() { dump("doTest8()\n"); origin = httpBarOrigin; xaltsvc = h2BarRoute; @@ -323,8 +340,7 @@ function doTest8() } // http://bar served from h2=:port, which is like the bar route in 8 -function doTest9() -{ +function doTest9() { dump("doTest9()\n"); origin = httpBarOrigin; xaltsvc = h2Route; @@ -337,11 +353,10 @@ function doTest9() } // check again https://bar should fail because host bar has cert for foo -function doTest10() -{ +function doTest10() { dump("doTest10()\n"); origin = httpsBarOrigin; - xaltsvc = ''; + xaltsvc = ""; expectPass = false; nextTest = doTest11; do_test_pending(); @@ -351,8 +366,7 @@ function doTest10() // http://bar served from h2=foo, should fail because host foo only has // cert for foo. Fail in this case means alt-svc is not used, but content // is served -function doTest11() -{ +function doTest11() { dump("doTest11()\n"); origin = httpBarOrigin; xaltsvc = h2FooRoute; @@ -365,8 +379,7 @@ function doTest11() // Test 12-15: // Insert a cache of http://foo served from h2=:port with origin attributes. -function doTest12() -{ +function doTest12() { dump("doTest12()\n"); origin = httpFooOrigin; xaltsvc = h2Route; @@ -381,11 +394,10 @@ function doTest12() } // Make sure we get a cache miss with a different userContextId. -function doTest13() -{ +function doTest13() { dump("doTest13()\n"); origin = httpFooOrigin; - xaltsvc = 'NA'; + xaltsvc = "NA"; originAttributes = { userContextId: 2, firstPartyDomain: "a.com", @@ -397,11 +409,10 @@ function doTest13() } // Make sure we get a cache miss with a different firstPartyDomain. -function doTest14() -{ +function doTest14() { dump("doTest14()\n"); origin = httpFooOrigin; - xaltsvc = 'NA'; + xaltsvc = "NA"; originAttributes = { userContextId: 1, firstPartyDomain: "b.com", @@ -413,11 +424,10 @@ function doTest14() } // // Make sure we get a cache hit with the same origin attributes. -function doTest15() -{ +function doTest15() { dump("doTest15()\n"); origin = httpFooOrigin; - xaltsvc = 'NA'; + xaltsvc = "NA"; originAttributes = { userContextId: 1, firstPartyDomain: "a.com", @@ -431,15 +441,19 @@ function doTest15() } // Check we don't connect to blocked ports -function doTest16() -{ +function doTest16() { dump("doTest16()\n"); origin = httpFooOrigin; nextTest = testsDone; - otherServer = Cc["@mozilla.org/network/server-socket;1"].createInstance(Ci.nsIServerSocket); + otherServer = Cc["@mozilla.org/network/server-socket;1"].createInstance( + Ci.nsIServerSocket + ); otherServer.init(-1, true, -1); xaltsvc = "localhost:" + otherServer.port; - Services.prefs.setCharPref("network.security.ports.banned", "" + otherServer.port); + Services.prefs.setCharPref( + "network.security.ports.banned", + "" + otherServer.port + ); dump("Blocked port: " + otherServer.port); waitFor = 500; otherServer.asyncListen({ diff --git a/netwerk/test/unit/test_anonymous-coalescing.js b/netwerk/test/unit/test_anonymous-coalescing.js index 09dd8125c0c8..ea79326953ca 100644 --- a/netwerk/test/unit/test_anonymous-coalescing.js +++ b/netwerk/test/unit/test_anonymous-coalescing.js @@ -1,4 +1,3 @@ - /* - test to check we use only a single connection for both onymous and anonymous requests over an existing h2 session - request from a domain w/o LOAD_ANONYMOUS flag @@ -13,7 +12,9 @@ var http2pref; var extpref; function run_test() { - var env = Cc["@mozilla.org/process/environment;1"].getService(Ci.nsIEnvironment); + var env = Cc["@mozilla.org/process/environment;1"].getService( + Ci.nsIEnvironment + ); h2Port = env.get("MOZHTTP2_PORT"); Assert.notEqual(h2Port, null); Assert.notEqual(h2Port, ""); @@ -29,12 +30,16 @@ function run_test() { prefs.setBoolPref("network.http.spdy.enabled", true); prefs.setBoolPref("network.http.spdy.enabled.http2", true); prefs.setBoolPref("network.http.originextension", true); - prefs.setCharPref("network.dns.localDomains", "foo.example.com, alt1.example.com"); + prefs.setCharPref( + "network.dns.localDomains", + "foo.example.com, alt1.example.com" + ); // The moz-http2 cert is for {foo, alt1, alt2}.example.com and is signed by http2-ca.pem // so add that cert to the trust list as a signing cert. - let certdb = Cc["@mozilla.org/security/x509certdb;1"] - .getService(Ci.nsIX509CertDB); + let certdb = Cc["@mozilla.org/security/x509certdb;1"].getService( + Ci.nsIX509CertDB + ); addCertFromFile(certdb, "http2-ca.pem", "CTu,u,u"); doTest1(); @@ -50,7 +55,7 @@ function resetPrefs() { function makeChan(origin) { return NetUtil.newChannel({ uri: origin, - loadUsingSystemPrincipal: true + loadUsingSystemPrincipal: true, }).QueryInterface(Ci.nsIHttpChannel); } @@ -81,24 +86,22 @@ Listener.prototype = { onStopRequest: function testOnStopRequest(request, status) { Assert.ok(Components.isSuccessCode(status)); if (nextPortExpectedToBeSame) { - Assert.equal(currentPort, this.clientPort); + Assert.equal(currentPort, this.clientPort); } else { - Assert.notEqual(currentPort, this.clientPort); + Assert.notEqual(currentPort, this.clientPort); } currentPort = this.clientPort; nextTest(); do_test_finished(); - } + }, }; -function testsDone() -{ +function testsDone() { dump("testsDone\n"); resetPrefs(); } -function doTest() -{ +function doTest() { dump("execute doTest " + origin + "\n"); var loadFlags = Ci.nsIChannel.LOAD_INITIAL_DOCUMENT_URI; @@ -118,8 +121,7 @@ function doTest() chan.asyncOpen(listener); } -function doTest1() -{ +function doTest1() { dump("doTest1()\n"); origin = "https://foo.example.com:" + h2Port + "/origin-1"; nextTest = doTest2; @@ -128,8 +130,7 @@ function doTest1() doTest(); } -function doTest2() -{ +function doTest2() { // connection expected to be reused for an anonymous request dump("doTest2()\n"); origin = "https://foo.example.com:" + h2Port + "/origin-2"; @@ -140,8 +141,7 @@ function doTest2() doTest(); } -function doTest3() -{ +function doTest3() { dump("doTest3()\n"); origin = "https://foo.example.com:" + h2Port + "/origin-3"; nextTest = doTest4; @@ -152,8 +152,7 @@ function doTest3() doTest(); } -function doTest4() -{ +function doTest4() { dump("doTest4()\n"); origin = "https://foo.example.com:" + h2Port + "/origin-4"; nextTest = testsDone; diff --git a/netwerk/test/unit/test_auth_dialog_permission.js b/netwerk/test/unit/test_auth_dialog_permission.js index cd9802fc39fe..583f6aff847e 100644 --- a/netwerk/test/unit/test_auth_dialog_permission.js +++ b/netwerk/test/unit/test_auth_dialog_permission.js @@ -6,10 +6,11 @@ // but don't allow it for cross-origin sub-resources // 2 - allow the cross-origin authentication as well. -const {HttpServer} = ChromeUtils.import("resource://testing-common/httpd.js"); +const { HttpServer } = ChromeUtils.import("resource://testing-common/httpd.js"); -var prefs = Cc["@mozilla.org/preferences-service;1"]. - getService(Ci.nsIPrefBranch); +var prefs = Cc["@mozilla.org/preferences-service;1"].getService( + Ci.nsIPrefBranch +); // Since this test creates a TYPE_DOCUMENT channel via javascript, it will // end up using the wrong LoadInfo constructor. Setting this pref will disable @@ -21,9 +22,10 @@ function authHandler(metadata, response) { var expectedHeader = "Basic Z3Vlc3Q6Z3Vlc3Q="; var body; - if (metadata.hasHeader("Authorization") && - metadata.getHeader("Authorization") == expectedHeader) { - + if ( + metadata.hasHeader("Authorization") && + metadata.getHeader("Authorization") == expectedHeader + ) { response.setStatusLine(metadata.httpVersion, 200, "OK, authorized"); response.setHeader("WWW-Authenticate", 'Basic realm="secret"', false); @@ -66,8 +68,7 @@ AuthPrompt.prototype = { }, promptUsernameAndPassword(title, text, realm, savePW, user, pw) { - Assert.ok(this.promptExpected, - "Not expected the authentication prompt."); + Assert.ok(this.promptExpected, "Not expected the authentication prompt."); user.value = this.user; pw.value = this.pass; @@ -76,8 +77,7 @@ AuthPrompt.prototype = { promptPassword(title, text, realm, save, pwd) { do_throw("unexpected promptPassword call"); - } - + }, }; function Requestor(promptExpected) { @@ -96,18 +96,18 @@ Requestor.prototype = { throw Cr.NS_ERROR_NO_INTERFACE; }, - prompter: null + prompter: null, }; function make_uri(url) { - var ios = Cc["@mozilla.org/network/io-service;1"]. - getService(Ci.nsIIOService); + var ios = Cc["@mozilla.org/network/io-service;1"].getService(Ci.nsIIOService); return ios.newURI(url); } function makeChan(loadingUrl, url, contentPolicy) { - var ssm = Cc["@mozilla.org/scriptsecuritymanager;1"] - .getService(Ci.nsIScriptSecurityManager); + var ssm = Cc["@mozilla.org/scriptsecuritymanager;1"].getService( + Ci.nsIScriptSecurityManager + ); var uri = make_uri(loadingUrl); var principal = ssm.createCodebasePrincipal(uri, {}); @@ -115,12 +115,17 @@ function makeChan(loadingUrl, url, contentPolicy) { uri: url, loadingPrincipal: principal, securityFlags: Ci.nsILoadInfo.SEC_ALLOW_CROSS_ORIGIN_DATA_INHERITS, - contentPolicyType: contentPolicy + contentPolicyType: contentPolicy, }).QueryInterface(Ci.nsIHttpChannel); } -function Test(subresource_http_auth_allow_pref, loadingUri, uri, contentPolicy, - expectedCode) { +function Test( + subresource_http_auth_allow_pref, + loadingUri, + uri, + contentPolicy, + expectedCode +) { this._subresource_http_auth_allow_pref = subresource_http_auth_allow_pref; this._loadingUri = loadingUri; this._uri = uri; @@ -148,7 +153,6 @@ Test.prototype = { Assert.equal(request.responseStatus, this._expectedCode); // The request should be succeeded iff we expect 200 Assert.equal(request.requestSucceeded, this._expectedCode == 200); - } catch (e) { do_throw("Unexpected exception: " + e); } @@ -172,18 +176,24 @@ Test.prototype = { }, run() { - dump("Run test: " + this._subresource_http_auth_allow_pref - + this._loadingUri - + this._uri - + this._contentPolicy - + this._expectedCode + " \n"); + dump( + "Run test: " + + this._subresource_http_auth_allow_pref + + this._loadingUri + + this._uri + + this._contentPolicy + + this._expectedCode + + " \n" + ); - prefs.setIntPref("network.auth.subresource-http-auth-allow", - this._subresource_http_auth_allow_pref); + prefs.setIntPref( + "network.auth.subresource-http-auth-allow", + this._subresource_http_auth_allow_pref + ); let chan = makeChan(this._loadingUri, this._uri, this._contentPolicy); chan.notificationCallbacks = new Requestor(this._expectedCode == 200); chan.asyncOpen(this); - } + }, }; var tests = [ @@ -191,41 +201,68 @@ var tests = [ // authentication as well. // A cross-origin request. - new Test(2, "http://example.com", URL + "/auth", - Ci.nsIContentPolicy.TYPE_OTHER, 200), + new Test( + 2, + "http://example.com", + URL + "/auth", + Ci.nsIContentPolicy.TYPE_OTHER, + 200 + ), // A non cross-origin sub-resource request. - new Test(2, URL + "/", URL + "/auth", - Ci.nsIContentPolicy.TYPE_OTHER, 200), + new Test(2, URL + "/", URL + "/auth", Ci.nsIContentPolicy.TYPE_OTHER, 200), // A top level document. - new Test(2, URL + "/auth", URL + "/auth", - Ci.nsIContentPolicy.TYPE_DOCUMENT, 200), + new Test( + 2, + URL + "/auth", + URL + "/auth", + Ci.nsIContentPolicy.TYPE_DOCUMENT, + 200 + ), // For the next 3 tests the preference is set to 1 - allow sub-resources to // open HTTP authentication credentials dialogs, but don't allow it for // cross-origin sub-resources // A cross-origin request. - new Test(1, "http://example.com", URL + "/auth", - Ci.nsIContentPolicy.TYPE_OTHER, 401), + new Test( + 1, + "http://example.com", + URL + "/auth", + Ci.nsIContentPolicy.TYPE_OTHER, + 401 + ), // A non cross-origin sub-resource request. - new Test(1, URL + "/", URL + "/auth", - Ci.nsIContentPolicy.TYPE_OTHER, 200), + new Test(1, URL + "/", URL + "/auth", Ci.nsIContentPolicy.TYPE_OTHER, 200), // A top level document. - new Test(1, URL + "/auth", URL + "/auth", - Ci.nsIContentPolicy.TYPE_DOCUMENT, 200), + new Test( + 1, + URL + "/auth", + URL + "/auth", + Ci.nsIContentPolicy.TYPE_DOCUMENT, + 200 + ), // For the next 3 tests the preference is set to 0 - don't allow sub-resources // to open HTTP authentication credentials dialogs. // A cross-origin request. - new Test(0, "http://example.com", URL + "/auth", - Ci.nsIContentPolicy.TYPE_OTHER, 401), + new Test( + 0, + "http://example.com", + URL + "/auth", + Ci.nsIContentPolicy.TYPE_OTHER, + 401 + ), // A sub-resource request. - new Test(0, URL + "/", URL + "/auth", - Ci.nsIContentPolicy.TYPE_OTHER, 401), + new Test(0, URL + "/", URL + "/auth", Ci.nsIContentPolicy.TYPE_OTHER, 401), // A top level request. - new Test(0, URL + "/auth", URL + "/auth", - Ci.nsIContentPolicy.TYPE_DOCUMENT, 200), + new Test( + 0, + URL + "/auth", + URL + "/auth", + Ci.nsIContentPolicy.TYPE_DOCUMENT, + 200 + ), ]; function run_next_test() { diff --git a/netwerk/test/unit/test_auth_jar.js b/netwerk/test/unit/test_auth_jar.js index d97e8b07b12b..25143cf466d4 100644 --- a/netwerk/test/unit/test_auth_jar.js +++ b/netwerk/test/unit/test_auth_jar.js @@ -1,28 +1,74 @@ function createURI(s) { - let service = Cc["@mozilla.org/network/io-service;1"] - .getService(Ci.nsIIOService); + let service = Cc["@mozilla.org/network/io-service;1"].getService( + Ci.nsIIOService + ); return service.newURI(s); } - + function run_test() { // Set up a profile. do_get_profile(); - var secMan = Cc["@mozilla.org/scriptsecuritymanager;1"].getService(Ci.nsIScriptSecurityManager); + var secMan = Cc["@mozilla.org/scriptsecuritymanager;1"].getService( + Ci.nsIScriptSecurityManager + ); const kURI1 = "http://example.com"; var app = secMan.createCodebasePrincipal(createURI(kURI1), {}); - var appbrowser = secMan.createCodebasePrincipal(createURI(kURI1), {inIsolatedMozBrowser: true}); + var appbrowser = secMan.createCodebasePrincipal(createURI(kURI1), { + inIsolatedMozBrowser: true, + }); - var am = Cc["@mozilla.org/network/http-auth-manager;1"]. - getService(Ci.nsIHttpAuthManager); - am.setAuthIdentity("http", "a.example.com", -1, "basic", "realm", "", "example.com", "user", "pass", false, app); - am.setAuthIdentity("http", "a.example.com", -1, "basic", "realm", "", "example.com", "user3", "pass3", false, appbrowser); + var am = Cc["@mozilla.org/network/http-auth-manager;1"].getService( + Ci.nsIHttpAuthManager + ); + am.setAuthIdentity( + "http", + "a.example.com", + -1, + "basic", + "realm", + "", + "example.com", + "user", + "pass", + false, + app + ); + am.setAuthIdentity( + "http", + "a.example.com", + -1, + "basic", + "realm", + "", + "example.com", + "user3", + "pass3", + false, + appbrowser + ); - Services.clearData.deleteDataFromOriginAttributesPattern({ inIsolatedMozBrowser:true }); - - var domain = {value: ""}, user = {value: ""}, pass = {value: ""}; + Services.clearData.deleteDataFromOriginAttributesPattern({ + inIsolatedMozBrowser: true, + }); + + var domain = { value: "" }, + user = { value: "" }, + pass = { value: "" }; try { - am.getAuthIdentity("http", "a.example.com", -1, "basic", "realm", "", domain, user, pass, false, appbrowser); + am.getAuthIdentity( + "http", + "a.example.com", + -1, + "basic", + "realm", + "", + domain, + user, + pass, + false, + appbrowser + ); Assert.equal(false, true); // no identity should be present } catch (x) { Assert.equal(domain.value, ""); @@ -30,7 +76,19 @@ function run_test() { Assert.equal(pass.value, ""); } - am.getAuthIdentity("http", "a.example.com", -1, "basic", "realm", "", domain, user, pass, false, app); + am.getAuthIdentity( + "http", + "a.example.com", + -1, + "basic", + "realm", + "", + domain, + user, + pass, + false, + app + ); Assert.equal(domain.value, "example.com"); Assert.equal(user.value, "user"); Assert.equal(pass.value, "pass"); diff --git a/netwerk/test/unit/test_auth_proxy.js b/netwerk/test/unit/test_auth_proxy.js index 06fc4f7ec939..7ec12e64f7dc 100644 --- a/netwerk/test/unit/test_auth_proxy.js +++ b/netwerk/test/unit/test_auth_proxy.js @@ -10,9 +10,9 @@ * */ -const {HttpServer} = ChromeUtils.import("resource://testing-common/httpd.js"); +const { HttpServer } = ChromeUtils.import("resource://testing-common/httpd.js"); -const FLAG_RETURN_FALSE = 1 << 0; +const FLAG_RETURN_FALSE = 1 << 0; const FLAG_WRONG_PASSWORD = 1 << 1; const FLAG_PREVIOUS_FAILED = 1 << 2; @@ -21,39 +21,47 @@ function AuthPrompt2(proxyFlags, hostFlags) { this.hostCred.flags = hostFlags; } AuthPrompt2.prototype = { - proxyCred : { user: "proxy", pass: "guest", - realmExpected: "intern", flags : 0 }, - hostCred : { user: "host", pass: "guest", - realmExpected: "extern", flags : 0 }, + proxyCred: { + user: "proxy", + pass: "guest", + realmExpected: "intern", + flags: 0, + }, + hostCred: { user: "host", pass: "guest", realmExpected: "extern", flags: 0 }, QueryInterface: ChromeUtils.generateQI(["nsIAuthPrompt2"]), - promptAuth: - function ap2_promptAuth(channel, encryptionLevel, authInfo) - { + promptAuth: function ap2_promptAuth(channel, encryptionLevel, authInfo) { try { - // never HOST and PROXY set at the same time in prompt - Assert.equal((authInfo.flags & Ci.nsIAuthInformation.AUTH_HOST) != 0, - (authInfo.flags & Ci.nsIAuthInformation.AUTH_PROXY) == 0); + Assert.equal( + (authInfo.flags & Ci.nsIAuthInformation.AUTH_HOST) != 0, + (authInfo.flags & Ci.nsIAuthInformation.AUTH_PROXY) == 0 + ); var isProxy = (authInfo.flags & Ci.nsIAuthInformation.AUTH_PROXY) != 0; var cred = isProxy ? this.proxyCred : this.hostCred; - dump("with flags: " + - ((cred.flags & FLAG_WRONG_PASSWORD) !=0 ? "wrong password" : "")+" "+ - ((cred.flags & FLAG_PREVIOUS_FAILED) !=0 ? "previous failed" : "")+" "+ - ((cred.flags & FLAG_RETURN_FALSE) !=0 ? "return false" : "") + "\n"); + dump( + "with flags: " + + ((cred.flags & FLAG_WRONG_PASSWORD) != 0 ? "wrong password" : "") + + " " + + ((cred.flags & FLAG_PREVIOUS_FAILED) != 0 ? "previous failed" : "") + + " " + + ((cred.flags & FLAG_RETURN_FALSE) != 0 ? "return false" : "") + + "\n" + ); // PROXY properly set by necko (checked using realm) Assert.equal(cred.realmExpected, authInfo.realm); // PREVIOUS_FAILED properly set by necko - Assert.equal((cred.flags & FLAG_PREVIOUS_FAILED) != 0, - (authInfo.flags & Ci.nsIAuthInformation.PREVIOUS_FAILED) != 0); + Assert.equal( + (cred.flags & FLAG_PREVIOUS_FAILED) != 0, + (authInfo.flags & Ci.nsIAuthInformation.PREVIOUS_FAILED) != 0 + ); - if (cred.flags & FLAG_RETURN_FALSE) - { + if (cred.flags & FLAG_RETURN_FALSE) { cred.flags |= FLAG_PREVIOUS_FAILED; cred.flags &= ~FLAG_RETURN_FALSE; return false; @@ -70,36 +78,48 @@ AuthPrompt2.prototype = { cred.flags &= ~FLAG_PREVIOUS_FAILED; } return true; - - } catch (e) { do_throw(e); } + } catch (e) { + do_throw(e); + } }, - asyncPromptAuth: - function ap2_async(channel, callback, context, encryptionLevel, authInfo) - { + asyncPromptAuth: function ap2_async( + channel, + callback, + context, + encryptionLevel, + authInfo + ) { try { var me = this; var allOverAndDead = false; executeSoon(function() { try { - if (allOverAndDead) + if (allOverAndDead) { throw "already canceled"; + } var ret = me.promptAuth(channel, encryptionLevel, authInfo); - if (!ret) + if (!ret) { callback.onAuthCancelled(context, true); - else + } else { callback.onAuthAvailable(context, authInfo); + } allOverAndDead = true; - } catch (e) { do_throw(e); } + } catch (e) { + do_throw(e); + } }); return new Cancelable(function() { - if (allOverAndDead) - throw "can't cancel, already ran"; - callback.onAuthAvailable(context, authInfo); - allOverAndDead = true; - }); - } catch (e) { do_throw(e); } - } + if (allOverAndDead) { + throw "can't cancel, already ran"; + } + callback.onAuthAvailable(context, authInfo); + allOverAndDead = true; + }); + } catch (e) { + do_throw(e); + } + }, }; function Cancelable(onCancelFunc) { @@ -110,8 +130,10 @@ Cancelable.prototype = { cancel: function cancel() { try { this.onCancelFunc(); - } catch (e) { do_throw(e); } - } + } catch (e) { + do_throw(e); + } + }, }; function Requestor(proxyFlags, hostFlags) { @@ -129,15 +151,18 @@ Requestor.prototype = { if (iid.equals(Ci.nsIAuthPrompt2)) { try { // Allow the prompt to store state by caching it here - if (!this.prompt2) + if (!this.prompt2) { this.prompt2 = new AuthPrompt2(this.proxyFlags, this.hostFlags); + } return this.prompt2; - } catch (e) { do_throw(e); } + } catch (e) { + do_throw(e); + } } throw Cr.NS_ERROR_NO_INTERFACE; }, - prompt2: null + prompt2: null, }; var listener = { @@ -146,12 +171,16 @@ var listener = { onStartRequest: function test_onStartR(request) { try { // Proxy auth cancellation return failures to avoid spoofing - if (!Components.isSuccessCode(request.status) && - (this.expectedCode != 407)) + if ( + !Components.isSuccessCode(request.status) && + this.expectedCode != 407 + ) { do_throw("Channel should have a success code!"); + } - if (!(request instanceof Ci.nsIHttpChannel)) + if (!(request instanceof Ci.nsIHttpChannel)) { do_throw("Expecting an HTTP channel"); + } Assert.equal(this.expectedCode, request.responseStatus); // If we expect 200, the request should have succeeded @@ -160,9 +189,8 @@ var listener = { var cookie = ""; try { cookie = request.getRequestHeader("Cookie"); - } catch (e) { } + } catch (e) {} Assert.equal(cookie, ""); - } catch (e) { do_throw("Unexpected exception: " + e); } @@ -177,11 +205,11 @@ var listener = { onStopRequest: function test_onStopR(request, status) { Assert.equal(status, Cr.NS_ERROR_ABORT); - if (current_test < (tests.length - 1)) { + if (current_test < tests.length - 1) { // First, need to clear the auth cache Cc["@mozilla.org/network/http-auth-manager;1"] - .getService(Ci.nsIHttpAuthManager) - .clearAll(); + .getService(Ci.nsIHttpAuthManager) + .clearAll(); current_test++; tests[current_test](); @@ -191,15 +219,18 @@ var listener = { } do_test_finished(); - } + }, }; function makeChan(url) { - if (!url) + if (!url) { url = "http://somesite/"; + } - return NetUtil.newChannel({uri: url, loadUsingSystemPrincipal: true}) - .QueryInterface(Ci.nsIHttpChannel); + return NetUtil.newChannel({ + uri: url, + loadUsingSystemPrincipal: true, + }).QueryInterface(Ci.nsIHttpChannel); } var current_test = 0; @@ -212,13 +243,19 @@ function run_test() { httpserv.start(-1); Services.prefs.setCharPref("network.proxy.http", "localhost"); - Services.prefs.setIntPref("network.proxy.http_port", httpserv.identity.primaryPort); + Services.prefs.setIntPref( + "network.proxy.http_port", + httpserv.identity.primaryPort + ); Services.prefs.setCharPref("network.proxy.no_proxies_on", ""); Services.prefs.setIntPref("network.proxy.type", 1); // Turn off the authentication dialog blocking for this test. Services.prefs.setIntPref("network.auth.subresource-http-auth-allow", 2); - Services.prefs.setBoolPref("network.auth.non-web-content-triggered-resources-http-auth-allow", true); + Services.prefs.setBoolPref( + "network.auth.non-web-content-triggered-resources-http-auth-allow", + true + ); registerCleanupFunction(() => { Services.prefs.clearUserPref("network.proxy.http"); @@ -226,7 +263,9 @@ function run_test() { Services.prefs.clearUserPref("network.proxy.no_proxies_on"); Services.prefs.clearUserPref("network.proxy.type"); Services.prefs.clearUserPref("network.auth.subresource-http-auth-allow"); - Services.prefs.clearUserPref("network.auth.non-web-content-triggered-resources-http-auth-allow"); + Services.prefs.clearUserPref( + "network.auth.non-web-content-triggered-resources-http-auth-allow" + ); }); tests[current_test](); @@ -301,8 +340,10 @@ function test_host_wrongpw() { function test_proxy_wrongpw_host_wrongpw() { dump("\ntest: proxy wrongpw, host wrongpw\n"); var chan = makeChan(); - chan.notificationCallbacks = - new Requestor(FLAG_WRONG_PASSWORD, FLAG_WRONG_PASSWORD); + chan.notificationCallbacks = new Requestor( + FLAG_WRONG_PASSWORD, + FLAG_WRONG_PASSWORD + ); listener.expectedCode = 200; // OK chan.asyncOpen(listener); do_test_pending(); @@ -311,18 +352,26 @@ function test_proxy_wrongpw_host_wrongpw() { function test_proxy_wrongpw_host_returnfalse() { dump("\ntest: proxy wrongpw, host return false\n"); var chan = makeChan(); - chan.notificationCallbacks = - new Requestor(FLAG_WRONG_PASSWORD, FLAG_RETURN_FALSE); + chan.notificationCallbacks = new Requestor( + FLAG_WRONG_PASSWORD, + FLAG_RETURN_FALSE + ); listener.expectedCode = 401; // Host Unauthorized chan.asyncOpen(listener); do_test_pending(); } -var tests = [test_proxy_returnfalse, test_proxy_wrongpw, test_all_ok, - test_proxy_407_cookie, test_proxy_200_cookie, - test_host_returnfalse, test_host_wrongpw, - test_proxy_wrongpw_host_wrongpw, test_proxy_wrongpw_host_returnfalse]; - +var tests = [ + test_proxy_returnfalse, + test_proxy_wrongpw, + test_all_ok, + test_proxy_407_cookie, + test_proxy_200_cookie, + test_host_returnfalse, + test_host_wrongpw, + test_proxy_wrongpw_host_wrongpw, + test_proxy_wrongpw_host_returnfalse, +]; // PATH HANDLERS @@ -334,29 +383,39 @@ function proxyAuthHandler(metadata, response) { var expectedHeader = "Basic cHJveHk6Z3Vlc3Q="; var body; - if (metadata.hasHeader("Proxy-Authorization") && - metadata.getHeader("Proxy-Authorization") == expectedHeader) - { + if ( + metadata.hasHeader("Proxy-Authorization") && + metadata.getHeader("Proxy-Authorization") == expectedHeader + ) { dump("proxy password ok\n"); - response.setHeader("Proxy-Authenticate", - 'Basic realm="' + realm + '"', false); + response.setHeader( + "Proxy-Authenticate", + 'Basic realm="' + realm + '"', + false + ); hostAuthHandler(metadata, response); - } - else - { + } else { dump("proxy password required\n"); - response.setStatusLine(metadata.httpVersion, 407, - "Unauthorized by HTTP proxy"); - response.setHeader("Proxy-Authenticate", - 'Basic realm="' + realm + '"', false); + response.setStatusLine( + metadata.httpVersion, + 407, + "Unauthorized by HTTP proxy" + ); + response.setHeader( + "Proxy-Authenticate", + 'Basic realm="' + realm + '"', + false + ); if (metadata.hasHeader("X-Set-407-Cookie")) { - response.setHeader("Set-Cookie", "chewy", false); + response.setHeader("Set-Cookie", "chewy", false); } body = "failed"; response.bodyOutputStream.write(body, body.length); } - } catch (e) { do_throw(e); } + } catch (e) { + do_throw(e); + } } // Host /auth @@ -367,25 +426,38 @@ function hostAuthHandler(metadata, response) { var expectedHeader = "Basic aG9zdDpndWVzdA=="; var body; - if (metadata.hasHeader("Authorization") && - metadata.getHeader("Authorization") == expectedHeader) - { + if ( + metadata.hasHeader("Authorization") && + metadata.getHeader("Authorization") == expectedHeader + ) { dump("host password ok\n"); - response.setStatusLine(metadata.httpVersion, 200, - "OK, authorized for host"); - response.setHeader("WWW-Authenticate", - 'Basic realm="' + realm + '"', false); + response.setStatusLine( + metadata.httpVersion, + 200, + "OK, authorized for host" + ); + response.setHeader( + "WWW-Authenticate", + 'Basic realm="' + realm + '"', + false + ); body = "success"; - } - else - { + } else { dump("host password required\n"); - response.setStatusLine(metadata.httpVersion, 401, - "Unauthorized by HTTP server host"); - response.setHeader("WWW-Authenticate", - 'Basic realm="' + realm + '"', false); + response.setStatusLine( + metadata.httpVersion, + 401, + "Unauthorized by HTTP server host" + ); + response.setHeader( + "WWW-Authenticate", + 'Basic realm="' + realm + '"', + false + ); body = "failed"; } response.bodyOutputStream.write(body, body.length); - } catch (e) { do_throw(e); } + } catch (e) { + do_throw(e); + } } diff --git a/netwerk/test/unit/test_authentication.js b/netwerk/test/unit/test_authentication.js index 4ea024fcddd8..413c8e97bee1 100644 --- a/netwerk/test/unit/test_authentication.js +++ b/netwerk/test/unit/test_authentication.js @@ -1,13 +1,14 @@ // This file tests authentication prompt callbacks // TODO NIT use do_check_eq(expected, actual) consistently, not sometimes eq(actual, expected) -const {HttpServer} = ChromeUtils.import("resource://testing-common/httpd.js"); +const { HttpServer } = ChromeUtils.import("resource://testing-common/httpd.js"); Cu.importGlobalProperties(["XMLHttpRequest"]); // Turn off the authentication dialog blocking for this test. -var prefs = Cc["@mozilla.org/preferences-service;1"]. - getService(Ci.nsIPrefBranch); +var prefs = Cc["@mozilla.org/preferences-service;1"].getService( + Ci.nsIPrefBranch +); prefs.setIntPref("network.auth.subresource-http-auth-allow", 2); XPCOMUtils.defineLazyGetter(this, "URL", function() { @@ -18,7 +19,7 @@ XPCOMUtils.defineLazyGetter(this, "PORT", function() { return httpserv.identity.primaryPort; }); -const FLAG_RETURN_FALSE = 1 << 0; +const FLAG_RETURN_FALSE = 1 << 0; const FLAG_WRONG_PASSWORD = 1 << 1; const FLAG_BOGUS_USER = 1 << 2; const FLAG_PREVIOUS_FAILED = 1 << 3; @@ -29,7 +30,6 @@ const FLAG_NON_ASCII_USER_PASSWORD = 1 << 6; const nsIAuthPrompt2 = Ci.nsIAuthPrompt2; const nsIAuthInformation = Ci.nsIAuthInformation; - function AuthPrompt1(flags) { this.flags = flags; } @@ -46,9 +46,14 @@ AuthPrompt1.prototype = { do_throw("unexpected prompt call"); }, - promptUsernameAndPassword: - function ap1_promptUP(title, text, realm, savePW, user, pw) - { + promptUsernameAndPassword: function ap1_promptUP( + title, + text, + realm, + savePW, + user, + pw + ) { if (this.flags & FLAG_NO_REALM) { // Note that the realm here isn't actually the realm. it's a pw mgr key. Assert.equal(URL + " (" + this.expectedRealm + ")", realm); @@ -60,15 +65,19 @@ AuthPrompt1.prototype = { } else if (text.includes(this.expectedRealm)) { do_throw("There should not be realm for cross origin"); } - if (!text.includes("localhost")) + if (!text.includes("localhost")) { do_throw("Text must indicate the hostname"); - if (!text.includes(String(PORT))) + } + if (!text.includes(String(PORT))) { do_throw("Text must indicate the port"); - if (text.includes("-1")) + } + if (text.includes("-1")) { do_throw("Text must contain negative numbers"); + } - if (this.flags & FLAG_RETURN_FALSE) + if (this.flags & FLAG_RETURN_FALSE) { return false; + } if (this.flags & FLAG_BOGUS_USER) { this.user = "foo\nbar"; @@ -91,8 +100,7 @@ AuthPrompt1.prototype = { promptPassword: function ap1_promptPW(title, text, realm, save, pwd) { do_throw("unexpected promptPassword call"); - } - + }, }; function AuthPrompt2(flags) { @@ -107,33 +115,35 @@ AuthPrompt2.prototype = { QueryInterface: ChromeUtils.generateQI(["nsIAuthPrompt2"]), - promptAuth: - function ap2_promptAuth(channel, level, authInfo) - { + promptAuth: function ap2_promptAuth(channel, level, authInfo) { var isNTLM = channel.URI.pathQueryRef.includes("ntlm"); var isDigest = channel.URI.pathQueryRef.includes("digest"); - if (isNTLM || (this.flags & FLAG_NO_REALM)) { + if (isNTLM || this.flags & FLAG_NO_REALM) { this.expectedRealm = ""; // NTLM knows no realms } Assert.equal(this.expectedRealm, authInfo.realm); - var expectedLevel = (isNTLM || isDigest) ? - nsIAuthPrompt2.LEVEL_PW_ENCRYPTED : - nsIAuthPrompt2.LEVEL_NONE; + var expectedLevel = + isNTLM || isDigest + ? nsIAuthPrompt2.LEVEL_PW_ENCRYPTED + : nsIAuthPrompt2.LEVEL_NONE; Assert.equal(expectedLevel, level); var expectedFlags = nsIAuthInformation.AUTH_HOST; - if (this.flags & FLAG_PREVIOUS_FAILED) + if (this.flags & FLAG_PREVIOUS_FAILED) { expectedFlags |= nsIAuthInformation.PREVIOUS_FAILED; + } - if (this.flags & CROSS_ORIGIN) + if (this.flags & CROSS_ORIGIN) { expectedFlags |= nsIAuthInformation.CROSS_ORIGIN_SUB_RESOURCE; + } - if (isNTLM) + if (isNTLM) { expectedFlags |= nsIAuthInformation.NEED_DOMAIN; + } const kAllKnownFlags = 127; // Don't fail test for newly added flags Assert.equal(expectedFlags, authInfo.flags & kAllKnownFlags); @@ -146,8 +156,7 @@ AuthPrompt2.prototype = { Assert.equal(authInfo.password, ""); Assert.equal(authInfo.domain, ""); - if (this.flags & FLAG_RETURN_FALSE) - { + if (this.flags & FLAG_RETURN_FALSE) { this.flags |= FLAG_PREVIOUS_FAILED; return false; } @@ -175,7 +184,7 @@ AuthPrompt2.prototype = { asyncPromptAuth: function ap2_async(chan, cb, ctx, lvl, info) { throw Cr.NS_ERROR_NOT_IMPLEMENTED; - } + }, }; function Requestor(flags, versions) { @@ -187,18 +196,18 @@ Requestor.prototype = { QueryInterface: ChromeUtils.generateQI(["nsIInterfaceRequestor"]), getInterface: function requestor_gi(iid) { - if (this.versions & 1 && - iid.equals(Ci.nsIAuthPrompt)) { + if (this.versions & 1 && iid.equals(Ci.nsIAuthPrompt)) { // Allow the prompt to store state by caching it here - if (!this.prompt1) + if (!this.prompt1) { this.prompt1 = new AuthPrompt1(this.flags); + } return this.prompt1; } - if (this.versions & 2 && - iid.equals(Ci.nsIAuthPrompt2)) { + if (this.versions & 2 && iid.equals(Ci.nsIAuthPrompt2)) { // Allow the prompt to store state by caching it here - if (!this.prompt2) + if (!this.prompt2) { this.prompt2 = new AuthPrompt2(this.flags); + } return this.prompt2; } @@ -206,30 +215,34 @@ Requestor.prototype = { }, prompt1: null, - prompt2: null + prompt2: null, }; function RealmTestRequestor() {} RealmTestRequestor.prototype = { - QueryInterface: ChromeUtils.generateQI(["nsIInterfaceRequestor", "nsIAuthPrompt2"]), + QueryInterface: ChromeUtils.generateQI([ + "nsIInterfaceRequestor", + "nsIAuthPrompt2", + ]), getInterface: function realmtest_interface(iid) { - if (iid.equals(Ci.nsIAuthPrompt2)) + if (iid.equals(Ci.nsIAuthPrompt2)) { return this; + } throw Cr.NS_ERROR_NO_INTERFACE; }, promptAuth: function realmtest_checkAuth(channel, level, authInfo) { - Assert.equal(authInfo.realm, '\"foo_bar'); + Assert.equal(authInfo.realm, '"foo_bar'); return false; }, asyncPromptAuth: function realmtest_async(chan, cb, ctx, lvl, info) { throw Cr.NS_ERROR_NOT_IMPLEMENTED; - } + }, }; var listener = { @@ -237,16 +250,17 @@ var listener = { onStartRequest: function test_onStartR(request) { try { - if (!Components.isSuccessCode(request.status)) + if (!Components.isSuccessCode(request.status)) { do_throw("Channel should have a success code!"); + } - if (!(request instanceof Ci.nsIHttpChannel)) + if (!(request instanceof Ci.nsIHttpChannel)) { do_throw("Expecting an HTTP channel"); + } Assert.equal(request.responseStatus, this.expectedCode); // The request should be succeeded iff we expect 200 Assert.equal(request.requestSucceeded, this.expectedCode == 200); - } catch (e) { do_throw("Unexpected exception: " + e); } @@ -262,35 +276,51 @@ var listener = { Assert.equal(status, Cr.NS_ERROR_ABORT); moveToNextTest(); - } + }, }; function makeChan(url, loadingUrl) { - var ios = Cc["@mozilla.org/network/io-service;1"]. - getService(Ci.nsIIOService); - var ssm = Cc["@mozilla.org/scriptsecuritymanager;1"] - .getService(Ci.nsIScriptSecurityManager); + var ios = Cc["@mozilla.org/network/io-service;1"].getService(Ci.nsIIOService); + var ssm = Cc["@mozilla.org/scriptsecuritymanager;1"].getService( + Ci.nsIScriptSecurityManager + ); var principal = ssm.createCodebasePrincipal(ios.newURI(loadingUrl), {}); - return NetUtil.newChannel( - { uri: url, loadingPrincipal: principal, - securityFlags: Ci.nsILoadInfo.SEC_ALLOW_CROSS_ORIGIN_DATA_IS_NULL, - contentPolicyType: Ci.nsIContentPolicy.TYPE_OTHER - }); + return NetUtil.newChannel({ + uri: url, + loadingPrincipal: principal, + securityFlags: Ci.nsILoadInfo.SEC_ALLOW_CROSS_ORIGIN_DATA_IS_NULL, + contentPolicyType: Ci.nsIContentPolicy.TYPE_OTHER, + }); } -var tests = [test_noauth, test_returnfalse1, test_wrongpw1, test_prompt1, - test_prompt1CrossOrigin, test_prompt2CrossOrigin, - test_returnfalse2, test_wrongpw2, test_prompt2, test_ntlm, - test_basicrealm, test_nonascii, test_digest_noauth, test_digest, - test_digest_bogus_user, test_short_digest, test_large_realm, - test_large_domain, test_nonascii_xhr]; +var tests = [ + test_noauth, + test_returnfalse1, + test_wrongpw1, + test_prompt1, + test_prompt1CrossOrigin, + test_prompt2CrossOrigin, + test_returnfalse2, + test_wrongpw2, + test_prompt2, + test_ntlm, + test_basicrealm, + test_nonascii, + test_digest_noauth, + test_digest, + test_digest_bogus_user, + test_short_digest, + test_large_realm, + test_large_domain, + test_nonascii_xhr, +]; var current_test = 0; var httpserv = null; function moveToNextTest() { - if (current_test < (tests.length - 1)) { + if (current_test < tests.length - 1) { // First, gotta clear the auth cache Cc["@mozilla.org/network/http-auth-manager;1"] .getService(Ci.nsIHttpAuthManager) @@ -479,7 +509,7 @@ function test_digest() { function test_digest_bogus_user() { var chan = makeChan(URL + "/auth/digest", URL); - chan.notificationCallbacks = new Requestor(FLAG_BOGUS_USER, 2); + chan.notificationCallbacks = new Requestor(FLAG_BOGUS_USER, 2); listener.expectedCode = 401; // unauthorized chan.asyncOpen(listener); @@ -489,7 +519,7 @@ function test_digest_bogus_user() { // Test header "WWW-Authenticate: Digest" - bug 1338876. function test_short_digest() { var chan = makeChan(URL + "/auth/short_digest", URL); - chan.notificationCallbacks = new Requestor(FLAG_NO_REALM, 2); + chan.notificationCallbacks = new Requestor(FLAG_NO_REALM, 2); listener.expectedCode = 401; // OK chan.asyncOpen(listener); @@ -504,16 +534,15 @@ function authHandler(metadata, response) { var expectedHeader = "Basic Z3Vlc3Q6Z3Vlc3Q="; var body; - if (metadata.hasHeader("Authorization") && - metadata.getHeader("Authorization") == expectedHeader) - { + if ( + metadata.hasHeader("Authorization") && + metadata.getHeader("Authorization") == expectedHeader + ) { response.setStatusLine(metadata.httpVersion, 200, "OK, authorized"); response.setHeader("WWW-Authenticate", 'Basic realm="secret"', false); body = "success"; - } - else - { + } else { // didn't know guest:guest, failure response.setStatusLine(metadata.httpVersion, 401, "Unauthorized"); response.setHeader("WWW-Authenticate", 'Basic realm="secret"', false); @@ -527,12 +556,16 @@ function authHandler(metadata, response) { // /auth/ntlm/simple function authNtlmSimple(metadata, response) { response.setStatusLine(metadata.httpVersion, 401, "Unauthorized"); - response.setHeader("WWW-Authenticate", "NTLM" /* + ' realm="secret"' */, false); - - var body = "NOTE: This just sends an NTLM challenge, it never\n" + - "accepts the authentication. It also closes\n" + - "the connection after sending the challenge\n"; + response.setHeader( + "WWW-Authenticate", + "NTLM" /* + ' realm="secret"' */, + false + ); + var body = + "NOTE: This just sends an NTLM challenge, it never\n" + + "accepts the authentication. It also closes\n" + + "the connection after sending the challenge\n"; response.bodyOutputStream.write(body, body.length); } @@ -552,17 +585,16 @@ function authNonascii(metadata, response) { var expectedHeader = "Basic w6k6w6k="; var body; - if (metadata.hasHeader("Authorization") && - metadata.getHeader("Authorization") == expectedHeader) - { + if ( + metadata.hasHeader("Authorization") && + metadata.getHeader("Authorization") == expectedHeader + ) { response.setStatusLine(metadata.httpVersion, 200, "OK, authorized"); response.setHeader("WWW-Authenticate", 'Basic realm="secret"', false); // Use correct XML syntax since this function is also used for testing XHR. body = "success"; - } - else - { + } else { // didn't know é:é, failure response.setStatusLine(metadata.httpVersion, 401, "Unauthorized"); response.setHeader("WWW-Authenticate", 'Basic realm="secret"', false); @@ -575,29 +607,28 @@ function authNonascii(metadata, response) { // // Digest functions -// +// function bytesFromString(str) { - var converter = - Cc["@mozilla.org/intl/scriptableunicodeconverter"] - .createInstance(Ci.nsIScriptableUnicodeConverter); - converter.charset = "UTF-8"; - var data = converter.convertToByteArray(str); - return data; + var converter = Cc[ + "@mozilla.org/intl/scriptableunicodeconverter" + ].createInstance(Ci.nsIScriptableUnicodeConverter); + converter.charset = "UTF-8"; + var data = converter.convertToByteArray(str); + return data; } // return the two-digit hexadecimal code for a byte function toHexString(charCode) { - return ("0" + charCode.toString(16)).slice(-2); + return ("0" + charCode.toString(16)).slice(-2); } function H(str) { - var data = bytesFromString(str); - var ch = Cc["@mozilla.org/security/hash;1"] - .createInstance(Ci.nsICryptoHash); - ch.init(Ci.nsICryptoHash.MD5); - ch.update(data, data.length); - var hash = ch.finish(false); - return Array.from(hash, (c, i) => toHexString(hash.charCodeAt(i))).join(""); + var data = bytesFromString(str); + var ch = Cc["@mozilla.org/security/hash;1"].createInstance(Ci.nsICryptoHash); + ch.init(Ci.nsICryptoHash.MD5); + ch.update(data, data.length); + var hash = ch.finish(false); + return Array.from(hash, (c, i) => toHexString(hash.charCodeAt(i))).join(""); } // @@ -605,56 +636,60 @@ function H(str) { // // /auth/digest function authDigest(metadata, response) { - var nonce = "6f93719059cf8d568005727f3250e798"; - var opaque = "1234opaque1234"; - var cnonceRE = /cnonce="(\w+)"/; - var responseRE = /response="(\w+)"/; - var usernameRE = /username="(\w+)"/; - var authenticate = 'Digest realm="secret", domain="/", qop=auth,' + - 'algorithm=MD5, nonce="' + nonce+ '" opaque="' + - opaque + '"'; - var body; - // check creds if we have them - if (metadata.hasHeader("Authorization")) { - var auth = metadata.getHeader("Authorization"); - var cnonce = (auth.match(cnonceRE))[1]; - var clientDigest = (auth.match(responseRE))[1]; - var username = (auth.match(usernameRE))[1]; - var nc = "00000001"; - - if (username != "guest") { - response.setStatusLine(metadata.httpVersion, 400, "bad request"); - body = "should never get here"; - } else { - // see RFC2617 for the description of this calculation - var A1 = "guest:secret:guest"; - var A2 = "GET:/auth/digest"; - var noncebits = [nonce, nc, cnonce, "auth", H(A2)].join(":"); - var digest = H([H(A1), noncebits].join(":")); + var nonce = "6f93719059cf8d568005727f3250e798"; + var opaque = "1234opaque1234"; + var cnonceRE = /cnonce="(\w+)"/; + var responseRE = /response="(\w+)"/; + var usernameRE = /username="(\w+)"/; + var authenticate = + 'Digest realm="secret", domain="/", qop=auth,' + + 'algorithm=MD5, nonce="' + + nonce + + '" opaque="' + + opaque + + '"'; + var body; + // check creds if we have them + if (metadata.hasHeader("Authorization")) { + var auth = metadata.getHeader("Authorization"); + var cnonce = auth.match(cnonceRE)[1]; + var clientDigest = auth.match(responseRE)[1]; + var username = auth.match(usernameRE)[1]; + var nc = "00000001"; - if (clientDigest == digest) { - response.setStatusLine(metadata.httpVersion, 200, "OK, authorized"); - body = "success"; - } else { - response.setStatusLine(metadata.httpVersion, 401, "Unauthorized"); - response.setHeader("WWW-Authenticate", authenticate, false); - body = "auth failed"; - } - } - } else { - // no header, send one - response.setStatusLine(metadata.httpVersion, 401, "Unauthorized"); - response.setHeader("WWW-Authenticate", authenticate, false); - body = "failed, no header"; - } - - response.bodyOutputStream.write(body, body.length); + if (username != "guest") { + response.setStatusLine(metadata.httpVersion, 400, "bad request"); + body = "should never get here"; + } else { + // see RFC2617 for the description of this calculation + var A1 = "guest:secret:guest"; + var A2 = "GET:/auth/digest"; + var noncebits = [nonce, nc, cnonce, "auth", H(A2)].join(":"); + var digest = H([H(A1), noncebits].join(":")); + + if (clientDigest == digest) { + response.setStatusLine(metadata.httpVersion, 200, "OK, authorized"); + body = "success"; + } else { + response.setStatusLine(metadata.httpVersion, 401, "Unauthorized"); + response.setHeader("WWW-Authenticate", authenticate, false); + body = "auth failed"; + } + } + } else { + // no header, send one + response.setStatusLine(metadata.httpVersion, 401, "Unauthorized"); + response.setHeader("WWW-Authenticate", authenticate, false); + body = "failed, no header"; + } + + response.bodyOutputStream.write(body, body.length); } function authShortDigest(metadata, response) { // no header, send one response.setStatusLine(metadata.httpVersion, 401, "Unauthorized"); - response.setHeader("WWW-Authenticate", 'Digest', false); + response.setHeader("WWW-Authenticate", "Digest", false); body = "failed, no header"; } @@ -670,28 +705,32 @@ let buildLargePayload = (function() { ret += "a"; } return ret; - } + }; })(); function largeRealm(metadata, response) { - // test > 32KB realm tokens + // test > 32KB realm tokens var body; response.setStatusLine(metadata.httpVersion, 401, "Unauthorized"); - response.setHeader("WWW-Authenticate", - 'Digest realm="' + buildLargePayload() + '", domain="foo"'); + response.setHeader( + "WWW-Authenticate", + 'Digest realm="' + buildLargePayload() + '", domain="foo"' + ); body = "need to authenticate"; response.bodyOutputStream.write(body, body.length); } function largeDomain(metadata, response) { - // test > 32KB domain tokens + // test > 32KB domain tokens var body; response.setStatusLine(metadata.httpVersion, 401, "Unauthorized"); - response.setHeader("WWW-Authenticate", - 'Digest realm="foo", domain="' + buildLargePayload() + '"'); + response.setHeader( + "WWW-Authenticate", + 'Digest realm="foo", domain="' + buildLargePayload() + '"' + ); body = "need to authenticate"; response.bodyOutputStream.write(body, body.length); diff --git a/netwerk/test/unit/test_authpromptwrapper.js b/netwerk/test/unit/test_authpromptwrapper.js index 449b56dae66a..b606aed479e2 100644 --- a/netwerk/test/unit/test_authpromptwrapper.js +++ b/netwerk/test/unit/test_authpromptwrapper.js @@ -31,7 +31,7 @@ function run_test() { flags: nsIAuthInformation.AUTH_HOST, authenticationScheme: "basic", - realm: "secretrealm" + realm: "secretrealm", }; const CALLED_PROMPT = 1 << 0; @@ -55,9 +55,14 @@ function run_test() { return this.rv; }, - promptUsernameAndPassword: - function ap1_promptUP(title, text, realm, savePW, user, pw) - { + promptUsernameAndPassword: function ap1_promptUP( + title, + text, + realm, + savePW, + user, + pw + ) { this.called |= CALLED_PROMPTUP; this.doChecks(text, realm); user.value = this.user; @@ -82,23 +87,23 @@ function run_test() { } else { // Make sure that we show the realm if we have one and that we don't // show "" otherwise - if (info.realm != "") + if (info.realm != "") { Assert.notEqual(text.indexOf(info.realm), -1); - else + } else { Assert.equal(text.indexOf('""'), -1); + } // No explicit port in the URL; message should not contain -1 // for those cases Assert.equal(text.indexOf("-1"), -1); } - } + }, }; - // Also have to make up a channel - var uri = NetUtil.newURI("http://" + host) + var uri = NetUtil.newURI("http://" + host); var chan = NetUtil.newChannel({ uri, - loadUsingSystemPrincipal: true + loadUsingSystemPrincipal: true, }); function do_tests(expectedRV) { @@ -199,7 +204,7 @@ function run_test() { var uri2 = NetUtil.newURI("ftp://" + host); var ftpchan = NetUtil.newChannel({ uri: uri2, - loadUsingSystemPrincipal: true + loadUsingSystemPrincipal: true, }); prompt1 = new Prompt1(); @@ -224,4 +229,3 @@ function run_test() { do_tests(true); do_tests(false); } - diff --git a/netwerk/test/unit/test_backgroundfilesaver.js b/netwerk/test/unit/test_backgroundfilesaver.js index ce0c0ce9f2b1..476580e13842 100644 --- a/netwerk/test/unit/test_backgroundfilesaver.js +++ b/netwerk/test/unit/test_backgroundfilesaver.js @@ -10,25 +10,37 @@ //////////////////////////////////////////////////////////////////////////////// //// Globals -ChromeUtils.defineModuleGetter(this, "FileUtils", - "resource://gre/modules/FileUtils.jsm"); -ChromeUtils.defineModuleGetter(this, "NetUtil", - "resource://gre/modules/NetUtil.jsm"); -ChromeUtils.defineModuleGetter(this, "FileTestUtils", - "resource://testing-common/FileTestUtils.jsm"); +ChromeUtils.defineModuleGetter( + this, + "FileUtils", + "resource://gre/modules/FileUtils.jsm" +); +ChromeUtils.defineModuleGetter( + this, + "NetUtil", + "resource://gre/modules/NetUtil.jsm" +); +ChromeUtils.defineModuleGetter( + this, + "FileTestUtils", + "resource://testing-common/FileTestUtils.jsm" +); const BackgroundFileSaverOutputStream = Components.Constructor( - "@mozilla.org/network/background-file-saver;1?mode=outputstream", - "nsIBackgroundFileSaver"); + "@mozilla.org/network/background-file-saver;1?mode=outputstream", + "nsIBackgroundFileSaver" +); const BackgroundFileSaverStreamListener = Components.Constructor( - "@mozilla.org/network/background-file-saver;1?mode=streamlistener", - "nsIBackgroundFileSaver"); + "@mozilla.org/network/background-file-saver;1?mode=streamlistener", + "nsIBackgroundFileSaver" +); const StringInputStream = Components.Constructor( - "@mozilla.org/io/string-input-stream;1", - "nsIStringInputStream", - "setData"); + "@mozilla.org/io/string-input-stream;1", + "nsIStringInputStream", + "setData" +); const REQUEST_SUSPEND_AT = 1024 * 1024 * 4; const TEST_DATA_SHORT = "This test string is written to the file."; @@ -39,15 +51,15 @@ const TEST_FILE_NAME_3 = "test-backgroundfilesaver-3.txt"; // A map of test data length to the expected SHA-256 hashes const EXPECTED_HASHES = { // No data - 0 : "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855", + 0: "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855", // TEST_DATA_SHORT - 40 : "f37176b690e8744ee990a206c086cba54d1502aa2456c3b0c84ef6345d72a192", + 40: "f37176b690e8744ee990a206c086cba54d1502aa2456c3b0c84ef6345d72a192", // TEST_DATA_SHORT + TEST_DATA_SHORT - 80 : "780c0e91f50bb7ec922cc11e16859e6d5df283c0d9470f61772e3d79f41eeb58", + 80: "780c0e91f50bb7ec922cc11e16859e6d5df283c0d9470f61772e3d79f41eeb58", // TEST_DATA_LONG - 8388608 : "e3611a47714c42bdf326acfb2eb6ed9fa4cca65cb7d7be55217770a5bf5e7ff0", + 8388608: "e3611a47714c42bdf326acfb2eb6ed9fa4cca65cb7d7be55217770a5bf5e7ff0", // TEST_DATA_LONG + TEST_DATA_LONG - 16777216 : "03a0db69a30140f307587ee746a539247c181bafd85b85c8516a3533c7d9ea1d" + 16777216: "03a0db69a30140f307587ee746a539247c181bafd85b85c8516a3533c7d9ea1d", }; const gTextDecoder = new TextDecoder(); @@ -74,9 +86,9 @@ function getTempFile(leafName) { * @return A hex-encoded string. */ function toHex(str) { - var hex = ''; + var hex = ""; for (var i = 0; i < str.length; i++) { - hex += ('0' + str.charCodeAt(i).toString(16)).slice(-2); + hex += ("0" + str.charCodeAt(i).toString(16)).slice(-2); } return hex; } @@ -95,23 +107,27 @@ function toHex(str) { */ function promiseVerifyContents(aFile, aExpectedContents) { return new Promise(resolve => { - NetUtil.asyncFetch({ - uri: NetUtil.newURI(aFile), - loadUsingSystemPrincipal: true - }, function(aInputStream, aStatus) { - Assert.ok(Components.isSuccessCode(aStatus)); - let contents = NetUtil.readInputStreamToString(aInputStream, - aInputStream.available()); - if (contents.length <= TEST_DATA_SHORT.length * 2) { - Assert.equal(contents, aExpectedContents); - } else { - // Do not print the entire content string to the test log. - Assert.equal(contents.length, aExpectedContents.length); - Assert.ok(contents == aExpectedContents); + NetUtil.asyncFetch( + { + uri: NetUtil.newURI(aFile), + loadUsingSystemPrincipal: true, + }, + function(aInputStream, aStatus) { + Assert.ok(Components.isSuccessCode(aStatus)); + let contents = NetUtil.readInputStreamToString( + aInputStream, + aInputStream.available() + ); + if (contents.length <= TEST_DATA_SHORT.length * 2) { + Assert.equal(contents, aExpectedContents); + } else { + // Do not print the entire content string to the test log. + Assert.equal(contents.length, aExpectedContents.length); + Assert.ok(contents == aExpectedContents); + } + resolve(); } - resolve(); - }); - + ); }); } @@ -130,14 +146,12 @@ function promiseVerifyContents(aFile, aExpectedContents) { function promiseSaverComplete(aSaver, aOnTargetChangeFn) { return new Promise((resolve, reject) => { aSaver.observer = { - onTargetChange: function BFSO_onSaveComplete(aSaver, aTarget) - { + onTargetChange: function BFSO_onSaveComplete(aSaver, aTarget) { if (aOnTargetChangeFn) { aOnTargetChangeFn(aTarget); } }, - onSaveComplete: function BFSO_onSaveComplete(aSaver, aStatus) - { + onSaveComplete: function BFSO_onSaveComplete(aSaver, aStatus) { if (Components.isSuccessCode(aStatus)) { resolve(); } else { @@ -164,22 +178,36 @@ function promiseSaverComplete(aSaver, aOnTargetChangeFn) { */ function promiseCopyToSaver(aSourceString, aSaverOutputStream, aCloseWhenDone) { return new Promise((resolve, reject) => { - let inputStream = new StringInputStream(aSourceString, aSourceString.length); - let copier = Cc["@mozilla.org/network/async-stream-copier;1"] - .createInstance(Ci.nsIAsyncStreamCopier); - copier.init(inputStream, aSaverOutputStream, null, false, true, 0x8000, true, - aCloseWhenDone); - copier.asyncCopy({ - onStartRequest () { }, - onStopRequest (aRequest, aStatusCode) + let inputStream = new StringInputStream( + aSourceString, + aSourceString.length + ); + let copier = Cc[ + "@mozilla.org/network/async-stream-copier;1" + ].createInstance(Ci.nsIAsyncStreamCopier); + copier.init( + inputStream, + aSaverOutputStream, + null, + false, + true, + 0x8000, + true, + aCloseWhenDone + ); + copier.asyncCopy( { - if (Components.isSuccessCode(aStatusCode)) { - resolve(); - } else { - reject(new Components.Exception(aResult)); - } + onStartRequest() {}, + onStopRequest(aRequest, aStatusCode) { + if (Components.isSuccessCode(aStatusCode)) { + resolve(); + } else { + reject(new Components.Exception(aResult)); + } + }, }, - }, null); + null + ); }); } @@ -197,36 +225,50 @@ function promiseCopyToSaver(aSourceString, aSaverOutputStream, aCloseWhenDone) { * @resolves When the operation completes with a success code. * @rejects With an exception, if the operation fails. */ -function promisePumpToSaver(aSourceString, aSaverStreamListener, - aCloseWhenDone) { +function promisePumpToSaver( + aSourceString, + aSaverStreamListener, + aCloseWhenDone +) { return new Promise((resolve, reject) => { aSaverStreamListener.QueryInterface(Ci.nsIStreamListener); - let inputStream = new StringInputStream(aSourceString, aSourceString.length); - let pump = Cc["@mozilla.org/network/input-stream-pump;1"] - .createInstance(Ci.nsIInputStreamPump); + let inputStream = new StringInputStream( + aSourceString, + aSourceString.length + ); + let pump = Cc["@mozilla.org/network/input-stream-pump;1"].createInstance( + Ci.nsIInputStreamPump + ); pump.init(inputStream, 0, 0, true); - pump.asyncRead({ - onStartRequest: function PPTS_onStartRequest(aRequest) + pump.asyncRead( { - aSaverStreamListener.onStartRequest(aRequest); + onStartRequest: function PPTS_onStartRequest(aRequest) { + aSaverStreamListener.onStartRequest(aRequest); + }, + onStopRequest: function PPTS_onStopRequest(aRequest, aStatusCode) { + aSaverStreamListener.onStopRequest(aRequest, aStatusCode); + if (Components.isSuccessCode(aStatusCode)) { + resolve(); + } else { + reject(new Components.Exception(aResult)); + } + }, + onDataAvailable: function PPTS_onDataAvailable( + aRequest, + aInputStream, + aOffset, + aCount + ) { + aSaverStreamListener.onDataAvailable( + aRequest, + aInputStream, + aOffset, + aCount + ); + }, }, - onStopRequest: function PPTS_onStopRequest(aRequest, aStatusCode) - { - aSaverStreamListener.onStopRequest(aRequest, aStatusCode); - if (Components.isSuccessCode(aStatusCode)) { - resolve(); - } else { - reject(new Components.Exception(aResult)); - } - }, - onDataAvailable: function PPTS_onDataAvailable(aRequest, - aInputStream, aOffset, - aCount) - { - aSaverStreamListener.onDataAvailable(aRequest, aInputStream, - aOffset, aCount); - }, - }, null); + null + ); }); } @@ -235,18 +277,16 @@ var gStillRunning = true; //////////////////////////////////////////////////////////////////////////////// //// Tests -add_task(function test_setup() -{ +add_task(function test_setup() { // Wait 10 minutes, that is half of the external xpcshell timeout. do_timeout(10 * 60 * 1000, function() { if (gStillRunning) { do_throw("Test timed out."); } - }) + }); }); -add_task(async function test_normal() -{ +add_task(async function test_normal() { // This test demonstrates the most basic use case. let destFile = getTempFile(TEST_FILE_NAME_1); @@ -279,8 +319,7 @@ add_task(async function test_normal() destFile.remove(false); }); -add_task(async function test_combinations() -{ +add_task(async function test_combinations() { let initialFile = getTempFile(TEST_FILE_NAME_1); let renamedFile = getTempFile(TEST_FILE_NAME_2); @@ -302,17 +341,24 @@ add_task(async function test_combinations() let useLongData = !!(testFlags & 16); let startTime = Date.now(); - info("Starting keepPartialOnFailure = " + keepPartialOnFailure + - ", renameAtSomePoint = " + renameAtSomePoint + - ", cancelAtSomePoint = " + cancelAtSomePoint + - ", useStreamListener = " + useStreamListener + - ", useLongData = " + useLongData); + info( + "Starting keepPartialOnFailure = " + + keepPartialOnFailure + + ", renameAtSomePoint = " + + renameAtSomePoint + + ", cancelAtSomePoint = " + + cancelAtSomePoint + + ", useStreamListener = " + + useStreamListener + + ", useLongData = " + + useLongData + ); // Create the object and register the observers. currentFile = null; let saver = useStreamListener - ? new BackgroundFileSaverStreamListener() - : new BackgroundFileSaverOutputStream(); + ? new BackgroundFileSaverStreamListener() + : new BackgroundFileSaverOutputStream(); saver.enableSha256(); let completionPromise = promiseSaverComplete(saver, onTargetChange); @@ -320,8 +366,8 @@ add_task(async function test_combinations() // the stream listener, we only write one chunk. let testData = useLongData ? TEST_DATA_LONG : TEST_DATA_SHORT; let feedPromise = useStreamListener - ? promisePumpToSaver(testData + testData, saver) - : promiseCopyToSaver(testData, saver, false); + ? promisePumpToSaver(testData + testData, saver) + : promiseCopyToSaver(testData, saver, false); // Set a target output file. saver.setTarget(initialFile, keepPartialOnFailure); @@ -362,8 +408,10 @@ add_task(async function test_combinations() Assert.ok(currentFile.exists()); let expectedContents = testData + testData; await promiseVerifyContents(currentFile, expectedContents); - Assert.equal(EXPECTED_HASHES[expectedContents.length], - toHex(saver.sha256Hash)); + Assert.equal( + EXPECTED_HASHES[expectedContents.length], + toHex(saver.sha256Hash) + ); currentFile.remove(false); // If the target was really renamed, the old file should not exist. @@ -390,8 +438,7 @@ add_task(async function test_combinations() } }); -add_task(async function test_setTarget_after_close_stream() -{ +add_task(async function test_setTarget_after_close_stream() { // This test checks the case where we close the output stream before we call // the setTarget method. All the data should be buffered and written anyway. let destFile = getTempFile(TEST_FILE_NAME_1); @@ -416,16 +463,17 @@ add_task(async function test_setTarget_after_close_stream() // Verify results. await promiseVerifyContents(destFile, TEST_DATA_SHORT); - Assert.equal(EXPECTED_HASHES[TEST_DATA_SHORT.length], - toHex(saver.sha256Hash)); + Assert.equal( + EXPECTED_HASHES[TEST_DATA_SHORT.length], + toHex(saver.sha256Hash) + ); } // Clean up. destFile.remove(false); }); -add_task(async function test_setTarget_fast() -{ +add_task(async function test_setTarget_fast() { // This test checks a fast rename of the target file. let destFile1 = getTempFile(TEST_FILE_NAME_1); let destFile2 = getTempFile(TEST_FILE_NAME_2); @@ -447,8 +495,7 @@ add_task(async function test_setTarget_fast() destFile2.remove(false); }); -add_task(async function test_setTarget_multiple() -{ +add_task(async function test_setTarget_multiple() { // This test checks multiple renames of the target file. let destFile = getTempFile(TEST_FILE_NAME_1); let saver = new BackgroundFileSaverOutputStream(); @@ -472,8 +519,7 @@ add_task(async function test_setTarget_multiple() destFile.remove(false); }); -add_task(async function test_enableAppend() -{ +add_task(async function test_enableAppend() { // This test checks append mode with hashing disabled. let destFile = getTempFile(TEST_FILE_NAME_1); @@ -491,8 +537,8 @@ add_task(async function test_enableAppend() await completionPromise; // Verify results. - let expectedContents = (i == 0 ? TEST_DATA_LONG - : TEST_DATA_LONG + TEST_DATA_LONG); + let expectedContents = + i == 0 ? TEST_DATA_LONG : TEST_DATA_LONG + TEST_DATA_LONG; await promiseVerifyContents(destFile, expectedContents); } @@ -500,8 +546,7 @@ add_task(async function test_enableAppend() destFile.remove(false); }); -add_task(async function test_enableAppend_setTarget_fast() -{ +add_task(async function test_enableAppend_setTarget_fast() { // This test checks a fast rename of the target file in append mode. let destFile1 = getTempFile(TEST_FILE_NAME_1); let destFile2 = getTempFile(TEST_FILE_NAME_2); @@ -518,8 +563,8 @@ add_task(async function test_enableAppend_setTarget_fast() // The first time, we start appending to the first file and rename to the // second file. The second time, we start appending to the second file, // that was created the first time, and rename back to the first file. - let firstFile = (i == 0) ? destFile1 : destFile2; - let secondFile = (i == 0) ? destFile2 : destFile1; + let firstFile = i == 0 ? destFile1 : destFile2; + let secondFile = i == 0 ? destFile2 : destFile1; saver.setTarget(firstFile, false); saver.setTarget(secondFile, false); @@ -528,8 +573,8 @@ add_task(async function test_enableAppend_setTarget_fast() // Verify results. Assert.ok(!firstFile.exists()); - let expectedContents = (i == 0 ? TEST_DATA_SHORT - : TEST_DATA_SHORT + TEST_DATA_SHORT); + let expectedContents = + i == 0 ? TEST_DATA_SHORT : TEST_DATA_SHORT + TEST_DATA_SHORT; await promiseVerifyContents(secondFile, expectedContents); } @@ -537,8 +582,7 @@ add_task(async function test_enableAppend_setTarget_fast() destFile1.remove(false); }); -add_task(async function test_enableAppend_hash() -{ +add_task(async function test_enableAppend_hash() { // This test checks append mode, also verifying that the computed hash // includes the contents of the existing data. let destFile = getTempFile(TEST_FILE_NAME_1); @@ -558,19 +602,20 @@ add_task(async function test_enableAppend_hash() await completionPromise; // Verify results. - let expectedContents = (i == 0 ? TEST_DATA_LONG - : TEST_DATA_LONG + TEST_DATA_LONG); + let expectedContents = + i == 0 ? TEST_DATA_LONG : TEST_DATA_LONG + TEST_DATA_LONG; await promiseVerifyContents(destFile, expectedContents); - Assert.equal(EXPECTED_HASHES[expectedContents.length], - toHex(saver.sha256Hash)); + Assert.equal( + EXPECTED_HASHES[expectedContents.length], + toHex(saver.sha256Hash) + ); } // Clean up. destFile.remove(false); }); -add_task(async function test_finish_only() -{ +add_task(async function test_finish_only() { // This test checks creating the object and doing nothing. let destFile = getTempFile(TEST_FILE_NAME_1); let saver = new BackgroundFileSaverOutputStream(); @@ -582,8 +627,7 @@ add_task(async function test_finish_only() await completionPromise; }); -add_task(async function test_empty() -{ +add_task(async function test_empty() { // This test checks we still create an empty file when no data is fed. let destFile = getTempFile(TEST_FILE_NAME_1); @@ -604,8 +648,7 @@ add_task(async function test_empty() destFile.remove(false); }); -add_task(async function test_empty_hash() -{ +add_task(async function test_empty_hash() { // This test checks the hash of an empty file, both in normal and append mode. let destFile = getTempFile(TEST_FILE_NAME_1); @@ -633,8 +676,7 @@ add_task(async function test_empty_hash() destFile.remove(false); }); -add_task(async function test_invalid_hash() -{ +add_task(async function test_invalid_hash() { let saver = new BackgroundFileSaverStreamListener(); let completionPromise = promiseSaverComplete(saver); // We shouldn't be able to get the hash if hashing hasn't been enabled @@ -675,8 +717,7 @@ add_task(async function test_invalid_hash() } }); -add_task(async function test_signature() -{ +add_task(async function test_signature() { // Check that we get a signature if the saver is finished. let destFile = getTempFile(TEST_FILE_NAME_1); @@ -707,8 +748,7 @@ add_task(async function test_signature() destFile.remove(false); }); -add_task(async function test_signature_not_enabled() -{ +add_task(async function test_signature_not_enabled() { // Check that we get a signature if the saver is finished on Windows. let destFile = getTempFile(TEST_FILE_NAME_1); @@ -732,7 +772,6 @@ add_task(async function test_signature_not_enabled() destFile.remove(false); }); -add_task(function test_teardown() -{ +add_task(function test_teardown() { gStillRunning = false; }); diff --git a/netwerk/test/unit/test_be_conservative.js b/netwerk/test/unit/test_be_conservative.js index 829fd47214b8..f5ef6b7bb7c5 100644 --- a/netwerk/test/unit/test_be_conservative.js +++ b/netwerk/test/unit/test_be_conservative.js @@ -9,15 +9,15 @@ // starting a TLS server that requires the advanced features and then ensuring // that a client that is set to be conservative will fail when connecting. - // Get a profile directory and ensure PSM initializes NSS. do_get_profile(); Cc["@mozilla.org/psm;1"].getService(Ci.nsISupports); function getCert() { return new Promise((resolve, reject) => { - let certService = Cc["@mozilla.org/security/local-cert-service;1"] - .getService(Ci.nsILocalCertService); + let certService = Cc[ + "@mozilla.org/security/local-cert-service;1" + ].getService(Ci.nsILocalCertService); certService.getOrCreateCert("beConservative-test", { handleCert(c, rv) { if (rv) { @@ -25,7 +25,7 @@ function getCert() { return; } resolve(c); - } + }, }); }); } @@ -47,21 +47,31 @@ class InputStreamCallback { available = stream.available(); } catch (e) { // onInputStreamReady may fire when the stream has been closed. - equal(e.result, Cr.NS_BASE_STREAM_CLOSED, - "error should be NS_BASE_STREAM_CLOSED"); + equal( + e.result, + Cr.NS_BASE_STREAM_CLOSED, + "error should be NS_BASE_STREAM_CLOSED" + ); } if (available > 0) { - let request = NetUtil.readInputStreamToString(stream, available, - { charset: "utf8"}); - ok(request.startsWith("GET / HTTP/1.1\r\n"), - "Should get a simple GET / HTTP/1.1 request"); - let response = "HTTP/1.1 200 OK\r\n" + - "Content-Length: 2\r\n" + - "Content-Type: text/plain\r\n" + - "\r\nOK"; + let request = NetUtil.readInputStreamToString(stream, available, { + charset: "utf8", + }); + ok( + request.startsWith("GET / HTTP/1.1\r\n"), + "Should get a simple GET / HTTP/1.1 request" + ); + let response = + "HTTP/1.1 200 OK\r\n" + + "Content-Length: 2\r\n" + + "Content-Type: text/plain\r\n" + + "\r\nOK"; let written = this.output.write(response, response.length); - equal(written, response.length, - "should have been able to write entire response"); + equal( + written, + response.length, + "should have been able to write entire response" + ); } this.output.close(); info("done with input stream ready"); @@ -99,7 +109,7 @@ class TLSServerSecurityObserver { this.stopped = true; this.input.close(); this.output.close(); - this.callbacks.forEach((callback) => { + this.callbacks.forEach(callback => { callback.stop(); }); } @@ -112,8 +122,9 @@ class ServerSocketListener { onSocketAccepted(socket, transport) { info("accepted TLS client connection"); - let connectionInfo = transport.securityInfo - .QueryInterface(Ci.nsITLSServerConnectionInfo); + let connectionInfo = transport.securityInfo.QueryInterface( + Ci.nsITLSServerConnectionInfo + ); let input = transport.openInputStream(0, 0, 0); let output = transport.openOutputStream(0, 0, 0); let securityObserver = new TLSServerSecurityObserver(input, output); @@ -125,15 +136,16 @@ class ServerSocketListener { // listening, so this ensures we just drop those events. onStopListening() { info("onStopListening"); - this.securityObservers.forEach((observer) => { + this.securityObservers.forEach(observer => { observer.stop(); }); } } function startServer(cert, minServerVersion, maxServerVersion) { - let tlsServer = Cc["@mozilla.org/network/tls-server-socket;1"] - .createInstance(Ci.nsITLSServerSocket); + let tlsServer = Cc["@mozilla.org/network/tls-server-socket;1"].createInstance( + Ci.nsITLSServerSocket + ); tlsServer.init(-1, true, -1); tlsServer.serverCert = cert; tlsServer.setVersionRange(minServerVersion, maxServerVersion); @@ -142,15 +154,22 @@ function startServer(cert, minServerVersion, maxServerVersion) { return tlsServer; } -const hostname = "example.com" +const hostname = "example.com"; function storeCertOverride(port, cert) { - let certOverrideService = Cc["@mozilla.org/security/certoverride;1"] - .getService(Ci.nsICertOverrideService); - let overrideBits = Ci.nsICertOverrideService.ERROR_UNTRUSTED | - Ci.nsICertOverrideService.ERROR_MISMATCH; - certOverrideService.rememberValidityOverride(hostname, port, cert, - overrideBits, true); + let certOverrideService = Cc[ + "@mozilla.org/security/certoverride;1" + ].getService(Ci.nsICertOverrideService); + let overrideBits = + Ci.nsICertOverrideService.ERROR_UNTRUSTED | + Ci.nsICertOverrideService.ERROR_MISMATCH; + certOverrideService.rememberValidityOverride( + hostname, + port, + cert, + overrideBits, + true + ); } function startClient(port, beConservative, expectSuccess) { @@ -160,14 +179,18 @@ function startClient(port, beConservative, expectSuccess) { internalChannel.beConservative = beConservative; return new Promise((resolve, reject) => { req.onload = () => { - ok(expectSuccess, - `should ${expectSuccess ? "" : "not "}have gotten load event`); + ok( + expectSuccess, + `should ${expectSuccess ? "" : "not "}have gotten load event` + ); equal(req.responseText, "OK", "response text should be 'OK'"); resolve(); }; req.onerror = () => { - ok(!expectSuccess, - `should ${!expectSuccess ? "" : "not "}have gotten an error`); + ok( + !expectSuccess, + `should ${!expectSuccess ? "" : "not "}have gotten an error` + ); resolve(); }; @@ -182,24 +205,39 @@ add_task(async function() { // First run a server that accepts TLS 1.2 and 1.3. A conservative client // should succeed in connecting. - let server = startServer(cert, Ci.nsITLSClientStatus.TLS_VERSION_1_2, - Ci.nsITLSClientStatus.TLS_VERSION_1_3); + let server = startServer( + cert, + Ci.nsITLSClientStatus.TLS_VERSION_1_2, + Ci.nsITLSClientStatus.TLS_VERSION_1_3 + ); storeCertOverride(server.port, cert); - await startClient(server.port, true /*be conservative*/, - true /*should succeed*/); + await startClient( + server.port, + true /*be conservative*/, + true /*should succeed*/ + ); server.close(); // Now run a server that only accepts TLS 1.3. A conservative client will not // succeed in this case. - server = startServer(cert, Ci.nsITLSClientStatus.TLS_VERSION_1_3, - Ci.nsITLSClientStatus.TLS_VERSION_1_3); + server = startServer( + cert, + Ci.nsITLSClientStatus.TLS_VERSION_1_3, + Ci.nsITLSClientStatus.TLS_VERSION_1_3 + ); storeCertOverride(server.port, cert); - await startClient(server.port, true /*be conservative*/, - false /*should fail*/); + await startClient( + server.port, + true /*be conservative*/, + false /*should fail*/ + ); // However, a non-conservative client should succeed. - await startClient(server.port, false /*don't be conservative*/, - true /*should succeed*/); + await startClient( + server.port, + false /*don't be conservative*/, + true /*should succeed*/ + ); server.close(); }); diff --git a/netwerk/test/unit/test_be_conservative_error_handling.js b/netwerk/test/unit/test_be_conservative_error_handling.js index adf1cc21524f..190fbba157f4 100644 --- a/netwerk/test/unit/test_be_conservative_error_handling.js +++ b/netwerk/test/unit/test_be_conservative_error_handling.js @@ -9,15 +9,15 @@ // starting a TLS server that requires the advanced features and then ensuring // that a client that is set to be conservative will fail when connecting. - // Get a profile directory and ensure PSM initializes NSS. do_get_profile(); Cc["@mozilla.org/psm;1"].getService(Ci.nsISupports); function getCert() { return new Promise((resolve, reject) => { - let certService = Cc["@mozilla.org/security/local-cert-service;1"] - .getService(Ci.nsILocalCertService); + let certService = Cc[ + "@mozilla.org/security/local-cert-service;1" + ].getService(Ci.nsILocalCertService); certService.getOrCreateCert("beConservative-test", { handleCert(c, rv) { if (rv) { @@ -25,7 +25,7 @@ function getCert() { return; } resolve(c); - } + }, }); }); } @@ -47,21 +47,31 @@ class InputStreamCallback { available = stream.available(); } catch (e) { // onInputStreamReady may fire when the stream has been closed. - equal(e.result, Cr.NS_BASE_STREAM_CLOSED, - "error should be NS_BASE_STREAM_CLOSED"); + equal( + e.result, + Cr.NS_BASE_STREAM_CLOSED, + "error should be NS_BASE_STREAM_CLOSED" + ); } if (available > 0) { - let request = NetUtil.readInputStreamToString(stream, available, - { charset: "utf8"}); - ok(request.startsWith("GET / HTTP/1.1\r\n"), - "Should get a simple GET / HTTP/1.1 request"); - let response = "HTTP/1.1 200 OK\r\n" + - "Content-Length: 2\r\n" + - "Content-Type: text/plain\r\n" + - "\r\nOK"; + let request = NetUtil.readInputStreamToString(stream, available, { + charset: "utf8", + }); + ok( + request.startsWith("GET / HTTP/1.1\r\n"), + "Should get a simple GET / HTTP/1.1 request" + ); + let response = + "HTTP/1.1 200 OK\r\n" + + "Content-Length: 2\r\n" + + "Content-Type: text/plain\r\n" + + "\r\nOK"; let written = this.output.write(response, response.length); - equal(written, response.length, - "should have been able to write entire response"); + equal( + written, + response.length, + "should have been able to write entire response" + ); } this.output.close(); info("done with input stream ready"); @@ -99,7 +109,7 @@ class TLSServerSecurityObserver { this.stopped = true; this.input.close(); this.output.close(); - this.callbacks.forEach((callback) => { + this.callbacks.forEach(callback => { callback.stop(); }); } @@ -112,8 +122,9 @@ class ServerSocketListener { onSocketAccepted(socket, transport) { info("accepted TLS client connection"); - let connectionInfo = transport.securityInfo - .QueryInterface(Ci.nsITLSServerConnectionInfo); + let connectionInfo = transport.securityInfo.QueryInterface( + Ci.nsITLSServerConnectionInfo + ); let input = transport.openInputStream(0, 0, 0); let output = transport.openOutputStream(0, 0, 0); let securityObserver = new TLSServerSecurityObserver(input, output); @@ -125,15 +136,16 @@ class ServerSocketListener { // listening, so this ensures we just drop those events. onStopListening() { info("onStopListening"); - this.securityObservers.forEach((observer) => { + this.securityObservers.forEach(observer => { observer.stop(); }); } } function startServer(cert, minServerVersion, maxServerVersion) { - let tlsServer = Cc["@mozilla.org/network/tls-server-socket;1"] - .createInstance(Ci.nsITLSServerSocket); + let tlsServer = Cc["@mozilla.org/network/tls-server-socket;1"].createInstance( + Ci.nsITLSServerSocket + ); tlsServer.init(-1, true, -1); tlsServer.serverCert = cert; tlsServer.setVersionRange(minServerVersion, maxServerVersion); @@ -142,15 +154,22 @@ function startServer(cert, minServerVersion, maxServerVersion) { return tlsServer; } -const hostname = "example.com" +const hostname = "example.com"; function storeCertOverride(port, cert) { - let certOverrideService = Cc["@mozilla.org/security/certoverride;1"] - .getService(Ci.nsICertOverrideService); - let overrideBits = Ci.nsICertOverrideService.ERROR_UNTRUSTED | - Ci.nsICertOverrideService.ERROR_MISMATCH; - certOverrideService.rememberValidityOverride(hostname, port, cert, - overrideBits, true); + let certOverrideService = Cc[ + "@mozilla.org/security/certoverride;1" + ].getService(Ci.nsICertOverrideService); + let overrideBits = + Ci.nsICertOverrideService.ERROR_UNTRUSTED | + Ci.nsICertOverrideService.ERROR_MISMATCH; + certOverrideService.rememberValidityOverride( + hostname, + port, + cert, + overrideBits, + true + ); } function startClient(port, beConservative, expectSuccess) { @@ -160,14 +179,18 @@ function startClient(port, beConservative, expectSuccess) { internalChannel.beConservative = beConservative; return new Promise((resolve, reject) => { req.onload = () => { - ok(expectSuccess, - `should ${expectSuccess ? "" : "not "}have gotten load event`); + ok( + expectSuccess, + `should ${expectSuccess ? "" : "not "}have gotten load event` + ); equal(req.responseText, "OK", "response text should be 'OK'"); resolve(); }; req.onerror = () => { - ok(!expectSuccess, - `should ${!expectSuccess ? "" : "not "}have gotten an error`); + ok( + !expectSuccess, + `should ${!expectSuccess ? "" : "not "}have gotten an error` + ); resolve(); }; @@ -183,20 +206,32 @@ add_task(async function() { let cert = await getCert(); // Run a server that accepts TLS 1.2 and 1.3. The connection should succeed. - let server = startServer(cert, Ci.nsITLSClientStatus.TLS_VERSION_1_2, - Ci.nsITLSClientStatus.TLS_VERSION_1_3); + let server = startServer( + cert, + Ci.nsITLSClientStatus.TLS_VERSION_1_2, + Ci.nsITLSClientStatus.TLS_VERSION_1_3 + ); storeCertOverride(server.port, cert); - await startClient(server.port, true /*be conservative*/, - true /*should succeed*/); + await startClient( + server.port, + true /*be conservative*/, + true /*should succeed*/ + ); server.close(); // Now run a server that only accepts TLS 1.3. A conservative client will not // succeed in this case. - server = startServer(cert, Ci.nsITLSClientStatus.TLS_VERSION_1_3, - Ci.nsITLSClientStatus.TLS_VERSION_1_3); + server = startServer( + cert, + Ci.nsITLSClientStatus.TLS_VERSION_1_3, + Ci.nsITLSClientStatus.TLS_VERSION_1_3 + ); storeCertOverride(server.port, cert); - await startClient(server.port, true /*be conservative*/, - false /*should fail*/); + await startClient( + server.port, + true /*be conservative*/, + false /*should fail*/ + ); server.close(); }); diff --git a/netwerk/test/unit/test_bug1064258.js b/netwerk/test/unit/test_bug1064258.js index 7cd7adea3ecc..34d11977f072 100644 --- a/netwerk/test/unit/test_bug1064258.js +++ b/netwerk/test/unit/test_bug1064258.js @@ -10,7 +10,7 @@ * - only difference is that we get a newer version of the content from the server during the second request */ -const {HttpServer} = ChromeUtils.import("resource://testing-common/httpd.js"); +const { HttpServer } = ChromeUtils.import("resource://testing-common/httpd.js"); XPCOMUtils.defineLazyGetter(this, "URL", function() { return "http://localhost:" + httpServer.identity.primaryPort; @@ -19,15 +19,14 @@ XPCOMUtils.defineLazyGetter(this, "URL", function() { var httpServer = null; function make_channel(url, callback, ctx) { - return NetUtil.newChannel({uri: url, loadUsingSystemPrincipal: true}); + return NetUtil.newChannel({ uri: url, loadUsingSystemPrincipal: true }); } const responseBody1 = "response body 1"; const responseBody2a = "response body 2a"; const responseBody2b = "response body 2b"; -function contentHandler1(metadata, response) -{ +function contentHandler1(metadata, response) { response.setHeader("Content-Type", "text/plain"); response.setHeader("Cache-control", "max-age=999999"); response.bodyOutputStream.write(responseBody1, responseBody1.length); @@ -35,8 +34,7 @@ function contentHandler1(metadata, response) var content2passCount = 0; -function contentHandler2(metadata, response) -{ +function contentHandler2(metadata, response) { response.setHeader("Content-Type", "text/plain"); response.setHeader("Cache-control", "no-cache"); switch (content2passCount++) { @@ -54,9 +52,7 @@ function contentHandler2(metadata, response) } } - -function run_test() -{ +function run_test() { httpServer = new HttpServer(); httpServer.registerPathHandler("/content1", contentHandler1); httpServer.registerPathHandler("/content2", contentHandler2); @@ -66,29 +62,25 @@ function run_test() do_test_pending(); } -function run_test_content1a() -{ +function run_test_content1a() { var chan = make_channel(URL + "/content1"); caching = chan.QueryInterface(Ci.nsICachingChannel); caching.cacheOnlyMetadata = true; chan.asyncOpen(new ChannelListener(contentListener1a, null)); } -function contentListener1a(request, buffer) -{ +function contentListener1a(request, buffer) { Assert.equal(buffer, responseBody1); - asyncOpenCacheEntry(URL + "/content1", "disk", 0, null, cacheCheck1) + asyncOpenCacheEntry(URL + "/content1", "disk", 0, null, cacheCheck1); } -function cacheCheck1(status, entry) -{ +function cacheCheck1(status, entry) { Assert.equal(status, 0); Assert.equal(entry.dataSize, 0); try { Assert.notEqual(entry.getMetaDataElement("response-head"), null); - } - catch (ex) { + } catch (ex) { do_throw("Missing response head"); } @@ -98,8 +90,7 @@ function cacheCheck1(status, entry) chan.asyncOpen(new ChannelListener(contentListener1b, null, CL_IGNORE_CL)); } -function contentListener1b(request, buffer) -{ +function contentListener1b(request, buffer) { request.QueryInterface(Ci.nsIHttpChannel); Assert.equal(request.requestMethod, "GET"); Assert.equal(request.responseStatus, 200); @@ -111,30 +102,28 @@ function contentListener1b(request, buffer) // Now same set of steps but this time for an immediately expiring content. -function run_test_content2a() -{ +function run_test_content2a() { var chan = make_channel(URL + "/content2"); caching = chan.QueryInterface(Ci.nsICachingChannel); caching.cacheOnlyMetadata = true; chan.asyncOpen(new ChannelListener(contentListener2a, null)); } -function contentListener2a(request, buffer) -{ +function contentListener2a(request, buffer) { Assert.equal(buffer, responseBody2a); - asyncOpenCacheEntry(URL + "/content2", "disk", 0, null, cacheCheck2) + asyncOpenCacheEntry(URL + "/content2", "disk", 0, null, cacheCheck2); } -function cacheCheck2(status, entry) -{ +function cacheCheck2(status, entry) { Assert.equal(status, 0); Assert.equal(entry.dataSize, 0); try { Assert.notEqual(entry.getMetaDataElement("response-head"), null); - Assert.ok(entry.getMetaDataElement("response-head").match('etag: testetag')); - } - catch (ex) { + Assert.ok( + entry.getMetaDataElement("response-head").match("etag: testetag") + ); + } catch (ex) { do_throw("Missing response head"); } @@ -144,8 +133,7 @@ function cacheCheck2(status, entry) chan.asyncOpen(new ChannelListener(contentListener2b, null)); } -function contentListener2b(request, buffer) -{ +function contentListener2b(request, buffer) { Assert.equal(buffer, responseBody2b); httpServer.stop(do_test_finished); diff --git a/netwerk/test/unit/test_bug1177909.js b/netwerk/test/unit/test_bug1177909.js index 58d558b6e979..210d624fbebe 100644 --- a/netwerk/test/unit/test_bug1177909.js +++ b/netwerk/test/unit/test_bug1177909.js @@ -1,10 +1,15 @@ "use strict"; -const {MockRegistrar} = ChromeUtils.import("resource://testing-common/MockRegistrar.jsm"); +const { MockRegistrar } = ChromeUtils.import( + "resource://testing-common/MockRegistrar.jsm" +); -XPCOMUtils.defineLazyServiceGetter(this, "gProxyService", - "@mozilla.org/network/protocol-proxy-service;1", - "nsIProtocolProxyService"); +XPCOMUtils.defineLazyServiceGetter( + this, + "gProxyService", + "@mozilla.org/network/protocol-proxy-service;1", + "nsIProtocolProxyService" +); XPCOMUtils.defineLazyGetter(this, "systemSettings", function() { return { @@ -15,20 +20,20 @@ XPCOMUtils.defineLazyGetter(this, "systemSettings", function() { getProxyForURI(aSpec, aScheme, aHost, aPort) { if (aPort != -1) { - return 'SOCKS5 http://localhost:9050' + return "SOCKS5 http://localhost:9050"; } - if (aScheme == 'http' || - aScheme == 'https' || - aScheme == 'ftp') { - return 'PROXY http://localhost:8080'; + if (aScheme == "http" || aScheme == "https" || aScheme == "ftp") { + return "PROXY http://localhost:8080"; } - return 'DIRECT'; - } + return "DIRECT"; + }, }; }); -let gMockProxy = MockRegistrar.register("@mozilla.org/system-proxy-settings;1", - systemSettings); +let gMockProxy = MockRegistrar.register( + "@mozilla.org/system-proxy-settings;1", + systemSettings +); registerCleanupFunction(() => { MockRegistrar.unregister(gMockProxy); @@ -42,17 +47,19 @@ function makeChannel(uri) { } async function TestProxyType(chan, flags) { - const prefs = Cc["@mozilla.org/preferences-service;1"] - .getService(Ci.nsIPrefBranch); + const prefs = Cc["@mozilla.org/preferences-service;1"].getService( + Ci.nsIPrefBranch + ); prefs.setIntPref( "network.proxy.type", - Ci.nsIProtocolProxyService.PROXYCONFIG_SYSTEM); + Ci.nsIProtocolProxyService.PROXYCONFIG_SYSTEM + ); return await new Promise((resolve, reject) => { gProxyService.asyncResolve(chan, flags, { onProxyAvailable(req, uri, pi, status) { resolve(pi); - } + }, }); }); } @@ -92,24 +99,27 @@ add_task(async function testSocksProxy() { add_task(async function testDirectProxy() { // Do what |WebSocketChannel::AsyncOpen| do, but do not prefer https proxy. let proxyURI = Cc["@mozilla.org/network/standard-url-mutator;1"] - .createInstance(Ci.nsIURIMutator) - .setSpec("wss://ws.mozilla.org/") - .finalize(); - let uri = proxyURI.mutate() - .setScheme("https") - .finalize(); + .createInstance(Ci.nsIURIMutator) + .setSpec("wss://ws.mozilla.org/") + .finalize(); + let uri = proxyURI + .mutate() + .setScheme("https") + .finalize(); - let ioService = Cc["@mozilla.org/network/io-service;1"]. - getService(Ci.nsIIOService); - let chan = ioService. - newChannelFromURIWithProxyFlags(uri, - proxyURI, - 0, - null, - Services.scriptSecurityManager.getSystemPrincipal(), - null, - Ci.nsILoadInfo.SEC_ALLOW_CROSS_ORIGIN_DATA_IS_NULL, - Ci.nsIContentPolicy.TYPE_OTHER); + let ioService = Cc["@mozilla.org/network/io-service;1"].getService( + Ci.nsIIOService + ); + let chan = ioService.newChannelFromURIWithProxyFlags( + uri, + proxyURI, + 0, + null, + Services.scriptSecurityManager.getSystemPrincipal(), + null, + Ci.nsILoadInfo.SEC_ALLOW_CROSS_ORIGIN_DATA_IS_NULL, + Ci.nsIContentPolicy.TYPE_OTHER + ); let pi = await TestProxyType(chan, 0); equal(pi, null, "Expected proxy host to be null"); @@ -118,27 +128,31 @@ add_task(async function testDirectProxy() { add_task(async function testWebSocketProxy() { // Do what |WebSocketChannel::AsyncOpen| do let proxyURI = Cc["@mozilla.org/network/standard-url-mutator;1"] - .createInstance(Ci.nsIURIMutator) - .setSpec("wss://ws.mozilla.org/") - .finalize(); - let uri = proxyURI.mutate() - .setScheme("https") - .finalize(); + .createInstance(Ci.nsIURIMutator) + .setSpec("wss://ws.mozilla.org/") + .finalize(); + let uri = proxyURI + .mutate() + .setScheme("https") + .finalize(); - let proxyFlags = Ci.nsIProtocolProxyService.RESOLVE_PREFER_HTTPS_PROXY | - Ci.nsIProtocolProxyService.RESOLVE_ALWAYS_TUNNEL; + let proxyFlags = + Ci.nsIProtocolProxyService.RESOLVE_PREFER_HTTPS_PROXY | + Ci.nsIProtocolProxyService.RESOLVE_ALWAYS_TUNNEL; - let ioService = Cc["@mozilla.org/network/io-service;1"]. - getService(Ci.nsIIOService); - let chan = ioService. - newChannelFromURIWithProxyFlags(uri, - proxyURI, - proxyFlags, - null, - Services.scriptSecurityManager.getSystemPrincipal(), - null, - Ci.nsILoadInfo.SEC_ALLOW_CROSS_ORIGIN_DATA_IS_NULL, - Ci.nsIContentPolicy.TYPE_OTHER); + let ioService = Cc["@mozilla.org/network/io-service;1"].getService( + Ci.nsIIOService + ); + let chan = ioService.newChannelFromURIWithProxyFlags( + uri, + proxyURI, + proxyFlags, + null, + Services.scriptSecurityManager.getSystemPrincipal(), + null, + Ci.nsILoadInfo.SEC_ALLOW_CROSS_ORIGIN_DATA_IS_NULL, + Ci.nsIContentPolicy.TYPE_OTHER + ); let pi = await TestProxyType(chan, proxyFlags); equal(pi.host, "localhost", "Expected proxy host to be localhost"); diff --git a/netwerk/test/unit/test_bug1195415.js b/netwerk/test/unit/test_bug1195415.js index 212bec134684..24ded161f49c 100644 --- a/netwerk/test/unit/test_bug1195415.js +++ b/netwerk/test/unit/test_bug1195415.js @@ -1,43 +1,58 @@ // Test for bug 1195415 function run_test() { - var ios = Cc["@mozilla.org/network/io-service;1"]. - getService(Ci.nsIIOService); - var ssm = Cc["@mozilla.org/scriptsecuritymanager;1"]. - getService(Ci.nsIScriptSecurityManager); + var ios = Cc["@mozilla.org/network/io-service;1"].getService(Ci.nsIIOService); + var ssm = Cc["@mozilla.org/scriptsecuritymanager;1"].getService( + Ci.nsIScriptSecurityManager + ); // NON-UNICODE var uri = ios.newURI("http://foo.com/file.txt"); Assert.equal(uri.asciiHostPort, "foo.com"); - uri = uri.mutate().setPort(90).finalize(); + uri = uri + .mutate() + .setPort(90) + .finalize(); var prin = ssm.createCodebasePrincipal(uri, {}); Assert.equal(uri.asciiHostPort, "foo.com:90"); Assert.equal(prin.origin, "http://foo.com:90"); uri = ios.newURI("http://foo.com:10/file.txt"); Assert.equal(uri.asciiHostPort, "foo.com:10"); - uri = uri.mutate().setPort(500).finalize(); + uri = uri + .mutate() + .setPort(500) + .finalize(); prin = ssm.createCodebasePrincipal(uri, {}); Assert.equal(uri.asciiHostPort, "foo.com:500"); Assert.equal(prin.origin, "http://foo.com:500"); uri = ios.newURI("http://foo.com:5000/file.txt"); Assert.equal(uri.asciiHostPort, "foo.com:5000"); - uri = uri.mutate().setPort(20).finalize(); + uri = uri + .mutate() + .setPort(20) + .finalize(); prin = ssm.createCodebasePrincipal(uri, {}); Assert.equal(uri.asciiHostPort, "foo.com:20"); Assert.equal(prin.origin, "http://foo.com:20"); uri = ios.newURI("http://foo.com:5000/file.txt"); Assert.equal(uri.asciiHostPort, "foo.com:5000"); - uri = uri.mutate().setPort(-1).finalize(); + uri = uri + .mutate() + .setPort(-1) + .finalize(); prin = ssm.createCodebasePrincipal(uri, {}); Assert.equal(uri.asciiHostPort, "foo.com"); Assert.equal(prin.origin, "http://foo.com"); uri = ios.newURI("http://foo.com:5000/file.txt"); Assert.equal(uri.asciiHostPort, "foo.com:5000"); - uri = uri.mutate().setPort(80).finalize(); + uri = uri + .mutate() + .setPort(80) + .finalize(); prin = ssm.createCodebasePrincipal(uri, {}); Assert.equal(uri.asciiHostPort, "foo.com"); Assert.equal(prin.origin, "http://foo.com"); @@ -45,35 +60,50 @@ function run_test() { // UNICODE uri = ios.newURI("http://jos\u00e9.example.net.ch/file.txt"); Assert.equal(uri.asciiHostPort, "xn--jos-dma.example.net.ch"); - uri = uri.mutate().setPort(90).finalize(); + uri = uri + .mutate() + .setPort(90) + .finalize(); prin = ssm.createCodebasePrincipal(uri, {}); Assert.equal(uri.asciiHostPort, "xn--jos-dma.example.net.ch:90"); Assert.equal(prin.origin, "http://xn--jos-dma.example.net.ch:90"); uri = ios.newURI("http://jos\u00e9.example.net.ch:10/file.txt"); Assert.equal(uri.asciiHostPort, "xn--jos-dma.example.net.ch:10"); - uri = uri.mutate().setPort(500).finalize(); + uri = uri + .mutate() + .setPort(500) + .finalize(); prin = ssm.createCodebasePrincipal(uri, {}); Assert.equal(uri.asciiHostPort, "xn--jos-dma.example.net.ch:500"); Assert.equal(prin.origin, "http://xn--jos-dma.example.net.ch:500"); uri = ios.newURI("http://jos\u00e9.example.net.ch:5000/file.txt"); Assert.equal(uri.asciiHostPort, "xn--jos-dma.example.net.ch:5000"); - uri = uri.mutate().setPort(20).finalize(); + uri = uri + .mutate() + .setPort(20) + .finalize(); prin = ssm.createCodebasePrincipal(uri, {}); Assert.equal(uri.asciiHostPort, "xn--jos-dma.example.net.ch:20"); Assert.equal(prin.origin, "http://xn--jos-dma.example.net.ch:20"); uri = ios.newURI("http://jos\u00e9.example.net.ch:5000/file.txt"); Assert.equal(uri.asciiHostPort, "xn--jos-dma.example.net.ch:5000"); - uri = uri.mutate().setPort(-1).finalize(); + uri = uri + .mutate() + .setPort(-1) + .finalize(); prin = ssm.createCodebasePrincipal(uri, {}); Assert.equal(uri.asciiHostPort, "xn--jos-dma.example.net.ch"); Assert.equal(prin.origin, "http://xn--jos-dma.example.net.ch"); uri = ios.newURI("http://jos\u00e9.example.net.ch:5000/file.txt"); Assert.equal(uri.asciiHostPort, "xn--jos-dma.example.net.ch:5000"); - uri = uri.mutate().setPort(80).finalize(); + uri = uri + .mutate() + .setPort(80) + .finalize(); prin = ssm.createCodebasePrincipal(uri, {}); Assert.equal(uri.asciiHostPort, "xn--jos-dma.example.net.ch"); Assert.equal(prin.origin, "http://xn--jos-dma.example.net.ch"); @@ -81,35 +111,50 @@ function run_test() { // ipv6 uri = ios.newURI("http://[123:45::678]/file.txt"); Assert.equal(uri.asciiHostPort, "[123:45::678]"); - uri = uri.mutate().setPort(90).finalize(); + uri = uri + .mutate() + .setPort(90) + .finalize(); prin = ssm.createCodebasePrincipal(uri, {}); Assert.equal(uri.asciiHostPort, "[123:45::678]:90"); Assert.equal(prin.origin, "http://[123:45::678]:90"); uri = ios.newURI("http://[123:45::678]:10/file.txt"); Assert.equal(uri.asciiHostPort, "[123:45::678]:10"); - uri = uri.mutate().setPort(500).finalize(); + uri = uri + .mutate() + .setPort(500) + .finalize(); prin = ssm.createCodebasePrincipal(uri, {}); Assert.equal(uri.asciiHostPort, "[123:45::678]:500"); Assert.equal(prin.origin, "http://[123:45::678]:500"); uri = ios.newURI("http://[123:45::678]:5000/file.txt"); Assert.equal(uri.asciiHostPort, "[123:45::678]:5000"); - uri = uri.mutate().setPort(20).finalize(); + uri = uri + .mutate() + .setPort(20) + .finalize(); prin = ssm.createCodebasePrincipal(uri, {}); Assert.equal(uri.asciiHostPort, "[123:45::678]:20"); Assert.equal(prin.origin, "http://[123:45::678]:20"); uri = ios.newURI("http://[123:45::678]:5000/file.txt"); Assert.equal(uri.asciiHostPort, "[123:45::678]:5000"); - uri = uri.mutate().setPort(-1).finalize(); + uri = uri + .mutate() + .setPort(-1) + .finalize(); prin = ssm.createCodebasePrincipal(uri, {}); Assert.equal(uri.asciiHostPort, "[123:45::678]"); Assert.equal(prin.origin, "http://[123:45::678]"); uri = ios.newURI("http://[123:45::678]:5000/file.txt"); Assert.equal(uri.asciiHostPort, "[123:45::678]:5000"); - uri = uri.mutate().setPort(80).finalize(); + uri = uri + .mutate() + .setPort(80) + .finalize(); prin = ssm.createCodebasePrincipal(uri, {}); Assert.equal(uri.asciiHostPort, "[123:45::678]"); Assert.equal(prin.origin, "http://[123:45::678]"); diff --git a/netwerk/test/unit/test_bug1218029.js b/netwerk/test/unit/test_bug1218029.js index 99f51cd873d3..741255b974eb 100644 --- a/netwerk/test/unit/test_bug1218029.js +++ b/netwerk/test/unit/test_bug1218029.js @@ -2,20 +2,49 @@ http://creativecommons.org/publicdomain/zero/1.0/ */ var tests = [ - {data: '', chunks: [], status: Cr.NS_OK, consume: [], - dataChunks: ['']}, - {data: 'TWO-PARTS', chunks: [4, 5], status: Cr.NS_OK, consume: [4, 5], - dataChunks: ['TWO-', 'PARTS', '']}, - {data: 'TWO-PARTS', chunks: [4, 5], status: Cr.NS_OK, consume: [0, 0], - dataChunks: ['TWO-', 'TWO-PARTS', 'TWO-PARTS']}, - {data: '3-PARTS', chunks: [1, 1, 5], status: Cr.NS_OK, consume: [0, 2, 5], - dataChunks: ['3', '3-', 'PARTS', '']}, - {data: 'ALL-AT-ONCE', chunks: [11], status: Cr.NS_OK, consume: [0], - dataChunks: ['ALL-AT-ONCE', 'ALL-AT-ONCE']}, - {data: 'ALL-AT-ONCE', chunks: [11], status: Cr.NS_OK, consume: [11], - dataChunks: ['ALL-AT-ONCE', '']}, - {data: 'ERROR', chunks: [1], status: Cr.NS_ERROR_OUT_OF_MEMORY, consume: [0], - dataChunks: ['E', 'E']} + { data: "", chunks: [], status: Cr.NS_OK, consume: [], dataChunks: [""] }, + { + data: "TWO-PARTS", + chunks: [4, 5], + status: Cr.NS_OK, + consume: [4, 5], + dataChunks: ["TWO-", "PARTS", ""], + }, + { + data: "TWO-PARTS", + chunks: [4, 5], + status: Cr.NS_OK, + consume: [0, 0], + dataChunks: ["TWO-", "TWO-PARTS", "TWO-PARTS"], + }, + { + data: "3-PARTS", + chunks: [1, 1, 5], + status: Cr.NS_OK, + consume: [0, 2, 5], + dataChunks: ["3", "3-", "PARTS", ""], + }, + { + data: "ALL-AT-ONCE", + chunks: [11], + status: Cr.NS_OK, + consume: [0], + dataChunks: ["ALL-AT-ONCE", "ALL-AT-ONCE"], + }, + { + data: "ALL-AT-ONCE", + chunks: [11], + status: Cr.NS_OK, + consume: [11], + dataChunks: ["ALL-AT-ONCE", ""], + }, + { + data: "ERROR", + chunks: [1], + status: Cr.NS_ERROR_OUT_OF_MEMORY, + consume: [0], + dataChunks: ["E", "E"], + }, ]; /** @@ -31,13 +60,14 @@ var tests = [ */ function execute_test(test) { - let stream = Cc["@mozilla.org/io/string-input-stream;1"]. - createInstance(Ci.nsIStringInputStream); + let stream = Cc["@mozilla.org/io/string-input-stream;1"].createInstance( + Ci.nsIStringInputStream + ); stream.data = test.data; let channel = { contentLength: -1, - QueryInterface: ChromeUtils.generateQI([Ci.nsIChannel]) + QueryInterface: ChromeUtils.generateQI([Ci.nsIChannel]), }; let chunkIndex = 0; @@ -51,7 +81,7 @@ function execute_test(test) { equal(status, test.status); }, - onIncrementalData (loader, context, length, data, consumed) { + onIncrementalData(loader, context, length, data, consumed) { ok(chunkIndex < test.dataChunks.length - 1); var expectedChunk = test.dataChunks[chunkIndex]; equal(length, expectedChunk.length); @@ -60,17 +90,19 @@ function execute_test(test) { consumed.value = test.consume[chunkIndex]; chunkIndex++; }, - QueryInterface: - ChromeUtils.generateQI([Ci.nsIIncrementalStreamLoaderObserver]) + QueryInterface: ChromeUtils.generateQI([ + Ci.nsIIncrementalStreamLoaderObserver, + ]), }; - let listener = Cc["@mozilla.org/network/incremental-stream-loader;1"] - .createInstance(Ci.nsIIncrementalStreamLoader); + let listener = Cc[ + "@mozilla.org/network/incremental-stream-loader;1" + ].createInstance(Ci.nsIIncrementalStreamLoader); listener.init(observer); listener.onStartRequest(channel); var offset = 0; - test.chunks.forEach(function (chunkLength) { + test.chunks.forEach(function(chunkLength) { listener.onDataAvailable(channel, stream, offset, chunkLength); offset += chunkLength; }); diff --git a/netwerk/test/unit/test_bug1279246.js b/netwerk/test/unit/test_bug1279246.js index 59059f53f968..c33f5c2e0970 100644 --- a/netwerk/test/unit/test_bug1279246.js +++ b/netwerk/test/unit/test_bug1279246.js @@ -1,17 +1,16 @@ -const {HttpServer} = ChromeUtils.import("resource://testing-common/httpd.js"); +const { HttpServer } = ChromeUtils.import("resource://testing-common/httpd.js"); var httpserver = new HttpServer(); var pass = 0; -var responseBody = [0x0B, 0x02, 0x80, 0x74, 0x65, 0x73, 0x74, 0x0A, 0x03]; +var responseBody = [0x0b, 0x02, 0x80, 0x74, 0x65, 0x73, 0x74, 0x0a, 0x03]; var responseLen = 5; var testUrl = "/test/brotli"; - function setupChannel() { - return NetUtil.newChannel({ - uri: "http://localhost:" + httpserver.identity.primaryPort + testUrl, - loadUsingSystemPrincipal: true - }); + return NetUtil.newChannel({ + uri: "http://localhost:" + httpserver.identity.primaryPort + testUrl, + loadUsingSystemPrincipal: true, + }); } function Listener() {} @@ -19,7 +18,10 @@ function Listener() {} Listener.prototype = { _buffer: null, - QueryInterface: ChromeUtils.generateQI(["nsIStreamListener", "nsIRequestObserver"]), + QueryInterface: ChromeUtils.generateQI([ + "nsIStreamListener", + "nsIRequestObserver", + ]), onStartRequest(request) { Assert.equal(request.status, Cr.NS_OK); @@ -51,7 +53,7 @@ Listener.prototype = { httpserver.stop(do_test_finished); prefs.setCharPref("network.http.accept-encoding", cePref); } - } + }, }; var prefs; @@ -83,8 +85,9 @@ function handler(metadata, response) { response.setHeader("Content-Encoding", "br", false); response.setHeader("Content-Length", "" + responseBody.length, false); - var bos = Cc["@mozilla.org/binaryoutputstream;1"] - .createInstance(Ci.nsIBinaryOutputStream); + var bos = Cc["@mozilla.org/binaryoutputstream;1"].createInstance( + Ci.nsIBinaryOutputStream + ); bos.setOutputStream(response.bodyOutputStream); response.processAsync(); diff --git a/netwerk/test/unit/test_bug1312774_http1.js b/netwerk/test/unit/test_bug1312774_http1.js index debcc320a71e..5eabd47d452f 100644 --- a/netwerk/test/unit/test_bug1312774_http1.js +++ b/netwerk/test/unit/test_bug1312774_http1.js @@ -13,16 +13,15 @@ // Note: if the urgent request handling is broken (the urgent-marked requests // get blocked by queuing) this test will time out -const {HttpServer} = ChromeUtils.import("resource://testing-common/httpd.js"); +const { HttpServer } = ChromeUtils.import("resource://testing-common/httpd.js"); var server = new HttpServer(); server.start(-1); var baseURL = "http://localhost:" + server.identity.primaryPort + "/"; var maxConnections = 0; var urgentRequests = 0; -var totalRequests = 0; +var totalRequests = 0; var debug = false; - function log(msg) { if (!debug) { return; @@ -34,7 +33,10 @@ function log(msg) { } function make_channel(url) { - var request = NetUtil.newChannel({uri: url, loadUsingSystemPrincipal: true}); + var request = NetUtil.newChannel({ + uri: url, + loadUsingSystemPrincipal: true, + }); request.QueryInterface(Ci.nsIHttpChannel); return request; } @@ -67,7 +69,7 @@ function urgentStartHttpRequest(id) { function setup_httpRequests() { log("setup_httpRequests"); - for (var i = 0; i < maxConnections ; i++) { + for (var i = 0; i < maxConnections; i++) { commonHttpRequest(i); do_test_pending(); } @@ -80,44 +82,45 @@ function setup_urgentStartRequests() { } } -function HttpResponseListener(id) -{ - this.id = id -}; +function HttpResponseListener(id) { + this.id = id; +} var testOrder = 0; -HttpResponseListener.prototype = -{ - onStartRequest (request) { - }, +HttpResponseListener.prototype = { + onStartRequest(request) {}, - onDataAvailable (request, stream, off, cnt) { - }, + onDataAvailable(request, stream, off, cnt) {}, - onStopRequest (request, status) { + onStopRequest(request, status) { log("STOP id=" + this.id); do_test_finished(); - } + }, }; var responseQueue = new Array(); -function setup_http_server() -{ +function setup_http_server() { log("setup_http_server"); - var prefs = Cc["@mozilla.org/preferences-service;1"].getService(Ci.nsIPrefBranch); - maxConnections = prefs.getIntPref("network.http.max-persistent-connections-per-server"); + var prefs = Cc["@mozilla.org/preferences-service;1"].getService( + Ci.nsIPrefBranch + ); + maxConnections = prefs.getIntPref( + "network.http.max-persistent-connections-per-server" + ); urgentRequests = 2; totalRequests = maxConnections + urgentRequests; var allCommonHttpRequestReceived = false; // Start server; will be stopped at test cleanup time. - server.registerPathHandler('/', function(metadata, response) - { + server.registerPathHandler("/", function(metadata, response) { var id = metadata.getHeader("X-ID"); log("Server recived the response id=" + id); response.processAsync(); responseQueue.push(response); - if (responseQueue.length == maxConnections && !allCommonHttpRequestReceived) { + if ( + responseQueue.length == maxConnections && + !allCommonHttpRequestReceived + ) { allCommonHttpRequestReceived = true; setup_urgentStartRequests(); } @@ -146,4 +149,3 @@ function run_test() { setup_http_server(); setup_httpRequests(); } - diff --git a/netwerk/test/unit/test_bug1312782_http1.js b/netwerk/test/unit/test_bug1312782_http1.js index 7f47aeb08fef..9d15d203a1ea 100644 --- a/netwerk/test/unit/test_bug1312782_http1.js +++ b/netwerk/test/unit/test_bug1312782_http1.js @@ -20,7 +20,7 @@ // plus 4. Also, the request ids of the rest requests should be less than non-focused // window id + 2. -const {HttpServer} = ChromeUtils.import("resource://testing-common/httpd.js"); +const { HttpServer } = ChromeUtils.import("resource://testing-common/httpd.js"); var server = new HttpServer(); server.start(-1); @@ -43,7 +43,10 @@ function log(msg) { } function make_channel(url) { - var request = NetUtil.newChannel({uri: url, loadUsingSystemPrincipal: true}); + var request = NetUtil.newChannel({ + uri: url, + loadUsingSystemPrincipal: true, + }); request.QueryInterface(Ci.nsIHttpChannel); return request; } @@ -65,7 +68,7 @@ function createHttpRequest(windowId, requestId) { function setup_dummyHttpRequests() { log("setup_dummyHttpRequests"); - for (var i = 0; i < maxConnections ; i++) { + for (var i = 0; i < maxConnections; i++) { createHttpRequest(0, i); do_test_pending(); } @@ -73,7 +76,7 @@ function setup_dummyHttpRequests() { function setup_focusedWindowHttpRequests() { log("setup_focusedWindowHttpRequests"); - for (var i = 0; i < FOCUSED_WINDOW_REQUEST_COUNT ; i++) { + for (var i = 0; i < FOCUSED_WINDOW_REQUEST_COUNT; i++) { createHttpRequest(FOCUSED_WINDOW_ID, FOCUSED_WINDOW_ID + i); do_test_pending(); } @@ -81,54 +84,52 @@ function setup_focusedWindowHttpRequests() { function setup_nonFocusedWindowHttpRequests() { log("setup_nonFocusedWindowHttpRequests"); - for (var i = 0; i < NON_FOCUSED_WINDOW_REQUEST_COUNT ; i++) { + for (var i = 0; i < NON_FOCUSED_WINDOW_REQUEST_COUNT; i++) { createHttpRequest(NON_FOCUSED_WINDOW_ID, NON_FOCUSED_WINDOW_ID + i); do_test_pending(); } } -function HttpResponseListener(id) -{ - this.id = id -}; +function HttpResponseListener(id) { + this.id = id; +} -HttpResponseListener.prototype = -{ - onStartRequest (request) { - }, +HttpResponseListener.prototype = { + onStartRequest(request) {}, - onDataAvailable (request, stream, off, cnt) { - }, + onDataAvailable(request, stream, off, cnt) {}, - onStopRequest (request, status) { + onStopRequest(request, status) { log("STOP id=" + this.id); do_test_finished(); - } + }, }; -function check_response_id(responses, maxWindowId) -{ +function check_response_id(responses, maxWindowId) { for (var i = 0; i < responses.length; i++) { var id = responses[i].getHeader("X-ID"); - log("response id=" + id + " maxWindowId=" + maxWindowId); + log("response id=" + id + " maxWindowId=" + maxWindowId); Assert.ok(id < maxWindowId); } } var responseQueue = new Array(); -function setup_http_server() -{ +function setup_http_server() { log("setup_http_server"); - var prefs = Cc["@mozilla.org/preferences-service;1"].getService(Ci.nsIPrefBranch); - maxConnections = prefs.getIntPref("network.http.max-persistent-connections-per-server"); + var prefs = Cc["@mozilla.org/preferences-service;1"].getService( + Ci.nsIPrefBranch + ); + maxConnections = prefs.getIntPref( + "network.http.max-persistent-connections-per-server" + ); FOCUSED_WINDOW_REQUEST_COUNT = Math.floor(maxConnections * 0.8); - NON_FOCUSED_WINDOW_REQUEST_COUNT = maxConnections - FOCUSED_WINDOW_REQUEST_COUNT; + NON_FOCUSED_WINDOW_REQUEST_COUNT = + maxConnections - FOCUSED_WINDOW_REQUEST_COUNT; NON_FOCUSED_WINDOW_ID = FOCUSED_WINDOW_ID + FOCUSED_WINDOW_REQUEST_COUNT; var allDummyHttpRequestReceived = false; // Start server; will be stopped at test cleanup time. - server.registerPathHandler('/', function(metadata, response) - { + server.registerPathHandler("/", function(metadata, response) { var id = metadata.getHeader("X-ID"); log("Server recived the response id=" + id); @@ -136,26 +137,39 @@ function setup_http_server() response.setHeader("X-ID", id); responseQueue.push(response); - if (responseQueue.length == maxConnections && !allDummyHttpRequestReceived) { + if ( + responseQueue.length == maxConnections && + !allDummyHttpRequestReceived + ) { log("received all dummy http requets"); allDummyHttpRequestReceived = true; setup_nonFocusedWindowHttpRequests(); setup_focusedWindowHttpRequests(); processResponses(); } else if (responseQueue.length == maxConnections) { - var focusedWindowResponses = responseQueue.slice(0, FOCUSED_WINDOW_REQUEST_COUNT); - var nonFocusedWindowResponses = responseQueue.slice(FOCUSED_WINDOW_REQUEST_COUNT, responseQueue.length); - check_response_id(focusedWindowResponses, FOCUSED_WINDOW_ID + FOCUSED_WINDOW_REQUEST_COUNT); - check_response_id(nonFocusedWindowResponses, NON_FOCUSED_WINDOW_ID + NON_FOCUSED_WINDOW_REQUEST_COUNT); + var focusedWindowResponses = responseQueue.slice( + 0, + FOCUSED_WINDOW_REQUEST_COUNT + ); + var nonFocusedWindowResponses = responseQueue.slice( + FOCUSED_WINDOW_REQUEST_COUNT, + responseQueue.length + ); + check_response_id( + focusedWindowResponses, + FOCUSED_WINDOW_ID + FOCUSED_WINDOW_REQUEST_COUNT + ); + check_response_id( + nonFocusedWindowResponses, + NON_FOCUSED_WINDOW_ID + NON_FOCUSED_WINDOW_REQUEST_COUNT + ); processResponses(); } - }); registerCleanupFunction(function() { server.stop(serverStopListener); }); - } function processResponses() { @@ -168,17 +182,23 @@ function processResponses() { function run_test() { // Make sure "network.http.active_tab_priority" is true, so we can expect to // receive http requests with focused window id before others. - var prefs = Cc["@mozilla.org/preferences-service;1"] - .getService(Ci.nsIPrefBranch); + var prefs = Cc["@mozilla.org/preferences-service;1"].getService( + Ci.nsIPrefBranch + ); prefs.setBoolPref("network.http.active_tab_priority", true); setup_http_server(); setup_dummyHttpRequests(); - var windowIdWrapper = Cc["@mozilla.org/supports-PRUint64;1"] - .createInstance(Ci.nsISupportsPRUint64); + var windowIdWrapper = Cc["@mozilla.org/supports-PRUint64;1"].createInstance( + Ci.nsISupportsPRUint64 + ); windowIdWrapper.data = FOCUSED_WINDOW_ID; - var obsvc = Cc["@mozilla.org/observer-service;1"]. - getService(Ci.nsIObserverService); - obsvc.notifyObservers(windowIdWrapper, "net:current-toplevel-outer-content-windowid"); + var obsvc = Cc["@mozilla.org/observer-service;1"].getService( + Ci.nsIObserverService + ); + obsvc.notifyObservers( + windowIdWrapper, + "net:current-toplevel-outer-content-windowid" + ); } diff --git a/netwerk/test/unit/test_bug1355539_http1.js b/netwerk/test/unit/test_bug1355539_http1.js index 8d9e3bb39fb1..db1384689c6c 100644 --- a/netwerk/test/unit/test_bug1355539_http1.js +++ b/netwerk/test/unit/test_bug1355539_http1.js @@ -17,7 +17,7 @@ // 4. When the server receive all 6 requests, check if the order in |responseQueue| is // equal to |transactionQueue| by comparing the value of X-ID. -const {HttpServer} = ChromeUtils.import("resource://testing-common/httpd.js"); +const { HttpServer } = ChromeUtils.import("resource://testing-common/httpd.js"); var server = new HttpServer(); server.start(-1); @@ -38,7 +38,10 @@ function log(msg) { } function make_channel(url) { - var request = NetUtil.newChannel({uri: url, loadUsingSystemPrincipal: true}); + var request = NetUtil.newChannel({ + uri: url, + loadUsingSystemPrincipal: true, + }); request.QueryInterface(Ci.nsIHttpChannel); return request; } @@ -64,25 +67,49 @@ function createHttpRequest(requestId, priority, isBlocking, callback) { function setup_dummyHttpRequests(callback) { log("setup_dummyHttpRequests"); - for (var i = 0; i < maxConnections ; i++) { + for (var i = 0; i < maxConnections; i++) { createHttpRequest(i, i, false, callback); do_test_pending(); } } var transactionQueue = [ - {requestId: 101, priority: Ci.nsISupportsPriority.PRIORITY_HIGH, isBlocking: true}, - {requestId: 102, priority: Ci.nsISupportsPriority.PRIORITY_NORMAL, isBlocking: true}, - {requestId: 103, priority: Ci.nsISupportsPriority.PRIORITY_LOW, isBlocking: true}, - {requestId: 104, priority: Ci.nsISupportsPriority.PRIORITY_HIGH, isBlocking: false}, - {requestId: 105, priority: Ci.nsISupportsPriority.PRIORITY_NORMAL, isBlocking: false}, - {requestId: 106, priority: Ci.nsISupportsPriority.PRIORITY_LOW, isBlocking: false}, + { + requestId: 101, + priority: Ci.nsISupportsPriority.PRIORITY_HIGH, + isBlocking: true, + }, + { + requestId: 102, + priority: Ci.nsISupportsPriority.PRIORITY_NORMAL, + isBlocking: true, + }, + { + requestId: 103, + priority: Ci.nsISupportsPriority.PRIORITY_LOW, + isBlocking: true, + }, + { + requestId: 104, + priority: Ci.nsISupportsPriority.PRIORITY_HIGH, + isBlocking: false, + }, + { + requestId: 105, + priority: Ci.nsISupportsPriority.PRIORITY_NORMAL, + isBlocking: false, + }, + { + requestId: 106, + priority: Ci.nsISupportsPriority.PRIORITY_LOW, + isBlocking: false, + }, ]; function setup_HttpRequests() { log("setup_HttpRequests"); // Create channels in reverse order - for (var i = transactionQueue.length - 1; i > -1;) { + for (var i = transactionQueue.length - 1; i > -1; ) { var e = transactionQueue[i]; createHttpRequest(e.requestId, e.priority, e.isBlocking); do_test_pending(); @@ -90,47 +117,44 @@ function setup_HttpRequests() { } } -function check_response_id(responses) -{ +function check_response_id(responses) { for (var i = 0; i < responses.length; i++) { var id = responses[i].getHeader("X-ID"); Assert.equal(id, transactionQueue[i].requestId); } } -function HttpResponseListener(id, onStopCallback) -{ - this.id = id +function HttpResponseListener(id, onStopCallback) { + this.id = id; this.stopCallback = onStopCallback; -}; +} -HttpResponseListener.prototype = -{ - onStartRequest (request) { - }, +HttpResponseListener.prototype = { + onStartRequest(request) {}, - onDataAvailable (request, stream, off, cnt) { - }, + onDataAvailable(request, stream, off, cnt) {}, - onStopRequest (request, status) { + onStopRequest(request, status) { log("STOP id=" + this.id); do_test_finished(); if (this.stopCallback) { this.stopCallback(); } - } + }, }; -function setup_http_server() -{ +function setup_http_server() { log("setup_http_server"); - var prefs = Cc["@mozilla.org/preferences-service;1"].getService(Ci.nsIPrefBranch); - maxConnections = prefs.getIntPref("network.http.max-persistent-connections-per-server"); + var prefs = Cc["@mozilla.org/preferences-service;1"].getService( + Ci.nsIPrefBranch + ); + maxConnections = prefs.getIntPref( + "network.http.max-persistent-connections-per-server" + ); var allDummyHttpRequestReceived = false; // Start server; will be stopped at test cleanup time. - server.registerPathHandler('/', function(metadata, response) - { + server.registerPathHandler("/", function(metadata, response) { var id = metadata.getHeader("X-ID"); log("Server recived the response id=" + id); @@ -153,13 +177,11 @@ function setup_http_server() check_response_id(responseQueue); processResponses(); } - }); registerCleanupFunction(function() { server.stop(serverStopListener); }); - } function processDummyResponse() { diff --git a/netwerk/test/unit/test_bug1378385_http1.js b/netwerk/test/unit/test_bug1378385_http1.js index 47ae0cb0feec..d18fc502d4c6 100644 --- a/netwerk/test/unit/test_bug1378385_http1.js +++ b/netwerk/test/unit/test_bug1378385_http1.js @@ -25,7 +25,7 @@ // Second, we check if the request id of the rest requests is equal to focused // window id. -const {HttpServer} = ChromeUtils.import("resource://testing-common/httpd.js"); +const { HttpServer } = ChromeUtils.import("resource://testing-common/httpd.js"); var server = new HttpServer(); server.start(-1); @@ -48,7 +48,10 @@ function log(msg) { } function make_channel(url) { - var request = NetUtil.newChannel({uri: url, loadUsingSystemPrincipal: true}); + var request = NetUtil.newChannel({ + uri: url, + loadUsingSystemPrincipal: true, + }); request.QueryInterface(Ci.nsIHttpChannel); return request; } @@ -71,7 +74,7 @@ function createHttpRequest(windowId, requestId, priority) { function setup_dummyHttpRequests() { log("setup_dummyHttpRequests"); - for (var i = 0; i < maxConnections ; i++) { + for (var i = 0; i < maxConnections; i++) { createHttpRequest(0, i, Ci.nsISupportsPriority.PRIORITY_NORMAL); do_test_pending(); } @@ -79,64 +82,68 @@ function setup_dummyHttpRequests() { function setup_focusedWindowHttpRequests() { log("setup_focusedWindowHttpRequests"); - for (var i = 0; i < FOCUSED_WINDOW_REQUEST_COUNT ; i++) { - createHttpRequest(FOCUSED_WINDOW_ID, FOCUSED_WINDOW_ID, - Ci.nsISupportsPriority.PRIORITY_NORMAL); + for (var i = 0; i < FOCUSED_WINDOW_REQUEST_COUNT; i++) { + createHttpRequest( + FOCUSED_WINDOW_ID, + FOCUSED_WINDOW_ID, + Ci.nsISupportsPriority.PRIORITY_NORMAL + ); do_test_pending(); } } function setup_nonFocusedWindowHttpRequests() { log("setup_nonFocusedWindowHttpRequests"); - for (var i = 0; i < NON_FOCUSED_WINDOW_REQUEST_COUNT ; i++) { - createHttpRequest(NON_FOCUSED_WINDOW_ID, NON_FOCUSED_WINDOW_ID, - Ci.nsISupportsPriority.PRIORITY_HIGHEST); + for (var i = 0; i < NON_FOCUSED_WINDOW_REQUEST_COUNT; i++) { + createHttpRequest( + NON_FOCUSED_WINDOW_ID, + NON_FOCUSED_WINDOW_ID, + Ci.nsISupportsPriority.PRIORITY_HIGHEST + ); do_test_pending(); } } -function HttpResponseListener(id) -{ - this.id = id +function HttpResponseListener(id) { + this.id = id; } -HttpResponseListener.prototype = -{ - onStartRequest (request) { - }, +HttpResponseListener.prototype = { + onStartRequest(request) {}, - onDataAvailable (request, stream, off, cnt) { - }, + onDataAvailable(request, stream, off, cnt) {}, - onStopRequest (request, status) { + onStopRequest(request, status) { log("STOP id=" + this.id); do_test_finished(); - } + }, }; -function check_response_id(responses, windowId) -{ +function check_response_id(responses, windowId) { for (var i = 0; i < responses.length; i++) { var id = responses[i].getHeader("X-ID"); - log("response id=" + id + " windowId=" + windowId); + log("response id=" + id + " windowId=" + windowId); Assert.equal(id, windowId); } } var responseQueue = new Array(); -function setup_http_server() -{ +function setup_http_server() { log("setup_http_server"); - var prefs = Cc["@mozilla.org/preferences-service;1"].getService(Ci.nsIPrefBranch); - maxConnections = prefs.getIntPref("network.http.max-persistent-connections-per-server"); + var prefs = Cc["@mozilla.org/preferences-service;1"].getService( + Ci.nsIPrefBranch + ); + maxConnections = prefs.getIntPref( + "network.http.max-persistent-connections-per-server" + ); FOCUSED_WINDOW_REQUEST_COUNT = Math.floor(maxConnections * 0.5); - NON_FOCUSED_WINDOW_REQUEST_COUNT = maxConnections - FOCUSED_WINDOW_REQUEST_COUNT; + NON_FOCUSED_WINDOW_REQUEST_COUNT = + maxConnections - FOCUSED_WINDOW_REQUEST_COUNT; NON_FOCUSED_WINDOW_ID = FOCUSED_WINDOW_ID + FOCUSED_WINDOW_REQUEST_COUNT; var allDummyHttpRequestReceived = false; // Start server; will be stopped at test cleanup time. - server.registerPathHandler('/', function(metadata, response) - { + server.registerPathHandler("/", function(metadata, response) { var id = metadata.getHeader("X-ID"); log("Server recived the response id=" + id); @@ -144,26 +151,33 @@ function setup_http_server() response.setHeader("X-ID", id); responseQueue.push(response); - if (responseQueue.length == maxConnections && !allDummyHttpRequestReceived) { + if ( + responseQueue.length == maxConnections && + !allDummyHttpRequestReceived + ) { log("received all dummy http requets"); allDummyHttpRequestReceived = true; setup_nonFocusedWindowHttpRequests(); setup_focusedWindowHttpRequests(); processResponses(); } else if (responseQueue.length == maxConnections) { - var nonFocusedWindowResponses = responseQueue.slice(0, NON_FOCUSED_WINDOW_REQUEST_COUNT); - var focusedWindowResponses = responseQueue.slice(NON_FOCUSED_WINDOW_REQUEST_COUNT, responseQueue.length); + var nonFocusedWindowResponses = responseQueue.slice( + 0, + NON_FOCUSED_WINDOW_REQUEST_COUNT + ); + var focusedWindowResponses = responseQueue.slice( + NON_FOCUSED_WINDOW_REQUEST_COUNT, + responseQueue.length + ); check_response_id(nonFocusedWindowResponses, NON_FOCUSED_WINDOW_ID); check_response_id(focusedWindowResponses, FOCUSED_WINDOW_ID); processResponses(); } - }); registerCleanupFunction(function() { server.stop(serverStopListener); }); - } function processResponses() { @@ -176,8 +190,9 @@ function processResponses() { function run_test() { // Set "network.http.active_tab_priority" to false, so we can expect to // receive http requests with higher priority first. - var prefs = Cc["@mozilla.org/preferences-service;1"] - .getService(Ci.nsIPrefBranch); + var prefs = Cc["@mozilla.org/preferences-service;1"].getService( + Ci.nsIPrefBranch + ); prefs.setBoolPref("network.http.active_tab_priority", false); setup_http_server(); diff --git a/netwerk/test/unit/test_bug1411316_http1.js b/netwerk/test/unit/test_bug1411316_http1.js index 62832888def1..5bd40b57764d 100644 --- a/netwerk/test/unit/test_bug1411316_http1.js +++ b/netwerk/test/unit/test_bug1411316_http1.js @@ -12,7 +12,7 @@ // 3. We expect that all 6 active connections should be closed with the status // NS_ERROR_ABORT. -const {HttpServer} = ChromeUtils.import("resource://testing-common/httpd.js"); +const { HttpServer } = ChromeUtils.import("resource://testing-common/httpd.js"); var server = new HttpServer(); server.start(-1); @@ -32,7 +32,10 @@ function log(msg) { } function make_channel(url) { - var request = NetUtil.newChannel({uri: url, loadUsingSystemPrincipal: true}); + var request = NetUtil.newChannel({ + uri: url, + loadUsingSystemPrincipal: true, + }); request.QueryInterface(Ci.nsIHttpChannel); return request; } @@ -53,44 +56,42 @@ function createHttpRequest(status) { function setupHttpRequests(status) { log("setupHttpRequests"); - for (var i = 0; i < maxConnections ; i++) { + for (var i = 0; i < maxConnections; i++) { createHttpRequest(status); do_test_pending(); } } -function HttpResponseListener(id, onStopRequestStatus) -{ - this.id = id +function HttpResponseListener(id, onStopRequestStatus) { + this.id = id; this.onStopRequestStatus = onStopRequestStatus; -}; +} -HttpResponseListener.prototype = -{ - onStartRequest (request) { - }, +HttpResponseListener.prototype = { + onStartRequest(request) {}, - onDataAvailable (request, stream, off, cnt) { - }, + onDataAvailable(request, stream, off, cnt) {}, - onStopRequest (request, status) { + onStopRequest(request, status) { log("STOP id=" + this.id + " status=" + status); Assert.ok(this.onStopRequestStatus == status); do_test_finished(); - } + }, }; var responseQueue = new Array(); -function setup_http_server() -{ +function setup_http_server() { log("setup_http_server"); - var prefs = Cc["@mozilla.org/preferences-service;1"].getService(Ci.nsIPrefBranch); - maxConnections = prefs.getIntPref("network.http.max-persistent-connections-per-server"); + var prefs = Cc["@mozilla.org/preferences-service;1"].getService( + Ci.nsIPrefBranch + ); + maxConnections = prefs.getIntPref( + "network.http.max-persistent-connections-per-server" + ); var allDummyHttpRequestReceived = false; // Start server; will be stopped at test cleanup time. - server.registerPathHandler('/', function(metadata, response) - { + server.registerPathHandler("/", function(metadata, response) { var id = metadata.getHeader("X-ID"); log("Server recived the response id=" + id); @@ -102,13 +103,11 @@ function setup_http_server() log("received all http requets"); Services.obs.notifyObservers(null, "net:cancel-all-connections"); } - }); registerCleanupFunction(function() { server.stop(serverStopListener); }); - } function run_test() { diff --git a/netwerk/test/unit/test_bug1527293.js b/netwerk/test/unit/test_bug1527293.js index 1b15bf608b42..6a1fb6f28e4e 100644 --- a/netwerk/test/unit/test_bug1527293.js +++ b/netwerk/test/unit/test_bug1527293.js @@ -13,9 +13,7 @@ // 3. Check that the request isn't conditional, i.e. the entry from previous // load was doomed. - -const {HttpServer} = ChromeUtils.import("resource://testing-common/httpd.js"); - +const { HttpServer } = ChromeUtils.import("resource://testing-common/httpd.js"); XPCOMUtils.defineLazyGetter(this, "URL", function() { return "http://localhost:" + httpServer.identity.primaryPort; @@ -24,7 +22,7 @@ XPCOMUtils.defineLazyGetter(this, "URL", function() { var httpServer = null; function make_channel(url, callback, ctx) { - return NetUtil.newChannel({uri: url, loadUsingSystemPrincipal: true}); + return NetUtil.newChannel({ uri: url, loadUsingSystemPrincipal: true }); } // need something bigger than 1024 bytes @@ -41,14 +39,18 @@ const responseBody = "0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef" + "0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef"; -function contentHandler(metadata, response) -{ +function contentHandler(metadata, response) { response.setHeader("Content-Type", "text/plain"); response.setHeader("ETag", "Just testing"); response.setHeader("Cache-Control", "max-age=99999"); - Assert.throws(() => { var etag = metadata.getHeader("If-None-Match"); }, - /NS_ERROR_NOT_AVAILABLE/, "conditional request not expected"); + Assert.throws( + () => { + var etag = metadata.getHeader("If-None-Match"); + }, + /NS_ERROR_NOT_AVAILABLE/, + "conditional request not expected" + ); response.setHeader("Accept-Ranges", "bytes"); let len = responseBody.length; @@ -56,8 +58,7 @@ function contentHandler(metadata, response) response.bodyOutputStream.write(responseBody, responseBody.length); } -function run_test() -{ +function run_test() { // Static check Assert.ok(responseBody.length > 1024); @@ -76,16 +77,14 @@ function run_test() do_test_pending(); } -function firstTimeThrough(request, buffer) -{ +function firstTimeThrough(request, buffer) { Assert.equal(buffer, responseBody); var chan = make_channel(URL + "/content"); chan.asyncOpen(new ChannelListener(secondTimeThrough, null)); } -function secondTimeThrough(request, buffer) -{ +function secondTimeThrough(request, buffer) { Assert.equal(buffer, responseBody); httpServer.stop(do_test_finished); } diff --git a/netwerk/test/unit/test_bug203271.js b/netwerk/test/unit/test_bug203271.js index f89c2803d8e4..28c8d65a4103 100644 --- a/netwerk/test/unit/test_bug203271.js +++ b/netwerk/test/unit/test_bug203271.js @@ -4,173 +4,243 @@ // specified in RFC 2616 section 14.9.3 by letting max-age // take precedence -const {HttpServer} = ChromeUtils.import("resource://testing-common/httpd.js"); +const { HttpServer } = ChromeUtils.import("resource://testing-common/httpd.js"); const BUGID = "203271"; var httpserver = new HttpServer(); var index = 0; var tests = [ - // original problem described in bug#203271 - {url: "/precedence", server: "0", expected: "0", - responseheader: [ "Expires: " + getDateString(-1), - "Cache-Control: max-age=3600"]}, + // original problem described in bug#203271 + { + url: "/precedence", + server: "0", + expected: "0", + responseheader: [ + "Expires: " + getDateString(-1), + "Cache-Control: max-age=3600", + ], + }, - {url: "/precedence?0", server: "0", expected: "0", - responseheader: [ "Cache-Control: max-age=3600", - "Expires: " + getDateString(-1)]}, + { + url: "/precedence?0", + server: "0", + expected: "0", + responseheader: [ + "Cache-Control: max-age=3600", + "Expires: " + getDateString(-1), + ], + }, - // max-age=1s, expires=1 year from now - {url: "/precedence?1", server: "0", expected: "0", - responseheader: [ "Expires: " + getDateString(1), - "Cache-Control: max-age=1"]}, + // max-age=1s, expires=1 year from now + { + url: "/precedence?1", + server: "0", + expected: "0", + responseheader: [ + "Expires: " + getDateString(1), + "Cache-Control: max-age=1", + ], + }, - // expires=now - {url: "/precedence?2", server: "0", expected: "0", - responseheader: [ "Expires: " + getDateString(0)]}, + // expires=now + { + url: "/precedence?2", + server: "0", + expected: "0", + responseheader: ["Expires: " + getDateString(0)], + }, - // max-age=1s - {url: "/precedence?3", server: "0", expected: "0", - responseheader: ["Cache-Control: max-age=1"]}, + // max-age=1s + { + url: "/precedence?3", + server: "0", + expected: "0", + responseheader: ["Cache-Control: max-age=1"], + }, - // The test below is the example from - // - // https://bugzilla.mozilla.org/show_bug.cgi?id=203271#c27 - // - // max-age=2592000s (1 month), expires=1 year from now, date=1 year ago - {url: "/precedence?4", server: "0", expected: "0", - responseheader: [ "Cache-Control: private, max-age=2592000", - "Expires: " + getDateString(+1)], - explicitDate: getDateString(-1)}, + // The test below is the example from + // + // https://bugzilla.mozilla.org/show_bug.cgi?id=203271#c27 + // + // max-age=2592000s (1 month), expires=1 year from now, date=1 year ago + { + url: "/precedence?4", + server: "0", + expected: "0", + responseheader: [ + "Cache-Control: private, max-age=2592000", + "Expires: " + getDateString(+1), + ], + explicitDate: getDateString(-1), + }, - // The two tests below are also examples of clocks really out of synch - // max-age=1s, date=1 year from now - {url: "/precedence?5", server: "0", expected: "0", - responseheader: [ "Cache-Control: max-age=1"], - explicitDate: getDateString(1)}, + // The two tests below are also examples of clocks really out of synch + // max-age=1s, date=1 year from now + { + url: "/precedence?5", + server: "0", + expected: "0", + responseheader: ["Cache-Control: max-age=1"], + explicitDate: getDateString(1), + }, - // max-age=60s, date=1 year from now - {url: "/precedence?6", server: "0", expected: "0", - responseheader: [ "Cache-Control: max-age=60"], - explicitDate: getDateString(1)}, + // max-age=60s, date=1 year from now + { + url: "/precedence?6", + server: "0", + expected: "0", + responseheader: ["Cache-Control: max-age=60"], + explicitDate: getDateString(1), + }, - // this is just to get a pause of 3s to allow cache-entries to expire - {url: "/precedence?999", server: "0", expected: "0", delay: "3000"}, + // this is just to get a pause of 3s to allow cache-entries to expire + { url: "/precedence?999", server: "0", expected: "0", delay: "3000" }, - // Below are the cases which actually matters - {url: "/precedence", server: "1", expected: "0"}, // should be cached - - {url: "/precedence?0", server: "1", expected: "0"}, // should be cached + // Below are the cases which actually matters + { url: "/precedence", server: "1", expected: "0" }, // should be cached - {url: "/precedence?1", server: "1", expected: "1"}, // should have expired + { url: "/precedence?0", server: "1", expected: "0" }, // should be cached - {url: "/precedence?2", server: "1", expected: "1"}, // should have expired + { url: "/precedence?1", server: "1", expected: "1" }, // should have expired - {url: "/precedence?3", server: "1", expected: "1"}, // should have expired + { url: "/precedence?2", server: "1", expected: "1" }, // should have expired - {url: "/precedence?4", server: "1", expected: "1"}, // should have expired + { url: "/precedence?3", server: "1", expected: "1" }, // should have expired - {url: "/precedence?5", server: "1", expected: "1"}, // should have expired - - {url: "/precedence?6", server: "1", expected: "0"}, // should be cached + { url: "/precedence?4", server: "1", expected: "1" }, // should have expired + { url: "/precedence?5", server: "1", expected: "1" }, // should have expired + + { url: "/precedence?6", server: "1", expected: "0" }, // should be cached ]; function logit(i, data, ctx) { - dump("requested [" + tests[i].server + "] " + - "got [" + data + "] " + - "expected [" + tests[i].expected + "]"); + dump( + "requested [" + + tests[i].server + + "] " + + "got [" + + data + + "] " + + "expected [" + + tests[i].expected + + "]" + ); - if (tests[i].responseheader) - dump("\t[" + tests[i].responseheader + "]"); - dump("\n"); - // Dump all response-headers - dump("\n===================================\n") - ctx.visitResponseHeaders({ - visitHeader(key, val) { - dump("\t" + key + ":"+val + "\n"); - }} - ); - dump("===================================\n") + if (tests[i].responseheader) { + dump("\t[" + tests[i].responseheader + "]"); + } + dump("\n"); + // Dump all response-headers + dump("\n===================================\n"); + ctx.visitResponseHeaders({ + visitHeader(key, val) { + dump("\t" + key + ":" + val + "\n"); + }, + }); + dump("===================================\n"); } function setupChannel(suffix, value) { - var chan = NetUtil.newChannel({ - uri: "http://localhost:" + httpserver.identity.primaryPort + suffix, - loadUsingSystemPrincipal: true - }); - var httpChan = chan.QueryInterface(Ci.nsIHttpChannel); - httpChan.requestMethod = "GET"; // default value, just being paranoid... - httpChan.setRequestHeader("x-request", value, false); - return httpChan; + var chan = NetUtil.newChannel({ + uri: "http://localhost:" + httpserver.identity.primaryPort + suffix, + loadUsingSystemPrincipal: true, + }); + var httpChan = chan.QueryInterface(Ci.nsIHttpChannel); + httpChan.requestMethod = "GET"; // default value, just being paranoid... + httpChan.setRequestHeader("x-request", value, false); + return httpChan; } function triggerNextTest() { - var channel = setupChannel(tests[index].url, tests[index].server); - channel.asyncOpen(new ChannelListener(checkValueAndTrigger, channel)); + var channel = setupChannel(tests[index].url, tests[index].server); + channel.asyncOpen(new ChannelListener(checkValueAndTrigger, channel)); } function checkValueAndTrigger(request, data, ctx) { - logit(index, data, ctx); - Assert.equal(tests[index].expected, data); + logit(index, data, ctx); + Assert.equal(tests[index].expected, data); - if (index < tests.length - 1) { - var delay = tests[index++].delay; - if (delay) { - do_timeout(delay, triggerNextTest); - } else { - triggerNextTest(); - } + if (index < tests.length - 1) { + var delay = tests[index++].delay; + if (delay) { + do_timeout(delay, triggerNextTest); } else { - httpserver.stop(do_test_finished); + triggerNextTest(); } + } else { + httpserver.stop(do_test_finished); + } } function run_test() { - httpserver.registerPathHandler("/precedence", handler); - httpserver.start(-1); + httpserver.registerPathHandler("/precedence", handler); + httpserver.start(-1); - // clear cache - evict_cache_entries(); + // clear cache + evict_cache_entries(); - triggerNextTest(); - do_test_pending(); + triggerNextTest(); + do_test_pending(); } function handler(metadata, response) { - var body = metadata.getHeader("x-request"); - response.setHeader("Content-Type", "text/plain", false); + var body = metadata.getHeader("x-request"); + response.setHeader("Content-Type", "text/plain", false); - var date = tests[index].explicitDate; - if (date == undefined) { - response.setHeader("Date", getDateString(0), false); - } else { - response.setHeader("Date", date, false); - } + var date = tests[index].explicitDate; + if (date == undefined) { + response.setHeader("Date", getDateString(0), false); + } else { + response.setHeader("Date", date, false); + } - var header = tests[index].responseheader; - if (header == undefined) { - response.setHeader("Last-Modified", getDateString(-1), false); - } else { - for (var i = 0; i < header.length; i++) { - var splitHdr = header[i].split(": "); - response.setHeader(splitHdr[0], splitHdr[1], false); - } + var header = tests[index].responseheader; + if (header == undefined) { + response.setHeader("Last-Modified", getDateString(-1), false); + } else { + for (var i = 0; i < header.length; i++) { + var splitHdr = header[i].split(": "); + response.setHeader(splitHdr[0], splitHdr[1], false); } - - response.setStatusLine(metadata.httpVersion, 200, "OK"); - response.bodyOutputStream.write(body, body.length); + } + + response.setStatusLine(metadata.httpVersion, 200, "OK"); + response.bodyOutputStream.write(body, body.length); } - + function getDateString(yearDelta) { - var months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', - 'Sep', 'Oct', 'Nov', 'Dec']; - var days = ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat']; + var months = [ + "Jan", + "Feb", + "Mar", + "Apr", + "May", + "Jun", + "Jul", + "Aug", + "Sep", + "Oct", + "Nov", + "Dec", + ]; + var days = ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"]; - var d = new Date(); - return days[d.getUTCDay()] + ", " + - d.getUTCDate() + " " + - months[d.getUTCMonth()] + " " + - (d.getUTCFullYear() + yearDelta) + " " + - d.getUTCHours() + ":" + d.getUTCMinutes() + ":" + - d.getUTCSeconds() + " UTC"; + var d = new Date(); + return ( + days[d.getUTCDay()] + + ", " + + d.getUTCDate() + + " " + + months[d.getUTCMonth()] + + " " + + (d.getUTCFullYear() + yearDelta) + + " " + + d.getUTCHours() + + ":" + + d.getUTCMinutes() + + ":" + + d.getUTCSeconds() + + " UTC" + ); } diff --git a/netwerk/test/unit/test_bug248970_cache.js b/netwerk/test/unit/test_bug248970_cache.js index 236418efddd7..5b8a2696865c 100644 --- a/netwerk/test/unit/test_bug248970_cache.js +++ b/netwerk/test/unit/test_bug248970_cache.js @@ -14,26 +14,26 @@ const kCacheC = "http://cache/C"; const kTestContent = "test content"; function make_input_stream_scriptable(input) { - var wrapper = Cc["@mozilla.org/scriptableinputstream;1"]. - createInstance(Ci.nsIScriptableInputStream); + var wrapper = Cc["@mozilla.org/scriptableinputstream;1"].createInstance( + Ci.nsIScriptableInputStream + ); wrapper.init(input); return wrapper; } const entries = [ -// key content device should exist after leaving PB - [kCacheA, kTestContent, kMemoryDevice, true], - [kCacheA2, kTestContent, kDiskDevice, false], - [kCacheB, kTestContent, kDiskDevice, true], - [kCacheC, kTestContent, kOfflineDevice, true] -] + // key content device should exist after leaving PB + [kCacheA, kTestContent, kMemoryDevice, true], + [kCacheA2, kTestContent, kDiskDevice, false], + [kCacheB, kTestContent, kDiskDevice, true], + [kCacheC, kTestContent, kOfflineDevice, true], +]; var store_idx; var store_cb = null; var appCache = null; -function store_entries(cb) -{ +function store_entries(cb) { if (cb) { store_cb = cb; store_idx = 0; @@ -44,13 +44,16 @@ function store_entries(cb) return; } - asyncOpenCacheEntry(entries[store_idx][0], - entries[store_idx][2], - Ci.nsICacheStorage.OPEN_TRUNCATE, - Services.loadContextInfo.custom(false, - {privateBrowsingId : entries[store_idx][3] ? 0 : 1}), - store_data, - appCache); + asyncOpenCacheEntry( + entries[store_idx][0], + entries[store_idx][2], + Ci.nsICacheStorage.OPEN_TRUNCATE, + Services.loadContextInfo.custom(false, { + privateBrowsingId: entries[store_idx][3] ? 0 : 1, + }), + store_data, + appCache + ); } var store_data = function(status, entry) { @@ -59,9 +62,15 @@ var store_data = function(status, entry) { var written = os.write(entries[store_idx][1], entries[store_idx][1].length); if (written != entries[store_idx][1].length) { - do_throw("os.write has not written all data!\n" + - " Expected: " + entries[store_idx][1].length + "\n" + - " Actual: " + written + "\n"); + do_throw( + "os.write has not written all data!\n" + + " Expected: " + + entries[store_idx][1].length + + "\n" + + " Actual: " + + written + + "\n" + ); } os.close(); entry.close(); @@ -72,8 +81,7 @@ var store_data = function(status, entry) { var check_idx; var check_cb = null; var check_pb_exited; -function check_entries(cb, pbExited) -{ +function check_entries(cb, pbExited) { if (cb) { check_cb = cb; check_idx = 0; @@ -85,20 +93,23 @@ function check_entries(cb, pbExited) return; } - asyncOpenCacheEntry(entries[check_idx][0], - entries[check_idx][2], - Ci.nsICacheStorage.OPEN_READONLY, - Services.loadContextInfo.custom(false, - {privateBrowsingId : entries[check_idx][3] ? 0 : 1}), - check_data, - appCache); + asyncOpenCacheEntry( + entries[check_idx][0], + entries[check_idx][2], + Ci.nsICacheStorage.OPEN_READONLY, + Services.loadContextInfo.custom(false, { + privateBrowsingId: entries[check_idx][3] ? 0 : 1, + }), + check_data, + appCache + ); } -var check_data = function (status, entry) { +var check_data = function(status, entry) { var cont = function() { check_idx++; executeSoon(check_entries); - } + }; if (!check_pb_exited || entries[check_idx][3]) { Assert.equal(status, Cr.NS_OK); @@ -118,9 +129,9 @@ function run_test() { // Simulate a profile dir for xpcshell do_get_profile(); - appCache = Cc["@mozilla.org/network/application-cache-service;1"]. - getService(Ci.nsIApplicationCacheService). - getApplicationCache("fake-client-id|fake-group-id"); + appCache = Cc["@mozilla.org/network/application-cache-service;1"] + .getService(Ci.nsIApplicationCacheService) + .getApplicationCache("fake-client-id|fake-group-id"); // Start off with an empty cache evict_cache_entries(); @@ -138,8 +149,9 @@ function run_test2() { function run_test3() { // Simulate all private browsing instances being closed - var obsvc = Cc["@mozilla.org/observer-service;1"]. - getService(Ci.nsIObserverService); + var obsvc = Cc["@mozilla.org/observer-service;1"].getService( + Ci.nsIObserverService + ); obsvc.notifyObservers(null, "last-pb-context-exited"); // Make sure the memory device is not empty diff --git a/netwerk/test/unit/test_bug248970_cookie.js b/netwerk/test/unit/test_bug248970_cookie.js index a9d8703b227d..b1299124e448 100644 --- a/netwerk/test/unit/test_bug248970_cookie.js +++ b/netwerk/test/unit/test_bug248970_cookie.js @@ -2,42 +2,47 @@ * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ -const {HttpServer} = ChromeUtils.import("resource://testing-common/httpd.js"); +const { HttpServer } = ChromeUtils.import("resource://testing-common/httpd.js"); var httpserver; function inChildProcess() { - return Cc["@mozilla.org/xre/app-info;1"] - .getService(Ci.nsIXULRuntime) - .processType != Ci.nsIXULRuntime.PROCESS_TYPE_DEFAULT; + return ( + Cc["@mozilla.org/xre/app-info;1"].getService(Ci.nsIXULRuntime) + .processType != Ci.nsIXULRuntime.PROCESS_TYPE_DEFAULT + ); } function makeChan(path) { return NetUtil.newChannel({ uri: "http://localhost:" + httpserver.identity.primaryPort + "/" + path, - loadUsingSystemPrincipal: true + loadUsingSystemPrincipal: true, }).QueryInterface(Ci.nsIHttpChannel); } function setup_chan(path, isPrivate, callback) { var chan = makeChan(path); chan.QueryInterface(Ci.nsIPrivateBrowsingChannel).setPrivate(isPrivate); - chan.asyncOpen(new ChannelListener(callback)); - } + chan.asyncOpen(new ChannelListener(callback)); +} function set_cookie(value, callback) { - return setup_chan('set?cookie=' + value, false, callback); + return setup_chan("set?cookie=" + value, false, callback); } function set_private_cookie(value, callback) { - return setup_chan('set?cookie=' + value, true, callback); + return setup_chan("set?cookie=" + value, true, callback); } function check_cookie_presence(value, isPrivate, expected, callback) { - var chan = setup_chan('present?cookie=' + value.replace('=','|'), isPrivate, function(req) { - req.QueryInterface(Ci.nsIHttpChannel); - Assert.equal(req.responseStatus, expected ? 200 : 404); - callback(req); - }); + var chan = setup_chan( + "present?cookie=" + value.replace("=", "|"), + isPrivate, + function(req) { + req.QueryInterface(Ci.nsIHttpChannel); + Assert.equal(req.responseStatus, expected ? 200 : 404); + callback(req); + } + ); } function presentHandler(metadata, response) { @@ -45,9 +50,10 @@ function presentHandler(metadata, response) { var match = /cookie=([^&]*)/.exec(metadata.queryString); if (match) { try { - present = metadata.getHeader("Cookie").includes(match[1].replace("|","=")); - } catch (x) { - } + present = metadata + .getHeader("Cookie") + .includes(match[1].replace("|", "=")); + } catch (x) {} } response.setStatusLine("1.0", present ? 200 : 404, ""); } @@ -64,21 +70,27 @@ function run_test() { // Allow all cookies if the pref service is available in this process. if (!inChildProcess()) { Services.prefs.setIntPref("network.cookie.cookieBehavior", 0); - Services.prefs.setBoolPref("network.cookieSettings.unblocked_for_testing", true); + Services.prefs.setBoolPref( + "network.cookieSettings.unblocked_for_testing", + true + ); } httpserver = new HttpServer(); httpserver.registerPathHandler("/set", setHandler); httpserver.registerPathHandler("/present", presentHandler); httpserver.start(-1); - + do_test_pending(); - + function check_cookie(req) { req.QueryInterface(Ci.nsIHttpChannel); Assert.equal(req.responseStatus, 200); try { - Assert.ok(req.getResponseHeader("Set-Cookie") != "", "expected a Set-Cookie header"); + Assert.ok( + req.getResponseHeader("Set-Cookie") != "", + "expected a Set-Cookie header" + ); } catch (x) { do_throw("missing Set-Cookie header"); } @@ -87,11 +99,11 @@ function run_test() { } let tests = []; - + function runNextTest() { executeSoon(tests.shift()); } - + tests.push(function() { set_cookie("C1=V1", check_cookie); }); @@ -117,19 +129,22 @@ function run_test() { // The following test only works in a non-e10s situation at the moment, // since the notification needs to run in the parent process but there is - // no existing mechanism to make that happen. + // no existing mechanism to make that happen. if (!inChildProcess()) { tests.push(function() { // Simulate all private browsing instances being closed - var obsvc = Cc["@mozilla.org/observer-service;1"]. - getService(Ci.nsIObserverService); + var obsvc = Cc["@mozilla.org/observer-service;1"].getService( + Ci.nsIObserverService + ); obsvc.notifyObservers(null, "last-pb-context-exited"); // Check that all private cookies are now unavailable in new private requests check_cookie_presence("C2=V2", true, false, runNextTest); }); } - - tests.push(function() { httpserver.stop(do_test_finished); }); - + + tests.push(function() { + httpserver.stop(do_test_finished); + }); + runNextTest(); } diff --git a/netwerk/test/unit/test_bug261425.js b/netwerk/test/unit/test_bug261425.js index 62c82b8f8618..915818c67127 100644 --- a/netwerk/test/unit/test_bug261425.js +++ b/netwerk/test/unit/test_bug261425.js @@ -1,26 +1,35 @@ function run_test() { - var ios = Cc["@mozilla.org/network/io-service;1"]. - getService(Ci.nsIIOService); + var ios = Cc["@mozilla.org/network/io-service;1"].getService(Ci.nsIIOService); var newURI = ios.newURI("http://foo.com"); var success = false; try { - newURI = newURI.mutate().setSpec("http: //foo.com").finalize(); - } - catch (e) { + newURI = newURI + .mutate() + .setSpec("http: //foo.com") + .finalize(); + } catch (e) { success = e.result == Cr.NS_ERROR_MALFORMED_URI; } - if (!success) - do_throw("We didn't throw NS_ERROR_MALFORMED_URI when a space was passed in the hostname!"); + if (!success) { + do_throw( + "We didn't throw NS_ERROR_MALFORMED_URI when a space was passed in the hostname!" + ); + } success = false; try { - newURI = newURI.mutate().setHost(" foo.com").finalize(); - } - catch (e) { + newURI = newURI + .mutate() + .setHost(" foo.com") + .finalize(); + } catch (e) { success = e.result == Cr.NS_ERROR_MALFORMED_URI; } - if (!success) - do_throw("We didn't throw NS_ERROR_MALFORMED_URI when a space was passed in the hostname!"); + if (!success) { + do_throw( + "We didn't throw NS_ERROR_MALFORMED_URI when a space was passed in the hostname!" + ); + } } diff --git a/netwerk/test/unit/test_bug263127.js b/netwerk/test/unit/test_bug263127.js index 0b1a97e3c305..d0bbeb300785 100644 --- a/netwerk/test/unit/test_bug263127.js +++ b/netwerk/test/unit/test_bug263127.js @@ -1,4 +1,4 @@ -const {HttpServer} = ChromeUtils.import("resource://testing-common/httpd.js"); +const { HttpServer } = ChromeUtils.import("resource://testing-common/httpd.js"); var server; const BUGID = "263127"; @@ -10,21 +10,21 @@ var listener = { do_test_pending(); server.stop(do_test_finished); - if (!file) + if (!file) { do_throw("Download failed"); + } try { file.remove(false); - } - catch (e) { + } catch (e) { do_throw(e); } Assert.ok(!file.exists()); do_test_finished(); - } -} + }, +}; function run_test() { // start server @@ -34,17 +34,19 @@ function run_test() { // Initialize downloader var channel = NetUtil.newChannel({ uri: "http://localhost:" + server.identity.primaryPort + "/", - loadUsingSystemPrincipal: true + loadUsingSystemPrincipal: true, }); var targetFile = Cc["@mozilla.org/file/directory_service;1"] - .getService(Ci.nsIProperties) - .get("TmpD", Ci.nsIFile); + .getService(Ci.nsIProperties) + .get("TmpD", Ci.nsIFile); targetFile.append("bug" + BUGID + ".test"); - if (targetFile.exists()) + if (targetFile.exists()) { targetFile.remove(false); + } - var downloader = Cc["@mozilla.org/network/downloader;1"] - .createInstance(Ci.nsIDownloader); + var downloader = Cc["@mozilla.org/network/downloader;1"].createInstance( + Ci.nsIDownloader + ); downloader.init(listener, targetFile); // Start download diff --git a/netwerk/test/unit/test_bug282432.js b/netwerk/test/unit/test_bug282432.js index 2a7cb9df2fad..70d20577baba 100644 --- a/netwerk/test/unit/test_bug282432.js +++ b/netwerk/test/unit/test_bug282432.js @@ -1,11 +1,13 @@ - function run_test() { do_test_pending(); function StreamListener() {} StreamListener.prototype = { - QueryInterface: ChromeUtils.generateQI(["nsIStreamListener", "nsIRequestObserver"]), + QueryInterface: ChromeUtils.generateQI([ + "nsIStreamListener", + "nsIRequestObserver", + ]), onStartRequest(aRequest) {}, @@ -17,19 +19,18 @@ function run_test() { onDataAvailable(aRequest, aStream, aOffset, aCount) { do_throw("The channel must not call onDataAvailable()."); - } + }, }; let listener = new StreamListener(); - let ios = Cc["@mozilla.org/network/io-service;1"] - .getService(Ci.nsIIOService); + let ios = Cc["@mozilla.org/network/io-service;1"].getService(Ci.nsIIOService); // This file does not exist. let file = do_get_file("_NOT_EXIST_.txt", true); Assert.ok(!file.exists()); let channel = NetUtil.newChannel({ uri: ios.newFileURI(file), - loadUsingSystemPrincipal: true + loadUsingSystemPrincipal: true, }); channel.asyncOpen(listener); } diff --git a/netwerk/test/unit/test_bug321706.js b/netwerk/test/unit/test_bug321706.js index bd721699eb16..636d0cc154c0 100644 --- a/netwerk/test/unit/test_bug321706.js +++ b/netwerk/test/unit/test_bug321706.js @@ -1,8 +1,7 @@ const url = "http://foo.com/folder/file?/."; function run_test() { - var ios = Cc["@mozilla.org/network/io-service;1"]. - getService(Ci.nsIIOService); + var ios = Cc["@mozilla.org/network/io-service;1"].getService(Ci.nsIIOService); var newURI = ios.newURI(url); Assert.equal(newURI.spec, url); diff --git a/netwerk/test/unit/test_bug331825.js b/netwerk/test/unit/test_bug331825.js index 982c2a7ad402..796f784f1664 100644 --- a/netwerk/test/unit/test_bug331825.js +++ b/netwerk/test/unit/test_bug331825.js @@ -1,18 +1,16 @@ -const {HttpServer} = ChromeUtils.import("resource://testing-common/httpd.js"); +const { HttpServer } = ChromeUtils.import("resource://testing-common/httpd.js"); var server; const BUGID = "331825"; -function TestListener() { -} -TestListener.prototype.onStartRequest = function(request) { -} +function TestListener() {} +TestListener.prototype.onStartRequest = function(request) {}; TestListener.prototype.onStopRequest = function(request, status) { var channel = request.QueryInterface(Ci.nsIHttpChannel); Assert.equal(channel.responseStatus, 304); server.stop(do_test_finished); -} +}; function run_test() { // start server @@ -25,7 +23,7 @@ function run_test() { // make request var channel = NetUtil.newChannel({ uri: "http://localhost:" + server.identity.primaryPort + "/bug" + BUGID, - loadUsingSystemPrincipal: true + loadUsingSystemPrincipal: true, }); channel.QueryInterface(Ci.nsIHttpChannel); diff --git a/netwerk/test/unit/test_bug336501.js b/netwerk/test/unit/test_bug336501.js index 51a4bd065101..25b30cafd2aa 100644 --- a/netwerk/test/unit/test_bug336501.js +++ b/netwerk/test/unit/test_bug336501.js @@ -1,19 +1,19 @@ function run_test() { - var f = do_get_file('test_bug336501.js'); + var f = do_get_file("test_bug336501.js"); - var fis = - Cc["@mozilla.org/network/file-input-stream;1"]. - createInstance(Ci.nsIFileInputStream); - fis.init(f, -1, -1, 0); + var fis = Cc["@mozilla.org/network/file-input-stream;1"].createInstance( + Ci.nsIFileInputStream + ); + fis.init(f, -1, -1, 0); - var bis = - Cc["@mozilla.org/network/buffered-input-stream;1"]. - createInstance(Ci.nsIBufferedInputStream); + var bis = Cc["@mozilla.org/network/buffered-input-stream;1"].createInstance( + Ci.nsIBufferedInputStream + ); bis.init(fis, 32); - var sis = - Cc["@mozilla.org/scriptableinputstream;1"]. - createInstance(Ci.nsIScriptableInputStream); + var sis = Cc["@mozilla.org/scriptableinputstream;1"].createInstance( + Ci.nsIScriptableInputStream + ); sis.init(bis); sis.read(45); diff --git a/netwerk/test/unit/test_bug337744.js b/netwerk/test/unit/test_bug337744.js index e3fbdd5e7814..688a8ebd32c9 100644 --- a/netwerk/test/unit/test_bug337744.js +++ b/netwerk/test/unit/test_bug337744.js @@ -29,42 +29,63 @@ const error_specs = [ var uri = NetUtil.newURI("http://www.example.com"); var principal = Services.scriptSecurityManager.createCodebasePrincipal(uri, {}); -function get_channel(spec) -{ +function get_channel(spec) { var channelURI = NetUtil.newURI(spec); var channel = NetUtil.newChannel({ uri: NetUtil.newURI(spec), loadingPrincipal: principal, securityFlags: Ci.nsILoadInfo.SEC_ALLOW_CROSS_ORIGIN_DATA_IS_NULL, - contentPolicyType: Ci.nsIContentPolicy.TYPE_OTHER + contentPolicyType: Ci.nsIContentPolicy.TYPE_OTHER, }); - Assert.throws(() => { channel.asyncOpen(null); }, /NS_ERROR_DOM_BAD_URI/, `asyncOpen() of uri: ${spec} should throw`); - Assert.throws(() => { channel.open(); }, /NS_ERROR_DOM_BAD_URI/, `Open() of uri: ${spec} should throw`); + Assert.throws( + () => { + channel.asyncOpen(null); + }, + /NS_ERROR_DOM_BAD_URI/, + `asyncOpen() of uri: ${spec} should throw` + ); + Assert.throws( + () => { + channel.open(); + }, + /NS_ERROR_DOM_BAD_URI/, + `Open() of uri: ${spec} should throw` + ); return channel; } -function check_safe_resolution(spec, rootURI) -{ +function check_safe_resolution(spec, rootURI) { info(`Testing URL "${spec}"`); let channel = get_channel(spec); - ok(channel.name.startsWith(rootURI), `URL resolved safely to ${channel.name}`); + ok( + channel.name.startsWith(rootURI), + `URL resolved safely to ${channel.name}` + ); let startOfQuery = channel.name.indexOf("?"); if (startOfQuery == -1) { ok(!/%2f/i.test(channel.name), `URL contains no escaped / characters`); } else { // Escaped slashes are allowed in the query or hash part of the URL - ok(!channel.name.replace(/\?.*/, "").includes("%2f"), `URL contains no escaped slashes before the query ${channel.name}`); + ok( + !channel.name.replace(/\?.*/, "").includes("%2f"), + `URL contains no escaped slashes before the query ${channel.name}` + ); } } -function check_resolution_error(spec) -{ - Assert.throws(() => { get_channel(spec); }, /NS_ERROR_MALFORMED_URI/, "Expected a malformed URI error"); +function check_resolution_error(spec) { + Assert.throws( + () => { + get_channel(spec); + }, + /NS_ERROR_MALFORMED_URI/, + "Expected a malformed URI error" + ); } function run_test() { @@ -72,7 +93,9 @@ function run_test() { // to create a temporary resource package to test the standard logic // with. - let resProto = Cc['@mozilla.org/network/protocol;1?name=resource'].getService(Ci.nsIResProtocolHandler); + let resProto = Cc["@mozilla.org/network/protocol;1?name=resource"].getService( + Ci.nsIResProtocolHandler + ); let rootFile = Services.dirsvc.get("GreD", Ci.nsIFile); let rootURI = Services.io.newFileURI(rootFile); @@ -91,7 +114,10 @@ function run_test() { for (var spec of specs) { check_safe_resolution(spec, rootURI.spec); - check_safe_resolution(spec.replace("res-test", "res-inexistent"), inexistentURI.spec); + check_safe_resolution( + spec.replace("res-test", "res-inexistent"), + inexistentURI.spec + ); check_safe_resolution(spec.replace("res-test", ""), baseRoot); check_safe_resolution(spec.replace("res-test", "gre"), greRoot); } diff --git a/netwerk/test/unit/test_bug365133.js b/netwerk/test/unit/test_bug365133.js index 5b74d835ac65..d7d66b73c0f0 100644 --- a/netwerk/test/unit/test_bug365133.js +++ b/netwerk/test/unit/test_bug365133.js @@ -1,63 +1,79 @@ const URL = "ftp://localhost/bug365133/"; const tests = [ - [ /* Unix style listing, space at the end of filename */ - "drwxrwxr-x 2 500 500 4096 Jan 01 2000 a \r\n" - , - "300: " + URL + "\n" + - "200: filename content-length last-modified file-type\n" + - "201: \"a%20\" 0 Sat%2C%2001%20Jan%202000%2000%3A00%3A00 DIRECTORY \n" + [ + /* Unix style listing, space at the end of filename */ + "drwxrwxr-x 2 500 500 4096 Jan 01 2000 a \r\n", + "300: " + + URL + + "\n" + + "200: filename content-length last-modified file-type\n" + + '201: "a%20" 0 Sat%2C%2001%20Jan%202000%2000%3A00%3A00 DIRECTORY \n', ], - [ /* Unix style listing, space at the end of link name */ - "lrwxrwxrwx 1 500 500 2 Jan 01 2000 l -> a \r\n" - , - "300: " + URL + "\n" + - "200: filename content-length last-modified file-type\n" + - "201: \"l%20\" 2 Sat%2C%2001%20Jan%202000%2000%3A00%3A00 SYMBOLIC-LINK \n" + [ + /* Unix style listing, space at the end of link name */ + "lrwxrwxrwx 1 500 500 2 Jan 01 2000 l -> a \r\n", + "300: " + + URL + + "\n" + + "200: filename content-length last-modified file-type\n" + + '201: "l%20" 2 Sat%2C%2001%20Jan%202000%2000%3A00%3A00 SYMBOLIC-LINK \n', ], - [ /* Unix style listing, regular file with " -> " in name */ - "-rw-rw-r-- 1 500 500 0 Jan 01 2000 arrow -> in name \r\n" - , - "300: " + URL + "\n" + - "200: filename content-length last-modified file-type\n" + - "201: \"arrow%20-%3E%20in%20name%20\" 0 Sat%2C%2001%20Jan%202000%2000%3A00%3A00 FILE \n" + [ + /* Unix style listing, regular file with " -> " in name */ + "-rw-rw-r-- 1 500 500 0 Jan 01 2000 arrow -> in name \r\n", + "300: " + + URL + + "\n" + + "200: filename content-length last-modified file-type\n" + + '201: "arrow%20-%3E%20in%20name%20" 0 Sat%2C%2001%20Jan%202000%2000%3A00%3A00 FILE \n', ], - [ /* Unix style listing, tab at the end of filename */ - "drwxrwxrwx 2 500 500 4096 Jan 01 2000 t \r\n" - , - "300: " + URL + "\n" + - "200: filename content-length last-modified file-type\n" + - "201: \"t%09\" 0 Sat%2C%2001%20Jan%202000%2000%3A00%3A00 DIRECTORY \n" + [ + /* Unix style listing, tab at the end of filename */ + "drwxrwxrwx 2 500 500 4096 Jan 01 2000 t \r\n", + "300: " + + URL + + "\n" + + "200: filename content-length last-modified file-type\n" + + '201: "t%09" 0 Sat%2C%2001%20Jan%202000%2000%3A00%3A00 DIRECTORY \n', ], - [ /* Unix style listing, multiple " -> " in filename */ - "lrwxrwxrwx 1 500 500 26 Jan 01 2000 symlink with arrow -> in name -> file with arrow -> in name\r\n" - , - "300: " + URL + "\n" + - "200: filename content-length last-modified file-type\n" + - "201: \"symlink%20with%20arrow%20-%3E%20in%20name\" 26 Sat%2C%2001%20Jan%202000%2000%3A00%3A00 SYMBOLIC-LINK \n" + [ + /* Unix style listing, multiple " -> " in filename */ + "lrwxrwxrwx 1 500 500 26 Jan 01 2000 symlink with arrow -> in name -> file with arrow -> in name\r\n", + "300: " + + URL + + "\n" + + "200: filename content-length last-modified file-type\n" + + '201: "symlink%20with%20arrow%20-%3E%20in%20name" 26 Sat%2C%2001%20Jan%202000%2000%3A00%3A00 SYMBOLIC-LINK \n', ], - [ /* Unix style listing, multiple " -> " in filename, incorrect filesize */ - "lrwxrwxrwx 1 500 500 0 Jan 01 2000 symlink with arrow -> in name -> file with arrow -> in name\r\n" - , - "300: " + URL + "\n" + - "200: filename content-length last-modified file-type\n" + - "201: \"symlink%20with%20arrow%20-%3E%20in%20name%20-%3E%20file%20with%20arrow\" 0 Sat%2C%2001%20Jan%202000%2000%3A00%3A00 SYMBOLIC-LINK \n" + [ + /* Unix style listing, multiple " -> " in filename, incorrect filesize */ + "lrwxrwxrwx 1 500 500 0 Jan 01 2000 symlink with arrow -> in name -> file with arrow -> in name\r\n", + "300: " + + URL + + "\n" + + "200: filename content-length last-modified file-type\n" + + '201: "symlink%20with%20arrow%20-%3E%20in%20name%20-%3E%20file%20with%20arrow" 0 Sat%2C%2001%20Jan%202000%2000%3A00%3A00 SYMBOLIC-LINK \n', ], - [ /* DOS style listing, space at the end of filename, year 1999 */ - "01-01-99 01:00AM 1024 file \r\n" - , - "300: " + URL + "\n" + - "200: filename content-length last-modified file-type\n" + - "201: \"file%20\" 1024 Fri%2C%2001%20Jan%201999%2001%3A00%3A00 FILE \n" + [ + /* DOS style listing, space at the end of filename, year 1999 */ + "01-01-99 01:00AM 1024 file \r\n", + "300: " + + URL + + "\n" + + "200: filename content-length last-modified file-type\n" + + '201: "file%20" 1024 Fri%2C%2001%20Jan%201999%2001%3A00%3A00 FILE \n', ], - [ /* DOS style listing, tab at the end of filename, year 2000 */ - "01-01-00 01:00AM 1024 file \r\n" - , - "300: " + URL + "\n" + - "200: filename content-length last-modified file-type\n" + - "201: \"file%09\" 1024 Sat%2C%2001%20Jan%202000%2001%3A00%3A00 FILE \n" - ] -] + [ + /* DOS style listing, tab at the end of filename, year 2000 */ + "01-01-00 01:00AM 1024 file \r\n", + "300: " + + URL + + "\n" + + "200: filename content-length last-modified file-type\n" + + '201: "file%09" 1024 Sat%2C%2001%20Jan%202000%2001%3A00%3A00 FILE \n', + ], +]; function checkData(request, data, ctx) { Assert.equal(tests[0][1], data); @@ -66,13 +82,19 @@ function checkData(request, data, ctx) { } function storeData() { - var scs = Cc["@mozilla.org/streamConverters;1"]. - getService(Ci.nsIStreamConverterService); - var converter = scs.asyncConvertData("text/ftp-dir", "application/http-index-format", - new ChannelListener(checkData, null, CL_ALLOW_UNKNOWN_CL), null); + var scs = Cc["@mozilla.org/streamConverters;1"].getService( + Ci.nsIStreamConverterService + ); + var converter = scs.asyncConvertData( + "text/ftp-dir", + "application/http-index-format", + new ChannelListener(checkData, null, CL_ALLOW_UNKNOWN_CL), + null + ); - var stream = Cc["@mozilla.org/io/string-input-stream;1"]. - createInstance(Ci.nsIStringInputStream); + var stream = Cc["@mozilla.org/io/string-input-stream;1"].createInstance( + Ci.nsIStringInputStream + ); stream.data = tests[0][0]; var url = NetUtil.newURI(URL); @@ -84,7 +106,7 @@ function storeData() { isPending() { return this.pending; }, - QueryInterface: ChromeUtils.generateQI([Ci.nsIChannel]) + QueryInterface: ChromeUtils.generateQI([Ci.nsIChannel]), }; converter.onStartRequest(channel, null); @@ -94,9 +116,9 @@ function storeData() { } function next_test() { - if (tests.length == 0) + if (tests.length == 0) { do_test_finished(); - else { + } else { storeData(); } } diff --git a/netwerk/test/unit/test_bug368702.js b/netwerk/test/unit/test_bug368702.js index 79821a5325d2..ca2b26dd6113 100644 --- a/netwerk/test/unit/test_bug368702.js +++ b/netwerk/test/unit/test_bug368702.js @@ -1,7 +1,7 @@ function run_test() { - var tld = - Cc["@mozilla.org/network/effective-tld-service;1"]. - getService(Ci.nsIEffectiveTLDService); + var tld = Cc["@mozilla.org/network/effective-tld-service;1"].getService( + Ci.nsIEffectiveTLDService + ); var etld; @@ -18,63 +18,63 @@ function run_test() { try { etld = tld.getPublicSuffixFromHost(""); do_throw("this should fail"); - } catch(e) { + } catch (e) { Assert.equal(e.result, Cr.NS_ERROR_INSUFFICIENT_DOMAIN_LEVELS); } try { etld = tld.getBaseDomainFromHost("domain.co.uk", 1); do_throw("this should fail"); - } catch(e) { + } catch (e) { Assert.equal(e.result, Cr.NS_ERROR_INSUFFICIENT_DOMAIN_LEVELS); } try { etld = tld.getBaseDomainFromHost("co.uk"); do_throw("this should fail"); - } catch(e) { + } catch (e) { Assert.equal(e.result, Cr.NS_ERROR_INSUFFICIENT_DOMAIN_LEVELS); } try { etld = tld.getBaseDomainFromHost(""); do_throw("this should fail"); - } catch(e) { + } catch (e) { Assert.equal(e.result, Cr.NS_ERROR_INSUFFICIENT_DOMAIN_LEVELS); } try { etld = tld.getPublicSuffixFromHost("1.2.3.4"); do_throw("this should fail"); - } catch(e) { + } catch (e) { Assert.equal(e.result, Cr.NS_ERROR_HOST_IS_IP_ADDRESS); } try { etld = tld.getPublicSuffixFromHost("2010:836B:4179::836B:4179"); do_throw("this should fail"); - } catch(e) { + } catch (e) { Assert.equal(e.result, Cr.NS_ERROR_HOST_IS_IP_ADDRESS); } try { etld = tld.getPublicSuffixFromHost("3232235878"); do_throw("this should fail"); - } catch(e) { + } catch (e) { Assert.equal(e.result, Cr.NS_ERROR_HOST_IS_IP_ADDRESS); } try { etld = tld.getPublicSuffixFromHost("::ffff:192.9.5.5"); do_throw("this should fail"); - } catch(e) { + } catch (e) { Assert.equal(e.result, Cr.NS_ERROR_HOST_IS_IP_ADDRESS); } try { etld = tld.getPublicSuffixFromHost("::1"); do_throw("this should fail"); - } catch(e) { + } catch (e) { Assert.equal(e.result, Cr.NS_ERROR_HOST_IS_IP_ADDRESS); } @@ -83,25 +83,29 @@ function run_test() { try { etld = tld.getPublicSuffixFromHost("127.0.0.1."); do_throw("this should fail"); - } catch(e) { + } catch (e) { Assert.equal(e.result, Cr.NS_ERROR_HOST_IS_IP_ADDRESS); } try { etld = tld.getPublicSuffixFromHost("::ffff:127.0.0.1."); do_throw("this should fail"); - } catch(e) { + } catch (e) { Assert.equal(e.result, Cr.NS_ERROR_HOST_IS_IP_ADDRESS); } // check normalization: output should be consistent with // nsIURI::GetAsciiHost(), i.e. lowercased and ASCII/ACE encoded - var ioService = Cc["@mozilla.org/network/io-service;1"] - .getService(Ci.nsIIOService); + var ioService = Cc["@mozilla.org/network/io-service;1"].getService( + Ci.nsIIOService + ); var uri = ioService.newURI("http://b\u00FCcher.co.uk"); Assert.equal(tld.getBaseDomain(uri), "xn--bcher-kva.co.uk"); - Assert.equal(tld.getBaseDomainFromHost("b\u00FCcher.co.uk"), "xn--bcher-kva.co.uk"); + Assert.equal( + tld.getBaseDomainFromHost("b\u00FCcher.co.uk"), + "xn--bcher-kva.co.uk" + ); Assert.equal(tld.getPublicSuffix(uri), "co.uk"); Assert.equal(tld.getPublicSuffixFromHost("b\u00FCcher.co.uk"), "co.uk"); @@ -109,42 +113,42 @@ function run_test() { try { etld = tld.getBaseDomainFromHost("domain.co.uk.."); do_throw("this should fail"); - } catch(e) { + } catch (e) { Assert.equal(e.result, Cr.NS_ERROR_ILLEGAL_VALUE); } try { etld = tld.getBaseDomainFromHost("domain.co..uk"); do_throw("this should fail"); - } catch(e) { + } catch (e) { Assert.equal(e.result, Cr.NS_ERROR_ILLEGAL_VALUE); } try { etld = tld.getBaseDomainFromHost(".domain.co.uk"); do_throw("this should fail"); - } catch(e) { + } catch (e) { Assert.equal(e.result, Cr.NS_ERROR_ILLEGAL_VALUE); } try { etld = tld.getBaseDomainFromHost(".domain.co.uk"); do_throw("this should fail"); - } catch(e) { + } catch (e) { Assert.equal(e.result, Cr.NS_ERROR_ILLEGAL_VALUE); } try { etld = tld.getBaseDomainFromHost("."); do_throw("this should fail"); - } catch(e) { + } catch (e) { Assert.equal(e.result, Cr.NS_ERROR_ILLEGAL_VALUE); } try { etld = tld.getBaseDomainFromHost(".."); do_throw("this should fail"); - } catch(e) { + } catch (e) { Assert.equal(e.result, Cr.NS_ERROR_ILLEGAL_VALUE); } } diff --git a/netwerk/test/unit/test_bug369787.js b/netwerk/test/unit/test_bug369787.js index e85eeb35d353..65270c2636ef 100644 --- a/netwerk/test/unit/test_bug369787.js +++ b/netwerk/test/unit/test_bug369787.js @@ -1,4 +1,4 @@ -const {HttpServer} = ChromeUtils.import("resource://testing-common/httpd.js"); +const { HttpServer } = ChromeUtils.import("resource://testing-common/httpd.js"); const BUGID = "369787"; var server = null; @@ -13,8 +13,7 @@ function change_content_type() { Assert.equal(channel.contentType, origType); } -function TestListener() { -} +function TestListener() {} TestListener.prototype.onStartRequest = function(request) { try { // request might be different from channel @@ -25,7 +24,7 @@ TestListener.prototype.onStartRequest = function(request) { print(ex); throw ex; } -} +}; TestListener.prototype.onStopRequest = function(request, status) { try { change_content_type(); @@ -35,7 +34,7 @@ TestListener.prototype.onStopRequest = function(request, status) { } do_timeout(0, after_channel_closed); -} +}; function after_channel_closed() { try { @@ -56,7 +55,7 @@ function run_test() { // make request channel = NetUtil.newChannel({ uri: "http://localhost:" + server.identity.primaryPort + "/bug" + BUGID, - loadUsingSystemPrincipal: true + loadUsingSystemPrincipal: true, }); channel.QueryInterface(Ci.nsIHttpChannel); channel.asyncOpen(new TestListener()); diff --git a/netwerk/test/unit/test_bug371473.js b/netwerk/test/unit/test_bug371473.js index 23f33540e843..5a403003e30d 100644 --- a/netwerk/test/unit/test_bug371473.js +++ b/netwerk/test/unit/test_bug371473.js @@ -1,19 +1,16 @@ function test_not_too_long() { - var ios = Cc["@mozilla.org/network/io-service;1"]. - getService(Ci.nsIIOService); + var ios = Cc["@mozilla.org/network/io-service;1"].getService(Ci.nsIIOService); var spec = "jar:http://example.com/bar.jar!/"; try { var newURI = ios.newURI(spec); - } - catch (e) { + } catch (e) { do_throw("newURI threw even though it wasn't passed a large nested URI?"); } } function test_too_long() { - var ios = Cc["@mozilla.org/network/io-service;1"]. - getService(Ci.nsIIOService); + var ios = Cc["@mozilla.org/network/io-service;1"].getService(Ci.nsIIOService); var i; var prefix = "jar:"; @@ -32,9 +29,7 @@ function test_too_long() { // do not crash here and thus an exception is caught // we have passed the test. var newURI = ios.newURI(spec); - } - catch (e) { - } + } catch (e) {} } function run_test() { diff --git a/netwerk/test/unit/test_bug376844.js b/netwerk/test/unit/test_bug376844.js index bf6aa7493fe4..cdfbfd8a7abb 100644 --- a/netwerk/test/unit/test_bug376844.js +++ b/netwerk/test/unit/test_bug376844.js @@ -2,17 +2,17 @@ const testURLs = [ ["http://example.com/<", "http://example.com/%3C"], ["http://example.com/>", "http://example.com/%3E"], ["http://example.com/'", "http://example.com/'"], - ["http://example.com/\"", "http://example.com/%22"], + ['http://example.com/"', "http://example.com/%22"], ["http://example.com/?<", "http://example.com/?%3C"], ["http://example.com/?>", "http://example.com/?%3E"], ["http://example.com/?'", "http://example.com/?%27"], - ["http://example.com/?\"", "http://example.com/?%22"] -] + ['http://example.com/?"', "http://example.com/?%22"], +]; function run_test() { - var ioServ = - Cc["@mozilla.org/network/io-service;1"]. - getService(Ci.nsIIOService); + var ioServ = Cc["@mozilla.org/network/io-service;1"].getService( + Ci.nsIIOService + ); for (var i = 0; i < testURLs.length; i++) { var uri = ioServ.newURI(testURLs[i][0]); diff --git a/netwerk/test/unit/test_bug376865.js b/netwerk/test/unit/test_bug376865.js index bd50d707812f..f08f07faac4f 100644 --- a/netwerk/test/unit/test_bug376865.js +++ b/netwerk/test/unit/test_bug376865.js @@ -1,18 +1,19 @@ function run_test() { - var stream = Cc["@mozilla.org/io/string-input-stream;1"]. - createInstance(Ci.nsISupportsCString); + var stream = Cc["@mozilla.org/io/string-input-stream;1"].createInstance( + Ci.nsISupportsCString + ); stream.data = "foo bar baz"; - var pump = Cc["@mozilla.org/network/input-stream-pump;1"]. - createInstance(Ci.nsIInputStreamPump); + var pump = Cc["@mozilla.org/network/input-stream-pump;1"].createInstance( + Ci.nsIInputStreamPump + ); pump.init(stream, 0, 0, false); // When we pass a null listener argument too asyncRead we expect it to throw // instead of crashing. try { pump.asyncRead(null, null); - } - catch (e) { + } catch (e) { return; } diff --git a/netwerk/test/unit/test_bug379034.js b/netwerk/test/unit/test_bug379034.js index 4e7809fdff3d..203cc78072de 100644 --- a/netwerk/test/unit/test_bug379034.js +++ b/netwerk/test/unit/test_bug379034.js @@ -1,6 +1,7 @@ function run_test() { - const ios = Cc["@mozilla.org/network/io-service;1"] - .getService(Ci.nsIIOService); + const ios = Cc["@mozilla.org/network/io-service;1"].getService( + Ci.nsIIOService + ); var base = ios.newURI("http://localhost/bug379034/index.html"); diff --git a/netwerk/test/unit/test_bug380994.js b/netwerk/test/unit/test_bug380994.js index 4ad5187dcd16..e30fc8c89ace 100644 --- a/netwerk/test/unit/test_bug380994.js +++ b/netwerk/test/unit/test_bug380994.js @@ -7,16 +7,18 @@ const specs = [ "resource:///chrome%2f%2e%2e%2fplugins", "resource:///../../../..", "resource:///..%2f..%2f..%2f..", - "resource:///%2e%2e" + "resource:///%2e%2e", ]; function run_test() { - var ios = Cc["@mozilla.org/network/io-service;1"]. - getService(Ci.nsIIOService); + var ios = Cc["@mozilla.org/network/io-service;1"].getService(Ci.nsIIOService); for (var spec of specs) { var uri = ios.newURI(spec); - if (uri.spec.includes("..")) - do_throw("resource: traversal remains: '"+spec+"' ==> '"+uri.spec+"'"); + if (uri.spec.includes("..")) { + do_throw( + "resource: traversal remains: '" + spec + "' ==> '" + uri.spec + "'" + ); + } } } diff --git a/netwerk/test/unit/test_bug388281.js b/netwerk/test/unit/test_bug388281.js index c40f8851b7a8..c45116aab8bd 100644 --- a/netwerk/test/unit/test_bug388281.js +++ b/netwerk/test/unit/test_bug388281.js @@ -1,24 +1,40 @@ function run_test() { - const ios = Cc["@mozilla.org/network/io-service;1"]. - getService(Ci.nsIIOService); + const ios = Cc["@mozilla.org/network/io-service;1"].getService( + Ci.nsIIOService + ); var uri = ios.newURI("http://foo.com/file.txt"); - uri = uri.mutate().setPort(90).finalize(); + uri = uri + .mutate() + .setPort(90) + .finalize(); Assert.equal(uri.hostPort, "foo.com:90"); uri = ios.newURI("http://foo.com:10/file.txt"); - uri = uri.mutate().setPort(500).finalize(); + uri = uri + .mutate() + .setPort(500) + .finalize(); Assert.equal(uri.hostPort, "foo.com:500"); uri = ios.newURI("http://foo.com:5000/file.txt"); - uri = uri.mutate().setPort(20).finalize(); + uri = uri + .mutate() + .setPort(20) + .finalize(); Assert.equal(uri.hostPort, "foo.com:20"); uri = ios.newURI("http://foo.com:5000/file.txt"); - uri = uri.mutate().setPort(-1).finalize(); + uri = uri + .mutate() + .setPort(-1) + .finalize(); Assert.equal(uri.hostPort, "foo.com"); uri = ios.newURI("http://foo.com:5000/file.txt"); - uri = uri.mutate().setPort(80).finalize(); + uri = uri + .mutate() + .setPort(80) + .finalize(); Assert.equal(uri.hostPort, "foo.com"); } diff --git a/netwerk/test/unit/test_bug396389.js b/netwerk/test/unit/test_bug396389.js index 0d870e5bbf7b..4b65b16f6e5c 100644 --- a/netwerk/test/unit/test_bug396389.js +++ b/netwerk/test/unit/test_bug396389.js @@ -1,33 +1,33 @@ function round_trip(uri) { - var objectOutStream = Cc["@mozilla.org/binaryoutputstream;1"]. - createInstance(Ci.nsIObjectOutputStream); + var objectOutStream = Cc["@mozilla.org/binaryoutputstream;1"].createInstance( + Ci.nsIObjectOutputStream + ); var pipe = Cc["@mozilla.org/pipe;1"].createInstance(Ci.nsIPipe); pipe.init(false, false, 0, 0xffffffff, null); objectOutStream.setOutputStream(pipe.outputStream); objectOutStream.writeCompoundObject(uri, Ci.nsISupports, true); objectOutStream.close(); - var objectInStream = Cc["@mozilla.org/binaryinputstream;1"]. - createInstance(Ci.nsIObjectInputStream); + var objectInStream = Cc["@mozilla.org/binaryinputstream;1"].createInstance( + Ci.nsIObjectInputStream + ); objectInStream.setInputStream(pipe.inputStream); return objectInStream.readObject(true).QueryInterface(Ci.nsIURI); } -var prefData = - [ - { - name: "network.IDN_show_punycode", - newVal: false - }, - { - name: "network.IDN.whitelist.ch", - newVal: true - } - ]; +var prefData = [ + { + name: "network.IDN_show_punycode", + newVal: false, + }, + { + name: "network.IDN.whitelist.ch", + newVal: true, + }, +]; function run_test() { - var ios = Cc["@mozilla.org/network/io-service;1"]. - getService(Ci.nsIIOService); + var ios = Cc["@mozilla.org/network/io-service;1"].getService(Ci.nsIIOService); var uri1 = ios.newURI("file:///"); Assert.ok(uri1 instanceof Ci.nsIFileURL); @@ -41,31 +41,32 @@ function run_test() { Assert.ok(uri1.equals(uri3)); // Make sure our prefs are set such that this test actually means something - var prefs = Cc["@mozilla.org/preferences-service;1"]. - getService(Ci.nsIPrefBranch); + var prefs = Cc["@mozilla.org/preferences-service;1"].getService( + Ci.nsIPrefBranch + ); for (var pref of prefData) { try { pref.oldVal = prefs.getBoolPref(pref.name); - } catch(e) { - } + } catch (e) {} prefs.setBoolPref(pref.name, pref.newVal); } - + try { // URI stolen from // http://lists.w3.org/Archives/Public/public-iri/2004Mar/0012.html var uri4 = ios.newURI("http://xn--jos-dma.example.net.ch/"); Assert.equal(uri4.asciiHost, "xn--jos-dma.example.net.ch"); Assert.equal(uri4.displayHost, "jos\u00e9.example.net.ch"); - + var uri5 = round_trip(uri4); Assert.ok(uri4.equals(uri5)); Assert.equal(uri4.displayHost, uri5.displayHost); Assert.equal(uri4.asciiHost, uri5.asciiHost); } finally { for (var pref of prefData) { - if (prefs.prefHasUserValue(pref.name)) + if (prefs.prefHasUserValue(pref.name)) { prefs.clearUserPref(pref.name); + } } } } diff --git a/netwerk/test/unit/test_bug401564.js b/netwerk/test/unit/test_bug401564.js index cc12095cb062..f4e8aead33e3 100644 --- a/netwerk/test/unit/test_bug401564.js +++ b/netwerk/test/unit/test_bug401564.js @@ -1,42 +1,38 @@ /* -*- indent-tabs-mode: nil; js-indent-level: 2 -*- */ "use strict"; -const {HttpServer} = ChromeUtils.import("resource://testing-common/httpd.js"); +const { HttpServer } = ChromeUtils.import("resource://testing-common/httpd.js"); var httpserver = null; const noRedirectURI = "/content"; const pageValue = "Final page"; const acceptType = "application/json"; -function redirectHandler(metadata, response) -{ +function redirectHandler(metadata, response) { response.setStatusLine(metadata.httpVersion, 302, "Moved Temporarily"); response.setHeader("Location", noRedirectURI, false); } -function contentHandler(metadata, response) -{ +function contentHandler(metadata, response) { Assert.equal(metadata.getHeader("Accept"), acceptType); httpserver.stop(do_test_finished); } -function dummyHandler(request, buffer) -{ -} +function dummyHandler(request, buffer) {} -function run_test() -{ +function run_test() { httpserver = new HttpServer(); httpserver.registerPathHandler("/redirect", redirectHandler); httpserver.registerPathHandler("/content", contentHandler); httpserver.start(-1); - var prefs = Cc["@mozilla.org/preferences-service;1"] - .getService(Ci.nsIPrefBranch); + var prefs = Cc["@mozilla.org/preferences-service;1"].getService( + Ci.nsIPrefBranch + ); prefs.setBoolPref("network.http.prompt-temp-redirect", false); var chan = NetUtil.newChannel({ uri: "http://localhost:" + httpserver.identity.primaryPort + "/redirect", - loadUsingSystemPrincipal: true + loadUsingSystemPrincipal: true, }); chan.QueryInterface(Ci.nsIHttpChannel); chan.setRequestHeader("Accept", acceptType, false); diff --git a/netwerk/test/unit/test_bug411952.js b/netwerk/test/unit/test_bug411952.js index a16573a5316d..dc49e01511df 100644 --- a/netwerk/test/unit/test_bug411952.js +++ b/netwerk/test/unit/test_bug411952.js @@ -1,25 +1,41 @@ function run_test() { try { - var cm = Cc["@mozilla.org/cookiemanager;1"]. - getService(Ci.nsICookieManager); + var cm = Cc["@mozilla.org/cookiemanager;1"].getService(Ci.nsICookieManager); Assert.notEqual(cm, null, "Retrieving the cookie manager failed"); - const time = (new Date("Jan 1, 2030")).getTime() / 1000; - cm.add("example.com", "/", "C", "V", false, true, false, time, {}, Ci.nsICookie.SAMESITE_NONE); - const now = Math.floor((new Date()).getTime() / 1000); + const time = new Date("Jan 1, 2030").getTime() / 1000; + cm.add( + "example.com", + "/", + "C", + "V", + false, + true, + false, + time, + {}, + Ci.nsICookie.SAMESITE_NONE + ); + const now = Math.floor(new Date().getTime() / 1000); var found = false; for (let cookie of cm.enumerator) { - if (cookie.host == "example.com" && - cookie.path == "/" && - cookie.name == "C") { - Assert.ok("creationTime" in cookie, - "creationTime attribute is not accessible on the cookie"); + if ( + cookie.host == "example.com" && + cookie.path == "/" && + cookie.name == "C" + ) { + Assert.ok( + "creationTime" in cookie, + "creationTime attribute is not accessible on the cookie" + ); var creationTime = Math.floor(cookie.creationTime / 1000000); // allow the times to slip by one second at most, // which should be fine under normal circumstances. - Assert.ok(Math.abs(creationTime - now) <= 1, - "Cookie's creationTime is set incorrectly"); + Assert.ok( + Math.abs(creationTime - now) <= 1, + "Cookie's creationTime is set incorrectly" + ); found = true; break; } diff --git a/netwerk/test/unit/test_bug412457.js b/netwerk/test/unit/test_bug412457.js index 13b5784cc3fa..7166f3bf694f 100644 --- a/netwerk/test/unit/test_bug412457.js +++ b/netwerk/test/unit/test_bug412457.js @@ -1,45 +1,115 @@ function run_test() { - var ios = Cc["@mozilla.org/network/io-service;1"]. - getService(Ci.nsIIOService); + var ios = Cc["@mozilla.org/network/io-service;1"].getService(Ci.nsIIOService); // check if hostname is unescaped before applying IDNA var newURI = ios.newURI("http://\u5341%2ecom/"); Assert.equal(newURI.asciiHost, "xn--kkr.com"); // escaped UTF8 - newURI = newURI.mutate().setSpec("http://%e5%8d%81.com").finalize(); + newURI = newURI + .mutate() + .setSpec("http://%e5%8d%81.com") + .finalize(); Assert.equal(newURI.asciiHost, "xn--kkr.com"); // There should be only allowed characters in hostname after // unescaping and attempting to apply IDNA. "\x80" is illegal in // UTF-8, so IDNA fails, and 0x80 is illegal in DNS too. - Assert.throws(() => { newURI = newURI.mutate().setSpec("http://%80.com").finalize(); }, - /NS_ERROR_UNEXPECTED/, "illegal UTF character"); + Assert.throws( + () => { + newURI = newURI + .mutate() + .setSpec("http://%80.com") + .finalize(); + }, + /NS_ERROR_UNEXPECTED/, + "illegal UTF character" + ); // test parsing URL with all possible host terminators - newURI = newURI.mutate().setSpec("http://example.com?foo").finalize(); + newURI = newURI + .mutate() + .setSpec("http://example.com?foo") + .finalize(); Assert.equal(newURI.asciiHost, "example.com"); - newURI = newURI.mutate().setSpec("http://example.com#foo").finalize(); + newURI = newURI + .mutate() + .setSpec("http://example.com#foo") + .finalize(); Assert.equal(newURI.asciiHost, "example.com"); - newURI = newURI.mutate().setSpec("http://example.com:80").finalize(); + newURI = newURI + .mutate() + .setSpec("http://example.com:80") + .finalize(); Assert.equal(newURI.asciiHost, "example.com"); - newURI = newURI.mutate().setSpec("http://example.com/foo").finalize(); + newURI = newURI + .mutate() + .setSpec("http://example.com/foo") + .finalize(); Assert.equal(newURI.asciiHost, "example.com"); // Characters that are invalid in the host - Assert.throws(() => { newURI = newURI.mutate().setSpec("http://example.com%3ffoo").finalize(); }, - /NS_ERROR_MALFORMED_URI/, "bad escaped character"); - Assert.throws(() => { newURI = newURI.mutate().setSpec("http://example.com%23foo").finalize(); }, - /NS_ERROR_MALFORMED_URI/, "bad escaped character"); - Assert.throws(() => { newURI = newURI.mutate().setSpec("http://example.com%3bfoo").finalize(); }, - /NS_ERROR_MALFORMED_URI/, "bad escaped character"); - Assert.throws(() => { newURI = newURI.mutate().setSpec("http://example.com%3a80").finalize(); }, - /NS_ERROR_MALFORMED_URI/, "bad escaped character"); - Assert.throws(() => { newURI = newURI.mutate().setSpec("http://example.com%2ffoo").finalize(); }, - /NS_ERROR_MALFORMED_URI/, "bad escaped character"); - Assert.throws(() => { newURI = newURI.mutate().setSpec("http://example.com%00").finalize(); }, - /NS_ERROR_MALFORMED_URI/, "bad escaped character"); + Assert.throws( + () => { + newURI = newURI + .mutate() + .setSpec("http://example.com%3ffoo") + .finalize(); + }, + /NS_ERROR_MALFORMED_URI/, + "bad escaped character" + ); + Assert.throws( + () => { + newURI = newURI + .mutate() + .setSpec("http://example.com%23foo") + .finalize(); + }, + /NS_ERROR_MALFORMED_URI/, + "bad escaped character" + ); + Assert.throws( + () => { + newURI = newURI + .mutate() + .setSpec("http://example.com%3bfoo") + .finalize(); + }, + /NS_ERROR_MALFORMED_URI/, + "bad escaped character" + ); + Assert.throws( + () => { + newURI = newURI + .mutate() + .setSpec("http://example.com%3a80") + .finalize(); + }, + /NS_ERROR_MALFORMED_URI/, + "bad escaped character" + ); + Assert.throws( + () => { + newURI = newURI + .mutate() + .setSpec("http://example.com%2ffoo") + .finalize(); + }, + /NS_ERROR_MALFORMED_URI/, + "bad escaped character" + ); + Assert.throws( + () => { + newURI = newURI + .mutate() + .setSpec("http://example.com%00") + .finalize(); + }, + /NS_ERROR_MALFORMED_URI/, + "bad escaped character" + ); } diff --git a/netwerk/test/unit/test_bug412945.js b/netwerk/test/unit/test_bug412945.js index 2a1ba234a804..958a01a46aa8 100644 --- a/netwerk/test/unit/test_bug412945.js +++ b/netwerk/test/unit/test_bug412945.js @@ -1,16 +1,14 @@ -const {HttpServer} = ChromeUtils.import("resource://testing-common/httpd.js"); +const { HttpServer } = ChromeUtils.import("resource://testing-common/httpd.js"); var httpserv; -function TestListener() { -} +function TestListener() {} -TestListener.prototype.onStartRequest = function(request) { -} +TestListener.prototype.onStartRequest = function(request) {}; TestListener.prototype.onStopRequest = function(request, status) { httpserv.stop(do_test_finished); -} +}; function run_test() { httpserv = new HttpServer(); @@ -22,7 +20,7 @@ function run_test() { // make request var channel = NetUtil.newChannel({ uri: "http://localhost:" + httpserv.identity.primaryPort + "/bug412945", - loadUsingSystemPrincipal: true + loadUsingSystemPrincipal: true, }); channel.QueryInterface(Ci.nsIHttpChannel); @@ -33,9 +31,10 @@ function run_test() { } function bug412945(metadata, response) { - if (!metadata.hasHeader("Content-Length") || - metadata.getHeader("Content-Length") != "0") - { + if ( + !metadata.hasHeader("Content-Length") || + metadata.getHeader("Content-Length") != "0" + ) { do_throw("Content-Length header not found!"); } } diff --git a/netwerk/test/unit/test_bug414122.js b/netwerk/test/unit/test_bug414122.js index c843bced329d..072bfe239331 100644 --- a/netwerk/test/unit/test_bug414122.js +++ b/netwerk/test/unit/test_bug414122.js @@ -1,57 +1,59 @@ const PR_RDONLY = 0x1; -var etld = Cc["@mozilla.org/network/effective-tld-service;1"] - .getService(Ci.nsIEffectiveTLDService); -var idn = Cc["@mozilla.org/network/idn-service;1"] - .getService(Ci.nsIIDNService); +var etld = Cc["@mozilla.org/network/effective-tld-service;1"].getService( + Ci.nsIEffectiveTLDService +); +var idn = Cc["@mozilla.org/network/idn-service;1"].getService(Ci.nsIIDNService); -function run_test() -{ - var fis = Cc["@mozilla.org/network/file-input-stream;1"] - .createInstance(Ci.nsIFileInputStream); - fis.init(do_get_file("effective_tld_names.dat"), - PR_RDONLY, 0o444, Ci.nsIFileInputStream.CLOSE_ON_EOF); +function run_test() { + var fis = Cc["@mozilla.org/network/file-input-stream;1"].createInstance( + Ci.nsIFileInputStream + ); + fis.init( + do_get_file("effective_tld_names.dat"), + PR_RDONLY, + 0o444, + Ci.nsIFileInputStream.CLOSE_ON_EOF + ); - var lis = Cc["@mozilla.org/intl/converter-input-stream;1"] - .createInstance(Ci.nsIConverterInputStream); + var lis = Cc["@mozilla.org/intl/converter-input-stream;1"].createInstance( + Ci.nsIConverterInputStream + ); lis.init(fis, "UTF-8", 1024, 0); lis.QueryInterface(Ci.nsIUnicharLineInputStream); var out = { value: "" }; - do - { + do { var more = lis.readLine(out); var line = out.value; line = line.replace(/^\s+/, ""); var firstTwo = line.substring(0, 2); // a misnomer, but whatever - if (firstTwo == "" || firstTwo == "//") + if (firstTwo == "" || firstTwo == "//") { continue; + } var space = line.search(/[ \t]/); line = line.substring(0, space == -1 ? line.length : space); - if ("*." == firstTwo) - { + if ("*." == firstTwo) { let rest = line.substring(2); - checkPublicSuffix("foo.SUPER-SPECIAL-AWESOME-PREFIX." + rest, - "SUPER-SPECIAL-AWESOME-PREFIX." + rest); - } - else if ("!" == line.charAt(0)) - { - checkPublicSuffix(line.substring(1), - line.substring(line.indexOf(".") + 1)); - } - else - { + checkPublicSuffix( + "foo.SUPER-SPECIAL-AWESOME-PREFIX." + rest, + "SUPER-SPECIAL-AWESOME-PREFIX." + rest + ); + } else if ("!" == line.charAt(0)) { + checkPublicSuffix( + line.substring(1), + line.substring(line.indexOf(".") + 1) + ); + } else { checkPublicSuffix("SUPER-SPECIAL-AWESOME-PREFIX." + line, line); } - } - while (more); + } while (more); } -function checkPublicSuffix(host, expectedSuffix) -{ +function checkPublicSuffix(host, expectedSuffix) { expectedSuffix = idn.convertUTF8toACE(expectedSuffix).toLowerCase(); var actualSuffix = etld.getPublicSuffixFromHost(host); Assert.equal(actualSuffix, expectedSuffix); diff --git a/netwerk/test/unit/test_bug427957.js b/netwerk/test/unit/test_bug427957.js index 3b404c213a1c..10697aa3f421 100644 --- a/netwerk/test/unit/test_bug427957.js +++ b/netwerk/test/unit/test_bug427957.js @@ -4,34 +4,33 @@ var idnService; -function expected_pass(inputIDN) -{ +function expected_pass(inputIDN) { var isASCII = {}; var displayIDN = idnService.convertToDisplayIDN(inputIDN, isASCII); Assert.equal(displayIDN, inputIDN); } -function expected_fail(inputIDN) -{ +function expected_fail(inputIDN) { var isASCII = {}; var displayIDN = ""; try { displayIDN = idnService.convertToDisplayIDN(inputIDN, isASCII); - } - catch(e) {} + } catch (e) {} Assert.notEqual(displayIDN, inputIDN); } function run_test() { - // add an IDN whitelist pref - var pbi = Cc["@mozilla.org/preferences-service;1"] - .getService(Ci.nsIPrefBranch); + // add an IDN whitelist pref + var pbi = Cc["@mozilla.org/preferences-service;1"].getService( + Ci.nsIPrefBranch + ); pbi.setBoolPref("network.IDN.whitelist.com", true); - - idnService = Cc["@mozilla.org/network/idn-service;1"] - .getService(Ci.nsIIDNService); + + idnService = Cc["@mozilla.org/network/idn-service;1"].getService( + Ci.nsIIDNService + ); /* * In any profile that specifies bidirectional character handling, all * three of the following requirements MUST be met: @@ -47,7 +46,9 @@ function run_test() { expected_fail("foo\200ebar.com"); // 200F; RIGHT-TO-LEFT MARK // Note: this is an RTL IDN so that it doesn't fail test 2) below - expected_fail("\u200f\u0645\u062B\u0627\u0644.\u0622\u0632\u0645\u0627\u06CC\u0634\u06CC"); + expected_fail( + "\u200f\u0645\u062B\u0627\u0644.\u0622\u0632\u0645\u0627\u06CC\u0634\u06CC" + ); // 202A; LEFT-TO-RIGHT EMBEDDING expected_fail("foo\u202abar.com"); // 202B; RIGHT-TO-LEFT EMBEDDING @@ -74,7 +75,7 @@ function run_test() { /* * 2) If a string contains any RandALCat character, the string MUST NOT * contain any LCat character. - */ + */ // www.מיץpetel.com is invalid expected_fail("www.\u05DE\u05D9\u05E5petel.com"); @@ -101,4 +102,3 @@ function run_test() { // But www.מיץ1פטל.com is fine expected_pass("www.\u05DE\u05D9\u05E51\u05E4\u05D8\u05DC.com"); } - diff --git a/netwerk/test/unit/test_bug429347.js b/netwerk/test/unit/test_bug429347.js index df231e5737a9..cd4d865c695a 100644 --- a/netwerk/test/unit/test_bug429347.js +++ b/netwerk/test/unit/test_bug429347.js @@ -1,38 +1,73 @@ function run_test() { - var ios = Cc["@mozilla.org/network/io-service;1"]. - getService(Ci.nsIIOService); + var ios = Cc["@mozilla.org/network/io-service;1"].getService(Ci.nsIIOService); var uri1 = ios.newURI("http://example.com#bar"); var uri2 = ios.newURI("http://example.com/#bar"); Assert.ok(uri1.equals(uri2)); - uri1 = uri1.mutate().setSpec("http://example.com?bar").finalize(); - uri2 = uri2.mutate().setSpec("http://example.com/?bar").finalize(); + uri1 = uri1 + .mutate() + .setSpec("http://example.com?bar") + .finalize(); + uri2 = uri2 + .mutate() + .setSpec("http://example.com/?bar") + .finalize(); Assert.ok(uri1.equals(uri2)); // see https://bugzilla.mozilla.org/show_bug.cgi?id=665706 // ";" is not parsed as special anymore and thus ends up // in the authority component (see RFC 3986) - uri1 = uri1.mutate().setSpec("http://example.com;bar").finalize(); - uri2 = uri2.mutate().setSpec("http://example.com/;bar").finalize(); + uri1 = uri1 + .mutate() + .setSpec("http://example.com;bar") + .finalize(); + uri2 = uri2 + .mutate() + .setSpec("http://example.com/;bar") + .finalize(); Assert.ok(!uri1.equals(uri2)); - uri1 = uri1.mutate().setSpec("http://example.com#").finalize(); - uri2 = uri2.mutate().setSpec("http://example.com/#").finalize(); + uri1 = uri1 + .mutate() + .setSpec("http://example.com#") + .finalize(); + uri2 = uri2 + .mutate() + .setSpec("http://example.com/#") + .finalize(); Assert.ok(uri1.equals(uri2)); - uri1 = uri1.mutate().setSpec("http://example.com?").finalize(); - uri2 = uri2.mutate().setSpec("http://example.com/?").finalize(); + uri1 = uri1 + .mutate() + .setSpec("http://example.com?") + .finalize(); + uri2 = uri2 + .mutate() + .setSpec("http://example.com/?") + .finalize(); Assert.ok(uri1.equals(uri2)); // see https://bugzilla.mozilla.org/show_bug.cgi?id=665706 // ";" is not parsed as special anymore and thus ends up // in the authority component (see RFC 3986) - uri1 = uri1.mutate().setSpec("http://example.com;").finalize(); - uri2 = uri2.mutate().setSpec("http://example.com/;").finalize(); + uri1 = uri1 + .mutate() + .setSpec("http://example.com;") + .finalize(); + uri2 = uri2 + .mutate() + .setSpec("http://example.com/;") + .finalize(); Assert.ok(!uri1.equals(uri2)); - uri1 = uri1.mutate().setSpec("http://example.com").finalize(); - uri2 = uri2.mutate().setSpec("http://example.com/").finalize(); + uri1 = uri1 + .mutate() + .setSpec("http://example.com") + .finalize(); + uri2 = uri2 + .mutate() + .setSpec("http://example.com/") + .finalize(); Assert.ok(uri1.equals(uri2)); } diff --git a/netwerk/test/unit/test_bug455311.js b/netwerk/test/unit/test_bug455311.js index f9be99f2e02a..395147a034d6 100644 --- a/netwerk/test/unit/test_bug455311.js +++ b/netwerk/test/unit/test_bug455311.js @@ -1,6 +1,4 @@ - -function getLinkFile() -{ +function getLinkFile() { if (mozinfo.os == "win") { return do_get_file("test_link.url"); } @@ -15,20 +13,20 @@ const ios = Cc["@mozilla.org/network/io-service;1"].getService(Ci.nsIIOService); var link; var linkURI; const newURI = ios.newURI("http://www.mozilla.org/"); - -function NotificationCallbacks(origURI, newURI) -{ + +function NotificationCallbacks(origURI, newURI) { this._origURI = origURI; this._newURI = newURI; } NotificationCallbacks.prototype = { - QueryInterface: ChromeUtils.generateQI(["nsIInterfaceRequestor", "nsIChannelEventSink"]), - getInterface (iid) - { + QueryInterface: ChromeUtils.generateQI([ + "nsIInterfaceRequestor", + "nsIChannelEventSink", + ]), + getInterface(iid) { return this.QueryInterface(iid); }, - asyncOnChannelRedirect(oldChan, newChan, flags, callback) - { + asyncOnChannelRedirect(oldChan, newChan, flags, callback) { Assert.equal(oldChan.URI.spec, this._origURI.spec); Assert.equal(oldChan.URI, this._origURI); Assert.equal(oldChan.originalURI.spec, this._origURI.spec); @@ -37,31 +35,30 @@ NotificationCallbacks.prototype = { Assert.equal(newChan.originalURI, newChan.URI); Assert.equal(newChan.URI.spec, this._newURI.spec); throw Cr.NS_ERROR_ABORT; - } + }, }; -function RequestObserver(origURI, newURI, nextTest) -{ +function RequestObserver(origURI, newURI, nextTest) { this._origURI = origURI; this._newURI = newURI; this._nextTest = nextTest; } RequestObserver.prototype = { - QueryInterface: ChromeUtils.generateQI(["nsIRequestObserver", "nsIStreamListener"]), - onStartRequest (req) - { + QueryInterface: ChromeUtils.generateQI([ + "nsIRequestObserver", + "nsIStreamListener", + ]), + onStartRequest(req) { var chan = req.QueryInterface(Ci.nsIChannel); Assert.equal(chan.URI.spec, this._origURI.spec); Assert.equal(chan.URI, this._origURI); Assert.equal(chan.originalURI.spec, this._origURI.spec); Assert.equal(chan.originalURI, this._origURI); }, - onDataAvailable(req, stream, offset, count) - { + onDataAvailable(req, stream, offset, count) { do_throw("Unexpected call to onDataAvailable"); }, - onStopRequest (req, status) - { + onStopRequest(req, status) { var chan = req.QueryInterface(Ci.nsIChannel); try { Assert.equal(chan.URI.spec, this._origURI.spec); @@ -70,16 +67,15 @@ RequestObserver.prototype = { Assert.equal(chan.originalURI, this._origURI); Assert.equal(status, Cr.NS_ERROR_ABORT); Assert.ok(!chan.isPending()); - } catch(e) {} + } catch (e) {} this._nextTest(); - } + }, }; -function test_cancel() -{ +function test_cancel() { var chan = NetUtil.newChannel({ uri: linkURI, - loadUsingSystemPrincipal: true + loadUsingSystemPrincipal: true, }); Assert.equal(chan.URI, linkURI); Assert.equal(chan.originalURI, linkURI); @@ -89,8 +85,7 @@ function test_cancel() Assert.ok(chan.isPending()); } -function run_test() -{ +function run_test() { if (mozinfo.os != "win" && mozinfo.os != "linux") { return; } @@ -101,7 +96,7 @@ function run_test() do_test_pending(); var chan = NetUtil.newChannel({ uri: linkURI, - loadUsingSystemPrincipal: true + loadUsingSystemPrincipal: true, }); Assert.equal(chan.URI, linkURI); Assert.equal(chan.originalURI, linkURI); diff --git a/netwerk/test/unit/test_bug464591.js b/netwerk/test/unit/test_bug464591.js index 87d47b02465c..0201cd0ea91c 100644 --- a/netwerk/test/unit/test_bug464591.js +++ b/netwerk/test/unit/test_bug464591.js @@ -1,71 +1,78 @@ - // 1.percent-encoded IDN that contains blacklisted character should be converted - // to punycode, not UTF-8 string - // 2.only hostname-valid percent encoded ASCII characters should be decoded - // 3.IDN convertion must not bypassed by %00 +// 1.percent-encoded IDN that contains blacklisted character should be converted +// to punycode, not UTF-8 string +// 2.only hostname-valid percent encoded ASCII characters should be decoded +// 3.IDN convertion must not bypassed by %00 let reference = [ - ["www.example.com%e2%88%95www.mozill%d0%b0.com%e2%81%84www.mozilla.org", - "www.example.xn--comwww-re3c.xn--mozill-8nf.xn--comwww-rq0c.mozilla.org"], + [ + "www.example.com%e2%88%95www.mozill%d0%b0.com%e2%81%84www.mozilla.org", + "www.example.xn--comwww-re3c.xn--mozill-8nf.xn--comwww-rq0c.mozilla.org", + ], ]; let badURIs = [ - ["www.mozill%61%2f.org"], // a slash is not valid in the hostname - ["www.e%00xample.com%e2%88%95www.mozill%d0%b0.com%e2%81%84www.mozill%61.org"], -] + ["www.mozill%61%2f.org"], // a slash is not valid in the hostname + ["www.e%00xample.com%e2%88%95www.mozill%d0%b0.com%e2%81%84www.mozill%61.org"], +]; -let prefData = - [ - { - name: "network.enableIDN", - newVal: true - }, - { - name: "network.IDN_show_punycode", - newVal: false - }, - { - name: "network.IDN.whitelist.org", - newVal: true - } - ]; +let prefData = [ + { + name: "network.enableIDN", + newVal: true, + }, + { + name: "network.IDN_show_punycode", + newVal: false, + }, + { + name: "network.IDN.whitelist.org", + newVal: true, + }, +]; - let prefIdnBlackList = { - name: "network.IDN.extra_blocked_chars", - minimumList: "\u2215\u0430\u2044", - }; +let prefIdnBlackList = { + name: "network.IDN.extra_blocked_chars", + minimumList: "\u2215\u0430\u2044", +}; function stringToURL(str) { return Cc["@mozilla.org/network/standard-url-mutator;1"] - .createInstance(Ci.nsIStandardURLMutator) - .init(Ci.nsIStandardURL.URLTYPE_AUTHORITY, 80, str, "UTF-8", null) - .finalize() - .QueryInterface(Ci.nsIURL); + .createInstance(Ci.nsIStandardURLMutator) + .init(Ci.nsIStandardURL.URLTYPE_AUTHORITY, 80, str, "UTF-8", null) + .finalize() + .QueryInterface(Ci.nsIURL); } function run_test() { // Make sure our prefs are set such that this test actually means something - let prefs = Cc["@mozilla.org/preferences-service;1"]. - getService(Ci.nsIPrefBranch); + let prefs = Cc["@mozilla.org/preferences-service;1"].getService( + Ci.nsIPrefBranch + ); for (let pref of prefData) { prefs.setBoolPref(pref.name, pref.newVal); } prefIdnBlackList.set = false; try { - prefIdnBlackList.oldVal = prefs.getComplexValue(prefIdnBlackList.name, - Ci.nsIPrefLocalizedString).data; - prefs.getComplexValue(prefIdnBlackList.name, - Ci.nsIPrefLocalizedString).data=prefIdnBlackList.minimumList; + prefIdnBlackList.oldVal = prefs.getComplexValue( + prefIdnBlackList.name, + Ci.nsIPrefLocalizedString + ).data; + prefs.getComplexValue( + prefIdnBlackList.name, + Ci.nsIPrefLocalizedString + ).data = prefIdnBlackList.minimumList; prefIdnBlackList.set = true; - } catch (e) { - } + } catch (e) {} registerCleanupFunction(function() { for (let pref of prefData) { prefs.clearUserPref(pref.name); } if (prefIdnBlackList.set) { - prefs.getComplexValue(prefIdnBlackList.name, - Ci.nsIPrefLocalizedString).data = prefIdnBlackList.oldVal; + prefs.getComplexValue( + prefIdnBlackList.name, + Ci.nsIPrefLocalizedString + ).data = prefIdnBlackList.oldVal; } }); @@ -74,12 +81,17 @@ function run_test() { let result = stringToURL("http://" + reference[i][0]).host; equal(result, reference[i][1]); } catch (e) { - ok(false, "Error testing "+reference[i][0]); + ok(false, "Error testing " + reference[i][0]); } } for (let i = 0; i < badURIs.length; ++i) { - Assert.throws(() => { let result = stringToURL("http://" + badURIs[i][0]).host; }, - /NS_ERROR_MALFORMED_URI/, "bad escaped character"); + Assert.throws( + () => { + let result = stringToURL("http://" + badURIs[i][0]).host; + }, + /NS_ERROR_MALFORMED_URI/, + "bad escaped character" + ); } } diff --git a/netwerk/test/unit/test_bug468426.js b/netwerk/test/unit/test_bug468426.js index 20e683b76c54..03ab14f916cc 100644 --- a/netwerk/test/unit/test_bug468426.js +++ b/netwerk/test/unit/test_bug468426.js @@ -1,99 +1,127 @@ -const {HttpServer} = ChromeUtils.import("resource://testing-common/httpd.js"); +const { HttpServer } = ChromeUtils.import("resource://testing-common/httpd.js"); var httpserver = new HttpServer(); var index = 0; var tests = [ - // Initial request. Cached variant will have no cookie - { url : "/bug468426", server : "0", expected : "0", cookie: null}, + // Initial request. Cached variant will have no cookie + { url: "/bug468426", server: "0", expected: "0", cookie: null }, - // Cache now contains a variant with no value for cookie. If we don't - // set cookie we expect to receive the cached variant - { url : "/bug468426", server : "1", expected : "0", cookie: null}, + // Cache now contains a variant with no value for cookie. If we don't + // set cookie we expect to receive the cached variant + { url: "/bug468426", server: "1", expected: "0", cookie: null }, - // Cache still contains a variant with no value for cookie. If we - // set a value for cookie we expect a fresh value - { url : "/bug468426", server : "2", expected : "2", cookie: "c=2"}, + // Cache still contains a variant with no value for cookie. If we + // set a value for cookie we expect a fresh value + { url: "/bug468426", server: "2", expected: "2", cookie: "c=2" }, - // Cache now contains a variant with cookie "c=2". If the request - // also set cookie "c=2", we expect to receive the cached variant. - { url : "/bug468426", server : "3", expected : "2", cookie: "c=2"}, + // Cache now contains a variant with cookie "c=2". If the request + // also set cookie "c=2", we expect to receive the cached variant. + { url: "/bug468426", server: "3", expected: "2", cookie: "c=2" }, - // Cache still contains a variant with cookie "c=2". When setting - // cookie "c=4" in the request we expect a fresh value - { url : "/bug468426", server : "4", expected : "4", cookie: "c=4"}, + // Cache still contains a variant with cookie "c=2". When setting + // cookie "c=4" in the request we expect a fresh value + { url: "/bug468426", server: "4", expected: "4", cookie: "c=4" }, - // Cache now contains a variant with cookie "c=4". When setting - // cookie "c=4" in the request we expect the cached variant - { url : "/bug468426", server : "5", expected : "4", cookie: "c=4"}, - - // Cache still contains a variant with cookie "c=4". When setting - // no cookie in the request we expect a fresh value - { url : "/bug468426", server : "6", expected : "6", cookie: null}, + // Cache now contains a variant with cookie "c=4". When setting + // cookie "c=4" in the request we expect the cached variant + { url: "/bug468426", server: "5", expected: "4", cookie: "c=4" }, + // Cache still contains a variant with cookie "c=4". When setting + // no cookie in the request we expect a fresh value + { url: "/bug468426", server: "6", expected: "6", cookie: null }, ]; function setupChannel(suffix, value, cookie) { - var chan = NetUtil.newChannel({ - uri: "http://localhost:" + httpserver.identity.primaryPort + suffix, - loadUsingSystemPrincipal: true - }) - var httpChan = chan.QueryInterface(Ci.nsIHttpChannel); - httpChan.requestMethod = "GET"; - httpChan.setRequestHeader("x-request", value, false); - if (cookie != null) - httpChan.setRequestHeader("Cookie", cookie, false); - return httpChan; + var chan = NetUtil.newChannel({ + uri: "http://localhost:" + httpserver.identity.primaryPort + suffix, + loadUsingSystemPrincipal: true, + }); + var httpChan = chan.QueryInterface(Ci.nsIHttpChannel); + httpChan.requestMethod = "GET"; + httpChan.setRequestHeader("x-request", value, false); + if (cookie != null) { + httpChan.setRequestHeader("Cookie", cookie, false); + } + return httpChan; } function triggerNextTest() { - var channel = setupChannel(tests[index].url, tests[index].server, tests[index].cookie); - channel.asyncOpen(new ChannelListener(checkValueAndTrigger, null)); + var channel = setupChannel( + tests[index].url, + tests[index].server, + tests[index].cookie + ); + channel.asyncOpen(new ChannelListener(checkValueAndTrigger, null)); } function checkValueAndTrigger(request, data, ctx) { - Assert.equal(tests[index].expected, data); + Assert.equal(tests[index].expected, data); - if (index < tests.length - 1) { - index++; - // This call happens in onStopRequest from the channel. Opening a new - // channel to the same url here is no good idea! Post it instead... - do_timeout(1, triggerNextTest); - } else { - httpserver.stop(do_test_finished); - } + if (index < tests.length - 1) { + index++; + // This call happens in onStopRequest from the channel. Opening a new + // channel to the same url here is no good idea! Post it instead... + do_timeout(1, triggerNextTest); + } else { + httpserver.stop(do_test_finished); + } } function run_test() { - httpserver.registerPathHandler("/bug468426", handler); - httpserver.start(-1); + httpserver.registerPathHandler("/bug468426", handler); + httpserver.start(-1); - // Clear cache and trigger the first test - evict_cache_entries(); - triggerNextTest(); + // Clear cache and trigger the first test + evict_cache_entries(); + triggerNextTest(); - do_test_pending(); + do_test_pending(); } function handler(metadata, response) { - var body = "unset"; - try { - body = metadata.getHeader("x-request"); - } catch(e) { } - response.setStatusLine(metadata.httpVersion, 200, "Ok"); - response.setHeader("Content-Type", "text/plain", false); - response.setHeader("Last-Modified", getDateString(-1), false); - response.setHeader("Vary", "Cookie", false); - response.bodyOutputStream.write(body, body.length); + var body = "unset"; + try { + body = metadata.getHeader("x-request"); + } catch (e) {} + response.setStatusLine(metadata.httpVersion, 200, "Ok"); + response.setHeader("Content-Type", "text/plain", false); + response.setHeader("Last-Modified", getDateString(-1), false); + response.setHeader("Vary", "Cookie", false); + response.bodyOutputStream.write(body, body.length); } function getDateString(yearDelta) { - var months = [ 'Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', - 'Sep', 'Oct', 'Nov', 'Dec' ]; - var days = [ 'Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat' ]; + var months = [ + "Jan", + "Feb", + "Mar", + "Apr", + "May", + "Jun", + "Jul", + "Aug", + "Sep", + "Oct", + "Nov", + "Dec", + ]; + var days = ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"]; - var d = new Date(); - return days[d.getUTCDay()] + ", " + d.getUTCDate() + " " - + months[d.getUTCMonth()] + " " + (d.getUTCFullYear() + yearDelta) - + " " + d.getUTCHours() + ":" + d.getUTCMinutes() + ":" - + d.getUTCSeconds() + " UTC"; + var d = new Date(); + return ( + days[d.getUTCDay()] + + ", " + + d.getUTCDate() + + " " + + months[d.getUTCMonth()] + + " " + + (d.getUTCFullYear() + yearDelta) + + " " + + d.getUTCHours() + + ":" + + d.getUTCMinutes() + + ":" + + d.getUTCSeconds() + + " UTC" + ); } diff --git a/netwerk/test/unit/test_bug468594.js b/netwerk/test/unit/test_bug468594.js index da0dbf860e56..eb1d345c4de9 100644 --- a/netwerk/test/unit/test_bug468594.js +++ b/netwerk/test/unit/test_bug468594.js @@ -13,114 +13,162 @@ // Please see RFC 2616 section 13.2.1 6th paragraph for the // definition of "explicit expiration time" being used here. -const {HttpServer} = ChromeUtils.import("resource://testing-common/httpd.js"); +const { HttpServer } = ChromeUtils.import("resource://testing-common/httpd.js"); var httpserver = new HttpServer(); var index = 0; var tests = [ - {url: "/freshness", server: "0", expected: "0"}, - {url: "/freshness", server: "1", expected: "0"}, // cached + { url: "/freshness", server: "0", expected: "0" }, + { url: "/freshness", server: "1", expected: "0" }, // cached - // RFC 2616 section 13.9 2nd paragraph says not to heuristically cache - // querystring, but we allow it to maintain web compat - {url: "/freshness?a", server: "2", expected: "2"}, - {url: "/freshness?a", server: "3", expected: "2"}, + // RFC 2616 section 13.9 2nd paragraph says not to heuristically cache + // querystring, but we allow it to maintain web compat + { url: "/freshness?a", server: "2", expected: "2" }, + { url: "/freshness?a", server: "3", expected: "2" }, - // explicit expiration dates in the future should be cached - {url: "/freshness?b", server: "4", expected: "4", - responseheader: "Expires: "+getDateString(1)}, - {url: "/freshness?b", server: "5", expected: "4"},// cached due to Expires + // explicit expiration dates in the future should be cached + { + url: "/freshness?b", + server: "4", + expected: "4", + responseheader: "Expires: " + getDateString(1), + }, + { url: "/freshness?b", server: "5", expected: "4" }, // cached due to Expires - {url: "/freshness?c", server: "6", expected: "6", - responseheader: "Cache-Control: max-age=3600"}, - {url: "/freshness?c", server: "7", expected: "6"}, // cached due to max-age + { + url: "/freshness?c", + server: "6", + expected: "6", + responseheader: "Cache-Control: max-age=3600", + }, + { url: "/freshness?c", server: "7", expected: "6" }, // cached due to max-age - // explicit expiration dates in the past should NOT be cached - {url: "/freshness?d", server: "8", expected: "8", - responseheader: "Expires: "+getDateString(-1)}, - {url: "/freshness?d", server: "9", expected: "9"}, + // explicit expiration dates in the past should NOT be cached + { + url: "/freshness?d", + server: "8", + expected: "8", + responseheader: "Expires: " + getDateString(-1), + }, + { url: "/freshness?d", server: "9", expected: "9" }, - {url: "/freshness?e", server: "10", expected: "10", - responseheader: "Cache-Control: max-age=0"}, - {url: "/freshness?e", server: "11", expected: "11"}, + { + url: "/freshness?e", + server: "10", + expected: "10", + responseheader: "Cache-Control: max-age=0", + }, + { url: "/freshness?e", server: "11", expected: "11" }, - {url: "/freshness", server: "99", expected: "0"}, // cached + { url: "/freshness", server: "99", expected: "0" }, // cached ]; function logit(i, data) { - dump(tests[i].url + "\t requested [" + tests[i].server + "]" + - " got [" + data + "] expected [" + tests[i].expected + "]"); - if (tests[i].responseheader) - dump("\t[" + tests[i].responseheader + "]"); - dump("\n"); + dump( + tests[i].url + + "\t requested [" + + tests[i].server + + "]" + + " got [" + + data + + "] expected [" + + tests[i].expected + + "]" + ); + if (tests[i].responseheader) { + dump("\t[" + tests[i].responseheader + "]"); + } + dump("\n"); } function setupChannel(suffix, value) { - var chan = NetUtil.newChannel({ - uri: "http://localhost:" + httpserver.identity.primaryPort + suffix, - loadUsingSystemPrincipal: true - }); - var httpChan = chan.QueryInterface(Ci.nsIHttpChannel); - httpChan.requestMethod = "GET"; - httpChan.setRequestHeader("x-request", value, false); - return httpChan; + var chan = NetUtil.newChannel({ + uri: "http://localhost:" + httpserver.identity.primaryPort + suffix, + loadUsingSystemPrincipal: true, + }); + var httpChan = chan.QueryInterface(Ci.nsIHttpChannel); + httpChan.requestMethod = "GET"; + httpChan.setRequestHeader("x-request", value, false); + return httpChan; } function triggerNextTest() { - var channel = setupChannel(tests[index].url, tests[index].server); - channel.asyncOpen(new ChannelListener(checkValueAndTrigger, null)); + var channel = setupChannel(tests[index].url, tests[index].server); + channel.asyncOpen(new ChannelListener(checkValueAndTrigger, null)); } function checkValueAndTrigger(request, data, ctx) { - logit(index, data); - Assert.equal(tests[index].expected, data); + logit(index, data); + Assert.equal(tests[index].expected, data); - if (index < tests.length-1) { - index++; - triggerNextTest(); - } else { - httpserver.stop(do_test_finished); - } + if (index < tests.length - 1) { + index++; + triggerNextTest(); + } else { + httpserver.stop(do_test_finished); + } } function run_test() { - httpserver.registerPathHandler("/freshness", handler); - httpserver.start(-1); + httpserver.registerPathHandler("/freshness", handler); + httpserver.start(-1); - // clear cache - evict_cache_entries(); - triggerNextTest(); + // clear cache + evict_cache_entries(); + triggerNextTest(); - do_test_pending(); + do_test_pending(); } function handler(metadata, response) { - var body = metadata.getHeader("x-request"); - response.setHeader("Content-Type", "text/plain", false); - response.setHeader("Date", getDateString(0), false); + var body = metadata.getHeader("x-request"); + response.setHeader("Content-Type", "text/plain", false); + response.setHeader("Date", getDateString(0), false); - var header = tests[index].responseheader; - if (header == null) { - response.setHeader("Last-Modified", getDateString(-1), false); - } else { - var splitHdr = header.split(": "); - response.setHeader(splitHdr[0], splitHdr[1], false); - } + var header = tests[index].responseheader; + if (header == null) { + response.setHeader("Last-Modified", getDateString(-1), false); + } else { + var splitHdr = header.split(": "); + response.setHeader(splitHdr[0], splitHdr[1], false); + } - response.setStatusLine(metadata.httpVersion, 200, "OK"); - response.bodyOutputStream.write(body, body.length); + response.setStatusLine(metadata.httpVersion, 200, "OK"); + response.bodyOutputStream.write(body, body.length); } function getDateString(yearDelta) { - var months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', - 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']; - var days = ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat']; + var months = [ + "Jan", + "Feb", + "Mar", + "Apr", + "May", + "Jun", + "Jul", + "Aug", + "Sep", + "Oct", + "Nov", + "Dec", + ]; + var days = ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"]; - var d = new Date(); - return days[d.getUTCDay()] + ", " + - d.getUTCDate() + " " + - months[d.getUTCMonth()] + " " + - (d.getUTCFullYear() + yearDelta) + " " + - d.getUTCHours() + ":" + d.getUTCMinutes() +":" + - d.getUTCSeconds() + " UTC"; + var d = new Date(); + return ( + days[d.getUTCDay()] + + ", " + + d.getUTCDate() + + " " + + months[d.getUTCMonth()] + + " " + + (d.getUTCFullYear() + yearDelta) + + " " + + d.getUTCHours() + + ":" + + d.getUTCMinutes() + + ":" + + d.getUTCSeconds() + + " UTC" + ); } diff --git a/netwerk/test/unit/test_bug470716.js b/netwerk/test/unit/test_bug470716.js index 2ce29e41c6dd..0acf1f7bf94c 100644 --- a/netwerk/test/unit/test_bug470716.js +++ b/netwerk/test/unit/test_bug470716.js @@ -1,16 +1,18 @@ var CC = Components.Constructor; -const StreamCopier = CC("@mozilla.org/network/async-stream-copier;1", - "nsIAsyncStreamCopier", - "init"); +const StreamCopier = CC( + "@mozilla.org/network/async-stream-copier;1", + "nsIAsyncStreamCopier", + "init" +); -const ScriptableInputStream = CC("@mozilla.org/scriptableinputstream;1", - "nsIScriptableInputStream", - "init"); +const ScriptableInputStream = CC( + "@mozilla.org/scriptableinputstream;1", + "nsIScriptableInputStream", + "init" +); -const Pipe = CC("@mozilla.org/pipe;1", - "nsIPipe", - "init"); +const Pipe = CC("@mozilla.org/pipe;1", "nsIPipe", "init"); var pipe1; var pipe2; @@ -21,12 +23,10 @@ var test_source_closed; var test_sink_closed; var test_nr; -var copyObserver = -{ - onStartRequest(request) { }, +var copyObserver = { + onStartRequest(request) {}, - onStopRequest(request, statusCode) - { + onStopRequest(request, statusCode) { // check status code Assert.equal(statusCode, test_result); @@ -42,8 +42,7 @@ var copyObserver = try { pipe2.outputStream.write("closedSinkTest", 14); Assert.ok(!test_sink_closed); - } - catch (ex) { + } catch (ex) { Assert.ok(test_sink_closed); } @@ -51,112 +50,115 @@ var copyObserver = try { pipe1.outputStream.write("closedSourceTest", 16); Assert.ok(!test_source_closed); - } - catch (ex) { + } catch (ex) { Assert.ok(test_source_closed); } do_timeout(0, do_test); }, - QueryInterface: ChromeUtils.generateQI(["nsIRequestObserver"]) + QueryInterface: ChromeUtils.generateQI(["nsIRequestObserver"]), }; function startCopier(closeSource, closeSink) { - pipe1 = new Pipe(true /* nonBlockingInput */, - true /* nonBlockingOutput */, - 0 /* segmentSize */, - 0xffffffff /* segmentCount */, - null /* segmentAllocator */); + pipe1 = new Pipe( + true /* nonBlockingInput */, + true /* nonBlockingOutput */, + 0 /* segmentSize */, + 0xffffffff /* segmentCount */, + null /* segmentAllocator */ + ); - pipe2 = new Pipe(true /* nonBlockingInput */, - true /* nonBlockingOutput */, - 0 /* segmentSize */, - 0xffffffff /* segmentCount */, - null /* segmentAllocator */); + pipe2 = new Pipe( + true /* nonBlockingInput */, + true /* nonBlockingOutput */, + 0 /* segmentSize */, + 0xffffffff /* segmentCount */, + null /* segmentAllocator */ + ); - copier = new StreamCopier(pipe1.inputStream /* aSource */, - pipe2.outputStream /* aSink */, - null /* aTarget */, - true /* aSourceBuffered */, - true /* aSinkBuffered */, - 8192 /* aChunkSize */, - closeSource /* aCloseSource */, - closeSink /* aCloseSink */); + copier = new StreamCopier( + pipe1.inputStream /* aSource */, + pipe2.outputStream /* aSink */, + null /* aTarget */, + true /* aSourceBuffered */, + true /* aSinkBuffered */, + 8192 /* aChunkSize */, + closeSource /* aCloseSource */, + closeSink /* aCloseSink */ + ); copier.asyncCopy(copyObserver, null); } function do_test() { - test_nr++; test_content = "test" + test_nr; switch (test_nr) { - case 1: - case 2: // close sink - case 3: // close source - case 4: // close both - // test canceling transfer - // use some undefined error code to check if it is successfully passed - // to the request observer - test_result = 0x87654321; + case 1: + case 2: // close sink + case 3: // close source + case 4: // close both + // test canceling transfer + // use some undefined error code to check if it is successfully passed + // to the request observer + test_result = 0x87654321; - test_source_closed = ((test_nr-1)>>1 != 0); - test_sink_closed = ((test_nr-1)%2 != 0); + test_source_closed = (test_nr - 1) >> 1 != 0; + test_sink_closed = (test_nr - 1) % 2 != 0; - startCopier(test_source_closed, test_sink_closed); - pipe1.outputStream.write(test_content, test_content.length); - pipe1.outputStream.flush(); - do_timeout(20, - function(){ - copier.cancel(test_result); - pipe1.outputStream.write("a", 1);}); - break; - case 5: - case 6: // close sink - case 7: // close source - case 8: // close both - // test copying with EOF on source - test_result = 0; + startCopier(test_source_closed, test_sink_closed); + pipe1.outputStream.write(test_content, test_content.length); + pipe1.outputStream.flush(); + do_timeout(20, function() { + copier.cancel(test_result); + pipe1.outputStream.write("a", 1); + }); + break; + case 5: + case 6: // close sink + case 7: // close source + case 8: // close both + // test copying with EOF on source + test_result = 0; - test_source_closed = ((test_nr-5)>>1 != 0); - test_sink_closed = ((test_nr-5)%2 != 0); + test_source_closed = (test_nr - 5) >> 1 != 0; + test_sink_closed = (test_nr - 5) % 2 != 0; - startCopier(test_source_closed, test_sink_closed); - pipe1.outputStream.write(test_content, test_content.length); - // we will close the source - test_source_closed = true; - pipe1.outputStream.close(); - break; - case 9: - case 10: // close sink - case 11: // close source - case 12: // close both - // test copying with error on sink - // use some undefined error code to check if it is successfully passed - // to the request observer - test_result = 0x87654321; + startCopier(test_source_closed, test_sink_closed); + pipe1.outputStream.write(test_content, test_content.length); + // we will close the source + test_source_closed = true; + pipe1.outputStream.close(); + break; + case 9: + case 10: // close sink + case 11: // close source + case 12: // close both + // test copying with error on sink + // use some undefined error code to check if it is successfully passed + // to the request observer + test_result = 0x87654321; - test_source_closed = ((test_nr-9)>>1 != 0); - test_sink_closed = ((test_nr-9)%2 != 0); + test_source_closed = (test_nr - 9) >> 1 != 0; + test_sink_closed = (test_nr - 9) % 2 != 0; - startCopier(test_source_closed, test_sink_closed); - pipe1.outputStream.write(test_content, test_content.length); - pipe1.outputStream.flush(); - // we will close the sink - test_sink_closed = true; - do_timeout(20, - function() - { - pipe2.outputStream - .QueryInterface(Ci.nsIAsyncOutputStream) - .closeWithStatus(test_result); - pipe1.outputStream.write("a", 1);}); - break; - case 13: - do_test_finished(); - break; + startCopier(test_source_closed, test_sink_closed); + pipe1.outputStream.write(test_content, test_content.length); + pipe1.outputStream.flush(); + // we will close the sink + test_sink_closed = true; + do_timeout(20, function() { + pipe2.outputStream + .QueryInterface(Ci.nsIAsyncOutputStream) + .closeWithStatus(test_result); + pipe1.outputStream.write("a", 1); + }); + break; + case 13: + do_test_finished(); + break; } } diff --git a/netwerk/test/unit/test_bug477578.js b/netwerk/test/unit/test_bug477578.js index eb6438481501..14321c1ff41e 100644 --- a/netwerk/test/unit/test_bug477578.js +++ b/netwerk/test/unit/test_bug477578.js @@ -33,13 +33,13 @@ const testMethods = [ ["foo"], ["foO"], ["fOo"], - ["Foo"] -] + ["Foo"], +]; function run_test() { var chan = NetUtil.newChannel({ uri: "http://localhost/", - loadUsingSystemPrincipal: true + loadUsingSystemPrincipal: true, }).QueryInterface(Ci.nsIHttpChannel); for (var i = 0; i < testMethods.length; i++) { diff --git a/netwerk/test/unit/test_bug479413.js b/netwerk/test/unit/test_bug479413.js index 0c499b8493e7..b54fc362e44b 100644 --- a/netwerk/test/unit/test_bug479413.js +++ b/netwerk/test/unit/test_bug479413.js @@ -4,36 +4,35 @@ var idnService; -function expected_pass(inputIDN) -{ +function expected_pass(inputIDN) { var isASCII = {}; var displayIDN = idnService.convertToDisplayIDN(inputIDN, isASCII); Assert.equal(displayIDN, inputIDN); } -function expected_fail(inputIDN) -{ +function expected_fail(inputIDN) { var isASCII = {}; var displayIDN = ""; try { displayIDN = idnService.convertToDisplayIDN(inputIDN, isASCII); - } - catch(e) {} + } catch (e) {} Assert.notEqual(displayIDN, inputIDN); } function run_test() { - // add an IDN whitelist pref - var pbi = Cc["@mozilla.org/preferences-service;1"] - .getService(Ci.nsIPrefBranch); + // add an IDN whitelist pref + var pbi = Cc["@mozilla.org/preferences-service;1"].getService( + Ci.nsIPrefBranch + ); var whitelistPref = "network.IDN.whitelist.com"; pbi.setBoolPref(whitelistPref, true); - - idnService = Cc["@mozilla.org/network/idn-service;1"] - .getService(Ci.nsIIDNService); + + idnService = Cc["@mozilla.org/network/idn-service;1"].getService( + Ci.nsIIDNService + ); // assigned code point expected_pass("foo\u0101bar.com"); @@ -54,6 +53,7 @@ function run_test() { expected_fail("foo\u0370bar.com"); // reset the pref - if (pbi.prefHasUserValue(whitelistPref)) + if (pbi.prefHasUserValue(whitelistPref)) { pbi.clearUserPref(whitelistPref); + } } diff --git a/netwerk/test/unit/test_bug479485.js b/netwerk/test/unit/test_bug479485.js index 9791aaef46e5..0e2fc3dff6b5 100644 --- a/netwerk/test/unit/test_bug479485.js +++ b/netwerk/test/unit/test_bug479485.js @@ -1,40 +1,56 @@ function run_test() { - var ios = Cc["@mozilla.org/network/io-service;1"]. - getService(Ci.nsIIOService); - - var test_port = function(port, exception_expected) - { + var ios = Cc["@mozilla.org/network/io-service;1"].getService(Ci.nsIIOService); + + var test_port = function(port, exception_expected) { dump((port || "no port provided") + "\n"); var exception_threw = false; try { - var newURI = ios.newURI("http://foo.com"+port); - } - catch (e) { + var newURI = ios.newURI("http://foo.com" + port); + } catch (e) { exception_threw = e.result == Cr.NS_ERROR_MALFORMED_URI; } - if (exception_threw != exception_expected) - do_throw("We did"+(exception_expected?"n't":"")+" throw NS_ERROR_MALFORMED_URI when creating a new URI with "+port+" as a port"); + if (exception_threw != exception_expected) { + do_throw( + "We did" + + (exception_expected ? "n't" : "") + + " throw NS_ERROR_MALFORMED_URI when creating a new URI with " + + port + + " as a port" + ); + } Assert.equal(exception_threw, exception_expected); - + exception_threw = false; newURI = ios.newURI("http://foo.com"); try { - newURI = newURI.mutate().setSpec("http://foo.com"+port).finalize(); - } - catch (e) { + newURI = newURI + .mutate() + .setSpec("http://foo.com" + port) + .finalize(); + } catch (e) { exception_threw = e.result == Cr.NS_ERROR_MALFORMED_URI; } - if (exception_threw != exception_expected) - do_throw("We did"+(exception_expected?"n't":"")+" throw NS_ERROR_MALFORMED_URI when setting a spec of a URI with "+port+" as a port"); + if (exception_threw != exception_expected) { + do_throw( + "We did" + + (exception_expected ? "n't" : "") + + " throw NS_ERROR_MALFORMED_URI when setting a spec of a URI with " + + port + + " as a port" + ); + } Assert.equal(exception_threw, exception_expected); - } - + }; + test_port(":invalid", true); test_port(":-2", true); test_port(":-1", true); test_port(":0", false); - test_port(":185891548721348172817857824356013651809236172635716571865023757816234081723451516780356", true); - + test_port( + ":185891548721348172817857824356013651809236172635716571865023757816234081723451516780356", + true + ); + // Following 3 tests are all failing, we do not throw, although we parse the whole string and use only 5870 as a portnumber test_port(":5870:80", true); test_port(":5870-80", true); diff --git a/netwerk/test/unit/test_bug482601.js b/netwerk/test/unit/test_bug482601.js index 0f18c92d8ffd..8f5f9b6b782c 100644 --- a/netwerk/test/unit/test_bug482601.js +++ b/netwerk/test/unit/test_bug482601.js @@ -1,4 +1,4 @@ -const {HttpServer} = ChromeUtils.import("resource://testing-common/httpd.js"); +const { HttpServer } = ChromeUtils.import("resource://testing-common/httpd.js"); var httpserv = null; var test_nr = 0; @@ -10,29 +10,30 @@ var observer = { QueryInterface: ChromeUtils.generateQI(["nsIObserver"]), observe(subject, topic, data) { - if (observers_called.length) + if (observers_called.length) { observers_called += ","; + } observers_called += topic; - } + }, }; var listener = { - onStartRequest (request) { + onStartRequest(request) { buffer = ""; }, - onDataAvailable (request, stream, offset, count) { + onDataAvailable(request, stream, offset, count) { buffer = buffer.concat(read_stream(stream, count)); }, - onStopRequest (request, status) { + onStopRequest(request, status) { Assert.equal(status, Cr.NS_OK); Assert.equal(buffer, "0123456789"); Assert.equal(observers_called, results[test_nr]); test_nr++; do_timeout(0, do_test); - } + }, }; function run_test() { @@ -40,7 +41,10 @@ function run_test() { httpserv.registerPathHandler("/bug482601/nocache", bug482601_nocache); httpserv.registerPathHandler("/bug482601/partial", bug482601_partial); httpserv.registerPathHandler("/bug482601/cached", bug482601_cached); - httpserv.registerPathHandler("/bug482601/only_from_cache", bug482601_only_from_cache); + httpserv.registerPathHandler( + "/bug482601/only_from_cache", + bug482601_only_from_cache + ); httpserv.start(-1); var obs = Cc["@mozilla.org/observer-service;1"].getService(); @@ -56,26 +60,26 @@ function run_test() { function do_test() { if (test_nr < tests.length) { tests[test_nr](); - } - else { + } else { Assert.equal(handlers_called, "nocache,partial,cached"); httpserv.stop(do_test_finished); } } -var tests = [test_nocache, - test_partial, - test_cached, - test_only_from_cache]; +var tests = [test_nocache, test_partial, test_cached, test_only_from_cache]; -var results = ["http-on-examine-response", - "http-on-examine-response,http-on-examine-merged-response", - "http-on-examine-response,http-on-examine-merged-response", - "http-on-examine-cached-response"]; +var results = [ + "http-on-examine-response", + "http-on-examine-response,http-on-examine-merged-response", + "http-on-examine-response,http-on-examine-merged-response", + "http-on-examine-cached-response", +]; function makeChan(url) { - return NetUtil.newChannel({uri: url, loadUsingSystemPrincipal: true}) - .QueryInterface(Ci.nsIHttpChannel); + return NetUtil.newChannel({ + uri: url, + loadUsingSystemPrincipal: true, + }).QueryInterface(Ci.nsIHttpChannel); } function storeCache(aCacheEntry, aResponseHeads, aContent) { @@ -86,9 +90,15 @@ function storeCache(aCacheEntry, aResponseHeads, aContent) { var oStream = aCacheEntry.openOutputStream(0, aContent.length); var written = oStream.write(aContent, aContent.length); if (written != aContent.length) { - do_throw("oStream.write has not written all data!\n" + - " Expected: " + written + "\n" + - " Actual: " + aContent.length + "\n"); + do_throw( + "oStream.write has not written all data!\n" + + " Expected: " + + written + + "\n" + + " Actual: " + + aContent.length + + "\n" + ); } oStream.close(); aCacheEntry.close(); @@ -97,92 +107,114 @@ function storeCache(aCacheEntry, aResponseHeads, aContent) { function test_nocache() { observers_called = ""; - var chan = makeChan("http://localhost:" + httpserv.identity.primaryPort + - "/bug482601/nocache"); + var chan = makeChan( + "http://localhost:" + httpserv.identity.primaryPort + "/bug482601/nocache" + ); chan.asyncOpen(listener); } function test_partial() { - asyncOpenCacheEntry("http://localhost:" + httpserv.identity.primaryPort + - "/bug482601/partial", - "disk", Ci.nsICacheStorage.OPEN_NORMALLY, null, - test_partial2); + asyncOpenCacheEntry( + "http://localhost:" + httpserv.identity.primaryPort + "/bug482601/partial", + "disk", + Ci.nsICacheStorage.OPEN_NORMALLY, + null, + test_partial2 + ); } function test_partial2(status, entry) { Assert.equal(status, Cr.NS_OK); - storeCache(entry, - "HTTP/1.1 200 OK\r\n" + - "Date: Thu, 1 Jan 2009 00:00:00 GMT\r\n" + - "Server: httpd.js\r\n" + - "Last-Modified: Thu, 1 Jan 2009 00:00:00 GMT\r\n" + - "Accept-Ranges: bytes\r\n" + - "Content-Length: 10\r\n" + - "Content-Type: text/plain\r\n", - "0123"); + storeCache( + entry, + "HTTP/1.1 200 OK\r\n" + + "Date: Thu, 1 Jan 2009 00:00:00 GMT\r\n" + + "Server: httpd.js\r\n" + + "Last-Modified: Thu, 1 Jan 2009 00:00:00 GMT\r\n" + + "Accept-Ranges: bytes\r\n" + + "Content-Length: 10\r\n" + + "Content-Type: text/plain\r\n", + "0123" + ); observers_called = ""; - var chan = makeChan("http://localhost:" + httpserv.identity.primaryPort + - "/bug482601/partial"); + var chan = makeChan( + "http://localhost:" + httpserv.identity.primaryPort + "/bug482601/partial" + ); chan.asyncOpen(listener); } function test_cached() { - asyncOpenCacheEntry("http://localhost:" + httpserv.identity.primaryPort + - "/bug482601/cached", - "disk", Ci.nsICacheStorage.OPEN_NORMALLY, null, - test_cached2); + asyncOpenCacheEntry( + "http://localhost:" + httpserv.identity.primaryPort + "/bug482601/cached", + "disk", + Ci.nsICacheStorage.OPEN_NORMALLY, + null, + test_cached2 + ); } function test_cached2(status, entry) { Assert.equal(status, Cr.NS_OK); - storeCache(entry, - "HTTP/1.1 200 OK\r\n" + - "Date: Thu, 1 Jan 2009 00:00:00 GMT\r\n" + - "Server: httpd.js\r\n" + - "Last-Modified: Thu, 1 Jan 2009 00:00:00 GMT\r\n" + - "Accept-Ranges: bytes\r\n" + - "Content-Length: 10\r\n" + - "Content-Type: text/plain\r\n", - "0123456789"); + storeCache( + entry, + "HTTP/1.1 200 OK\r\n" + + "Date: Thu, 1 Jan 2009 00:00:00 GMT\r\n" + + "Server: httpd.js\r\n" + + "Last-Modified: Thu, 1 Jan 2009 00:00:00 GMT\r\n" + + "Accept-Ranges: bytes\r\n" + + "Content-Length: 10\r\n" + + "Content-Type: text/plain\r\n", + "0123456789" + ); observers_called = ""; - var chan = makeChan("http://localhost:" + httpserv.identity.primaryPort + - "/bug482601/cached"); + var chan = makeChan( + "http://localhost:" + httpserv.identity.primaryPort + "/bug482601/cached" + ); chan.loadFlags = Ci.nsIRequest.VALIDATE_ALWAYS; chan.asyncOpen(listener); } function test_only_from_cache() { - asyncOpenCacheEntry("http://localhost:" + httpserv.identity.primaryPort + - "/bug482601/only_from_cache", - "disk", Ci.nsICacheStorage.OPEN_NORMALLY, null, - test_only_from_cache2); + asyncOpenCacheEntry( + "http://localhost:" + + httpserv.identity.primaryPort + + "/bug482601/only_from_cache", + "disk", + Ci.nsICacheStorage.OPEN_NORMALLY, + null, + test_only_from_cache2 + ); } function test_only_from_cache2(status, entry) { Assert.equal(status, Cr.NS_OK); - storeCache(entry, - "HTTP/1.1 200 OK\r\n" + - "Date: Thu, 1 Jan 2009 00:00:00 GMT\r\n" + - "Server: httpd.js\r\n" + - "Last-Modified: Thu, 1 Jan 2009 00:00:00 GMT\r\n" + - "Accept-Ranges: bytes\r\n" + - "Content-Length: 10\r\n" + - "Content-Type: text/plain\r\n", - "0123456789"); + storeCache( + entry, + "HTTP/1.1 200 OK\r\n" + + "Date: Thu, 1 Jan 2009 00:00:00 GMT\r\n" + + "Server: httpd.js\r\n" + + "Last-Modified: Thu, 1 Jan 2009 00:00:00 GMT\r\n" + + "Accept-Ranges: bytes\r\n" + + "Content-Length: 10\r\n" + + "Content-Type: text/plain\r\n", + "0123456789" + ); observers_called = ""; - var chan = makeChan("http://localhost:" + httpserv.identity.primaryPort + - "/bug482601/only_from_cache"); + var chan = makeChan( + "http://localhost:" + + httpserv.identity.primaryPort + + "/bug482601/only_from_cache" + ); chan.loadFlags = Ci.nsICachingChannel.LOAD_ONLY_FROM_CACHE; chan.asyncOpen(listener); } - // PATHS // /bug482601/nocache @@ -196,8 +228,7 @@ function bug482601_nocache(metadata, response) { // /bug482601/partial function bug482601_partial(metadata, response) { Assert.ok(metadata.hasHeader("If-Range")); - Assert.equal(metadata.getHeader("If-Range"), - "Thu, 1 Jan 2009 00:00:00 GMT"); + Assert.equal(metadata.getHeader("If-Range"), "Thu, 1 Jan 2009 00:00:00 GMT"); Assert.ok(metadata.hasHeader("Range")); Assert.equal(metadata.getHeader("Range"), "bytes=4-"); @@ -214,8 +245,10 @@ function bug482601_partial(metadata, response) { // /bug482601/cached function bug482601_cached(metadata, response) { Assert.ok(metadata.hasHeader("If-Modified-Since")); - Assert.equal(metadata.getHeader("If-Modified-Since"), - "Thu, 1 Jan 2009 00:00:00 GMT"); + Assert.equal( + metadata.getHeader("If-Modified-Since"), + "Thu, 1 Jan 2009 00:00:00 GMT" + ); response.setStatusLine(metadata.httpVersion, 304, "Not Modified"); handlers_called += ",cached"; diff --git a/netwerk/test/unit/test_bug482934.js b/netwerk/test/unit/test_bug482934.js index ecfb143affc5..e84584236ccc 100644 --- a/netwerk/test/unit/test_bug482934.js +++ b/netwerk/test/unit/test_bug482934.js @@ -1,6 +1,6 @@ "use strict"; -const {HttpServer} = ChromeUtils.import("resource://testing-common/httpd.js"); +const { HttpServer } = ChromeUtils.import("resource://testing-common/httpd.js"); var response_code; var response_body; @@ -20,26 +20,22 @@ var resource_url = base_url + resource; // Test flags var hit_server = false; -function make_channel(aUrl) -{ +function make_channel(aUrl) { // Reset test global status hit_server = false; - var req = NetUtil.newChannel({uri: aUrl, loadUsingSystemPrincipal: true}); + var req = NetUtil.newChannel({ uri: aUrl, loadUsingSystemPrincipal: true }); req.QueryInterface(Ci.nsIHttpChannel); req.setRequestHeader("If-Modified-Since", request_time, false); return req; } -function make_uri(aUrl) -{ - var ios = Cc["@mozilla.org/network/io-service;1"]. - getService(Ci.nsIIOService); +function make_uri(aUrl) { + var ios = Cc["@mozilla.org/network/io-service;1"].getService(Ci.nsIIOService); return ios.newURI(aUrl); } -function resource_handler(aMetadata, aResponse) -{ +function resource_handler(aMetadata, aResponse) { hit_server = true; Assert.ok(aMetadata.hasHeader("If-Modified-Since")); Assert.equal(aMetadata.getHeader("If-Modified-Since"), request_time); @@ -56,9 +52,12 @@ function resource_handler(aMetadata, aResponse) } } -function check_cached_data(aCachedData, aCallback) -{ - asyncOpenCacheEntry(resource_url, "disk", Ci.nsICacheStorage.OPEN_READONLY, null, +function check_cached_data(aCachedData, aCallback) { + asyncOpenCacheEntry( + resource_url, + "disk", + Ci.nsICacheStorage.OPEN_READONLY, + null, function(aStatus, aEntry) { Assert.equal(aStatus, Cr.NS_OK); pumpReadStream(aEntry.openInputStream(0), function(aData) { @@ -69,8 +68,7 @@ function check_cached_data(aCachedData, aCallback) ); } -function run_test() -{ +function run_test() { do_get_profile(); evict_cache_entries(); @@ -91,14 +89,19 @@ add_test(() => { response_time = "Thu, 1 Jan 2009 00:00:00 GMT"; var ch = make_channel(resource_url); - ch.asyncOpen(new ChannelListener(function(aRequest, aData) { - Assert.ok(hit_server); - Assert.equal(aRequest.QueryInterface(Ci.nsIHttpChannel).responseStatus, 304); - Assert.ok(!cache_storage.exists(make_uri(resource_url), "")); - Assert.equal(aRequest.getResponseHeader("Returned-From-Handler"), "1"); + ch.asyncOpen( + new ChannelListener(function(aRequest, aData) { + Assert.ok(hit_server); + Assert.equal( + aRequest.QueryInterface(Ci.nsIHttpChannel).responseStatus, + 304 + ); + Assert.ok(!cache_storage.exists(make_uri(resource_url), "")); + Assert.equal(aRequest.getResponseHeader("Returned-From-Handler"), "1"); - run_next_test(); - }, null)); + run_next_test(); + }, null) + ); }); // 2. send custom conditional request when we don't have an entry @@ -110,13 +113,18 @@ add_test(() => { response_time = "Fri, 2 Jan 2009 00:00:00 GMT"; var ch = make_channel(resource_url); - ch.asyncOpen(new ChannelListener(function(aRequest, aData) { - Assert.ok(hit_server); - Assert.equal(aRequest.QueryInterface(Ci.nsIHttpChannel).responseStatus, 200); - Assert.ok(cache_storage.exists(make_uri(resource_url), "")); + ch.asyncOpen( + new ChannelListener(function(aRequest, aData) { + Assert.ok(hit_server); + Assert.equal( + aRequest.QueryInterface(Ci.nsIHttpChannel).responseStatus, + 200 + ); + Assert.ok(cache_storage.exists(make_uri(resource_url), "")); - check_cached_data(response_body, run_next_test); - }, null)); + check_cached_data(response_body, run_next_test); + }, null) + ); }); // 3. send custom conditional request when we have an entry @@ -129,16 +137,21 @@ add_test(() => { response_time = "Fri, 2 Jan 2009 00:00:00 GMT"; var ch = make_channel(resource_url); - ch.asyncOpen(new ChannelListener(function(aRequest, aData) { - Assert.ok(hit_server); - Assert.equal(aRequest.QueryInterface(Ci.nsIHttpChannel).responseStatus, 304); - Assert.ok(cache_storage.exists(make_uri(resource_url), "")); - Assert.equal(aRequest.getResponseHeader("Returned-From-Handler"), "1"); - Assert.equal(aData, ""); + ch.asyncOpen( + new ChannelListener(function(aRequest, aData) { + Assert.ok(hit_server); + Assert.equal( + aRequest.QueryInterface(Ci.nsIHttpChannel).responseStatus, + 304 + ); + Assert.ok(cache_storage.exists(make_uri(resource_url), "")); + Assert.equal(aRequest.getResponseHeader("Returned-From-Handler"), "1"); + Assert.equal(aData, ""); - // Check the cache data is not changed - check_cached_data(cached_body, run_next_test); - }, null)); + // Check the cache data is not changed + check_cached_data(cached_body, run_next_test); + }, null) + ); }); // 4. send custom conditional request when we have an entry @@ -149,15 +162,20 @@ add_test(() => { request_time = "Fri, 2 Jan 2009 00:00:00 GMT"; response_time = "Sat, 3 Jan 2009 00:00:00 GMT"; var ch = make_channel(resource_url); - ch.asyncOpen(new ChannelListener(function(aRequest, aData) { - Assert.ok(hit_server); - Assert.equal(aRequest.QueryInterface(Ci.nsIHttpChannel).responseStatus, 200); - Assert.ok(cache_storage.exists(make_uri(resource_url), "")); + ch.asyncOpen( + new ChannelListener(function(aRequest, aData) { + Assert.ok(hit_server); + Assert.equal( + aRequest.QueryInterface(Ci.nsIHttpChannel).responseStatus, + 200 + ); + Assert.ok(cache_storage.exists(make_uri(resource_url), "")); - // Check the cache data is updated - check_cached_data(response_body, () => { - run_next_test(); - httpserver.stop(do_test_finished); - }); - }, null)); + // Check the cache data is updated + check_cached_data(response_body, () => { + run_next_test(); + httpserver.stop(do_test_finished); + }); + }, null) + ); }); diff --git a/netwerk/test/unit/test_bug484684.js b/netwerk/test/unit/test_bug484684.js index 23e1c696104d..7279d9156583 100644 --- a/netwerk/test/unit/test_bug484684.js +++ b/netwerk/test/unit/test_bug484684.js @@ -2,66 +2,86 @@ const URL = "ftp://localhost/bug464884/"; const tests = [ // standard ls unix format - ["-rw-rw-r-- 1 500 500 0 Jan 01 2000 file1\r\n" + - "-rw-rw-r-- 1 500 500 0 Jan 01 2000 file2\r\n", + [ + "-rw-rw-r-- 1 500 500 0 Jan 01 2000 file1\r\n" + + "-rw-rw-r-- 1 500 500 0 Jan 01 2000 file2\r\n", - "300: " + URL + "\n" + - "200: filename content-length last-modified file-type\n" + - "201: \"file1\" 0 Sat%2C%2001%20Jan%202000%2000%3A00%3A00 FILE \n" + - "201: \"%20file2\" 0 Sat%2C%2001%20Jan%202000%2000%3A00%3A00 FILE \n"], + "300: " + + URL + + "\n" + + "200: filename content-length last-modified file-type\n" + + '201: "file1" 0 Sat%2C%2001%20Jan%202000%2000%3A00%3A00 FILE \n' + + '201: "%20file2" 0 Sat%2C%2001%20Jan%202000%2000%3A00%3A00 FILE \n', + ], // old Hellsoft unix format - ["-[RWCEMFA] supervisor 214059 Jan 01 2000 file1\r\n" + - "-[RWCEMFA] supervisor 214059 Jan 01 2000 file2\r\n", + [ + "-[RWCEMFA] supervisor 214059 Jan 01 2000 file1\r\n" + + "-[RWCEMFA] supervisor 214059 Jan 01 2000 file2\r\n", - "300: " + URL + "\n" + - "200: filename content-length last-modified file-type\n" + - "201: \"file1\" 214059 Sat%2C%2001%20Jan%202000%2000%3A00%3A00 FILE \n" + - "201: \"file2\" 214059 Sat%2C%2001%20Jan%202000%2000%3A00%3A00 FILE \n"], + "300: " + + URL + + "\n" + + "200: filename content-length last-modified file-type\n" + + '201: "file1" 214059 Sat%2C%2001%20Jan%202000%2000%3A00%3A00 FILE \n' + + '201: "file2" 214059 Sat%2C%2001%20Jan%202000%2000%3A00%3A00 FILE \n', + ], // new Hellsoft unix format - ["- [RWCEAFMS] jrd 192 Jan 01 2000 file1\r\n"+ - "- [RWCEAFMS] jrd 192 Jan 01 2000 file2\r\n", + [ + "- [RWCEAFMS] jrd 192 Jan 01 2000 file1\r\n" + + "- [RWCEAFMS] jrd 192 Jan 01 2000 file2\r\n", - "300: " + URL + "\n" + - "200: filename content-length last-modified file-type\n" + - "201: \"file1\" 192 Sat%2C%2001%20Jan%202000%2000%3A00%3A00 FILE \n" + - "201: \"%20file2\" 192 Sat%2C%2001%20Jan%202000%2000%3A00%3A00 FILE \n"], + "300: " + + URL + + "\n" + + "200: filename content-length last-modified file-type\n" + + '201: "file1" 192 Sat%2C%2001%20Jan%202000%2000%3A00%3A00 FILE \n' + + '201: "%20file2" 192 Sat%2C%2001%20Jan%202000%2000%3A00%3A00 FILE \n', + ], // DOS format with correct offsets - ["01-01-00 01:00AM dir1\r\n" + - "01-01-00 01:00AM junction1 -> foo1\r\n" + - "01-01-00 01:00AM 95077 file1\r\n" + - "01-01-00 01:00AM dir2\r\n" + - "01-01-00 01:00AM junction2 -> foo2\r\n" + - "01-01-00 01:00AM 95077 file2\r\n", + [ + "01-01-00 01:00AM dir1\r\n" + + "01-01-00 01:00AM junction1 -> foo1\r\n" + + "01-01-00 01:00AM 95077 file1\r\n" + + "01-01-00 01:00AM dir2\r\n" + + "01-01-00 01:00AM junction2 -> foo2\r\n" + + "01-01-00 01:00AM 95077 file2\r\n", - "300: " + URL + "\n" + - "200: filename content-length last-modified file-type\n" + - "201: \"dir1\" 0 Sat%2C%2001%20Jan%202000%2001%3A00%3A00 DIRECTORY \n" + - "201: \"junction1\" Sat%2C%2001%20Jan%202000%2001%3A00%3A00 SYMBOLIC-LINK \n" + - "201: \"file1\" 95077 Sat%2C%2001%20Jan%202000%2001%3A00%3A00 FILE \n" + - "201: \"%20dir2\" 0 Sat%2C%2001%20Jan%202000%2001%3A00%3A00 DIRECTORY \n" + - "201: \"%20junction2\" Sat%2C%2001%20Jan%202000%2001%3A00%3A00 SYMBOLIC-LINK \n" + - "201: \"%20file2\" 95077 Sat%2C%2001%20Jan%202000%2001%3A00%3A00 FILE \n"], + "300: " + + URL + + "\n" + + "200: filename content-length last-modified file-type\n" + + '201: "dir1" 0 Sat%2C%2001%20Jan%202000%2001%3A00%3A00 DIRECTORY \n' + + '201: "junction1" Sat%2C%2001%20Jan%202000%2001%3A00%3A00 SYMBOLIC-LINK \n' + + '201: "file1" 95077 Sat%2C%2001%20Jan%202000%2001%3A00%3A00 FILE \n' + + '201: "%20dir2" 0 Sat%2C%2001%20Jan%202000%2001%3A00%3A00 DIRECTORY \n' + + '201: "%20junction2" Sat%2C%2001%20Jan%202000%2001%3A00%3A00 SYMBOLIC-LINK \n' + + '201: "%20file2" 95077 Sat%2C%2001%20Jan%202000%2001%3A00%3A00 FILE \n', + ], // DOS format with wrong offsets - ["01-01-00 01:00AM dir1\r\n" + - "01-01-00 01:00AM dir2\r\n" + - "01-01-00 01:00AM dir3\r\n" + - "01-01-00 01:00AM junction1 -> foo1\r\n" + - "01-01-00 01:00AM junction2 -> foo2\r\n" + - "01-01-00 01:00AM junction3 -> foo3\r\n" + - "01-01-00 01:00AM 95077 file1\r\n" + - "01-01-00 01:00AM 95077 file2\r\n", + [ + "01-01-00 01:00AM dir1\r\n" + + "01-01-00 01:00AM dir2\r\n" + + "01-01-00 01:00AM dir3\r\n" + + "01-01-00 01:00AM junction1 -> foo1\r\n" + + "01-01-00 01:00AM junction2 -> foo2\r\n" + + "01-01-00 01:00AM junction3 -> foo3\r\n" + + "01-01-00 01:00AM 95077 file1\r\n" + + "01-01-00 01:00AM 95077 file2\r\n", - "300: " + URL + "\n" + - "200: filename content-length last-modified file-type\n" + - "201: \"dir1\" 0 Sat%2C%2001%20Jan%202000%2001%3A00%3A00 DIRECTORY \n" + - "201: \"dir2\" 0 Sat%2C%2001%20Jan%202000%2001%3A00%3A00 DIRECTORY \n" + - "201: \"dir3\" 0 Sat%2C%2001%20Jan%202000%2001%3A00%3A00 DIRECTORY \n" + - "201: \"junction1\" Sat%2C%2001%20Jan%202000%2001%3A00%3A00 SYMBOLIC-LINK \n" + - "201: \"junction2\" Sat%2C%2001%20Jan%202000%2001%3A00%3A00 SYMBOLIC-LINK \n" + - "201: \"junction3\" Sat%2C%2001%20Jan%202000%2001%3A00%3A00 SYMBOLIC-LINK \n" + - "201: \"file1\" 95077 Sat%2C%2001%20Jan%202000%2001%3A00%3A00 FILE \n" + - "201: \"file2\" 95077 Sat%2C%2001%20Jan%202000%2001%3A00%3A00 FILE \n"] -] + "300: " + + URL + + "\n" + + "200: filename content-length last-modified file-type\n" + + '201: "dir1" 0 Sat%2C%2001%20Jan%202000%2001%3A00%3A00 DIRECTORY \n' + + '201: "dir2" 0 Sat%2C%2001%20Jan%202000%2001%3A00%3A00 DIRECTORY \n' + + '201: "dir3" 0 Sat%2C%2001%20Jan%202000%2001%3A00%3A00 DIRECTORY \n' + + '201: "junction1" Sat%2C%2001%20Jan%202000%2001%3A00%3A00 SYMBOLIC-LINK \n' + + '201: "junction2" Sat%2C%2001%20Jan%202000%2001%3A00%3A00 SYMBOLIC-LINK \n' + + '201: "junction3" Sat%2C%2001%20Jan%202000%2001%3A00%3A00 SYMBOLIC-LINK \n' + + '201: "file1" 95077 Sat%2C%2001%20Jan%202000%2001%3A00%3A00 FILE \n' + + '201: "file2" 95077 Sat%2C%2001%20Jan%202000%2001%3A00%3A00 FILE \n', + ], +]; function checkData(request, data, ctx) { Assert.equal(tests[0][1], data); @@ -70,13 +90,19 @@ function checkData(request, data, ctx) { } function storeData(status, entry) { - var scs = Cc["@mozilla.org/streamConverters;1"]. - getService(Ci.nsIStreamConverterService); - var converter = scs.asyncConvertData("text/ftp-dir", "application/http-index-format", - new ChannelListener(checkData, null, CL_ALLOW_UNKNOWN_CL), null); + var scs = Cc["@mozilla.org/streamConverters;1"].getService( + Ci.nsIStreamConverterService + ); + var converter = scs.asyncConvertData( + "text/ftp-dir", + "application/http-index-format", + new ChannelListener(checkData, null, CL_ALLOW_UNKNOWN_CL), + null + ); - var stream = Cc["@mozilla.org/io/string-input-stream;1"]. - createInstance(Ci.nsIStringInputStream); + var stream = Cc["@mozilla.org/io/string-input-stream;1"].createInstance( + Ci.nsIStringInputStream + ); stream.data = tests[0][0]; var url = NetUtil.newURI(URL); @@ -88,7 +114,7 @@ function storeData(status, entry) { isPending() { return this.pending; }, - QueryInterface: ChromeUtils.generateQI([Ci.nsIChannel]) + QueryInterface: ChromeUtils.generateQI([Ci.nsIChannel]), }; converter.onStartRequest(channel, null); @@ -98,9 +124,9 @@ function storeData(status, entry) { } function next_test() { - if (tests.length == 0) + if (tests.length == 0) { do_test_finished(); - else { + } else { storeData(); } } diff --git a/netwerk/test/unit/test_bug490095.js b/netwerk/test/unit/test_bug490095.js index 6239d7fb3e22..964ec2b42240 100644 --- a/netwerk/test/unit/test_bug490095.js +++ b/netwerk/test/unit/test_bug490095.js @@ -3,113 +3,154 @@ // heuristic query freshness as defined in RFC 2616 section 13.9 // -const {HttpServer} = ChromeUtils.import("resource://testing-common/httpd.js"); +const { HttpServer } = ChromeUtils.import("resource://testing-common/httpd.js"); var httpserver = new HttpServer(); var index = 0; var tests = [ - {url: "/freshness?a", server: "0", expected: "0"}, - {url: "/freshness?a", server: "1", expected: "1"}, + { url: "/freshness?a", server: "0", expected: "0" }, + { url: "/freshness?a", server: "1", expected: "1" }, - // Setting the VALIDATE_NEVER flag should grab entry from cache - {url: "/freshness?a", server: "2", expected: "1", - flags: Ci.nsIRequest.VALIDATE_NEVER }, + // Setting the VALIDATE_NEVER flag should grab entry from cache + { + url: "/freshness?a", + server: "2", + expected: "1", + flags: Ci.nsIRequest.VALIDATE_NEVER, + }, - // Finally, check that request is validated with no flags set - {url: "/freshness?a", server: "99", expected: "99"}, - - {url: "/freshness?b", server: "0", expected: "0"}, - {url: "/freshness?b", server: "1", expected: "1"}, + // Finally, check that request is validated with no flags set + { url: "/freshness?a", server: "99", expected: "99" }, - // Setting the LOAD_FROM_CACHE flag also grab the entry from cache - {url: "/freshness?b", server: "2", expected: "1", - flags: Ci.nsIRequest.LOAD_FROM_CACHE }, + { url: "/freshness?b", server: "0", expected: "0" }, + { url: "/freshness?b", server: "1", expected: "1" }, - // Finally, check that request is validated with no flags set - {url: "/freshness?b", server: "99", expected: "99"}, + // Setting the LOAD_FROM_CACHE flag also grab the entry from cache + { + url: "/freshness?b", + server: "2", + expected: "1", + flags: Ci.nsIRequest.LOAD_FROM_CACHE, + }, + // Finally, check that request is validated with no flags set + { url: "/freshness?b", server: "99", expected: "99" }, ]; function logit(i, data) { - dump(tests[i].url + "\t requested [" + tests[i].server + "]" + - " got [" + data + "] expected [" + tests[i].expected + "]"); - if (tests[i].responseheader) - dump("\t[" + tests[i].responseheader + "]"); - dump("\n"); + dump( + tests[i].url + + "\t requested [" + + tests[i].server + + "]" + + " got [" + + data + + "] expected [" + + tests[i].expected + + "]" + ); + if (tests[i].responseheader) { + dump("\t[" + tests[i].responseheader + "]"); + } + dump("\n"); } function setupChannel(suffix, value) { - var chan = NetUtil.newChannel({ - uri: "http://localhost:" + httpserver.identity.primaryPort + suffix, - loadUsingSystemPrincipal: true - }); - var httpChan = chan.QueryInterface(Ci.nsIHttpChannel); - httpChan.requestMethod = "GET"; - httpChan.setRequestHeader("x-request", value, false); - return httpChan; + var chan = NetUtil.newChannel({ + uri: "http://localhost:" + httpserver.identity.primaryPort + suffix, + loadUsingSystemPrincipal: true, + }); + var httpChan = chan.QueryInterface(Ci.nsIHttpChannel); + httpChan.requestMethod = "GET"; + httpChan.setRequestHeader("x-request", value, false); + return httpChan; } function triggerNextTest() { - var test = tests[index]; - var channel = setupChannel(test.url, test.server); - if (test.flags) channel.loadFlags = test.flags; - channel.asyncOpen(new ChannelListener(checkValueAndTrigger, null)); + var test = tests[index]; + var channel = setupChannel(test.url, test.server); + if (test.flags) { + channel.loadFlags = test.flags; + } + channel.asyncOpen(new ChannelListener(checkValueAndTrigger, null)); } function checkValueAndTrigger(request, data, ctx) { - logit(index, data); - Assert.equal(tests[index].expected, data); + logit(index, data); + Assert.equal(tests[index].expected, data); - if (index < tests.length-1) { - index++; - // this call happens in onStopRequest from the channel, and opening a - // new channel to the same url here is no good idea... post it instead - do_timeout(1, triggerNextTest); - } else { - httpserver.stop(do_test_finished); - } + if (index < tests.length - 1) { + index++; + // this call happens in onStopRequest from the channel, and opening a + // new channel to the same url here is no good idea... post it instead + do_timeout(1, triggerNextTest); + } else { + httpserver.stop(do_test_finished); + } } function run_test() { - httpserver.registerPathHandler("/freshness", handler); - httpserver.start(-1); + httpserver.registerPathHandler("/freshness", handler); + httpserver.start(-1); - // clear cache - evict_cache_entries(); + // clear cache + evict_cache_entries(); - triggerNextTest(); + triggerNextTest(); - do_test_pending(); + do_test_pending(); } function handler(metadata, response) { - var body = metadata.getHeader("x-request"); - response.setHeader("Content-Type", "text/plain", false); - response.setHeader("Date", getDateString(0), false); - response.setHeader("Cache-Control", "max-age=0", false); - - var header = tests[index].responseheader; - if (header == null) { - response.setHeader("Last-Modified", getDateString(-1), false); - } else { - var splitHdr = header.split(": "); - response.setHeader(splitHdr[0], splitHdr[1], false); - } - - response.setStatusLine(metadata.httpVersion, 200, "OK"); - response.bodyOutputStream.write(body, body.length); -} - -function getDateString(yearDelta) { - var months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', - 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']; - var days = ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat']; + var body = metadata.getHeader("x-request"); + response.setHeader("Content-Type", "text/plain", false); + response.setHeader("Date", getDateString(0), false); + response.setHeader("Cache-Control", "max-age=0", false); - var d = new Date(); - return days[d.getUTCDay()] + ", " + - d.getUTCDate() + " " + - months[d.getUTCMonth()] + " " + - (d.getUTCFullYear() + yearDelta) + " " + - d.getUTCHours() + ":" + d.getUTCMinutes() +":" + - d.getUTCSeconds() + " UTC"; + var header = tests[index].responseheader; + if (header == null) { + response.setHeader("Last-Modified", getDateString(-1), false); + } else { + var splitHdr = header.split(": "); + response.setHeader(splitHdr[0], splitHdr[1], false); + } + + response.setStatusLine(metadata.httpVersion, 200, "OK"); + response.bodyOutputStream.write(body, body.length); +} + +function getDateString(yearDelta) { + var months = [ + "Jan", + "Feb", + "Mar", + "Apr", + "May", + "Jun", + "Jul", + "Aug", + "Sep", + "Oct", + "Nov", + "Dec", + ]; + var days = ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"]; + + var d = new Date(); + return ( + days[d.getUTCDay()] + + ", " + + d.getUTCDate() + + " " + + months[d.getUTCMonth()] + + " " + + (d.getUTCFullYear() + yearDelta) + + " " + + d.getUTCHours() + + ":" + + d.getUTCMinutes() + + ":" + + d.getUTCSeconds() + + " UTC" + ); } diff --git a/netwerk/test/unit/test_bug504014.js b/netwerk/test/unit/test_bug504014.js index 1ce758ad505c..bab9c4dd39bf 100644 --- a/netwerk/test/unit/test_bug504014.js +++ b/netwerk/test/unit/test_bug504014.js @@ -1,56 +1,59 @@ -var valid_URIs = [ "http://[::]/", - "http://[::1]/", - "http://[1::]/", - "http://[::]/", - "http://[::1]/", - "http://[1::]/", - "http://[1:2:3:4:5:6:7::]/", - "http://[::1:2:3:4:5:6:7]/", - "http://[1:2:a:B:c:D:e:F]/", - "http://[1::8]/", - "http://[1:2::8]/", - "http://[0000:0123:4567:89AB:CDEF:abcd:ef00:0000]/", - "http://[::192.168.1.1]/", - "http://[1::0.0.0.0]/", - "http://[1:2::255.255.255.255]/", - "http://[1:2:3::255.255.255.255]/", - "http://[1:2:3:4::255.255.255.255]/", - "http://[1:2:3:4:5::255.255.255.255]/", - "http://[1:2:3:4:5:6:255.255.255.255]/"]; +var valid_URIs = [ + "http://[::]/", + "http://[::1]/", + "http://[1::]/", + "http://[::]/", + "http://[::1]/", + "http://[1::]/", + "http://[1:2:3:4:5:6:7::]/", + "http://[::1:2:3:4:5:6:7]/", + "http://[1:2:a:B:c:D:e:F]/", + "http://[1::8]/", + "http://[1:2::8]/", + "http://[0000:0123:4567:89AB:CDEF:abcd:ef00:0000]/", + "http://[::192.168.1.1]/", + "http://[1::0.0.0.0]/", + "http://[1:2::255.255.255.255]/", + "http://[1:2:3::255.255.255.255]/", + "http://[1:2:3:4::255.255.255.255]/", + "http://[1:2:3:4:5::255.255.255.255]/", + "http://[1:2:3:4:5:6:255.255.255.255]/", +]; -var invalid_URIs = [ "http://[1]/", - "http://[192.168.1.1]/", - "http://[:::]/", - "http://[:::1]/", - "http://[1:::]/", - "http://[::1::]/", - "http://[1:2:3:4:5:6:7:]/", - "http://[:2:3:4:5:6:7:8]/", - "http://[1:2:3:4:5:6:7:8:]/", - "http://[:1:2:3:4:5:6:7:8]/", - "http://[1:2:3:4:5:6:7:8::]/", - "http://[::1:2:3:4:5:6:7:8]/", - "http://[1:2:3:4:5:6:7]/", - "http://[1:2:3:4:5:6:7:8:9]/", - "http://[00001:2:3:4:5:6:7:8]/", - "http://[0001:2:3:4:5:6:7:89abc]/", - "http://[A:b:C:d:E:f:G:h]/", - "http://[::192.168.1]/", - "http://[::192.168.1.]/", - "http://[::.168.1.1]/", - "http://[::192..1.1]/", - "http://[::0192.168.1.1]/", - "http://[::256.255.255.255]/", - "http://[::1x.255.255.255]/", - "http://[::192.4294967464.1.1]/", - "http://[1:2:3:4:5:6::255.255.255.255]/", - "http://[1:2:3:4:5:6:7:255.255.255.255]/"]; +var invalid_URIs = [ + "http://[1]/", + "http://[192.168.1.1]/", + "http://[:::]/", + "http://[:::1]/", + "http://[1:::]/", + "http://[::1::]/", + "http://[1:2:3:4:5:6:7:]/", + "http://[:2:3:4:5:6:7:8]/", + "http://[1:2:3:4:5:6:7:8:]/", + "http://[:1:2:3:4:5:6:7:8]/", + "http://[1:2:3:4:5:6:7:8::]/", + "http://[::1:2:3:4:5:6:7:8]/", + "http://[1:2:3:4:5:6:7]/", + "http://[1:2:3:4:5:6:7:8:9]/", + "http://[00001:2:3:4:5:6:7:8]/", + "http://[0001:2:3:4:5:6:7:89abc]/", + "http://[A:b:C:d:E:f:G:h]/", + "http://[::192.168.1]/", + "http://[::192.168.1.]/", + "http://[::.168.1.1]/", + "http://[::192..1.1]/", + "http://[::0192.168.1.1]/", + "http://[::256.255.255.255]/", + "http://[::1x.255.255.255]/", + "http://[::192.4294967464.1.1]/", + "http://[1:2:3:4:5:6::255.255.255.255]/", + "http://[1:2:3:4:5:6:7:255.255.255.255]/", +]; function run_test() { - var ios = Cc["@mozilla.org/network/io-service;1"]. - getService(Ci.nsIIOService); + var ios = Cc["@mozilla.org/network/io-service;1"].getService(Ci.nsIIOService); - for (var i=0 ; i 1) - triggerHandlers(); + if (handlers.length > 1) { + triggerHandlers(); + } } diff --git a/netwerk/test/unit/test_bug618835.js b/netwerk/test/unit/test_bug618835.js index f5259e6d5af0..ad80e75a18f2 100644 --- a/netwerk/test/unit/test_bug618835.js +++ b/netwerk/test/unit/test_bug618835.js @@ -11,67 +11,72 @@ // "/redirect" and "/cl" are loaded from server the expected number of times. // -const {HttpServer} = ChromeUtils.import("resource://testing-common/httpd.js"); +const { HttpServer } = ChromeUtils.import("resource://testing-common/httpd.js"); var httpserv; function setupChannel(path) { - return NetUtil.newChannel({uri: path, loadUsingSystemPrincipal: true}) - .QueryInterface(Ci.nsIHttpChannel); + return NetUtil.newChannel({ + uri: path, + loadUsingSystemPrincipal: true, + }).QueryInterface(Ci.nsIHttpChannel); } // Verify that Content-Location-URI has been loaded once, load post_target -function InitialListener() { } +function InitialListener() {} InitialListener.prototype = { - onStartRequest(request) { }, - onStopRequest(request, status) { - Assert.equal(1, numberOfCLHandlerCalls); - executeSoon(function() { - var channel = setupChannel("http://localhost:" + - httpserv.identity.primaryPort + "/post"); - channel.requestMethod = "POST"; - channel.asyncOpen(new RedirectingListener()); - }); - } + onStartRequest(request) {}, + onStopRequest(request, status) { + Assert.equal(1, numberOfCLHandlerCalls); + executeSoon(function() { + var channel = setupChannel( + "http://localhost:" + httpserv.identity.primaryPort + "/post" + ); + channel.requestMethod = "POST"; + channel.asyncOpen(new RedirectingListener()); + }); + }, }; // Verify that Location-URI has been loaded once, reload post_target -function RedirectingListener() { } +function RedirectingListener() {} RedirectingListener.prototype = { - onStartRequest(request) { }, - onStopRequest(request, status) { - Assert.equal(1, numberOfHandlerCalls); - executeSoon(function() { - var channel = setupChannel("http://localhost:" + - httpserv.identity.primaryPort + "/post"); - channel.requestMethod = "POST"; - channel.asyncOpen(new VerifyingListener()); - }); - } + onStartRequest(request) {}, + onStopRequest(request, status) { + Assert.equal(1, numberOfHandlerCalls); + executeSoon(function() { + var channel = setupChannel( + "http://localhost:" + httpserv.identity.primaryPort + "/post" + ); + channel.requestMethod = "POST"; + channel.asyncOpen(new VerifyingListener()); + }); + }, }; // Verify that Location-URI has been loaded twice (cached entry invalidated), // reload Content-Location-URI -function VerifyingListener() { } +function VerifyingListener() {} VerifyingListener.prototype = { - onStartRequest(request) { }, - onStopRequest(request, status) { - Assert.equal(2, numberOfHandlerCalls); - var channel = setupChannel("http://localhost:" + - httpserv.identity.primaryPort + "/cl"); - channel.asyncOpen(new FinalListener()); - } + onStartRequest(request) {}, + onStopRequest(request, status) { + Assert.equal(2, numberOfHandlerCalls); + var channel = setupChannel( + "http://localhost:" + httpserv.identity.primaryPort + "/cl" + ); + channel.asyncOpen(new FinalListener()); + }, }; // Verify that Location-URI has been loaded twice (cached entry invalidated), // stop test -function FinalListener() { } +function FinalListener() {} FinalListener.prototype = { - onStartRequest(request) { }, - onStopRequest(request, status) { - Assert.equal(2, numberOfCLHandlerCalls); - httpserv.stop(do_test_finished); - } + onStartRequest(request) {}, + onStopRequest(request, status) { + Assert.equal(2, numberOfCLHandlerCalls); + httpserv.stop(do_test_finished); + }, }; function run_test() { @@ -85,8 +90,9 @@ function run_test() { evict_cache_entries(); // Load Content-Location URI into cache and start the chain of loads - var channel = setupChannel("http://localhost:" + - httpserv.identity.primaryPort + "/cl"); + var channel = setupChannel( + "http://localhost:" + httpserv.identity.primaryPort + "/cl" + ); channel.asyncOpen(new InitialListener()); do_test_pending(); @@ -94,21 +100,21 @@ function run_test() { var numberOfCLHandlerCalls = 0; function content_location(metadata, response) { - numberOfCLHandlerCalls++; - response.setStatusLine(metadata.httpVersion, 200, "Ok"); - response.setHeader("Cache-Control", "max-age=360000", false); + numberOfCLHandlerCalls++; + response.setStatusLine(metadata.httpVersion, 200, "Ok"); + response.setHeader("Cache-Control", "max-age=360000", false); } function post_target(metadata, response) { - response.setStatusLine(metadata.httpVersion, 301, "Moved Permanently"); - response.setHeader("Location", "/redirect", false); - response.setHeader("Content-Location", "/cl", false); - response.setHeader("Cache-Control", "max-age=360000", false); + response.setStatusLine(metadata.httpVersion, 301, "Moved Permanently"); + response.setHeader("Location", "/redirect", false); + response.setHeader("Content-Location", "/cl", false); + response.setHeader("Cache-Control", "max-age=360000", false); } var numberOfHandlerCalls = 0; function redirect_target(metadata, response) { - numberOfHandlerCalls++; - response.setStatusLine(metadata.httpVersion, 200, "Ok"); - response.setHeader("Cache-Control", "max-age=360000", false); + numberOfHandlerCalls++; + response.setStatusLine(metadata.httpVersion, 200, "Ok"); + response.setHeader("Cache-Control", "max-age=360000", false); } diff --git a/netwerk/test/unit/test_bug633743.js b/netwerk/test/unit/test_bug633743.js index 8a4a1a294238..9d21a8b63b7f 100644 --- a/netwerk/test/unit/test_bug633743.js +++ b/netwerk/test/unit/test_bug633743.js @@ -1,4 +1,4 @@ -const {HttpServer} = ChromeUtils.import("resource://testing-common/httpd.js"); +const { HttpServer } = ChromeUtils.import("resource://testing-common/httpd.js"); const VALUE_HDR_NAME = "X-HTTP-VALUE-HEADER"; const VARY_HDR_NAME = "X-HTTP-VARY-HEADER"; @@ -9,17 +9,17 @@ var httpserver = null; function make_channel(flags, vary, value) { var chan = NetUtil.newChannel({ uri: "http://localhost:" + httpserver.identity.primaryPort + "/bug633743", - loadUsingSystemPrincipal: true + loadUsingSystemPrincipal: true, }).QueryInterface(Ci.nsIHttpChannel); return chan.QueryInterface(Ci.nsIHttpChannel); } function Test(flags, varyHdr, sendValue, expectValue, cacheHdr) { - this._flags = flags; - this._varyHdr = varyHdr; - this._sendVal = sendValue; - this._expectVal = expectValue; - this._cacheHdr = cacheHdr; + this._flags = flags; + this._varyHdr = varyHdr; + this._sendVal = sendValue; + this._expectVal = expectValue; + this._cacheHdr = cacheHdr; } Test.prototype = { @@ -30,9 +30,12 @@ Test.prototype = { _expectVal: null, _cacheHdr: null, - QueryInterface: ChromeUtils.generateQI(["nsIStreamListener", "nsIRequestObserver"]), + QueryInterface: ChromeUtils.generateQI([ + "nsIStreamListener", + "nsIRequestObserver", + ]), - onStartRequest(request) { }, + onStartRequest(request) {}, onDataAvailable(request, stream, offset, count) { this._buffer = this._buffer.concat(read_stream(stream, count)); @@ -48,89 +51,100 @@ Test.prototype = { channel.loadFlags = this._flags; channel.setRequestHeader(VALUE_HDR_NAME, this._sendVal, false); channel.setRequestHeader(VARY_HDR_NAME, this._varyHdr, false); - if (this._cacheHdr) - channel.setRequestHeader(CACHECTRL_HDR_NAME, this._cacheHdr, false); + if (this._cacheHdr) { + channel.setRequestHeader(CACHECTRL_HDR_NAME, this._cacheHdr, false); + } channel.asyncOpen(this); - } + }, }; var gTests = [ -// Test LOAD_FROM_CACHE: Load cache-entry - new Test(Ci.nsIRequest.LOAD_NORMAL, - "entity-initial", // hdr-value used to vary - "request1", // echoed by handler - "request1" // value expected to receive in channel - ), -// Verify that it was cached - new Test(Ci.nsIRequest.LOAD_NORMAL, - "entity-initial", // hdr-value used to vary - "fresh value with LOAD_NORMAL", // echoed by handler - "request1" // value expected to receive in channel - ), -// Load same entity with LOAD_FROM_CACHE-flag - new Test(Ci.nsIRequest.LOAD_FROM_CACHE, - "entity-initial", // hdr-value used to vary - "fresh value with LOAD_FROM_CACHE", // echoed by handler - "request1" // value expected to receive in channel - ), -// Load different entity with LOAD_FROM_CACHE-flag - new Test(Ci.nsIRequest.LOAD_FROM_CACHE, - "entity-l-f-c", // hdr-value used to vary - "request2", // echoed by handler - "request2" // value expected to receive in channel - ), -// Verify that new value was cached - new Test(Ci.nsIRequest.LOAD_NORMAL, - "entity-l-f-c", // hdr-value used to vary - "fresh value with LOAD_NORMAL", // echoed by handler - "request2" // value expected to receive in channel - ), + // Test LOAD_FROM_CACHE: Load cache-entry + new Test( + Ci.nsIRequest.LOAD_NORMAL, + "entity-initial", // hdr-value used to vary + "request1", // echoed by handler + "request1" // value expected to receive in channel + ), + // Verify that it was cached + new Test( + Ci.nsIRequest.LOAD_NORMAL, + "entity-initial", // hdr-value used to vary + "fresh value with LOAD_NORMAL", // echoed by handler + "request1" // value expected to receive in channel + ), + // Load same entity with LOAD_FROM_CACHE-flag + new Test( + Ci.nsIRequest.LOAD_FROM_CACHE, + "entity-initial", // hdr-value used to vary + "fresh value with LOAD_FROM_CACHE", // echoed by handler + "request1" // value expected to receive in channel + ), + // Load different entity with LOAD_FROM_CACHE-flag + new Test( + Ci.nsIRequest.LOAD_FROM_CACHE, + "entity-l-f-c", // hdr-value used to vary + "request2", // echoed by handler + "request2" // value expected to receive in channel + ), + // Verify that new value was cached + new Test( + Ci.nsIRequest.LOAD_NORMAL, + "entity-l-f-c", // hdr-value used to vary + "fresh value with LOAD_NORMAL", // echoed by handler + "request2" // value expected to receive in channel + ), -// Test VALIDATE_NEVER: Note previous cache-entry - new Test(Ci.nsIRequest.VALIDATE_NEVER, - "entity-v-n", // hdr-value used to vary - "request3", // echoed by handler - "request3" // value expected to receive in channel - ), -// Verify that cache-entry was replaced - new Test(Ci.nsIRequest.LOAD_NORMAL, - "entity-v-n", // hdr-value used to vary - "fresh value with LOAD_NORMAL", // echoed by handler - "request3" // value expected to receive in channel - ), + // Test VALIDATE_NEVER: Note previous cache-entry + new Test( + Ci.nsIRequest.VALIDATE_NEVER, + "entity-v-n", // hdr-value used to vary + "request3", // echoed by handler + "request3" // value expected to receive in channel + ), + // Verify that cache-entry was replaced + new Test( + Ci.nsIRequest.LOAD_NORMAL, + "entity-v-n", // hdr-value used to vary + "fresh value with LOAD_NORMAL", // echoed by handler + "request3" // value expected to receive in channel + ), -// Test combination VALIDATE_NEVER && no-store: Load new cache-entry - new Test(Ci.nsIRequest.LOAD_NORMAL, - "entity-2",// hdr-value used to vary - "request4", // echoed by handler - "request4", // value expected to receive in channel - "no-store" // set no-store on response - ), -// Ensure we validate without IMS header in this case (verified in handler) - new Test(Ci.nsIRequest.VALIDATE_NEVER, - "entity-2-v-n",// hdr-value used to vary - "request5", // echoed by handler - "request5" // value expected to receive in channel - ), + // Test combination VALIDATE_NEVER && no-store: Load new cache-entry + new Test( + Ci.nsIRequest.LOAD_NORMAL, + "entity-2", // hdr-value used to vary + "request4", // echoed by handler + "request4", // value expected to receive in channel + "no-store" // set no-store on response + ), + // Ensure we validate without IMS header in this case (verified in handler) + new Test( + Ci.nsIRequest.VALIDATE_NEVER, + "entity-2-v-n", // hdr-value used to vary + "request5", // echoed by handler + "request5" // value expected to receive in channel + ), -// Test VALIDATE-ALWAYS: Load new entity - new Test(Ci.nsIRequest.LOAD_NORMAL, - "entity-3",// hdr-value used to vary - "request6", // echoed by handler - "request6", // value expected to receive in channel - "no-cache" // set no-cache on response - ), -// Ensure we don't send IMS header also in this case (verified in handler) - new Test(Ci.nsIRequest.VALIDATE_ALWAYS, - "entity-3-v-a",// hdr-value used to vary - "request7", // echoed by handler - "request7" // value expected to receive in channel - ), - ]; + // Test VALIDATE-ALWAYS: Load new entity + new Test( + Ci.nsIRequest.LOAD_NORMAL, + "entity-3", // hdr-value used to vary + "request6", // echoed by handler + "request6", // value expected to receive in channel + "no-cache" // set no-cache on response + ), + // Ensure we don't send IMS header also in this case (verified in handler) + new Test( + Ci.nsIRequest.VALIDATE_ALWAYS, + "entity-3-v-a", // hdr-value used to vary + "request7", // echoed by handler + "request7" // value expected to receive in channel + ), +]; -function run_next_test() -{ +function run_next_test() { if (gTests.length == 0) { httpserver.stop(do_test_finished); return; @@ -141,7 +155,6 @@ function run_next_test() } function handler(metadata, response) { - // None of the tests above should send an IMS Assert.ok(!metadata.hasHeader("If-Modified-Since")); @@ -149,13 +162,13 @@ function handler(metadata, response) { var hdr = "default value"; try { hdr = metadata.getHeader(VALUE_HDR_NAME); - } catch(ex) { } + } catch (ex) {} // Pick up requested cache-control header-value var cctrlVal = "max-age=10000"; try { - cctrlVal = metadata.getHeader(CACHECTRL_HDR_NAME); - } catch(ex) { } + cctrlVal = metadata.getHeader(CACHECTRL_HDR_NAME); + } catch (ex) {} response.setStatusLine(metadata.httpVersion, 200, "OK"); response.setHeader("Content-Type", "text/plain", false); @@ -166,7 +179,6 @@ function handler(metadata, response) { } function run_test() { - // clear the cache evict_cache_entries(); diff --git a/netwerk/test/unit/test_bug650522.js b/netwerk/test/unit/test_bug650522.js index fa930fb4c7e4..5dc5dcd8b9ed 100644 --- a/netwerk/test/unit/test_bug650522.js +++ b/netwerk/test/unit/test_bug650522.js @@ -8,7 +8,21 @@ function run_test() { // Test our handling of host names with a single character at the beginning // followed by a dot. - cm.add("e.mail.com", "/", "foo", "bar", false, false, true, expiry, {}, Ci.nsICookie.SAMESITE_NONE); + cm.add( + "e.mail.com", + "/", + "foo", + "bar", + false, + false, + true, + expiry, + {}, + Ci.nsICookie.SAMESITE_NONE + ); Assert.equal(cm.countCookiesFromHost("e.mail.com"), 1); - Assert.equal(cs.getCookieString(NetUtil.newURI("http://e.mail.com"), null), "foo=bar"); + Assert.equal( + cs.getCookieString(NetUtil.newURI("http://e.mail.com"), null), + "foo=bar" + ); } diff --git a/netwerk/test/unit/test_bug650995.js b/netwerk/test/unit/test_bug650995.js index 01e50f594e1c..ff47a929891b 100644 --- a/netwerk/test/unit/test_bug650995.js +++ b/netwerk/test/unit/test_bug650995.js @@ -3,147 +3,184 @@ // caching resources with size out of bounds // -const {HttpServer} = ChromeUtils.import("resource://testing-common/httpd.js"); +const { HttpServer } = ChromeUtils.import("resource://testing-common/httpd.js"); do_get_profile(); -const prefService = Cc["@mozilla.org/preferences-service;1"] - .getService(Ci.nsIPrefBranch); +const prefService = Cc["@mozilla.org/preferences-service;1"].getService( + Ci.nsIPrefBranch +); const httpserver = new HttpServer(); // Repeats the given data until the total size is larger than 1K function repeatToLargerThan1K(data) { - while(data.length <= 1024) - data += data; - return data; + while (data.length <= 1024) { + data += data; + } + return data; } function setupChannel(suffix, value) { - var chan = NetUtil.newChannel({ - uri: "http://localhost:" + httpserver.identity.primaryPort + suffix, - loadUsingSystemPrincipal: true - }); - var httpChan = chan.QueryInterface(Ci.nsIHttpChannel); - httpChan.setRequestHeader("x-request", value, false); - - return httpChan; + var chan = NetUtil.newChannel({ + uri: "http://localhost:" + httpserver.identity.primaryPort + suffix, + loadUsingSystemPrincipal: true, + }); + var httpChan = chan.QueryInterface(Ci.nsIHttpChannel); + httpChan.setRequestHeader("x-request", value, false); + + return httpChan; } var tests = [ - new InitializeCacheDevices(true, false), // enable and create mem-device - new TestCacheEntrySize( - function() { prefService.setIntPref("browser.cache.memory.max_entry_size", 1); }, - "012345", "9876543210", "012345"), // expect cached value - new TestCacheEntrySize( - function() { prefService.setIntPref("browser.cache.memory.max_entry_size", 1); }, - "0123456789a", "9876543210", "9876543210"), // expect fresh value - new TestCacheEntrySize( - function() { prefService.setIntPref("browser.cache.memory.max_entry_size", -1); }, - "0123456789a", "9876543210", "0123456789a"), // expect cached value + new InitializeCacheDevices(true, false), // enable and create mem-device + new TestCacheEntrySize( + function() { + prefService.setIntPref("browser.cache.memory.max_entry_size", 1); + }, + "012345", + "9876543210", + "012345" + ), // expect cached value + new TestCacheEntrySize( + function() { + prefService.setIntPref("browser.cache.memory.max_entry_size", 1); + }, + "0123456789a", + "9876543210", + "9876543210" + ), // expect fresh value + new TestCacheEntrySize( + function() { + prefService.setIntPref("browser.cache.memory.max_entry_size", -1); + }, + "0123456789a", + "9876543210", + "0123456789a" + ), // expect cached value - new InitializeCacheDevices(false, true), // enable and create disk-device - new TestCacheEntrySize( - function() { prefService.setIntPref("browser.cache.disk.max_entry_size", 1); }, - "012345", "9876543210", "012345"), // expect cached value - new TestCacheEntrySize( - function() { prefService.setIntPref("browser.cache.disk.max_entry_size", 1); }, - "0123456789a", "9876543210", "9876543210"), // expect fresh value - new TestCacheEntrySize( - function() { prefService.setIntPref("browser.cache.disk.max_entry_size", -1); }, - "0123456789a", "9876543210", "0123456789a"), // expect cached value - ]; + new InitializeCacheDevices(false, true), // enable and create disk-device + new TestCacheEntrySize( + function() { + prefService.setIntPref("browser.cache.disk.max_entry_size", 1); + }, + "012345", + "9876543210", + "012345" + ), // expect cached value + new TestCacheEntrySize( + function() { + prefService.setIntPref("browser.cache.disk.max_entry_size", 1); + }, + "0123456789a", + "9876543210", + "9876543210" + ), // expect fresh value + new TestCacheEntrySize( + function() { + prefService.setIntPref("browser.cache.disk.max_entry_size", -1); + }, + "0123456789a", + "9876543210", + "0123456789a" + ), // expect cached value +]; function nextTest() { - // We really want each test to be self-contained. Make sure cache is - // cleared and also let all operations finish before starting a new test - syncWithCacheIOThread(function() { - get_cache_service().clear(); - syncWithCacheIOThread(runNextTest); - }); + // We really want each test to be self-contained. Make sure cache is + // cleared and also let all operations finish before starting a new test + syncWithCacheIOThread(function() { + get_cache_service().clear(); + syncWithCacheIOThread(runNextTest); + }); } function runNextTest() { - var aTest = tests.shift(); - if (!aTest) { - httpserver.stop(do_test_finished); - return; - } - executeSoon(function() { aTest.start(); } ); + var aTest = tests.shift(); + if (!aTest) { + httpserver.stop(do_test_finished); + return; + } + executeSoon(function() { + aTest.start(); + }); } // Just make sure devices are created function InitializeCacheDevices(memDevice, diskDevice) { - this.start = function() { - prefService.setBoolPref("browser.cache.memory.enable", memDevice); - if (memDevice) { - cap = prefService.getIntPref("browser.cache.memory.capacity", 0); - if (cap == 0) { - prefService.setIntPref("browser.cache.memory.capacity", 1024); - } - } - prefService.setBoolPref("browser.cache.disk.enable", diskDevice); - if (diskDevice) { - cap = prefService.getIntPref("browser.cache.disk.capacity", 0); - if (cap == 0) { - prefService.setIntPref("browser.cache.disk.capacity", 1024); - } - } - var channel = setupChannel("/bug650995", "Initial value"); - channel.asyncOpen(new ChannelListener(nextTest, null)); + this.start = function() { + prefService.setBoolPref("browser.cache.memory.enable", memDevice); + if (memDevice) { + cap = prefService.getIntPref("browser.cache.memory.capacity", 0); + if (cap == 0) { + prefService.setIntPref("browser.cache.memory.capacity", 1024); + } } + prefService.setBoolPref("browser.cache.disk.enable", diskDevice); + if (diskDevice) { + cap = prefService.getIntPref("browser.cache.disk.capacity", 0); + if (cap == 0) { + prefService.setIntPref("browser.cache.disk.capacity", 1024); + } + } + var channel = setupChannel("/bug650995", "Initial value"); + channel.asyncOpen(new ChannelListener(nextTest, null)); + }; } -function TestCacheEntrySize(setSizeFunc, firstRequest, secondRequest, secondExpectedReply) { +function TestCacheEntrySize( + setSizeFunc, + firstRequest, + secondRequest, + secondExpectedReply +) { + // Initially, this test used 10 bytes as the limit for caching entries. + // Since we now use 1K granularity we have to extend lengths to be larger + // than 1K if it is larger than 10 + if (firstRequest.length > 10) { + firstRequest = repeatToLargerThan1K(firstRequest); + } + if (secondExpectedReply.length > 10) { + secondExpectedReply = repeatToLargerThan1K(secondExpectedReply); + } - // Initially, this test used 10 bytes as the limit for caching entries. - // Since we now use 1K granularity we have to extend lengths to be larger - // than 1K if it is larger than 10 - if (firstRequest.length > 10) - firstRequest = repeatToLargerThan1K(firstRequest); - if (secondExpectedReply.length > 10) - secondExpectedReply = repeatToLargerThan1K(secondExpectedReply); - - this.start = function() { - setSizeFunc(); - var channel = setupChannel("/bug650995", firstRequest); - channel.asyncOpen(new ChannelListener(this.initialLoad, this)); - }, - - this.initialLoad = function(request, data, ctx) { - Assert.equal(firstRequest, data); - var channel = setupChannel("/bug650995", secondRequest); - executeSoon(function() { - channel.asyncOpen(new ChannelListener(ctx.testAndTriggerNext, ctx)); - }); - }, - - this.testAndTriggerNext = function(request, data, ctx) { - Assert.equal(secondExpectedReply, data); - executeSoon(nextTest); - } + (this.start = function() { + setSizeFunc(); + var channel = setupChannel("/bug650995", firstRequest); + channel.asyncOpen(new ChannelListener(this.initialLoad, this)); + }), + (this.initialLoad = function(request, data, ctx) { + Assert.equal(firstRequest, data); + var channel = setupChannel("/bug650995", secondRequest); + executeSoon(function() { + channel.asyncOpen(new ChannelListener(ctx.testAndTriggerNext, ctx)); + }); + }), + (this.testAndTriggerNext = function(request, data, ctx) { + Assert.equal(secondExpectedReply, data); + executeSoon(nextTest); + }); } -function run_test() -{ - httpserver.registerPathHandler("/bug650995", handler); - httpserver.start(-1); +function run_test() { + httpserver.registerPathHandler("/bug650995", handler); + httpserver.start(-1); - prefService.setBoolPref("browser.cache.offline.enable", false); - prefService.setBoolPref("network.http.rcwn.enabled", false); + prefService.setBoolPref("browser.cache.offline.enable", false); + prefService.setBoolPref("network.http.rcwn.enabled", false); - nextTest(); - do_test_pending(); + nextTest(); + do_test_pending(); } function handler(metadata, response) { - var body = "BOOM!"; - try { - body = metadata.getHeader("x-request"); - } catch(e) {} + var body = "BOOM!"; + try { + body = metadata.getHeader("x-request"); + } catch (e) {} - response.setStatusLine(metadata.httpVersion, 200, "Ok"); - response.setHeader("Content-Type", "text/plain", false); - response.setHeader("Cache-Control", "max-age=3600", false); - response.bodyOutputStream.write(body, body.length); + response.setStatusLine(metadata.httpVersion, 200, "Ok"); + response.setHeader("Content-Type", "text/plain", false); + response.setHeader("Cache-Control", "max-age=3600", false); + response.bodyOutputStream.write(body, body.length); } diff --git a/netwerk/test/unit/test_bug652761.js b/netwerk/test/unit/test_bug652761.js index e8664d6fa929..644cba4c598a 100644 --- a/netwerk/test/unit/test_bug652761.js +++ b/netwerk/test/unit/test_bug652761.js @@ -1,15 +1,17 @@ // This is just a crashtest for a url that is rejected at parse time (port 80,000) +function run_test() { + // Bug 1301621 makes invalid ports throw + Assert.throws( + () => { + var chan = NetUtil.newChannel({ + uri: "http://localhost:80000/", + loadUsingSystemPrincipal: true, + }); + }, + /NS_ERROR_MALFORMED_URI/, + "invalid port" + ); -function run_test() -{ - // Bug 1301621 makes invalid ports throw - Assert.throws(() => { - var chan = NetUtil.newChannel({ - uri: "http://localhost:80000/", - loadUsingSystemPrincipal: true - }); - }, /NS_ERROR_MALFORMED_URI/, "invalid port"); - - do_test_finished(); + do_test_finished(); } diff --git a/netwerk/test/unit/test_bug654926.js b/netwerk/test/unit/test_bug654926.js index 77a8f80ac53f..29e08bd1803c 100644 --- a/netwerk/test/unit/test_bug654926.js +++ b/netwerk/test/unit/test_bug654926.js @@ -1,41 +1,48 @@ var _PSvc; function get_pref_service() { - if (_PSvc) + if (_PSvc) { return _PSvc; + } - return _PSvc = Cc["@mozilla.org/preferences-service;1"]. - getService(Ci.nsIPrefBranch); + return (_PSvc = Cc["@mozilla.org/preferences-service;1"].getService( + Ci.nsIPrefBranch + )); } -function gen_1MiB() -{ +function gen_1MiB() { var i; - var data="x"; - for (i=0 ; i < 20 ; i++) - data+=data; + var data = "x"; + for (i = 0; i < 20; i++) { + data += data; + } return data; } -function write_and_check(str, data, len) -{ +function write_and_check(str, data, len) { var written = str.write(data, len); if (written != len) { - do_throw("str.write has not written all data!\n" + - " Expected: " + len + "\n" + - " Actual: " + written + "\n"); + do_throw( + "str.write has not written all data!\n" + + " Expected: " + + len + + "\n" + + " Actual: " + + written + + "\n" + ); } } -function write_datafile(status, entry) -{ +function write_datafile(status, entry) { Assert.equal(status, Cr.NS_OK); var data = gen_1MiB(); var os = entry.openOutputStream(0, data.length); // write 2MiB var i; - for (i=0 ; i<2 ; i++) + for (i = 0; i < 2; i++) { write_and_check(os, data, data.length); + } os.close(); entry.close(); @@ -44,13 +51,16 @@ function write_datafile(status, entry) get_pref_service().setIntPref("browser.cache.disk.max_entry_size", 1024); // append to entry - asyncOpenCacheEntry("http://data/", - "disk", Ci.nsICacheStorage.OPEN_NORMALLY, null, - append_datafile); + asyncOpenCacheEntry( + "http://data/", + "disk", + Ci.nsICacheStorage.OPEN_NORMALLY, + null, + append_datafile + ); } -function append_datafile(status, entry) -{ +function append_datafile(status, entry) { Assert.equal(status, Cr.NS_OK); var os = entry.openOutputStream(entry.dataSize, -1); var data = gen_1MiB(); @@ -59,15 +69,13 @@ function append_datafile(status, entry) try { write_and_check(os, data, data.length); do_throw(); - } - catch (ex) { } + } catch (ex) {} // closing the ostream should fail in this case try { os.close(); do_throw(); - } - catch (ex) { } + } catch (ex) {} entry.close(); @@ -80,9 +88,13 @@ function run_test() { // clear the cache evict_cache_entries(); - asyncOpenCacheEntry("http://data/", - "disk", Ci.nsICacheStorage.OPEN_NORMALLY, null, - write_datafile); + asyncOpenCacheEntry( + "http://data/", + "disk", + Ci.nsICacheStorage.OPEN_NORMALLY, + null, + write_datafile + ); do_test_pending(); } diff --git a/netwerk/test/unit/test_bug654926_doom_and_read.js b/netwerk/test/unit/test_bug654926_doom_and_read.js index 309834e1bf0d..c41b9172c441 100644 --- a/netwerk/test/unit/test_bug654926_doom_and_read.js +++ b/netwerk/test/unit/test_bug654926_doom_and_read.js @@ -1,31 +1,36 @@ -function gen_1MiB() -{ +function gen_1MiB() { var i; - var data="x"; - for (i=0 ; i < 20 ; i++) - data+=data; + var data = "x"; + for (i = 0; i < 20; i++) { + data += data; + } return data; } -function write_and_check(str, data, len) -{ +function write_and_check(str, data, len) { var written = str.write(data, len); if (written != len) { - do_throw("str.write has not written all data!\n" + - " Expected: " + len + "\n" + - " Actual: " + written + "\n"); + do_throw( + "str.write has not written all data!\n" + + " Expected: " + + len + + "\n" + + " Actual: " + + written + + "\n" + ); } } function make_input_stream_scriptable(input) { - var wrapper = Cc["@mozilla.org/scriptableinputstream;1"]. - createInstance(Ci.nsIScriptableInputStream); + var wrapper = Cc["@mozilla.org/scriptableinputstream;1"].createInstance( + Ci.nsIScriptableInputStream + ); wrapper.init(input); return wrapper; } -function write_datafile(status, entry) -{ +function write_datafile(status, entry) { Assert.equal(status, Cr.NS_OK); var data = gen_1MiB(); var os = entry.openOutputStream(0, data.length); @@ -36,14 +41,16 @@ function write_datafile(status, entry) entry.close(); // open, doom, append, read - asyncOpenCacheEntry("http://data/", - "disk", Ci.nsICacheStorage.OPEN_NORMALLY, null, - test_read_after_doom); - + asyncOpenCacheEntry( + "http://data/", + "disk", + Ci.nsICacheStorage.OPEN_NORMALLY, + null, + test_read_after_doom + ); } -function test_read_after_doom(status, entry) -{ +function test_read_after_doom(status, entry) { Assert.equal(status, Cr.NS_OK); var data = gen_1MiB(); var os = entry.openOutputStream(entry.dataSize, data.length); @@ -55,7 +62,7 @@ function test_read_after_doom(status, entry) var is = entry.openInputStream(0); pumpReadStream(is, function(read) { - Assert.equal(read.length, 2*1024*1024); + Assert.equal(read.length, 2 * 1024 * 1024); is.close(); entry.close(); @@ -69,9 +76,13 @@ function run_test() { // clear the cache evict_cache_entries(); - asyncOpenCacheEntry("http://data/", - "disk", Ci.nsICacheStorage.OPEN_NORMALLY, null, - write_datafile); + asyncOpenCacheEntry( + "http://data/", + "disk", + Ci.nsICacheStorage.OPEN_NORMALLY, + null, + write_datafile + ); do_test_pending(); } diff --git a/netwerk/test/unit/test_bug654926_test_seek.js b/netwerk/test/unit/test_bug654926_test_seek.js index 3aaf1b37afaf..02ce9df4647e 100644 --- a/netwerk/test/unit/test_bug654926_test_seek.js +++ b/netwerk/test/unit/test_bug654926_test_seek.js @@ -1,24 +1,28 @@ -function gen_1MiB() -{ +function gen_1MiB() { var i; - var data="x"; - for (i=0 ; i < 20 ; i++) - data+=data; + var data = "x"; + for (i = 0; i < 20; i++) { + data += data; + } return data; } -function write_and_check(str, data, len) -{ +function write_and_check(str, data, len) { var written = str.write(data, len); if (written != len) { - do_throw("str.write has not written all data!\n" + - " Expected: " + len + "\n" + - " Actual: " + written + "\n"); + do_throw( + "str.write has not written all data!\n" + + " Expected: " + + len + + "\n" + + " Actual: " + + written + + "\n" + ); } } -function write_datafile(status, entry) -{ +function write_datafile(status, entry) { Assert.equal(status, Cr.NS_OK); var data = gen_1MiB(); var os = entry.openOutputStream(0, data.length); @@ -29,13 +33,16 @@ function write_datafile(status, entry) entry.close(); // try to open the entry for appending - asyncOpenCacheEntry("http://data/", - "disk", Ci.nsICacheStorage.OPEN_NORMALLY, null, - open_for_readwrite); + asyncOpenCacheEntry( + "http://data/", + "disk", + Ci.nsICacheStorage.OPEN_NORMALLY, + null, + open_for_readwrite + ); } -function open_for_readwrite(status, entry) -{ +function open_for_readwrite(status, entry) { Assert.equal(status, Cr.NS_OK); var os = entry.openOutputStream(entry.dataSize, -1); @@ -55,9 +62,13 @@ function run_test() { // clear the cache evict_cache_entries(); - asyncOpenCacheEntry("http://data/", - "disk", Ci.nsICacheStorage.OPEN_NORMALLY, null, - write_datafile); + asyncOpenCacheEntry( + "http://data/", + "disk", + Ci.nsICacheStorage.OPEN_NORMALLY, + null, + write_datafile + ); do_test_pending(); } diff --git a/netwerk/test/unit/test_bug659569.js b/netwerk/test/unit/test_bug659569.js index 43e0fa84ecee..cdc1a5383496 100644 --- a/netwerk/test/unit/test_bug659569.js +++ b/netwerk/test/unit/test_bug659569.js @@ -1,58 +1,56 @@ -const {HttpServer} = ChromeUtils.import("resource://testing-common/httpd.js"); +const { HttpServer } = ChromeUtils.import("resource://testing-common/httpd.js"); var httpserver = new HttpServer(); -function setupChannel(suffix) -{ +function setupChannel(suffix) { return NetUtil.newChannel({ uri: "http://localhost:" + httpserver.identity.primaryPort + suffix, - loadUsingSystemPrincipal: true + loadUsingSystemPrincipal: true, }); } -function checkValueAndTrigger(request, data, ctx) -{ - Assert.equal("Ok", data); - httpserver.stop(do_test_finished); +function checkValueAndTrigger(request, data, ctx) { + Assert.equal("Ok", data); + httpserver.stop(do_test_finished); } -function run_test() -{ - // We don't want to have CookieSettings blocking this test. - Services.prefs.setBoolPref("network.cookieSettings.unblocked_for_testing", true); +function run_test() { + // We don't want to have CookieSettings blocking this test. + Services.prefs.setBoolPref( + "network.cookieSettings.unblocked_for_testing", + true + ); - // Allow all cookies. - Services.prefs.setIntPref("network.cookie.cookieBehavior", 0); + // Allow all cookies. + Services.prefs.setIntPref("network.cookie.cookieBehavior", 0); - httpserver.registerPathHandler("/redirect1", redirectHandler1); - httpserver.registerPathHandler("/redirect2", redirectHandler2); - httpserver.start(-1); + httpserver.registerPathHandler("/redirect1", redirectHandler1); + httpserver.registerPathHandler("/redirect2", redirectHandler2); + httpserver.start(-1); - // clear cache - evict_cache_entries(); + // clear cache + evict_cache_entries(); - // load first time - var channel = setupChannel("/redirect1"); - channel.asyncOpen(new ChannelListener(checkValueAndTrigger, null)); - do_test_pending(); + // load first time + var channel = setupChannel("/redirect1"); + channel.asyncOpen(new ChannelListener(checkValueAndTrigger, null)); + do_test_pending(); } -function redirectHandler1(metadata, response) -{ - if (!metadata.hasHeader("Cookie")) { - response.setStatusLine(metadata.httpVersion, 302, "Found"); - response.setHeader("Cache-Control", "max-age=600", false); - response.setHeader("Location", "/redirect2?query", false); - response.setHeader("Set-Cookie", "MyCookie=1", false); - } else { - response.setStatusLine(metadata.httpVersion, 200, "Ok"); - response.setHeader("Content-Type", "text/plain"); - response.bodyOutputStream.write("Ok", "Ok".length); - } -} - -function redirectHandler2(metadata, response) -{ +function redirectHandler1(metadata, response) { + if (!metadata.hasHeader("Cookie")) { response.setStatusLine(metadata.httpVersion, 302, "Found"); - response.setHeader("Location", "/redirect1", false); + response.setHeader("Cache-Control", "max-age=600", false); + response.setHeader("Location", "/redirect2?query", false); + response.setHeader("Set-Cookie", "MyCookie=1", false); + } else { + response.setStatusLine(metadata.httpVersion, 200, "Ok"); + response.setHeader("Content-Type", "text/plain"); + response.bodyOutputStream.write("Ok", "Ok".length); + } +} + +function redirectHandler2(metadata, response) { + response.setStatusLine(metadata.httpVersion, 302, "Found"); + response.setHeader("Location", "/redirect1", false); } diff --git a/netwerk/test/unit/test_bug660066.js b/netwerk/test/unit/test_bug660066.js index 5cb811e4fb5d..ddfb96a11c06 100644 --- a/netwerk/test/unit/test_bug660066.js +++ b/netwerk/test/unit/test_bug660066.js @@ -3,16 +3,25 @@ const SIMPLEURI_SPEC = "data:text/plain,hello world"; const BLOBURI_SPEC = "blob:123456"; function do_info(text, stack) { - if (!stack) + if (!stack) { stack = Components.stack.caller; + } - dump( "\n" + - "TEST-INFO | " + stack.filename + " | [" + stack.name + " : " + - stack.lineNumber + "] " + text + "\n"); + dump( + "\n" + + "TEST-INFO | " + + stack.filename + + " | [" + + stack.name + + " : " + + stack.lineNumber + + "] " + + text + + "\n" + ); } -function do_check_uri_neq(uri1, uri2) -{ +function do_check_uri_neq(uri1, uri2) { do_info("Checking equality in forward direction..."); Assert.ok(!uri1.equals(uri2)); Assert.ok(!uri1.equalsExceptRef(uri2)); @@ -22,8 +31,7 @@ function do_check_uri_neq(uri1, uri2) Assert.ok(!uri2.equalsExceptRef(uri1)); } -function run_test() -{ +function run_test() { var simpleURI = NetUtil.newURI(SIMPLEURI_SPEC); var fileDataURI = NetUtil.newURI(BLOBURI_SPEC); @@ -31,11 +39,16 @@ function run_test() do_check_uri_neq(simpleURI, fileDataURI); do_info("Changing the nsSimpleURI spec to match the nsFileDataURI"); - simpleURI = simpleURI.mutate().setSpec(BLOBURI_SPEC).finalize(); + simpleURI = simpleURI + .mutate() + .setSpec(BLOBURI_SPEC) + .finalize(); do_info("Verifying that .spec matches"); Assert.equal(simpleURI.spec, fileDataURI.spec); - do_info("Checking that nsSimpleURI != nsFileDataURI despite their .spec matching") + do_info( + "Checking that nsSimpleURI != nsFileDataURI despite their .spec matching" + ); do_check_uri_neq(simpleURI, fileDataURI); } diff --git a/netwerk/test/unit/test_bug667087.js b/netwerk/test/unit/test_bug667087.js index ad76fa7bb710..60ef32523102 100644 --- a/netwerk/test/unit/test_bug667087.js +++ b/netwerk/test/unit/test_bug667087.js @@ -8,7 +8,18 @@ function run_test() { // Test our handling of host names with a single character consisting only // of a single character - cm.add("a", "/", "foo", "bar", false, false, true, expiry, {}, Ci.nsICookie.SAMESITE_NONE); + cm.add( + "a", + "/", + "foo", + "bar", + false, + false, + true, + expiry, + {}, + Ci.nsICookie.SAMESITE_NONE + ); Assert.equal(cm.countCookiesFromHost("a"), 1); Assert.equal(cs.getCookieString(NetUtil.newURI("http://a"), null), "foo=bar"); } diff --git a/netwerk/test/unit/test_bug667818.js b/netwerk/test/unit/test_bug667818.js index eebd9c6100b0..4434be163b8a 100644 --- a/netwerk/test/unit/test_bug667818.js +++ b/netwerk/test/unit/test_bug667818.js @@ -1,19 +1,28 @@ function makeURI(str) { - return Cc["@mozilla.org/network/io-service;1"] - .getService(Ci.nsIIOService) - .newURI(str); + return Cc["@mozilla.org/network/io-service;1"] + .getService(Ci.nsIIOService) + .newURI(str); } function run_test() { - // Allow all cookies. - Services.prefs.setIntPref("network.cookie.cookieBehavior", 0); - var serv = Cc["@mozilla.org/cookieService;1"] - .getService(Ci.nsICookieService); - var uri = makeURI("http://example.com/"); - // Try an expiration time before the epoch - serv.setCookieString(uri, null, "test=test; path=/; domain=example.com; expires=Sun, 31-Dec-1899 16:00:00 GMT;", null); - Assert.equal(serv.getCookieString(uri, null), ""); - // Now sanity check - serv.setCookieString(uri, null, "test2=test2; path=/; domain=example.com;", null); - Assert.equal(serv.getCookieString(uri, null), "test2=test2"); + // Allow all cookies. + Services.prefs.setIntPref("network.cookie.cookieBehavior", 0); + var serv = Cc["@mozilla.org/cookieService;1"].getService(Ci.nsICookieService); + var uri = makeURI("http://example.com/"); + // Try an expiration time before the epoch + serv.setCookieString( + uri, + null, + "test=test; path=/; domain=example.com; expires=Sun, 31-Dec-1899 16:00:00 GMT;", + null + ); + Assert.equal(serv.getCookieString(uri, null), ""); + // Now sanity check + serv.setCookieString( + uri, + null, + "test2=test2; path=/; domain=example.com;", + null + ); + Assert.equal(serv.getCookieString(uri, null), "test2=test2"); } diff --git a/netwerk/test/unit/test_bug667907.js b/netwerk/test/unit/test_bug667907.js index e9b38cbf9b65..ea89a5236d0b 100644 --- a/netwerk/test/unit/test_bug667907.js +++ b/netwerk/test/unit/test_bug667907.js @@ -1,4 +1,4 @@ -const {HttpServer} = ChromeUtils.import("resource://testing-common/httpd.js"); +const { HttpServer } = ChromeUtils.import("resource://testing-common/httpd.js"); var httpserver = null; var simplePath = "/simple"; @@ -14,15 +14,20 @@ XPCOMUtils.defineLazyGetter(this, "uri2", function() { }); function make_channel(url) { - return NetUtil.newChannel({uri: url, loadUsingSystemPrincipal: true}); + return NetUtil.newChannel({ uri: url, loadUsingSystemPrincipal: true }); } var listener_proto = { - QueryInterface: ChromeUtils.generateQI(["nsIStreamListener", "nsIRequestObserver"]), + QueryInterface: ChromeUtils.generateQI([ + "nsIStreamListener", + "nsIRequestObserver", + ]), onStartRequest(request) { - Assert.equal(request.QueryInterface(Ci.nsIChannel).contentType, - this.contentType); + Assert.equal( + request.QueryInterface(Ci.nsIChannel).contentType, + this.contentType + ); request.cancel(Cr.NS_BINDING_ABORTED); }, @@ -33,7 +38,7 @@ var listener_proto = { onStopRequest(request, status) { Assert.equal(status, Cr.NS_BINDING_ABORTED); this.termination_func(); - } + }, }; function listener(contentType, termination_func) { @@ -42,36 +47,38 @@ function listener(contentType, termination_func) { } listener.prototype = listener_proto; -function run_test() -{ +function run_test() { httpserver = new HttpServer(); httpserver.registerPathHandler(simplePath, simpleHandler); httpserver.registerPathHandler(normalPath, normalHandler); httpserver.start(-1); var channel = make_channel(uri1); - channel.asyncOpen(new listener("text/plain", function() { run_test2();})); + channel.asyncOpen( + new listener("text/plain", function() { + run_test2(); + }) + ); do_test_pending(); } -function run_test2() -{ +function run_test2() { var channel = make_channel(uri2); - channel.asyncOpen(new listener("text/html", function() { - httpserver.stop(do_test_finished); - })); + channel.asyncOpen( + new listener("text/html", function() { + httpserver.stop(do_test_finished); + }) + ); } -function simpleHandler(metadata, response) -{ +function simpleHandler(metadata, response) { response.seizePower(); response.bodyOutputStream.write(httpbody, httpbody.length); response.finish(); } -function normalHandler(metadata, response) -{ +function normalHandler(metadata, response) { response.bodyOutputStream.write(httpbody, httpbody.length); response.finish(); } diff --git a/netwerk/test/unit/test_bug669001.js b/netwerk/test/unit/test_bug669001.js index d006c78be924..71a3a8723182 100644 --- a/netwerk/test/unit/test_bug669001.js +++ b/netwerk/test/unit/test_bug669001.js @@ -1,4 +1,4 @@ -const {HttpServer} = ChromeUtils.import("resource://testing-common/httpd.js"); +const { HttpServer } = ChromeUtils.import("resource://testing-common/httpd.js"); var httpServer = null; var path = "/bug699001"; @@ -8,7 +8,7 @@ XPCOMUtils.defineLazyGetter(this, "URI", function() { }); function make_channel(url) { - return NetUtil.newChannel({uri: url, loadUsingSystemPrincipal: true}); + return NetUtil.newChannel({ uri: url, loadUsingSystemPrincipal: true }); } var fetched; @@ -22,54 +22,52 @@ var fetched; // from the server var tests = [ -{ - prepare() { }, - test(response) { - Assert.ok(fetched); - } -}, -{ - prepare() { }, - test(response) { - Assert.ok(!fetched); - } -}, -{ - prepare() { - setUA("A different User Agent"); + { + prepare() {}, + test(response) { + Assert.ok(fetched); + }, }, - test(response) { - Assert.ok(fetched); - } -}, -{ - prepare() { }, - test(response) { - Assert.ok(!fetched); - } -}, -{ - prepare() { - setUA("And another User Agent"); + { + prepare() {}, + test(response) { + Assert.ok(!fetched); + }, + }, + { + prepare() { + setUA("A different User Agent"); + }, + test(response) { + Assert.ok(fetched); + }, + }, + { + prepare() {}, + test(response) { + Assert.ok(!fetched); + }, + }, + { + prepare() { + setUA("And another User Agent"); + }, + test(response) { + Assert.ok(fetched); + }, + }, + { + prepare() {}, + test(response) { + Assert.ok(!fetched); + }, }, - test(response) { - Assert.ok(fetched); - } -}, -{ - prepare() { }, - test(response) { - Assert.ok(!fetched); - } -} ]; -function handler(metadata, response) -{ +function handler(metadata, response) { if (metadata.hasHeader("If-None-Match")) { response.setStatusLine(metadata.httpVersion, 304, "Not modified"); - } - else { + } else { response.setStatusLine(metadata.httpVersion, 200, "OK"); response.setHeader("Content-Type", "text/plain"); @@ -85,8 +83,7 @@ function handler(metadata, response) response.setHeader("ETag", "1234"); } -function run_test() -{ +function run_test() { httpServer = new HttpServer(); httpServer.registerPathHandler(path, handler); httpServer.start(-1); @@ -96,8 +93,7 @@ function run_test() nextTest(); } -function nextTest() -{ +function nextTest() { fetched = false; tests[0].prepare(); @@ -111,8 +107,7 @@ function nextTest() }); } -function checkAndShiftTest(request, response) -{ +function checkAndShiftTest(request, response) { tests[0].test(response); tests.shift(); @@ -124,36 +119,59 @@ function checkAndShiftTest(request, response) nextTest(); } -function tearDown() -{ +function tearDown() { setUA(""); do_test_finished(); } // Helpers -function getUA() -{ - var httphandler = Cc["@mozilla.org/network/protocol;1?name=http"]. - getService(Ci.nsIHttpProtocolHandler); +function getUA() { + var httphandler = Cc["@mozilla.org/network/protocol;1?name=http"].getService( + Ci.nsIHttpProtocolHandler + ); return httphandler.userAgent; } -function setUA(value) -{ - var prefs = Cc["@mozilla.org/preferences-service;1"]. - getService(Ci.nsIPrefBranch); +function setUA(value) { + var prefs = Cc["@mozilla.org/preferences-service;1"].getService( + Ci.nsIPrefBranch + ); prefs.setCharPref("general.useragent.override", value); } function getDateString(yearDelta) { - var months = [ 'Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', - 'Sep', 'Oct', 'Nov', 'Dec' ]; - var days = [ 'Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat' ]; + var months = [ + "Jan", + "Feb", + "Mar", + "Apr", + "May", + "Jun", + "Jul", + "Aug", + "Sep", + "Oct", + "Nov", + "Dec", + ]; + var days = ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"]; var d = new Date(); - return days[d.getUTCDay()] + ", " + d.getUTCDate() + " " - + months[d.getUTCMonth()] + " " + (d.getUTCFullYear() + yearDelta) - + " " + d.getUTCHours() + ":" + d.getUTCMinutes() + ":" - + d.getUTCSeconds() + " UTC"; + return ( + days[d.getUTCDay()] + + ", " + + d.getUTCDate() + + " " + + months[d.getUTCMonth()] + + " " + + (d.getUTCFullYear() + yearDelta) + + " " + + d.getUTCHours() + + ":" + + d.getUTCMinutes() + + ":" + + d.getUTCSeconds() + + " UTC" + ); } diff --git a/netwerk/test/unit/test_bug767025.js b/netwerk/test/unit/test_bug767025.js index ce83f6347c32..2b18155a1858 100644 --- a/netwerk/test/unit/test_bug767025.js +++ b/netwerk/test/unit/test_bug767025.js @@ -1,6 +1,6 @@ /* -*- indent-tabs-mode: nil; js-indent-level: 2 -*- */ -const {HttpServer} = ChromeUtils.import("resource://testing-common/httpd.js"); +const { HttpServer } = ChromeUtils.import("resource://testing-common/httpd.js"); /** * This is testcase do following steps to make sure bug767025 removing @@ -25,13 +25,14 @@ const kNS_CACHESTORAGESERVICE_CONTRACTID = const kNS_APPLICATIONCACHESERVICE_CONTRACTID = "@mozilla.org/network/application-cache-service;1"; -const kManifest = "CACHE MANIFEST\n" + +const kManifest = + "CACHE MANIFEST\n" + "/pages/foo1\n" + "/pages/foo2\n" + "/pages/foo3\n" + "/pages/foo4\n"; -const kDataFileSize = 1024; // file size for each content page +const kDataFileSize = 1024; // file size for each content page const kHttpLocation = "http://localhost:4444/"; function manifest_handler(metadata, response) { @@ -45,8 +46,12 @@ function datafile_handler(metadata, response) { info("datafile_handler\n"); let data = ""; - while(data.length < kDataFileSize) { - data = data + Math.random().toString(36).substring(2, 15); + while (data.length < kDataFileSize) { + data = + data + + Math.random() + .toString(36) + .substring(2, 15); } response.setHeader("content-type", "text/plain"); @@ -63,12 +68,16 @@ function app_handler(metadata, response) { var httpServer; function init_profile() { - var ps = Cc["@mozilla.org/preferences-service;1"] - .getService(Ci.nsIPrefBranch); + var ps = Cc["@mozilla.org/preferences-service;1"].getService( + Ci.nsIPrefBranch + ); dump(ps.getBoolPref("browser.cache.offline.enable")); ps.setBoolPref("browser.cache.offline.enable", true); - ps.setComplexValue("browser.cache.offline.parent_directory", - Ci.nsIFile, do_get_profile()); + ps.setComplexValue( + "browser.cache.offline.parent_directory", + Ci.nsIFile, + do_get_profile() + ); info("profile " + do_get_profile()); } @@ -83,25 +92,33 @@ function init_http_server() { } function clean_app_cache() { - let cache_service = Cc[kNS_CACHESTORAGESERVICE_CONTRACTID]. - getService(Ci.nsICacheStorageService); - let storage = cache_service.appCacheStorage(Services.loadContextInfo.default, null); + let cache_service = Cc[kNS_CACHESTORAGESERVICE_CONTRACTID].getService( + Ci.nsICacheStorageService + ); + let storage = cache_service.appCacheStorage( + Services.loadContextInfo.default, + null + ); storage.asyncEvictStorage(null); } function do_app_cache(manifestURL, pageURL) { - let update_service = Cc[kNS_OFFLINECACHEUPDATESERVICE_CONTRACTID]. - getService(Ci.nsIOfflineCacheUpdateService); + let update_service = Cc[kNS_OFFLINECACHEUPDATESERVICE_CONTRACTID].getService( + Ci.nsIOfflineCacheUpdateService + ); - Services.perms.add(manifestURL, - "offline-app", - Ci.nsIPermissionManager.ALLOW_ACTION); + Services.perms.add( + manifestURL, + "offline-app", + Ci.nsIPermissionManager.ALLOW_ACTION + ); - let update = - update_service.scheduleUpdate(manifestURL, - pageURL, - Services.scriptSecurityManager.getSystemPrincipal(), - null); /* no window */ + let update = update_service.scheduleUpdate( + manifestURL, + pageURL, + Services.scriptSecurityManager.getSystemPrincipal(), + null + ); /* no window */ return update; } @@ -111,50 +128,59 @@ function watch_update(update, stateChangeHandler, cacheAvailHandler) { QueryInterface: ChromeUtils.generateQI([]), updateStateChanged: stateChangeHandler, - applicationCacheAvailable: cacheAvailHandler - };~ - update.addObserver(observer); + applicationCacheAvailable: cacheAvailHandler, + }; + ~update.addObserver(observer); return update; } -function start_and_watch_app_cache(manifestURL, - pageURL, - stateChangeHandler, - cacheAvailHandler) { - let ioService = Cc["@mozilla.org/network/io-service;1"]. - getService(Ci.nsIIOService); - let update = do_app_cache(ioService.newURI(manifestURL), - ioService.newURI(pageURL)); +function start_and_watch_app_cache( + manifestURL, + pageURL, + stateChangeHandler, + cacheAvailHandler +) { + let ioService = Cc["@mozilla.org/network/io-service;1"].getService( + Ci.nsIIOService + ); + let update = do_app_cache( + ioService.newURI(manifestURL), + ioService.newURI(pageURL) + ); watch_update(update, stateChangeHandler, cacheAvailHandler); return update; } -const {STATE_FINISHED: STATE_FINISHED, - STATE_CHECKING: STATE_CHECKING, - STATE_ERROR: STATE_ERROR } = Ci.nsIOfflineCacheUpdateObserver; +const { + STATE_FINISHED: STATE_FINISHED, + STATE_CHECKING: STATE_CHECKING, + STATE_ERROR: STATE_ERROR, +} = Ci.nsIOfflineCacheUpdateObserver; /* * Start caching app1 as a non-pinned app. */ function start_cache_nonpinned_app() { info("Start non-pinned App1"); - start_and_watch_app_cache(kHttpLocation + "app.appcache", - kHttpLocation + "app", - function (update, state) { - switch(state) { - case STATE_FINISHED: - check_bug(); - break; + start_and_watch_app_cache( + kHttpLocation + "app.appcache", + kHttpLocation + "app", + function(update, state) { + switch (state) { + case STATE_FINISHED: + check_bug(); + break; - case STATE_ERROR: - do_throw("App cache state = " + state); - break; - } - }, - function (appcache) { - info("app avail " + appcache + "\n"); - }); + case STATE_ERROR: + do_throw("App cache state = " + state); + break; + } + }, + function(appcache) { + info("app avail " + appcache + "\n"); + } + ); } var hold_entry_foo1 = null; @@ -163,19 +189,29 @@ function check_bug() { // activate foo1 asyncOpenCacheEntry( kHttpLocation + "pages/foo1", - "appcache", Ci.nsICacheStorage.OPEN_READONLY, null, + "appcache", + Ci.nsICacheStorage.OPEN_READONLY, + null, function(status, entry, appcache) { - let storage = get_cache_service().appCacheStorage(Services.loadContextInfo.default, appcache); + let storage = get_cache_service().appCacheStorage( + Services.loadContextInfo.default, + appcache + ); // Doom foo1 & foo2 - storage.asyncDoomURI(createURI(kHttpLocation + "pages/foo1"), "", { onCacheEntryDoomed() { - storage.asyncDoomURI(createURI(kHttpLocation + "pages/foo2"), "", { onCacheEntryDoomed() { - check_evict_cache(appcache); - }}); - }}); + storage.asyncDoomURI(createURI(kHttpLocation + "pages/foo1"), "", { + onCacheEntryDoomed() { + storage.asyncDoomURI(createURI(kHttpLocation + "pages/foo2"), "", { + onCacheEntryDoomed() { + check_evict_cache(appcache); + }, + }); + }, + }); hold_entry_foo1 = entry; - }); + } + ); } function check_evict_cache(appcache) { @@ -197,16 +233,21 @@ function check_evict_cache(appcache) { // activate foo3 asyncOpenCacheEntry( kHttpLocation + "pages/foo3", - "appcache", Ci.nsICacheStorage.OPEN_READONLY, null, + "appcache", + Ci.nsICacheStorage.OPEN_READONLY, + null, function(status, entry, appcache) { var hold_entry_foo3 = entry; // evict all documents. - let storage = get_cache_service().appCacheStorage(Services.loadContextInfo.default, appcache); + let storage = get_cache_service().appCacheStorage( + Services.loadContextInfo.default, + appcache + ); storage.asyncEvictStorage(null); // All documents are removed except foo1 & foo3. - syncWithCacheIOThread(function () { + syncWithCacheIOThread(function() { // foo1 let file = do_get_profile().clone(); file.append("OfflineCache"); @@ -259,8 +300,7 @@ function check_evict_cache(appcache) { } function run_test() { - if (typeof _XPCSHELL_PROCESS == "undefined" || - _XPCSHELL_PROCESS != "child") { + if (typeof _XPCSHELL_PROCESS == "undefined" || _XPCSHELL_PROCESS != "child") { init_profile(); clean_app_cache(); } diff --git a/netwerk/test/unit/test_bug770243.js b/netwerk/test/unit/test_bug770243.js index 58f61c5a3a35..4f274bf8608c 100644 --- a/netwerk/test/unit/test_bug770243.js +++ b/netwerk/test/unit/test_bug770243.js @@ -7,29 +7,38 @@ 5. 407 followed by 304 */ -const {HttpServer} = ChromeUtils.import("resource://testing-common/httpd.js"); +const { HttpServer } = ChromeUtils.import("resource://testing-common/httpd.js"); var httpserv; -function addCreds(scheme, host) -{ - var authMgr = Cc['@mozilla.org/network/http-auth-manager;1'] - .getService(Ci.nsIHttpAuthManager); - authMgr.setAuthIdentity(scheme, host, httpserv.identity.primaryPort, - "basic", "secret", "/", "", "user", "pass"); +function addCreds(scheme, host) { + var authMgr = Cc["@mozilla.org/network/http-auth-manager;1"].getService( + Ci.nsIHttpAuthManager + ); + authMgr.setAuthIdentity( + scheme, + host, + httpserv.identity.primaryPort, + "basic", + "secret", + "/", + "", + "user", + "pass" + ); } -function clearCreds() -{ - var authMgr = Cc['@mozilla.org/network/http-auth-manager;1'] - .getService(Ci.nsIHttpAuthManager); +function clearCreds() { + var authMgr = Cc["@mozilla.org/network/http-auth-manager;1"].getService( + Ci.nsIHttpAuthManager + ); authMgr.clearAll(); } function makeChan() { return NetUtil.newChannel({ uri: "http://localhost:" + httpserv.identity.primaryPort + "/", - loadUsingSystemPrincipal: true + loadUsingSystemPrincipal: true, }).QueryInterface(Ci.nsIHttpChannel); } @@ -41,8 +50,8 @@ var handlers = [ Assert.equal(metadata.hasHeader("Authorization"), false); response.setStatusLine(metadata.httpVersion, 200, "OK"); response.setHeader("ETag", '"one"', false); - response.setHeader("Cache-control", 'no-cache', false); - response.setHeader("Content-type", 'text/plain', false); + response.setHeader("Cache-control", "no-cache", false); + response.setHeader("Content-type", "text/plain", false); var body = "Response body 1"; response.bodyOutputStream.write(body, body.length); }, @@ -59,8 +68,8 @@ var handlers = [ Assert.equal(metadata.hasHeader("Authorization"), true); response.setStatusLine(metadata.httpVersion, 200, "OK"); response.setHeader("ETag", '"two"', false); - response.setHeader("Cache-control", 'no-cache', false); - response.setHeader("Content-type", 'text/plain', false); + response.setHeader("Cache-control", "no-cache", false); + response.setHeader("Content-type", "text/plain", false); var body = "Response body 2"; response.bodyOutputStream.write(body, body.length); clearCreds(); @@ -95,8 +104,8 @@ var handlers = [ Assert.equal(metadata.getHeader("If-None-Match"), '"two"'); response.setStatusLine(metadata.httpVersion, 200, "OK"); response.setHeader("ETag", '"three"', false); - response.setHeader("Cache-control", 'no-cache', false); - response.setHeader("Content-type", 'text/plain', false); + response.setHeader("Cache-control", "no-cache", false); + response.setHeader("Content-type", "text/plain", false); var body = "Response body 3"; response.bodyOutputStream.write(body, body.length); clearCreds(); @@ -115,20 +124,18 @@ var handlers = [ Assert.equal(metadata.getHeader("If-None-Match"), '"three"'); response.setStatusLine(metadata.httpVersion, 304, "OK"); response.setHeader("ETag", '"three"', false); - response.setHeader("Cache-control", 'no-cache', false); + response.setHeader("Cache-control", "no-cache", false); clearCreds(); - } + }, ]; -function handler(metadata, response) -{ +function handler(metadata, response) { handlers.shift()(metadata, response); } // Array of tests to run, self-driven -function sync_and_run_next_test() -{ +function sync_and_run_next_test() { syncWithCacheIOThread(function() { tests.shift()(); }); @@ -138,64 +145,94 @@ var tests = [ // Test 1: 200 (cacheable) function() { var ch = makeChan(); - ch.asyncOpen(new ChannelListener(function(req, body) { - Assert.equal(body, "Response body 1"); - sync_and_run_next_test(); - }, null, CL_NOT_FROM_CACHE)); + ch.asyncOpen( + new ChannelListener( + function(req, body) { + Assert.equal(body, "Response body 1"); + sync_and_run_next_test(); + }, + null, + CL_NOT_FROM_CACHE + ) + ); }, // Test 2: 401 and 200 + new content function() { var ch = makeChan(); - ch.asyncOpen(new ChannelListener(function(req, body) { - Assert.equal(body, "Response body 2"); - sync_and_run_next_test(); - }, null, CL_NOT_FROM_CACHE)); + ch.asyncOpen( + new ChannelListener( + function(req, body) { + Assert.equal(body, "Response body 2"); + sync_and_run_next_test(); + }, + null, + CL_NOT_FROM_CACHE + ) + ); }, // Test 3: 401 and 304 function() { var ch = makeChan(); - ch.asyncOpen(new ChannelListener(function(req, body) { - Assert.equal(body, "Response body 2"); - sync_and_run_next_test(); - }, null, CL_FROM_CACHE)); + ch.asyncOpen( + new ChannelListener( + function(req, body) { + Assert.equal(body, "Response body 2"); + sync_and_run_next_test(); + }, + null, + CL_FROM_CACHE + ) + ); }, // Test 4: 407 and 200 + new content function() { var ch = makeChan(); - ch.asyncOpen(new ChannelListener(function(req, body) { - Assert.equal(body, "Response body 3"); - sync_and_run_next_test(); - }, null, CL_NOT_FROM_CACHE)); + ch.asyncOpen( + new ChannelListener( + function(req, body) { + Assert.equal(body, "Response body 3"); + sync_and_run_next_test(); + }, + null, + CL_NOT_FROM_CACHE + ) + ); }, // Test 5: 407 and 304 function() { var ch = makeChan(); - ch.asyncOpen(new ChannelListener(function(req, body) { - Assert.equal(body, "Response body 3"); - sync_and_run_next_test(); - }, null, CL_FROM_CACHE)); + ch.asyncOpen( + new ChannelListener( + function(req, body) { + Assert.equal(body, "Response body 3"); + sync_and_run_next_test(); + }, + null, + CL_FROM_CACHE + ) + ); }, // End of test run function() { httpserv.stop(do_test_finished); - } + }, ]; -function run_test() -{ +function run_test() { do_get_profile(); httpserv = new HttpServer(); httpserv.registerPathHandler("/", handler); httpserv.start(-1); - const prefs = Cc["@mozilla.org/preferences-service;1"] - .getService(Ci.nsIPrefBranch); + const prefs = Cc["@mozilla.org/preferences-service;1"].getService( + Ci.nsIPrefBranch + ); prefs.setCharPref("network.proxy.http", "localhost"); prefs.setIntPref("network.proxy.http_port", httpserv.identity.primaryPort); prefs.setBoolPref("network.proxy.allow_hijacking_localhost", true); diff --git a/netwerk/test/unit/test_bug812167.js b/netwerk/test/unit/test_bug812167.js index 90fd744caff5..5006158c3a38 100644 --- a/netwerk/test/unit/test_bug812167.js +++ b/netwerk/test/unit/test_bug812167.js @@ -1,4 +1,4 @@ -const {HttpServer} = ChromeUtils.import("resource://testing-common/httpd.js"); +const { HttpServer } = ChromeUtils.import("resource://testing-common/httpd.js"); /* - get 302 with Cache-control: no-store @@ -22,95 +22,110 @@ XPCOMUtils.defineLazyGetter(this, "randomURI2", function() { }); function make_channel(url, callback, ctx) { - return NetUtil.newChannel({uri: url, loadUsingSystemPrincipal: true}); + return NetUtil.newChannel({ uri: url, loadUsingSystemPrincipal: true }); } const responseBody = "response body"; var redirectHandler_NoStore_calls = 0; -function redirectHandler_NoStore(metadata, response) -{ +function redirectHandler_NoStore(metadata, response) { response.setStatusLine(metadata.httpVersion, 302, "Found"); - response.setHeader("Location", "http://localhost:" + - httpserver.identity.primaryPort + "/content", false); + response.setHeader( + "Location", + "http://localhost:" + httpserver.identity.primaryPort + "/content", + false + ); response.setHeader("Cache-control", "no-store"); ++redirectHandler_NoStore_calls; } var redirectHandler_ExpiresInPast_calls = 0; -function redirectHandler_ExpiresInPast(metadata, response) -{ +function redirectHandler_ExpiresInPast(metadata, response) { response.setStatusLine(metadata.httpVersion, 302, "Found"); - response.setHeader("Location", "http://localhost:" + - httpserver.identity.primaryPort + "/content", false); + response.setHeader( + "Location", + "http://localhost:" + httpserver.identity.primaryPort + "/content", + false + ); response.setHeader("Expires", "-1"); ++redirectHandler_ExpiresInPast_calls; } -function contentHandler(metadata, response) -{ +function contentHandler(metadata, response) { response.setHeader("Content-Type", "text/plain"); response.bodyOutputStream.write(responseBody, responseBody.length); } -function check_response(path, request, buffer, expectedExpiration, continuation) -{ +function check_response( + path, + request, + buffer, + expectedExpiration, + continuation +) { Assert.equal(buffer, responseBody); // Entry is always there, old cache wrapping code does session->SetDoomEntriesIfExpired(false), // just check it's not persisted or is expired (dep on the test). - asyncOpenCacheEntry(path, "disk", Ci.nsICacheStorage.OPEN_READONLY, null, function(status, entry) { - Assert.equal(status, 0); + asyncOpenCacheEntry( + path, + "disk", + Ci.nsICacheStorage.OPEN_READONLY, + null, + function(status, entry) { + Assert.equal(status, 0); - // Expired entry is on disk, no-store entry is in memory - Assert.equal(entry.persistent, expectedExpiration); + // Expired entry is on disk, no-store entry is in memory + Assert.equal(entry.persistent, expectedExpiration); - // Do the request again and check the server handler is called appropriately - var chan = make_channel(path); - chan.asyncOpen(new ChannelListener(function(request, buffer) { - Assert.equal(buffer, responseBody); + // Do the request again and check the server handler is called appropriately + var chan = make_channel(path); + chan.asyncOpen( + new ChannelListener(function(request, buffer) { + Assert.equal(buffer, responseBody); - if (expectedExpiration) { - // Handler had to be called second time - Assert.equal(redirectHandler_ExpiresInPast_calls, 2); - } - else { - // Handler had to be called second time (no-store forces validate), - // and we are just in memory - Assert.equal(redirectHandler_NoStore_calls, 2); - Assert.ok(!entry.persistent); - } + if (expectedExpiration) { + // Handler had to be called second time + Assert.equal(redirectHandler_ExpiresInPast_calls, 2); + } else { + // Handler had to be called second time (no-store forces validate), + // and we are just in memory + Assert.equal(redirectHandler_NoStore_calls, 2); + Assert.ok(!entry.persistent); + } - continuation(); - }, null)); - }); + continuation(); + }, null) + ); + } + ); } -function run_test_no_store() -{ +function run_test_no_store() { var chan = make_channel(randomURI1); - chan.asyncOpen(new ChannelListener(function(request, buffer) { - // Cache-control: no-store response should only be found in the memory cache. - check_response(randomURI1, request, buffer, false, run_test_expires_past); - }, null)); + chan.asyncOpen( + new ChannelListener(function(request, buffer) { + // Cache-control: no-store response should only be found in the memory cache. + check_response(randomURI1, request, buffer, false, run_test_expires_past); + }, null) + ); } -function run_test_expires_past() -{ +function run_test_expires_past() { var chan = make_channel(randomURI2); - chan.asyncOpen(new ChannelListener(function(request, buffer) { - // Expires: -1 response should not be found in any cache. - check_response(randomURI2, request, buffer, true, finish_test); - }, null)); + chan.asyncOpen( + new ChannelListener(function(request, buffer) { + // Expires: -1 response should not be found in any cache. + check_response(randomURI2, request, buffer, true, finish_test); + }, null) + ); } -function finish_test() -{ +function finish_test() { httpserver.stop(do_test_finished); } -function run_test() -{ +function run_test() { do_get_profile(); httpserver = new HttpServer(); diff --git a/netwerk/test/unit/test_bug826063.js b/netwerk/test/unit/test_bug826063.js index 875fd5b35172..2ca70b16a5e2 100644 --- a/netwerk/test/unit/test_bug826063.js +++ b/netwerk/test/unit/test_bug826063.js @@ -6,26 +6,22 @@ * result for various combinations of .setPrivate() and nsILoadContexts */ - - -var URIs = [ - "http://example.org", - "https://example.org", - "ftp://example.org" - ]; +var URIs = ["http://example.org", "https://example.org", "ftp://example.org"]; function* getChannels() { for (let u of URIs) { yield NetUtil.newChannel({ uri: u, - loadUsingSystemPrincipal: true + loadUsingSystemPrincipal: true, }); } } function checkPrivate(channel, shouldBePrivate) { - Assert.equal(channel.QueryInterface(Ci.nsIPrivateBrowsingChannel).isChannelPrivate, - shouldBePrivate); + Assert.equal( + channel.QueryInterface(Ci.nsIPrivateBrowsingChannel).isChannelPrivate, + shouldBePrivate + ); } /** @@ -85,7 +81,6 @@ add_test(function test_LoadContextRegular() { run_next_test(); }); - // Do not test simultanous uses of .setPrivate and load context. // There is little merit in doing so, and combining both will assert in // Debug builds anyway. diff --git a/netwerk/test/unit/test_bug856978.js b/netwerk/test/unit/test_bug856978.js index 9f74c6790122..b7a61828e209 100644 --- a/netwerk/test/unit/test_bug856978.js +++ b/netwerk/test/unit/test_bug856978.js @@ -9,7 +9,7 @@ // authorization header got added at all and if so it gets removed. This test // passes iff both succeeds. -const {HttpServer} = ChromeUtils.import("resource://testing-common/httpd.js"); +const { HttpServer } = ChromeUtils.import("resource://testing-common/httpd.js"); var notification = "http-on-modify-request"; @@ -29,7 +29,7 @@ function authHandler(metadata, response) { } Assert.ok(noAuthHeader); } - // Not our test request yet. + // Not our test request yet. else if (!metadata.hasHeader("Authorization")) { response.setStatusLine(metadata.httpVersion, 401, "Unauthorized"); response.setHeader("WWW-Authenticate", 'Basic realm="secret"', false); @@ -43,11 +43,15 @@ function RequestObserver() { RequestObserver.prototype = { register() { info("Registering " + notification); - Cc["@mozilla.org/observer-service;1"].getService(Ci.nsIObserverService). - addObserver(this, notification, true); + Cc["@mozilla.org/observer-service;1"] + .getService(Ci.nsIObserverService) + .addObserver(this, notification, true); }, - QueryInterface: ChromeUtils.generateQI(["nsIObserver", "nsISupportsWeakReference"]), + QueryInterface: ChromeUtils.generateQI([ + "nsIObserver", + "nsISupportsWeakReference", + ]), observe(subject, topic, data) { if (topic == notification) { @@ -66,8 +70,8 @@ RequestObserver.prototype = { // We are still here. Let's remove the authorization header now. subject.setRequestHeader("Authorization", null, false); } - } -} + }, +}; var listener = { onStartRequest: function test_onStartR(request) {}, @@ -77,7 +81,7 @@ var listener = { }, onStopRequest: function test_onStopR(request, status) { - if (current_test < (tests.length - 1)) { + if (current_test < tests.length - 1) { current_test++; tests[current_test](); } else { @@ -85,12 +89,14 @@ var listener = { httpServer.stop(do_test_finished); } do_test_finished(); - } + }, }; function makeChan(url) { - return NetUtil.newChannel({uri: url, loadUsingSystemPrincipal: true}) - .QueryInterface(Ci.nsIHttpChannel); + return NetUtil.newChannel({ + uri: url, + loadUsingSystemPrincipal: true, + }).QueryInterface(Ci.nsIHttpChannel); } var tests = [startAuthHeaderTest, removeAuthHeaderTest]; diff --git a/netwerk/test/unit/test_bug894586.js b/netwerk/test/unit/test_bug894586.js index 1325a0997bea..b3bab36318a7 100644 --- a/netwerk/test/unit/test_bug894586.js +++ b/netwerk/test/unit/test_bug894586.js @@ -5,14 +5,15 @@ "use strict"; -var contentSecManager = Cc["@mozilla.org/contentsecuritymanager;1"] - .getService(Ci.nsIContentSecurityManager); +var contentSecManager = Cc["@mozilla.org/contentsecuritymanager;1"].getService( + Ci.nsIContentSecurityManager +); function ProtocolHandler() { this.uri = Cc["@mozilla.org/network/simple-uri-mutator;1"] - .createInstance(Ci.nsIURIMutator) - .setSpec(this.scheme + ":dummy") - .finalize(); + .createInstance(Ci.nsIURIMutator) + .setSpec(this.scheme + ":dummy") + .finalize(); } ProtocolHandler.prototype = { @@ -24,12 +25,14 @@ ProtocolHandler.prototype = { return -1; }, get protocolFlags() { - return Ci.nsIProtocolHandler.URI_NORELATIVE | - Ci.nsIProtocolHandler.URI_NOAUTH | - Ci.nsIProtocolHandler.URI_IS_UI_RESOURCE | - Ci.nsIProtocolHandler.URI_IS_LOCAL_RESOURCE | - Ci.nsIProtocolHandler.URI_NON_PERSISTABLE | - Ci.nsIProtocolHandler.URI_SYNC_LOAD_IS_OK; + return ( + Ci.nsIProtocolHandler.URI_NORELATIVE | + Ci.nsIProtocolHandler.URI_NOAUTH | + Ci.nsIProtocolHandler.URI_IS_UI_RESOURCE | + Ci.nsIProtocolHandler.URI_IS_LOCAL_RESOURCE | + Ci.nsIProtocolHandler.URI_NON_PERSISTABLE | + Ci.nsIProtocolHandler.URI_SYNC_LOAD_IS_OK + ); }, newChannel(aURI, aLoadInfo) { this.loadInfo = aLoadInfo; @@ -54,14 +57,16 @@ ProtocolHandler.prototype = { get contentType() { return "text/css"; }, - set contentType(val) { - }, + set contentType(val) {}, contentCharset: "UTF-8", get contentLength() { return -1; }, set contentLength(val) { - throw Components.Exception("Setting content length", NS_ERROR_NOT_IMPLEMENTED); + throw Components.Exception( + "Setting content length", + NS_ERROR_NOT_IMPLEMENTED + ); }, open() { // throws an error if security checks fail @@ -70,20 +75,20 @@ ProtocolHandler.prototype = { var file = do_get_file("test_bug894586.js", false); Assert.ok(file.exists()); var url = Services.io.newFileURI(file); - return NetUtil.newChannel({uri: url, loadUsingSystemPrincipal: true}).open(); + return NetUtil.newChannel({ + uri: url, + loadUsingSystemPrincipal: true, + }).open(); }, asyncOpen(aListener, aContext) { - throw Components.Exception("Not implemented", - Cr.NS_ERROR_NOT_IMPLEMENTED); + throw Components.Exception("Not implemented", Cr.NS_ERROR_NOT_IMPLEMENTED); }, contentDisposition: Ci.nsIChannel.DISPOSITION_INLINE, get contentDispositionFilename() { - throw Components.Exception("No file name", - Cr.NS_ERROR_NOT_AVAILABLE); + throw Components.Exception("No file name", Cr.NS_ERROR_NOT_AVAILABLE); }, get contentDispositionHeader() { - throw Components.Exception("No header", - Cr.NS_ERROR_NOT_AVAILABLE); + throw Components.Exception("No header", Cr.NS_ERROR_NOT_AVAILABLE); }, /** nsIRequest */ @@ -96,49 +101,57 @@ ProtocolHandler.prototype = { }, cancel(status) {}, loadGroup: null, - loadFlags: Ci.nsIRequest.LOAD_NORMAL | - Ci.nsIRequest.INHIBIT_CACHING | - Ci.nsIRequest.LOAD_BYPASS_CACHE, + loadFlags: + Ci.nsIRequest.LOAD_NORMAL | + Ci.nsIRequest.INHIBIT_CACHING | + Ci.nsIRequest.LOAD_BYPASS_CACHE, /** nsIFactory */ createInstance(aOuter, aIID) { if (aOuter) { - throw Components.Exception("createInstance no aggregation", - Cr.NS_ERROR_NO_AGGREGATION); + throw Components.Exception( + "createInstance no aggregation", + Cr.NS_ERROR_NO_AGGREGATION + ); } return this.QueryInterface(aIID); }, lockFactory() {}, /** nsISupports */ - QueryInterface: ChromeUtils.generateQI([Ci.nsIProtocolHandler, - Ci.nsIRequest, - Ci.nsIChannel, - Ci.nsIFactory]), - classID: Components.ID("{16d594bc-d9d8-47ae-a139-ea714dc0c35c}") + QueryInterface: ChromeUtils.generateQI([ + Ci.nsIProtocolHandler, + Ci.nsIRequest, + Ci.nsIChannel, + Ci.nsIFactory, + ]), + classID: Components.ID("{16d594bc-d9d8-47ae-a139-ea714dc0c35c}"), }; /** * Attempt a sync load; we use the stylesheet service to do this for us, * based on the knowledge that it forces a sync load under the hood. */ -function run_test() -{ +function run_test() { var handler = new ProtocolHandler(); - var registrar = Components.manager. - QueryInterface(Ci.nsIComponentRegistrar); - registrar.registerFactory(handler.classID, "", - "@mozilla.org/network/protocol;1?name=" + handler.scheme, - handler); + var registrar = Components.manager.QueryInterface(Ci.nsIComponentRegistrar); + registrar.registerFactory( + handler.classID, + "", + "@mozilla.org/network/protocol;1?name=" + handler.scheme, + handler + ); try { - var ss = Cc["@mozilla.org/content/style-sheet-service;1"]. - getService(Ci.nsIStyleSheetService); + var ss = Cc["@mozilla.org/content/style-sheet-service;1"].getService( + Ci.nsIStyleSheetService + ); ss.loadAndRegisterSheet(handler.uri, Ci.nsIStyleSheetService.AGENT_SHEET); - Assert.ok(ss.sheetRegistered(handler.uri, Ci.nsIStyleSheetService.AGENT_SHEET)); + Assert.ok( + ss.sheetRegistered(handler.uri, Ci.nsIStyleSheetService.AGENT_SHEET) + ); } finally { registrar.unregisterFactory(handler.classID, handler); } } // vim: set et ts=2 : - diff --git a/netwerk/test/unit/test_bug935499.js b/netwerk/test/unit/test_bug935499.js index 97e358627695..a1a3814276e9 100644 --- a/netwerk/test/unit/test_bug935499.js +++ b/netwerk/test/unit/test_bug935499.js @@ -1,6 +1,7 @@ function run_test() { - var idnService = Cc["@mozilla.org/network/idn-service;1"] - .getService(Ci.nsIIDNService); + var idnService = Cc["@mozilla.org/network/idn-service;1"].getService( + Ci.nsIIDNService + ); var isASCII = {}; Assert.equal(idnService.convertToDisplayIDN("xn--", isASCII), "xn--"); diff --git a/netwerk/test/unit/test_cache-control_request.js b/netwerk/test/unit/test_cache-control_request.js index e32cba86c499..a6180b50d62e 100644 --- a/netwerk/test/unit/test_cache-control_request.js +++ b/netwerk/test/unit/test_cache-control_request.js @@ -1,4 +1,4 @@ -const {HttpServer} = ChromeUtils.import("resource://testing-common/httpd.js"); +const { HttpServer } = ChromeUtils.import("resource://testing-common/httpd.js"); var httpserver = new HttpServer(); httpserver.start(-1); @@ -15,13 +15,11 @@ var resource_fresh_100_url = base_url + resource_fresh_100; // Test flags var hit_server = false; - -function make_channel(url, cache_control) -{ +function make_channel(url, cache_control) { // Reset test global status hit_server = false; - var req = NetUtil.newChannel({uri: url, loadUsingSystemPrincipal: true}); + var req = NetUtil.newChannel({ uri: url, loadUsingSystemPrincipal: true }); req.QueryInterface(Ci.nsIHttpChannel); if (cache_control) { req.setRequestHeader("Cache-control", cache_control, false); @@ -31,13 +29,11 @@ function make_channel(url, cache_control) } function make_uri(url) { - var ios = Cc["@mozilla.org/network/io-service;1"]. - getService(Ci.nsIIOService); + var ios = Cc["@mozilla.org/network/io-service;1"].getService(Ci.nsIIOService); return ios.newURI(url); } -function resource_age_100_handler(metadata, response) -{ +function resource_age_100_handler(metadata, response) { hit_server = true; response.setStatusLine(metadata.httpVersion, 200, "OK"); @@ -50,8 +46,7 @@ function resource_age_100_handler(metadata, response) response.bodyOutputStream.write(body, body.length); } -function resource_stale_100_handler(metadata, response) -{ +function resource_stale_100_handler(metadata, response) { hit_server = true; response.setStatusLine(metadata.httpVersion, 200, "OK"); @@ -65,8 +60,7 @@ function resource_stale_100_handler(metadata, response) response.bodyOutputStream.write(body, body.length); } -function resource_fresh_100_handler(metadata, response) -{ +function resource_fresh_100_handler(metadata, response) { hit_server = true; response.setStatusLine(metadata.httpVersion, 200, "OK"); @@ -79,9 +73,7 @@ function resource_fresh_100_handler(metadata, response) response.bodyOutputStream.write(body, body.length); } - -function run_test() -{ +function run_test() { do_get_profile(); do_test_pending(); @@ -89,8 +81,14 @@ function run_test() Services.prefs.setBoolPref("network.http.rcwn.enabled", false); httpserver.registerPathHandler(resource_age_100, resource_age_100_handler); - httpserver.registerPathHandler(resource_stale_100, resource_stale_100_handler); - httpserver.registerPathHandler(resource_fresh_100, resource_fresh_100_handler); + httpserver.registerPathHandler( + resource_stale_100, + resource_stale_100_handler + ); + httpserver.registerPathHandler( + resource_fresh_100, + resource_fresh_100_handler + ); cache = getCacheStorage("disk"); wait_for_cache_index(run_next_test); @@ -104,46 +102,54 @@ function run_test() add_test(() => { // Must not create a cache entry var ch = make_channel(resource_age_100_url, "no-store"); - ch.asyncOpen(new ChannelListener(function(request, data) { - Assert.ok(hit_server); - Assert.ok(!cache.exists(make_uri(resource_age_100_url), "")); + ch.asyncOpen( + new ChannelListener(function(request, data) { + Assert.ok(hit_server); + Assert.ok(!cache.exists(make_uri(resource_age_100_url), "")); - run_next_test(); - }, null)); + run_next_test(); + }, null) + ); }); add_test(() => { // Prepare state only, cache the entry var ch = make_channel(resource_age_100_url); - ch.asyncOpen(new ChannelListener(function(request, data) { - Assert.ok(hit_server); - Assert.ok(cache.exists(make_uri(resource_age_100_url), "")); + ch.asyncOpen( + new ChannelListener(function(request, data) { + Assert.ok(hit_server); + Assert.ok(cache.exists(make_uri(resource_age_100_url), "")); - run_next_test(); - }, null)); + run_next_test(); + }, null) + ); }); add_test(() => { // Check the prepared cache entry is used when no special directives are added var ch = make_channel(resource_age_100_url); - ch.asyncOpen(new ChannelListener(function(request, data) { - Assert.ok(!hit_server); - Assert.ok(cache.exists(make_uri(resource_age_100_url), "")); + ch.asyncOpen( + new ChannelListener(function(request, data) { + Assert.ok(!hit_server); + Assert.ok(cache.exists(make_uri(resource_age_100_url), "")); - run_next_test(); - }, null)); + run_next_test(); + }, null) + ); }); add_test(() => { // Try again, while we already keep a cache entry, // the channel must not use it, entry should stay in the cache var ch = make_channel(resource_age_100_url, "no-store"); - ch.asyncOpen(new ChannelListener(function(request, data) { - Assert.ok(hit_server); - Assert.ok(cache.exists(make_uri(resource_age_100_url), "")); + ch.asyncOpen( + new ChannelListener(function(request, data) { + Assert.ok(hit_server); + Assert.ok(cache.exists(make_uri(resource_age_100_url), "")); - run_next_test(); - }, null)); + run_next_test(); + }, null) + ); }); // ============================================================================ @@ -152,23 +158,27 @@ add_test(() => { add_test(() => { // Check the prepared cache entry is used when no special directives are added var ch = make_channel(resource_age_100_url); - ch.asyncOpen(new ChannelListener(function(request, data) { - Assert.ok(!hit_server); - Assert.ok(cache.exists(make_uri(resource_age_100_url), "")); + ch.asyncOpen( + new ChannelListener(function(request, data) { + Assert.ok(!hit_server); + Assert.ok(cache.exists(make_uri(resource_age_100_url), "")); - run_next_test(); - }, null)); + run_next_test(); + }, null) + ); }); add_test(() => { // The existing entry should be revalidated (we expect a server hit) var ch = make_channel(resource_age_100_url, "no-cache"); - ch.asyncOpen(new ChannelListener(function(request, data) { - Assert.ok(hit_server); - Assert.ok(cache.exists(make_uri(resource_age_100_url), "")); + ch.asyncOpen( + new ChannelListener(function(request, data) { + Assert.ok(hit_server); + Assert.ok(cache.exists(make_uri(resource_age_100_url), "")); - run_next_test(); - }, null)); + run_next_test(); + }, null) + ); }); // ============================================================================ @@ -177,48 +187,56 @@ add_test(() => { add_test(() => { // Check the prepared cache entry is used when no special directives are added var ch = make_channel(resource_age_100_url); - ch.asyncOpen(new ChannelListener(function(request, data) { - Assert.ok(!hit_server); - Assert.ok(cache.exists(make_uri(resource_age_100_url), "")); + ch.asyncOpen( + new ChannelListener(function(request, data) { + Assert.ok(!hit_server); + Assert.ok(cache.exists(make_uri(resource_age_100_url), "")); - run_next_test(); - }, null)); + run_next_test(); + }, null) + ); }); add_test(() => { // The existing entry's age is greater than the maximum requested, // should hit server var ch = make_channel(resource_age_100_url, "max-age=10"); - ch.asyncOpen(new ChannelListener(function(request, data) { - Assert.ok(hit_server); - Assert.ok(cache.exists(make_uri(resource_age_100_url), "")); + ch.asyncOpen( + new ChannelListener(function(request, data) { + Assert.ok(hit_server); + Assert.ok(cache.exists(make_uri(resource_age_100_url), "")); - run_next_test(); - }, null)); + run_next_test(); + }, null) + ); }); add_test(() => { // The existing entry's age is greater than the maximum requested, // but the max-stale directive says to use it when it's fresh enough var ch = make_channel(resource_age_100_url, "max-age=10, max-stale=99999"); - ch.asyncOpen(new ChannelListener(function(request, data) { - Assert.ok(!hit_server); - Assert.ok(cache.exists(make_uri(resource_age_100_url), "")); + ch.asyncOpen( + new ChannelListener(function(request, data) { + Assert.ok(!hit_server); + Assert.ok(cache.exists(make_uri(resource_age_100_url), "")); - run_next_test(); - }, null)); + run_next_test(); + }, null) + ); }); add_test(() => { // The existing entry's age is lesser than the maximum requested, // should go from cache var ch = make_channel(resource_age_100_url, "max-age=1000"); - ch.asyncOpen(new ChannelListener(function(request, data) { - Assert.ok(!hit_server); - Assert.ok(cache.exists(make_uri(resource_age_100_url), "")); + ch.asyncOpen( + new ChannelListener(function(request, data) { + Assert.ok(!hit_server); + Assert.ok(cache.exists(make_uri(resource_age_100_url), "")); - run_next_test(); - }, null)); + run_next_test(); + }, null) + ); }); // ============================================================================ @@ -227,59 +245,69 @@ add_test(() => { add_test(() => { // Preprate the entry first var ch = make_channel(resource_stale_100_url); - ch.asyncOpen(new ChannelListener(function(request, data) { - Assert.ok(hit_server); - Assert.ok(cache.exists(make_uri(resource_stale_100_url), "")); + ch.asyncOpen( + new ChannelListener(function(request, data) { + Assert.ok(hit_server); + Assert.ok(cache.exists(make_uri(resource_stale_100_url), "")); - // Must shift the expiration time set on the entry to |now| be in the past - do_timeout(1500, run_next_test); - }, null)); + // Must shift the expiration time set on the entry to |now| be in the past + do_timeout(1500, run_next_test); + }, null) + ); }); add_test(() => { // Check it's not reused (as it's stale) when no special directives // are provided var ch = make_channel(resource_stale_100_url); - ch.asyncOpen(new ChannelListener(function(request, data) { - Assert.ok(hit_server); - Assert.ok(cache.exists(make_uri(resource_stale_100_url), "")); + ch.asyncOpen( + new ChannelListener(function(request, data) { + Assert.ok(hit_server); + Assert.ok(cache.exists(make_uri(resource_stale_100_url), "")); - do_timeout(1500, run_next_test); - }, null)); + do_timeout(1500, run_next_test); + }, null) + ); }); add_test(() => { // Accept cached responses of any stale time var ch = make_channel(resource_stale_100_url, "max-stale"); - ch.asyncOpen(new ChannelListener(function(request, data) { - Assert.ok(!hit_server); - Assert.ok(cache.exists(make_uri(resource_stale_100_url), "")); + ch.asyncOpen( + new ChannelListener(function(request, data) { + Assert.ok(!hit_server); + Assert.ok(cache.exists(make_uri(resource_stale_100_url), "")); - do_timeout(1500, run_next_test); - }, null)); + do_timeout(1500, run_next_test); + }, null) + ); }); add_test(() => { // The entry is stale only by 100 seconds, accept it var ch = make_channel(resource_stale_100_url, "max-stale=1000"); - ch.asyncOpen(new ChannelListener(function(request, data) { - Assert.ok(!hit_server); - Assert.ok(cache.exists(make_uri(resource_stale_100_url), "")); + ch.asyncOpen( + new ChannelListener(function(request, data) { + Assert.ok(!hit_server); + Assert.ok(cache.exists(make_uri(resource_stale_100_url), "")); - do_timeout(1500, run_next_test); - }, null)); + do_timeout(1500, run_next_test); + }, null) + ); }); add_test(() => { // The entry is stale by 100 seconds but we only accept a 10 seconds stale // entry, go from server var ch = make_channel(resource_stale_100_url, "max-stale=10"); - ch.asyncOpen(new ChannelListener(function(request, data) { - Assert.ok(hit_server); - Assert.ok(cache.exists(make_uri(resource_stale_100_url), "")); + ch.asyncOpen( + new ChannelListener(function(request, data) { + Assert.ok(hit_server); + Assert.ok(cache.exists(make_uri(resource_stale_100_url), "")); - run_next_test(); - }, null)); + run_next_test(); + }, null) + ); }); // ============================================================================ @@ -288,45 +316,53 @@ add_test(() => { add_test(() => { // Preprate the entry first var ch = make_channel(resource_fresh_100_url); - ch.asyncOpen(new ChannelListener(function(request, data) { - Assert.ok(hit_server); - Assert.ok(cache.exists(make_uri(resource_fresh_100_url), "")); + ch.asyncOpen( + new ChannelListener(function(request, data) { + Assert.ok(hit_server); + Assert.ok(cache.exists(make_uri(resource_fresh_100_url), "")); - run_next_test(); - }, null)); + run_next_test(); + }, null) + ); }); add_test(() => { // Check it's reused when no special directives are provided var ch = make_channel(resource_fresh_100_url); - ch.asyncOpen(new ChannelListener(function(request, data) { - Assert.ok(!hit_server); - Assert.ok(cache.exists(make_uri(resource_fresh_100_url), "")); + ch.asyncOpen( + new ChannelListener(function(request, data) { + Assert.ok(!hit_server); + Assert.ok(cache.exists(make_uri(resource_fresh_100_url), "")); - run_next_test(); - }, null)); + run_next_test(); + }, null) + ); }); add_test(() => { // Entry fresh enough to be served from the cache var ch = make_channel(resource_fresh_100_url, "min-fresh=10"); - ch.asyncOpen(new ChannelListener(function(request, data) { - Assert.ok(!hit_server); - Assert.ok(cache.exists(make_uri(resource_fresh_100_url), "")); + ch.asyncOpen( + new ChannelListener(function(request, data) { + Assert.ok(!hit_server); + Assert.ok(cache.exists(make_uri(resource_fresh_100_url), "")); - run_next_test(); - }, null)); + run_next_test(); + }, null) + ); }); add_test(() => { // The entry is not fresh enough var ch = make_channel(resource_fresh_100_url, "min-fresh=1000"); - ch.asyncOpen(new ChannelListener(function(request, data) { - Assert.ok(hit_server); - Assert.ok(cache.exists(make_uri(resource_fresh_100_url), "")); + ch.asyncOpen( + new ChannelListener(function(request, data) { + Assert.ok(hit_server); + Assert.ok(cache.exists(make_uri(resource_fresh_100_url), "")); - run_next_test(); - }, null)); + run_next_test(); + }, null) + ); }); // ============================================================================ @@ -334,23 +370,30 @@ add_test(() => { // doesn't load from the server. add_test(() => { - var ch = make_channel(resource_fresh_100_url, "unknown1,unknown2 = \"a,b\", min-fresh = 1000 "); - ch.asyncOpen(new ChannelListener(function(request, data) { - Assert.ok(hit_server); - Assert.ok(cache.exists(make_uri(resource_fresh_100_url), "")); + var ch = make_channel( + resource_fresh_100_url, + 'unknown1,unknown2 = "a,b", min-fresh = 1000 ' + ); + ch.asyncOpen( + new ChannelListener(function(request, data) { + Assert.ok(hit_server); + Assert.ok(cache.exists(make_uri(resource_fresh_100_url), "")); - run_next_test(); - }, null)); + run_next_test(); + }, null) + ); }); add_test(() => { var ch = make_channel(resource_fresh_100_url, "no-cache = , min-fresh = 10"); - ch.asyncOpen(new ChannelListener(function(request, data) { - Assert.ok(hit_server); - Assert.ok(cache.exists(make_uri(resource_fresh_100_url), "")); + ch.asyncOpen( + new ChannelListener(function(request, data) { + Assert.ok(hit_server); + Assert.ok(cache.exists(make_uri(resource_fresh_100_url), "")); - run_next_test(); - }, null)); + run_next_test(); + }, null) + ); }); // ============================================================================ @@ -365,17 +408,38 @@ add_test(() => { // Helpers function date_string_from_now(delta_secs) { - var months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', - 'Sep', 'Oct', 'Nov', 'Dec']; - var days = ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat']; + var months = [ + "Jan", + "Feb", + "Mar", + "Apr", + "May", + "Jun", + "Jul", + "Aug", + "Sep", + "Oct", + "Nov", + "Dec", + ]; + var days = ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"]; - var d = new Date(); - d.setTime(d.getTime() + delta_secs * 1000); - return days[d.getUTCDay()] + ", " + - d.getUTCDate() + " " + - months[d.getUTCMonth()] + " " + - d.getUTCFullYear() + " " + - d.getUTCHours() + ":" + - d.getUTCMinutes() + ":" + - d.getUTCSeconds() + " UTC"; + var d = new Date(); + d.setTime(d.getTime() + delta_secs * 1000); + return ( + days[d.getUTCDay()] + + ", " + + d.getUTCDate() + + " " + + months[d.getUTCMonth()] + + " " + + d.getUTCFullYear() + + " " + + d.getUTCHours() + + ":" + + d.getUTCMinutes() + + ":" + + d.getUTCSeconds() + + " UTC" + ); } diff --git a/netwerk/test/unit/test_cache-entry-id.js b/netwerk/test/unit/test_cache-entry-id.js index 3717bec04982..3b2198f376e2 100644 --- a/netwerk/test/unit/test_cache-entry-id.js +++ b/netwerk/test/unit/test_cache-entry-id.js @@ -2,7 +2,7 @@ * Test for the "CacheEntryId" under several cases. */ -const {HttpServer} = ChromeUtils.import("resource://testing-common/httpd.js"); +const { HttpServer } = ChromeUtils.import("resource://testing-common/httpd.js"); XPCOMUtils.defineLazyGetter(this, "URL", function() { return "http://localhost:" + httpServer.identity.primaryPort + "/content"; @@ -16,22 +16,39 @@ const altContent = "!@#$%^&*()"; const altContentType = "text/binary"; function isParentProcess() { - let appInfo = Cc["@mozilla.org/xre/app-info;1"]; - return (!appInfo || appInfo.getService(Ci.nsIXULRuntime).processType == Ci.nsIXULRuntime.PROCESS_TYPE_DEFAULT); + let appInfo = Cc["@mozilla.org/xre/app-info;1"]; + return ( + !appInfo || + appInfo.getService(Ci.nsIXULRuntime).processType == + Ci.nsIXULRuntime.PROCESS_TYPE_DEFAULT + ); } var handlers = [ - (m, r) => {r.bodyOutputStream.write(responseContent, responseContent.length)}, - (m, r) => {r.setStatusLine(m.httpVersion, 304, "Not Modified")}, - (m, r) => {r.setStatusLine(m.httpVersion, 304, "Not Modified")}, - (m, r) => {r.setStatusLine(m.httpVersion, 304, "Not Modified")}, - (m, r) => {r.setStatusLine(m.httpVersion, 304, "Not Modified")}, - (m, r) => {r.bodyOutputStream.write(responseContent2, responseContent2.length)}, - (m, r) => {r.setStatusLine(m.httpVersion, 304, "Not Modified")}, + (m, r) => { + r.bodyOutputStream.write(responseContent, responseContent.length); + }, + (m, r) => { + r.setStatusLine(m.httpVersion, 304, "Not Modified"); + }, + (m, r) => { + r.setStatusLine(m.httpVersion, 304, "Not Modified"); + }, + (m, r) => { + r.setStatusLine(m.httpVersion, 304, "Not Modified"); + }, + (m, r) => { + r.setStatusLine(m.httpVersion, 304, "Not Modified"); + }, + (m, r) => { + r.bodyOutputStream.write(responseContent2, responseContent2.length); + }, + (m, r) => { + r.setStatusLine(m.httpVersion, 304, "Not Modified"); + }, ]; -function contentHandler(metadata, response) -{ +function contentHandler(metadata, response) { response.setHeader("Content-Type", "text/plain"); response.setHeader("Cache-Control", "no-cache"); @@ -44,28 +61,30 @@ function contentHandler(metadata, response) Assert.ok(false, "Should not reach here."); } -function fetch(preferredDataType = null) -{ +function fetch(preferredDataType = null) { return new Promise(resolve => { - var chan = NetUtil.newChannel({uri: URL, loadUsingSystemPrincipal: true}); + var chan = NetUtil.newChannel({ uri: URL, loadUsingSystemPrincipal: true }); if (preferredDataType) { var cc = chan.QueryInterface(Ci.nsICacheInfoChannel); cc.preferAlternativeDataType(altContentType, "", true); } - chan.asyncOpen(new ChannelListener((request, - buffer, - ctx, - isFromCache, - cacheEntryId) => { - resolve({request, buffer, isFromCache, cacheEntryId}); - }, null)); + chan.asyncOpen( + new ChannelListener((request, buffer, ctx, isFromCache, cacheEntryId) => { + resolve({ request, buffer, isFromCache, cacheEntryId }); + }, null) + ); }); } -function check(response, content, preferredDataType, isFromCache, cacheEntryIdChecker) -{ +function check( + response, + content, + preferredDataType, + isFromCache, + cacheEntryIdChecker +) { var cc = response.request.QueryInterface(Ci.nsICacheInfoChannel); Assert.equal(response.buffer, content); @@ -76,8 +95,7 @@ function check(response, content, preferredDataType, isFromCache, cacheEntryIdCh return response; } -function writeAltData(request) -{ +function writeAltData(request) { var cc = request.QueryInterface(Ci.nsICacheInfoChannel); var os = cc.openAlternativeOutputStream(altContentType, altContent.length); os.write(altContent, altContent.length); @@ -86,17 +104,15 @@ function writeAltData(request) return new Promise(resolve => { if (isParentProcess()) { - Services.cache2.QueryInterface(Ci.nsICacheTesting) - .flush(resolve); + Services.cache2.QueryInterface(Ci.nsICacheTesting).flush(resolve); } else { - do_send_remote_message('flush'); - do_await_remote_message('flushed').then(resolve); + do_send_remote_message("flush"); + do_await_remote_message("flushed").then(resolve); } }); } -function run_test() -{ +function run_test() { do_get_profile(); httpServer = new HttpServer(); httpServer.registerPathHandler("/content", contentHandler); @@ -105,42 +121,93 @@ function run_test() var targetCacheEntryId = null; - return Promise.resolve() - // Setup testing environment: Placing alternative data into HTTP cache. - .then(_ => fetch(altContentType)) - .then(r => check(r, responseContent, "", false, - cacheEntryId => cacheEntryId === undefined)) - .then(r => writeAltData(r.request)) + return ( + Promise.resolve() + // Setup testing environment: Placing alternative data into HTTP cache. + .then(_ => fetch(altContentType)) + .then(r => + check( + r, + responseContent, + "", + false, + cacheEntryId => cacheEntryId === undefined + ) + ) + .then(r => writeAltData(r.request)) - // Start testing. - .then(_ => fetch(altContentType)) - .then(r => check(r, altContent, altContentType, true, - cacheEntryId => cacheEntryId !== undefined)) - .then(r => targetCacheEntryId = r.cacheEntryId) + // Start testing. + .then(_ => fetch(altContentType)) + .then(r => + check( + r, + altContent, + altContentType, + true, + cacheEntryId => cacheEntryId !== undefined + ) + ) + .then(r => (targetCacheEntryId = r.cacheEntryId)) - .then(_ => fetch()) - .then(r => check(r, responseContent, "", true, - cacheEntryId => cacheEntryId === targetCacheEntryId)) + .then(_ => fetch()) + .then(r => + check( + r, + responseContent, + "", + true, + cacheEntryId => cacheEntryId === targetCacheEntryId + ) + ) - .then(_ => fetch(altContentType)) - .then(r => check(r, altContent, altContentType, true, - cacheEntryId => cacheEntryId === targetCacheEntryId)) + .then(_ => fetch(altContentType)) + .then(r => + check( + r, + altContent, + altContentType, + true, + cacheEntryId => cacheEntryId === targetCacheEntryId + ) + ) - .then(_ => fetch()) - .then(r => check(r, responseContent, "", true, - cacheEntryId => cacheEntryId === targetCacheEntryId)) + .then(_ => fetch()) + .then(r => + check( + r, + responseContent, + "", + true, + cacheEntryId => cacheEntryId === targetCacheEntryId + ) + ) - .then(_ => fetch()) // The response is changed here. - .then(r => check(r, responseContent2, "", false, - cacheEntryId => cacheEntryId === undefined)) + .then(_ => fetch()) // The response is changed here. + .then(r => + check( + r, + responseContent2, + "", + false, + cacheEntryId => cacheEntryId === undefined + ) + ) - .then(_ => fetch()) - .then(r => check(r, responseContent2, "", true, - cacheEntryId => cacheEntryId !== undefined && - cacheEntryId !== targetCacheEntryId)) + .then(_ => fetch()) + .then(r => + check( + r, + responseContent2, + "", + true, + cacheEntryId => + cacheEntryId !== undefined && cacheEntryId !== targetCacheEntryId + ) + ) - // Tear down. - .catch(e => Assert.ok(false, "Unexpected exception: " + e)) - .then(_ => Assert.equal(handlers.length, 0)) - .then(_ => httpServer.stop(do_test_finished)); + // Tear down. + .catch(e => Assert.ok(false, "Unexpected exception: " + e)) + .then(_ => Assert.equal(handlers.length, 0)) + .then(_ => httpServer.stop(do_test_finished)) + ); } diff --git a/netwerk/test/unit/test_cache2-00-service-get.js b/netwerk/test/unit/test_cache2-00-service-get.js index 2656a253678c..36a138abbf8b 100644 --- a/netwerk/test/unit/test_cache2-00-service-get.js +++ b/netwerk/test/unit/test_cache2-00-service-get.js @@ -1,12 +1,13 @@ -function run_test() -{ +function run_test() { // Just check the contract ID alias works well. try { - var serviceA = Cc["@mozilla.org/netwerk/cache-storage-service;1"] - .getService(Ci.nsICacheStorageService); + var serviceA = Cc[ + "@mozilla.org/netwerk/cache-storage-service;1" + ].getService(Ci.nsICacheStorageService); Assert.ok(serviceA); - var serviceB = Cc["@mozilla.org/network/cache-storage-service;1"] - .getService(Ci.nsICacheStorageService); + var serviceB = Cc[ + "@mozilla.org/network/cache-storage-service;1" + ].getService(Ci.nsICacheStorageService); Assert.ok(serviceB); Assert.equal(serviceA, serviceB); diff --git a/netwerk/test/unit/test_cache2-01-basic.js b/netwerk/test/unit/test_cache2-01-basic.js index dd8c340871b6..c438ed7fc16a 100644 --- a/netwerk/test/unit/test_cache2-01-basic.js +++ b/netwerk/test/unit/test_cache2-01-basic.js @@ -1,18 +1,33 @@ -function run_test() -{ +function run_test() { do_get_profile(); // Open for write, write - asyncOpenCacheEntry("http://a/", "disk", Ci.nsICacheStorage.OPEN_NORMALLY, null, + asyncOpenCacheEntry( + "http://a/", + "disk", + Ci.nsICacheStorage.OPEN_NORMALLY, + null, new OpenCallback(NEW, "a1m", "a1d", function(entry) { // Open for read and check - asyncOpenCacheEntry("http://a/", "disk", Ci.nsICacheStorage.OPEN_NORMALLY, null, + asyncOpenCacheEntry( + "http://a/", + "disk", + Ci.nsICacheStorage.OPEN_NORMALLY, + null, new OpenCallback(NORMAL, "a1m", "a1d", function(entry) { // Open for rewrite (truncate), write different meta and data - asyncOpenCacheEntry("http://a/", "disk", Ci.nsICacheStorage.OPEN_TRUNCATE, null, + asyncOpenCacheEntry( + "http://a/", + "disk", + Ci.nsICacheStorage.OPEN_TRUNCATE, + null, new OpenCallback(NEW, "a2m", "a2d", function(entry) { // Open for read and check - asyncOpenCacheEntry("http://a/", "disk", Ci.nsICacheStorage.OPEN_NORMALLY, null, + asyncOpenCacheEntry( + "http://a/", + "disk", + Ci.nsICacheStorage.OPEN_NORMALLY, + null, new OpenCallback(NORMAL, "a2m", "a2d", function(entry) { finish_cache2_test(); }) diff --git a/netwerk/test/unit/test_cache2-01a-basic-readonly.js b/netwerk/test/unit/test_cache2-01a-basic-readonly.js index bf1d31317132..cffc8bb2aeba 100644 --- a/netwerk/test/unit/test_cache2-01a-basic-readonly.js +++ b/netwerk/test/unit/test_cache2-01a-basic-readonly.js @@ -1,18 +1,33 @@ -function run_test() -{ +function run_test() { do_get_profile(); // Open for write, write - asyncOpenCacheEntry("http://ro/", "disk", Ci.nsICacheStorage.OPEN_NORMALLY, null, + asyncOpenCacheEntry( + "http://ro/", + "disk", + Ci.nsICacheStorage.OPEN_NORMALLY, + null, new OpenCallback(NEW, "a1m", "a1d", function(entry) { // Open for read and check - asyncOpenCacheEntry("http://ro/", "disk", Ci.nsICacheStorage.OPEN_READONLY, null, + asyncOpenCacheEntry( + "http://ro/", + "disk", + Ci.nsICacheStorage.OPEN_READONLY, + null, new OpenCallback(NORMAL, "a1m", "a1d", function(entry) { // Open for rewrite (truncate), write different meta and data - asyncOpenCacheEntry("http://ro/", "disk", Ci.nsICacheStorage.OPEN_TRUNCATE, null, + asyncOpenCacheEntry( + "http://ro/", + "disk", + Ci.nsICacheStorage.OPEN_TRUNCATE, + null, new OpenCallback(NEW, "a2m", "a2d", function(entry) { // Open for read and check - asyncOpenCacheEntry("http://ro/", "disk", Ci.nsICacheStorage.OPEN_READONLY, null, + asyncOpenCacheEntry( + "http://ro/", + "disk", + Ci.nsICacheStorage.OPEN_READONLY, + null, new OpenCallback(NORMAL, "a2m", "a2d", function(entry) { finish_cache2_test(); }) diff --git a/netwerk/test/unit/test_cache2-01b-basic-datasize.js b/netwerk/test/unit/test_cache2-01b-basic-datasize.js index 727554a739ae..c59a7fd38bee 100644 --- a/netwerk/test/unit/test_cache2-01b-basic-datasize.js +++ b/netwerk/test/unit/test_cache2-01b-basic-datasize.js @@ -1,21 +1,36 @@ -function run_test() -{ +function run_test() { do_get_profile(); // Open for write, write - asyncOpenCacheEntry("http://a/", "disk", Ci.nsICacheStorage.OPEN_NORMALLY, null, - new OpenCallback(NEW|WAITFORWRITE, "a1m", "a1d", function(entry) { + asyncOpenCacheEntry( + "http://a/", + "disk", + Ci.nsICacheStorage.OPEN_NORMALLY, + null, + new OpenCallback(NEW | WAITFORWRITE, "a1m", "a1d", function(entry) { // Open for read and check Assert.equal(entry.dataSize, 3); - asyncOpenCacheEntry("http://a/", "disk", Ci.nsICacheStorage.OPEN_NORMALLY, null, + asyncOpenCacheEntry( + "http://a/", + "disk", + Ci.nsICacheStorage.OPEN_NORMALLY, + null, new OpenCallback(NORMAL, "a1m", "a1d", function(entry) { // Open for rewrite (truncate), write different meta and data Assert.equal(entry.dataSize, 3); - asyncOpenCacheEntry("http://a/", "disk", Ci.nsICacheStorage.OPEN_TRUNCATE, null, - new OpenCallback(NEW|WAITFORWRITE, "a2m", "a2d", function(entry) { + asyncOpenCacheEntry( + "http://a/", + "disk", + Ci.nsICacheStorage.OPEN_TRUNCATE, + null, + new OpenCallback(NEW | WAITFORWRITE, "a2m", "a2d", function(entry) { // Open for read and check Assert.equal(entry.dataSize, 3); - asyncOpenCacheEntry("http://a/", "disk", Ci.nsICacheStorage.OPEN_NORMALLY, null, + asyncOpenCacheEntry( + "http://a/", + "disk", + Ci.nsICacheStorage.OPEN_NORMALLY, + null, new OpenCallback(NORMAL, "a2m", "a2d", function(entry) { Assert.equal(entry.dataSize, 3); finish_cache2_test(); diff --git a/netwerk/test/unit/test_cache2-01c-basic-hasmeta-only.js b/netwerk/test/unit/test_cache2-01c-basic-hasmeta-only.js index 0467656f0925..ba1d1375606c 100644 --- a/netwerk/test/unit/test_cache2-01c-basic-hasmeta-only.js +++ b/netwerk/test/unit/test_cache2-01c-basic-hasmeta-only.js @@ -1,18 +1,33 @@ -function run_test() -{ +function run_test() { do_get_profile(); // Open for write, write - asyncOpenCacheEntry("http://mt/", "disk", Ci.nsICacheStorage.OPEN_NORMALLY, null, - new OpenCallback(NEW|METAONLY, "a1m", "a1d", function(entry) { + asyncOpenCacheEntry( + "http://mt/", + "disk", + Ci.nsICacheStorage.OPEN_NORMALLY, + null, + new OpenCallback(NEW | METAONLY, "a1m", "a1d", function(entry) { // Open for read and check - asyncOpenCacheEntry("http://mt/", "disk", Ci.nsICacheStorage.OPEN_NORMALLY, null, + asyncOpenCacheEntry( + "http://mt/", + "disk", + Ci.nsICacheStorage.OPEN_NORMALLY, + null, new OpenCallback(NORMAL, "a1m", "", function(entry) { // Open for rewrite (truncate), write different meta and data - asyncOpenCacheEntry("http://mt/", "disk", Ci.nsICacheStorage.OPEN_TRUNCATE, null, + asyncOpenCacheEntry( + "http://mt/", + "disk", + Ci.nsICacheStorage.OPEN_TRUNCATE, + null, new OpenCallback(NEW, "a2m", "a2d", function(entry) { // Open for read and check - asyncOpenCacheEntry("http://mt/", "disk", Ci.nsICacheStorage.OPEN_NORMALLY, null, + asyncOpenCacheEntry( + "http://mt/", + "disk", + Ci.nsICacheStorage.OPEN_NORMALLY, + null, new OpenCallback(NORMAL, "a2m", "a2d", function(entry) { finish_cache2_test(); }) diff --git a/netwerk/test/unit/test_cache2-01d-basic-not-wanted.js b/netwerk/test/unit/test_cache2-01d-basic-not-wanted.js index b07831d7b0db..da8b495b8918 100644 --- a/netwerk/test/unit/test_cache2-01d-basic-not-wanted.js +++ b/netwerk/test/unit/test_cache2-01d-basic-not-wanted.js @@ -1,18 +1,33 @@ -function run_test() -{ +function run_test() { do_get_profile(); // Open for write, write - asyncOpenCacheEntry("http://a/", "disk", Ci.nsICacheStorage.OPEN_NORMALLY, null, + asyncOpenCacheEntry( + "http://a/", + "disk", + Ci.nsICacheStorage.OPEN_NORMALLY, + null, new OpenCallback(NEW, "a1m", "a1d", function(entry) { // Open for read and check - asyncOpenCacheEntry("http://a/", "disk", Ci.nsICacheStorage.OPEN_NORMALLY, null, + asyncOpenCacheEntry( + "http://a/", + "disk", + Ci.nsICacheStorage.OPEN_NORMALLY, + null, new OpenCallback(NORMAL, "a1m", "a1d", function(entry) { // Open but don't want the entry - asyncOpenCacheEntry("http://a/", "disk", Ci.nsICacheStorage.OPEN_NORMALLY, null, + asyncOpenCacheEntry( + "http://a/", + "disk", + Ci.nsICacheStorage.OPEN_NORMALLY, + null, new OpenCallback(NOTWANTED, "a1m", "a1d", function(entry) { // Open for read again and check the entry is OK - asyncOpenCacheEntry("http://a/", "disk", Ci.nsICacheStorage.OPEN_NORMALLY, null, + asyncOpenCacheEntry( + "http://a/", + "disk", + Ci.nsICacheStorage.OPEN_NORMALLY, + null, new OpenCallback(NORMAL, "a1m", "a1d", function(entry) { finish_cache2_test(); }) diff --git a/netwerk/test/unit/test_cache2-01e-basic-bypass-if-busy.js b/netwerk/test/unit/test_cache2-01e-basic-bypass-if-busy.js index 1846b6f47533..3e007e4180b2 100644 --- a/netwerk/test/unit/test_cache2-01e-basic-bypass-if-busy.js +++ b/netwerk/test/unit/test_cache2-01e-basic-bypass-if-busy.js @@ -1,14 +1,21 @@ -function run_test() -{ +function run_test() { do_get_profile(); // Open for write, delay the actual write - asyncOpenCacheEntry("http://a/", "disk", Ci.nsICacheStorage.OPEN_NORMALLY, null, - new OpenCallback(NEW|DONTFILL, "a1m", "a1d", function(entry) { + asyncOpenCacheEntry( + "http://a/", + "disk", + Ci.nsICacheStorage.OPEN_NORMALLY, + null, + new OpenCallback(NEW | DONTFILL, "a1m", "a1d", function(entry) { var bypassed = false; // Open and bypass - asyncOpenCacheEntry("http://a/", "disk", Ci.nsICacheStorage.OPEN_BYPASS_IF_BUSY, null, + asyncOpenCacheEntry( + "http://a/", + "disk", + Ci.nsICacheStorage.OPEN_BYPASS_IF_BUSY, + null, new OpenCallback(NOTFOUND, "", "", function(entry) { Assert.ok(!bypassed); bypassed = true; diff --git a/netwerk/test/unit/test_cache2-01f-basic-openTruncate.js b/netwerk/test/unit/test_cache2-01f-basic-openTruncate.js index ca8990310cea..3ef2c256a757 100644 --- a/netwerk/test/unit/test_cache2-01f-basic-openTruncate.js +++ b/netwerk/test/unit/test_cache2-01f-basic-openTruncate.js @@ -1,5 +1,4 @@ -function run_test() -{ +function run_test() { do_get_profile(); var storage = getCacheStorage("disk"); @@ -7,13 +6,17 @@ function run_test() Assert.ok(!!entry); // Fill the entry, and when done, check it's content - (new OpenCallback(NEW, "meta", "data", function() { - asyncOpenCacheEntry("http://new1/", "disk", Ci.nsICacheStorage.OPEN_NORMALLY, null, + new OpenCallback(NEW, "meta", "data", function() { + asyncOpenCacheEntry( + "http://new1/", + "disk", + Ci.nsICacheStorage.OPEN_NORMALLY, + null, new OpenCallback(NORMAL, "meta", "data", function() { finish_cache2_test(); }) ); - })).onCacheEntryAvailable(entry, true, null, 0); + }).onCacheEntryAvailable(entry, true, null, 0); do_test_pending(); } diff --git a/netwerk/test/unit/test_cache2-02-open-non-existing.js b/netwerk/test/unit/test_cache2-02-open-non-existing.js index 584ff7dfa790..ff6831913fd3 100644 --- a/netwerk/test/unit/test_cache2-02-open-non-existing.js +++ b/netwerk/test/unit/test_cache2-02-open-non-existing.js @@ -1,18 +1,33 @@ -function run_test() -{ +function run_test() { do_get_profile(); // Open non-existing for read, should fail - asyncOpenCacheEntry("http://b/", "disk", Ci.nsICacheStorage.OPEN_READONLY, null, + asyncOpenCacheEntry( + "http://b/", + "disk", + Ci.nsICacheStorage.OPEN_READONLY, + null, new OpenCallback(NOTFOUND, null, null, function(entry) { // Open the same non-existing for read again, should fail second time - asyncOpenCacheEntry("http://b/", "disk", Ci.nsICacheStorage.OPEN_READONLY, null, + asyncOpenCacheEntry( + "http://b/", + "disk", + Ci.nsICacheStorage.OPEN_READONLY, + null, new OpenCallback(NOTFOUND, null, null, function(entry) { // Try it again normally, should go - asyncOpenCacheEntry("http://b/", "disk", Ci.nsICacheStorage.OPEN_NORMALLY, null, + asyncOpenCacheEntry( + "http://b/", + "disk", + Ci.nsICacheStorage.OPEN_NORMALLY, + null, new OpenCallback(NEW, "b1m", "b1d", function(entry) { // ...and check - asyncOpenCacheEntry("http://b/", "disk", Ci.nsICacheStorage.OPEN_NORMALLY, null, + asyncOpenCacheEntry( + "http://b/", + "disk", + Ci.nsICacheStorage.OPEN_NORMALLY, + null, new OpenCallback(NORMAL, "b1m", "b1d", function(entry) { finish_cache2_test(); }) diff --git a/netwerk/test/unit/test_cache2-03-oncacheentryavail-throws.js b/netwerk/test/unit/test_cache2-03-oncacheentryavail-throws.js index 79c367410d8b..69ec99bec0e4 100644 --- a/netwerk/test/unit/test_cache2-03-oncacheentryavail-throws.js +++ b/netwerk/test/unit/test_cache2-03-oncacheentryavail-throws.js @@ -1,15 +1,26 @@ -function run_test() -{ +function run_test() { do_get_profile(); // Open but let OCEA throw - asyncOpenCacheEntry("http://c/", "disk", Ci.nsICacheStorage.OPEN_NORMALLY, null, - new OpenCallback(NEW|THROWAVAIL, null, null, function(entry) { + asyncOpenCacheEntry( + "http://c/", + "disk", + Ci.nsICacheStorage.OPEN_NORMALLY, + null, + new OpenCallback(NEW | THROWAVAIL, null, null, function(entry) { // Try it again, should go - asyncOpenCacheEntry("http://c/", "disk", Ci.nsICacheStorage.OPEN_NORMALLY, null, + asyncOpenCacheEntry( + "http://c/", + "disk", + Ci.nsICacheStorage.OPEN_NORMALLY, + null, new OpenCallback(NEW, "c1m", "c1d", function(entry) { // ...and check - asyncOpenCacheEntry("http://c/", "disk", Ci.nsICacheStorage.OPEN_NORMALLY, null, + asyncOpenCacheEntry( + "http://c/", + "disk", + Ci.nsICacheStorage.OPEN_NORMALLY, + null, new OpenCallback(false, "c1m", "c1d", function(entry) { finish_cache2_test(); }) @@ -21,4 +32,3 @@ function run_test() do_test_pending(); } - diff --git a/netwerk/test/unit/test_cache2-04-oncacheentryavail-throws2x.js b/netwerk/test/unit/test_cache2-04-oncacheentryavail-throws2x.js index f4e59bd360cb..84733697527a 100644 --- a/netwerk/test/unit/test_cache2-04-oncacheentryavail-throws2x.js +++ b/netwerk/test/unit/test_cache2-04-oncacheentryavail-throws2x.js @@ -1,18 +1,33 @@ -function run_test() -{ +function run_test() { do_get_profile(); // Open but let OCEA throw - asyncOpenCacheEntry("http://d/", "disk", Ci.nsICacheStorage.OPEN_NORMALLY, null, - new OpenCallback(NEW|THROWAVAIL, null, null, function(entry) { + asyncOpenCacheEntry( + "http://d/", + "disk", + Ci.nsICacheStorage.OPEN_NORMALLY, + null, + new OpenCallback(NEW | THROWAVAIL, null, null, function(entry) { // Open but let OCEA throw ones again - asyncOpenCacheEntry("http://d/", "disk", Ci.nsICacheStorage.OPEN_NORMALLY, null, - new OpenCallback(NEW|THROWAVAIL, null, null, function(entry) { + asyncOpenCacheEntry( + "http://d/", + "disk", + Ci.nsICacheStorage.OPEN_NORMALLY, + null, + new OpenCallback(NEW | THROWAVAIL, null, null, function(entry) { // Try it again, should go - asyncOpenCacheEntry("http://d/", "disk", Ci.nsICacheStorage.OPEN_NORMALLY, null, + asyncOpenCacheEntry( + "http://d/", + "disk", + Ci.nsICacheStorage.OPEN_NORMALLY, + null, new OpenCallback(NEW, "d1m", "d1d", function(entry) { // ...and check - asyncOpenCacheEntry("http://d/", "disk", Ci.nsICacheStorage.OPEN_NORMALLY, null, + asyncOpenCacheEntry( + "http://d/", + "disk", + Ci.nsICacheStorage.OPEN_NORMALLY, + null, new OpenCallback(NORMAL, "d1m", "d1d", function(entry) { finish_cache2_test(); }) diff --git a/netwerk/test/unit/test_cache2-05-visit.js b/netwerk/test/unit/test_cache2-05-visit.js index efbc1746343c..5a2fcad1d4c7 100644 --- a/netwerk/test/unit/test_cache2-05-visit.js +++ b/netwerk/test/unit/test_cache2-05-visit.js @@ -1,5 +1,4 @@ -function run_test() -{ +function run_test() { do_get_profile(); var storage = getCacheStorage("disk"); @@ -12,29 +11,41 @@ function run_test() // visit the storage. executeSoon(function() { syncWithCacheIOThread(function() { - var expectedConsumption = 4096; storage.asyncVisitStorage( // Test should store 4 entries - new VisitCallback(4, expectedConsumption, ["http://a/", "http://b/", "http://c/", "http://d/"], function() { - storage.asyncVisitStorage( - // Still 4 entries expected, now don't walk them - new VisitCallback(4, expectedConsumption, null, function() { - finish_cache2_test(); - }), - false - ); - }), + new VisitCallback( + 4, + expectedConsumption, + ["http://a/", "http://b/", "http://c/", "http://d/"], + function() { + storage.asyncVisitStorage( + // Still 4 entries expected, now don't walk them + new VisitCallback(4, expectedConsumption, null, function() { + finish_cache2_test(); + }), + false + ); + } + ), true ); }); }); }); - asyncOpenCacheEntry("http://a/", "disk", Ci.nsICacheStorage.OPEN_NORMALLY, null, + asyncOpenCacheEntry( + "http://a/", + "disk", + Ci.nsICacheStorage.OPEN_NORMALLY, + null, new OpenCallback(NEW, "a1m", "a1d", function(entry) { - asyncOpenCacheEntry("http://a/", "disk", Ci.nsICacheStorage.OPEN_NORMALLY, null, + asyncOpenCacheEntry( + "http://a/", + "disk", + Ci.nsICacheStorage.OPEN_NORMALLY, + null, new OpenCallback(NORMAL, "a1m", "a1d", function(entry) { mc.fired(); }) @@ -42,9 +53,17 @@ function run_test() }) ); - asyncOpenCacheEntry("http://b/", "disk", Ci.nsICacheStorage.OPEN_NORMALLY, null, + asyncOpenCacheEntry( + "http://b/", + "disk", + Ci.nsICacheStorage.OPEN_NORMALLY, + null, new OpenCallback(NEW, "b1m", "b1d", function(entry) { - asyncOpenCacheEntry("http://b/", "disk", Ci.nsICacheStorage.OPEN_NORMALLY, null, + asyncOpenCacheEntry( + "http://b/", + "disk", + Ci.nsICacheStorage.OPEN_NORMALLY, + null, new OpenCallback(NORMAL, "b1m", "b1d", function(entry) { mc.fired(); }) @@ -52,9 +71,17 @@ function run_test() }) ); - asyncOpenCacheEntry("http://c/", "disk", Ci.nsICacheStorage.OPEN_NORMALLY, null, + asyncOpenCacheEntry( + "http://c/", + "disk", + Ci.nsICacheStorage.OPEN_NORMALLY, + null, new OpenCallback(NEW, "c1m", "c1d", function(entry) { - asyncOpenCacheEntry("http://c/", "disk", Ci.nsICacheStorage.OPEN_NORMALLY, null, + asyncOpenCacheEntry( + "http://c/", + "disk", + Ci.nsICacheStorage.OPEN_NORMALLY, + null, new OpenCallback(NORMAL, "c1m", "c1d", function(entry) { mc.fired(); }) @@ -62,9 +89,17 @@ function run_test() }) ); - asyncOpenCacheEntry("http://d/", "disk", Ci.nsICacheStorage.OPEN_NORMALLY, null, + asyncOpenCacheEntry( + "http://d/", + "disk", + Ci.nsICacheStorage.OPEN_NORMALLY, + null, new OpenCallback(NEW, "d1m", "d1d", function(entry) { - asyncOpenCacheEntry("http://d/", "disk", Ci.nsICacheStorage.OPEN_NORMALLY, null, + asyncOpenCacheEntry( + "http://d/", + "disk", + Ci.nsICacheStorage.OPEN_NORMALLY, + null, new OpenCallback(NORMAL, "d1m", "d1d", function(entry) { mc.fired(); }) diff --git a/netwerk/test/unit/test_cache2-06-pb-mode.js b/netwerk/test/unit/test_cache2-06-pb-mode.js index 0211ac408a23..591353df0f43 100644 --- a/netwerk/test/unit/test_cache2-06-pb-mode.js +++ b/netwerk/test/unit/test_cache2-06-pb-mode.js @@ -1,22 +1,32 @@ -function exitPB() -{ - var obsvc = Cc["@mozilla.org/observer-service;1"]. - getService(Ci.nsIObserverService); +function exitPB() { + var obsvc = Cc["@mozilla.org/observer-service;1"].getService( + Ci.nsIObserverService + ); obsvc.notifyObservers(null, "last-pb-context-exited"); } -function run_test() -{ +function run_test() { do_get_profile(); // Store PB entry - asyncOpenCacheEntry("http://p1/", "disk", Ci.nsICacheStorage.OPEN_NORMALLY, Services.loadContextInfo.private, + asyncOpenCacheEntry( + "http://p1/", + "disk", + Ci.nsICacheStorage.OPEN_NORMALLY, + Services.loadContextInfo.private, new OpenCallback(NEW, "p1m", "p1d", function(entry) { - asyncOpenCacheEntry("http://p1/", "disk", Ci.nsICacheStorage.OPEN_NORMALLY, Services.loadContextInfo.private, + asyncOpenCacheEntry( + "http://p1/", + "disk", + Ci.nsICacheStorage.OPEN_NORMALLY, + Services.loadContextInfo.private, new OpenCallback(NORMAL, "p1m", "p1d", function(entry) { // Check it's there syncWithCacheIOThread(function() { - var storage = getCacheStorage("disk", Services.loadContextInfo.private); + var storage = getCacheStorage( + "disk", + Services.loadContextInfo.private + ); storage.asyncVisitStorage( new VisitCallback(1, 12, ["http://p1/"], function() { // Simulate PB exit diff --git a/netwerk/test/unit/test_cache2-07-visit-memory.js b/netwerk/test/unit/test_cache2-07-visit-memory.js index b0a8cd0baa67..3a2a9ca48050 100644 --- a/netwerk/test/unit/test_cache2-07-visit-memory.js +++ b/netwerk/test/unit/test_cache2-07-visit-memory.js @@ -1,5 +1,4 @@ -function run_test() -{ +function run_test() { do_get_profile(); // Add entry to the memory storage @@ -12,9 +11,14 @@ function run_test() storage = getCacheStorage("disk"); storage.asyncVisitStorage( // Previous tests should store 4 disk entries - new VisitCallback(4, 4096, ["http://a/", "http://b/", "http://c/", "http://d/"], function() { - finish_cache2_test(); - }), + new VisitCallback( + 4, + 4096, + ["http://a/", "http://b/", "http://c/", "http://d/"], + function() { + finish_cache2_test(); + } + ), true ); }), @@ -23,9 +27,17 @@ function run_test() }); }); - asyncOpenCacheEntry("http://mem1/", "memory", Ci.nsICacheStorage.OPEN_NORMALLY, null, + asyncOpenCacheEntry( + "http://mem1/", + "memory", + Ci.nsICacheStorage.OPEN_NORMALLY, + null, new OpenCallback(NEW, "m1m", "m1d", function(entry) { - asyncOpenCacheEntry("http://mem1/", "memory", Ci.nsICacheStorage.OPEN_NORMALLY, null, + asyncOpenCacheEntry( + "http://mem1/", + "memory", + Ci.nsICacheStorage.OPEN_NORMALLY, + null, new OpenCallback(NORMAL, "m1m", "m1d", function(entry) { mc.fired(); }) @@ -33,9 +45,17 @@ function run_test() }) ); - asyncOpenCacheEntry("http://a/", "disk", Ci.nsICacheStorage.OPEN_NORMALLY, null, + asyncOpenCacheEntry( + "http://a/", + "disk", + Ci.nsICacheStorage.OPEN_NORMALLY, + null, new OpenCallback(NEW, "a1m", "a1d", function(entry) { - asyncOpenCacheEntry("http://a/", "disk", Ci.nsICacheStorage.OPEN_NORMALLY, null, + asyncOpenCacheEntry( + "http://a/", + "disk", + Ci.nsICacheStorage.OPEN_NORMALLY, + null, new OpenCallback(NORMAL, "a1m", "a1d", function(entry) { mc.fired(); }) @@ -43,9 +63,17 @@ function run_test() }) ); - asyncOpenCacheEntry("http://b/", "disk", Ci.nsICacheStorage.OPEN_NORMALLY, null, + asyncOpenCacheEntry( + "http://b/", + "disk", + Ci.nsICacheStorage.OPEN_NORMALLY, + null, new OpenCallback(NEW, "a1m", "a1d", function(entry) { - asyncOpenCacheEntry("http://b/", "disk", Ci.nsICacheStorage.OPEN_NORMALLY, null, + asyncOpenCacheEntry( + "http://b/", + "disk", + Ci.nsICacheStorage.OPEN_NORMALLY, + null, new OpenCallback(NORMAL, "a1m", "a1d", function(entry) { mc.fired(); }) @@ -53,9 +81,17 @@ function run_test() }) ); - asyncOpenCacheEntry("http://c/", "disk", Ci.nsICacheStorage.OPEN_NORMALLY, null, + asyncOpenCacheEntry( + "http://c/", + "disk", + Ci.nsICacheStorage.OPEN_NORMALLY, + null, new OpenCallback(NEW, "a1m", "a1d", function(entry) { - asyncOpenCacheEntry("http://c/", "disk", Ci.nsICacheStorage.OPEN_NORMALLY, null, + asyncOpenCacheEntry( + "http://c/", + "disk", + Ci.nsICacheStorage.OPEN_NORMALLY, + null, new OpenCallback(NORMAL, "a1m", "a1d", function(entry) { mc.fired(); }) @@ -63,9 +99,17 @@ function run_test() }) ); - asyncOpenCacheEntry("http://d/", "disk", Ci.nsICacheStorage.OPEN_NORMALLY, null, + asyncOpenCacheEntry( + "http://d/", + "disk", + Ci.nsICacheStorage.OPEN_NORMALLY, + null, new OpenCallback(NEW, "a1m", "a1d", function(entry) { - asyncOpenCacheEntry("http://d/", "disk", Ci.nsICacheStorage.OPEN_NORMALLY, null, + asyncOpenCacheEntry( + "http://d/", + "disk", + Ci.nsICacheStorage.OPEN_NORMALLY, + null, new OpenCallback(NORMAL, "a1m", "a1d", function(entry) { mc.fired(); }) diff --git a/netwerk/test/unit/test_cache2-07a-open-memory.js b/netwerk/test/unit/test_cache2-07a-open-memory.js index 25b7c1306cca..9e98976b0767 100644 --- a/netwerk/test/unit/test_cache2-07a-open-memory.js +++ b/netwerk/test/unit/test_cache2-07a-open-memory.js @@ -1,43 +1,74 @@ -function run_test() -{ +function run_test() { do_get_profile(); // First check how behaves the memory storage. - asyncOpenCacheEntry("http://mem-first/", "memory", Ci.nsICacheStorage.OPEN_NORMALLY, null, + asyncOpenCacheEntry( + "http://mem-first/", + "memory", + Ci.nsICacheStorage.OPEN_NORMALLY, + null, new OpenCallback(NEW, "mem1-meta", "mem1-data", function(entryM1) { Assert.ok(!entryM1.persistent); - asyncOpenCacheEntry("http://mem-first/", "disk", Ci.nsICacheStorage.OPEN_NORMALLY, null, + asyncOpenCacheEntry( + "http://mem-first/", + "disk", + Ci.nsICacheStorage.OPEN_NORMALLY, + null, new OpenCallback(NORMAL, "mem1-meta", "mem1-data", function(entryM2) { Assert.ok(!entryM1.persistent); Assert.ok(!entryM2.persistent); // Now check the disk storage behavior. - asyncOpenCacheEntry("http://disk-first/", "disk", Ci.nsICacheStorage.OPEN_NORMALLY, null, + asyncOpenCacheEntry( + "http://disk-first/", + "disk", + Ci.nsICacheStorage.OPEN_NORMALLY, + null, // Must wait for write, since opening the entry as memory-only before the disk one // is written would cause NS_ERROR_NOT_AVAILABLE from openOutputStream when writing // this disk entry since it's doomed during opening of the memory-only entry for the same URL. - new OpenCallback(NEW|WAITFORWRITE, "disk1-meta", "disk1-data", function(entryD1) { - Assert.ok(entryD1.persistent); - // Now open the same URL as a memory-only entry, the disk entry must be doomed. - asyncOpenCacheEntry("http://disk-first/", "memory", Ci.nsICacheStorage.OPEN_NORMALLY, null, - // This must be recreated - new OpenCallback(NEW, "mem2-meta", "mem2-data", function(entryD2) { - Assert.ok(entryD1.persistent); - Assert.ok(!entryD2.persistent); - // Check we get it back, even when opening via the disk storage - asyncOpenCacheEntry("http://disk-first/", "disk", Ci.nsICacheStorage.OPEN_NORMALLY, null, - new OpenCallback(NORMAL, "mem2-meta", "mem2-data", function(entryD3) { - Assert.ok(entryD1.persistent); - Assert.ok(!entryD2.persistent); - Assert.ok(!entryD3.persistent); - finish_cache2_test(); - }) - ); - }) - ); - }) + new OpenCallback( + NEW | WAITFORWRITE, + "disk1-meta", + "disk1-data", + function(entryD1) { + Assert.ok(entryD1.persistent); + // Now open the same URL as a memory-only entry, the disk entry must be doomed. + asyncOpenCacheEntry( + "http://disk-first/", + "memory", + Ci.nsICacheStorage.OPEN_NORMALLY, + null, + // This must be recreated + new OpenCallback(NEW, "mem2-meta", "mem2-data", function( + entryD2 + ) { + Assert.ok(entryD1.persistent); + Assert.ok(!entryD2.persistent); + // Check we get it back, even when opening via the disk storage + asyncOpenCacheEntry( + "http://disk-first/", + "disk", + Ci.nsICacheStorage.OPEN_NORMALLY, + null, + new OpenCallback( + NORMAL, + "mem2-meta", + "mem2-data", + function(entryD3) { + Assert.ok(entryD1.persistent); + Assert.ok(!entryD2.persistent); + Assert.ok(!entryD3.persistent); + finish_cache2_test(); + } + ) + ); + }) + ); + } + ) ); }) ); diff --git a/netwerk/test/unit/test_cache2-08-evict-disk-by-memory-storage.js b/netwerk/test/unit/test_cache2-08-evict-disk-by-memory-storage.js index 246cb789c1df..9ed500338397 100644 --- a/netwerk/test/unit/test_cache2-08-evict-disk-by-memory-storage.js +++ b/netwerk/test/unit/test_cache2-08-evict-disk-by-memory-storage.js @@ -1,12 +1,17 @@ -function run_test() -{ +function run_test() { do_get_profile(); - asyncOpenCacheEntry("http://a/", "disk", Ci.nsICacheStorage.OPEN_NORMALLY, null, + asyncOpenCacheEntry( + "http://a/", + "disk", + Ci.nsICacheStorage.OPEN_NORMALLY, + null, new OpenCallback(NEW, "a1m", "a1d", function(entry) { var storage = getCacheStorage("memory"); // Have to fail - storage.asyncDoomURI(createURI("http://a/"), "", + storage.asyncDoomURI( + createURI("http://a/"), + "", new EvictionCallback(false, function() { finish_cache2_test(); }) diff --git a/netwerk/test/unit/test_cache2-09-evict-disk-by-uri.js b/netwerk/test/unit/test_cache2-09-evict-disk-by-uri.js index 24c736fe202c..943fd56ebed2 100644 --- a/netwerk/test/unit/test_cache2-09-evict-disk-by-uri.js +++ b/netwerk/test/unit/test_cache2-09-evict-disk-by-uri.js @@ -1,13 +1,22 @@ -function run_test() -{ +function run_test() { do_get_profile(); - asyncOpenCacheEntry("http://a/", "disk", Ci.nsICacheStorage.OPEN_NORMALLY, null, + asyncOpenCacheEntry( + "http://a/", + "disk", + Ci.nsICacheStorage.OPEN_NORMALLY, + null, new OpenCallback(NEW, "a1m", "a1d", function(entry) { - asyncOpenCacheEntry("http://a/", "disk", Ci.nsICacheStorage.OPEN_NORMALLY, null, + asyncOpenCacheEntry( + "http://a/", + "disk", + Ci.nsICacheStorage.OPEN_NORMALLY, + null, new OpenCallback(NORMAL, "a1m", "a1d", function(entry) { var storage = getCacheStorage("disk"); - storage.asyncDoomURI(createURI("http://a/"), "", + storage.asyncDoomURI( + createURI("http://a/"), + "", new EvictionCallback(true, function() { finish_cache2_test(); }) diff --git a/netwerk/test/unit/test_cache2-10-evict-direct.js b/netwerk/test/unit/test_cache2-10-evict-direct.js index edeeee416756..38d5944bafe9 100644 --- a/netwerk/test/unit/test_cache2-10-evict-direct.js +++ b/netwerk/test/unit/test_cache2-10-evict-direct.js @@ -1,10 +1,17 @@ -function run_test() -{ +function run_test() { do_get_profile(); - asyncOpenCacheEntry("http://b/", "disk", Ci.nsICacheStorage.OPEN_NORMALLY, null, + asyncOpenCacheEntry( + "http://b/", + "disk", + Ci.nsICacheStorage.OPEN_NORMALLY, + null, new OpenCallback(NEW, "b1m", "b1d", function(entry) { - asyncOpenCacheEntry("http://b/", "disk", Ci.nsICacheStorage.OPEN_NORMALLY, null, + asyncOpenCacheEntry( + "http://b/", + "disk", + Ci.nsICacheStorage.OPEN_NORMALLY, + null, new OpenCallback(NORMAL, "b1m", "b1d", function(entry) { entry.asyncDoom( new EvictionCallback(true, function() { diff --git a/netwerk/test/unit/test_cache2-10b-evict-direct-immediate.js b/netwerk/test/unit/test_cache2-10b-evict-direct-immediate.js index 6e9ff468a107..b98cd09f59b6 100644 --- a/netwerk/test/unit/test_cache2-10b-evict-direct-immediate.js +++ b/netwerk/test/unit/test_cache2-10b-evict-direct-immediate.js @@ -1,9 +1,12 @@ -function run_test() -{ +function run_test() { do_get_profile(); - asyncOpenCacheEntry("http://b/", "disk", Ci.nsICacheStorage.OPEN_NORMALLY, null, - new OpenCallback(NEW|DOOMED, "b1m", "b1d", function(entry) { + asyncOpenCacheEntry( + "http://b/", + "disk", + Ci.nsICacheStorage.OPEN_NORMALLY, + null, + new OpenCallback(NEW | DOOMED, "b1m", "b1d", function(entry) { entry.asyncDoom( new EvictionCallback(true, function() { finish_cache2_test(); diff --git a/netwerk/test/unit/test_cache2-11-evict-memory.js b/netwerk/test/unit/test_cache2-11-evict-memory.js index f341a0dbc578..56060861099b 100644 --- a/netwerk/test/unit/test_cache2-11-evict-memory.js +++ b/netwerk/test/unit/test_cache2-11-evict-memory.js @@ -1,5 +1,4 @@ -function run_test() -{ +function run_test() { do_get_profile(); var storage = getCacheStorage("memory"); @@ -13,9 +12,14 @@ function run_test() var expectedConsumption = 2048; storage.asyncVisitStorage( - new VisitCallback(2, expectedConsumption, ["http://a/", "http://b/"], function() { - finish_cache2_test(); - }), + new VisitCallback( + 2, + expectedConsumption, + ["http://a/", "http://b/"], + function() { + finish_cache2_test(); + } + ), true ); }), @@ -25,9 +29,17 @@ function run_test() ); }); - asyncOpenCacheEntry("http://mem1/", "memory", Ci.nsICacheStorage.OPEN_NORMALLY, null, + asyncOpenCacheEntry( + "http://mem1/", + "memory", + Ci.nsICacheStorage.OPEN_NORMALLY, + null, new OpenCallback(NEW, "m2m", "m2d", function(entry) { - asyncOpenCacheEntry("http://mem1/", "memory", Ci.nsICacheStorage.OPEN_NORMALLY, null, + asyncOpenCacheEntry( + "http://mem1/", + "memory", + Ci.nsICacheStorage.OPEN_NORMALLY, + null, new OpenCallback(NORMAL, "m2m", "m2d", function(entry) { mc.fired(); }) @@ -35,9 +47,17 @@ function run_test() }) ); - asyncOpenCacheEntry("http://a/", "disk", Ci.nsICacheStorage.OPEN_NORMALLY, null, + asyncOpenCacheEntry( + "http://a/", + "disk", + Ci.nsICacheStorage.OPEN_NORMALLY, + null, new OpenCallback(NEW, "a1m", "a1d", function(entry) { - asyncOpenCacheEntry("http://a/", "disk", Ci.nsICacheStorage.OPEN_NORMALLY, null, + asyncOpenCacheEntry( + "http://a/", + "disk", + Ci.nsICacheStorage.OPEN_NORMALLY, + null, new OpenCallback(NORMAL, "a1m", "a1d", function(entry) { mc.fired(); }) @@ -45,9 +65,17 @@ function run_test() }) ); - asyncOpenCacheEntry("http://b/", "disk", Ci.nsICacheStorage.OPEN_NORMALLY, null, + asyncOpenCacheEntry( + "http://b/", + "disk", + Ci.nsICacheStorage.OPEN_NORMALLY, + null, new OpenCallback(NEW, "a1m", "a1d", function(entry) { - asyncOpenCacheEntry("http://b/", "disk", Ci.nsICacheStorage.OPEN_NORMALLY, null, + asyncOpenCacheEntry( + "http://b/", + "disk", + Ci.nsICacheStorage.OPEN_NORMALLY, + null, new OpenCallback(NORMAL, "a1m", "a1d", function(entry) { mc.fired(); }) diff --git a/netwerk/test/unit/test_cache2-12-evict-disk.js b/netwerk/test/unit/test_cache2-12-evict-disk.js index 8b1333db3e84..444becc027bd 100644 --- a/netwerk/test/unit/test_cache2-12-evict-disk.js +++ b/netwerk/test/unit/test_cache2-12-evict-disk.js @@ -1,5 +1,4 @@ -function run_test() -{ +function run_test() { do_get_profile(); var mc = new MultipleCallbacks(3, function() { @@ -22,9 +21,17 @@ function run_test() ); }); - asyncOpenCacheEntry("http://mem1/", "memory", Ci.nsICacheStorage.OPEN_NORMALLY, null, + asyncOpenCacheEntry( + "http://mem1/", + "memory", + Ci.nsICacheStorage.OPEN_NORMALLY, + null, new OpenCallback(NEW, "m2m", "m2d", function(entry) { - asyncOpenCacheEntry("http://mem1/", "memory", Ci.nsICacheStorage.OPEN_NORMALLY, null, + asyncOpenCacheEntry( + "http://mem1/", + "memory", + Ci.nsICacheStorage.OPEN_NORMALLY, + null, new OpenCallback(NORMAL, "m2m", "m2d", function(entry) { mc.fired(); }) @@ -32,9 +39,17 @@ function run_test() }) ); - asyncOpenCacheEntry("http://a/", "disk", Ci.nsICacheStorage.OPEN_NORMALLY, null, + asyncOpenCacheEntry( + "http://a/", + "disk", + Ci.nsICacheStorage.OPEN_NORMALLY, + null, new OpenCallback(NEW, "a1m", "a1d", function(entry) { - asyncOpenCacheEntry("http://a/", "disk", Ci.nsICacheStorage.OPEN_NORMALLY, null, + asyncOpenCacheEntry( + "http://a/", + "disk", + Ci.nsICacheStorage.OPEN_NORMALLY, + null, new OpenCallback(NORMAL, "a1m", "a1d", function(entry) { mc.fired(); }) @@ -42,9 +57,17 @@ function run_test() }) ); - asyncOpenCacheEntry("http://b/", "disk", Ci.nsICacheStorage.OPEN_NORMALLY, null, + asyncOpenCacheEntry( + "http://b/", + "disk", + Ci.nsICacheStorage.OPEN_NORMALLY, + null, new OpenCallback(NEW, "b1m", "b1d", function(entry) { - asyncOpenCacheEntry("http://b/", "disk", Ci.nsICacheStorage.OPEN_NORMALLY, null, + asyncOpenCacheEntry( + "http://b/", + "disk", + Ci.nsICacheStorage.OPEN_NORMALLY, + null, new OpenCallback(NORMAL, "b1m", "b1d", function(entry) { mc.fired(); }) diff --git a/netwerk/test/unit/test_cache2-13-evict-non-existing.js b/netwerk/test/unit/test_cache2-13-evict-non-existing.js index 1aa1072953a4..e8c915e795c8 100644 --- a/netwerk/test/unit/test_cache2-13-evict-non-existing.js +++ b/netwerk/test/unit/test_cache2-13-evict-non-existing.js @@ -1,9 +1,10 @@ -function run_test() -{ +function run_test() { do_get_profile(); var storage = getCacheStorage("disk"); - storage.asyncDoomURI(createURI("http://non-existing/"), "", + storage.asyncDoomURI( + createURI("http://non-existing/"), + "", new EvictionCallback(false, function() { finish_cache2_test(); }) diff --git a/netwerk/test/unit/test_cache2-14-concurent-readers.js b/netwerk/test/unit/test_cache2-14-concurent-readers.js index 7355a2a9e8bb..fc5dd278ad22 100644 --- a/netwerk/test/unit/test_cache2-14-concurent-readers.js +++ b/netwerk/test/unit/test_cache2-14-concurent-readers.js @@ -1,8 +1,11 @@ -function run_test() -{ +function run_test() { do_get_profile(); - asyncOpenCacheEntry("http://x/", "disk", Ci.nsICacheStorage.OPEN_NORMALLY, null, + asyncOpenCacheEntry( + "http://x/", + "disk", + Ci.nsICacheStorage.OPEN_NORMALLY, + null, new OpenCallback(NEW, "x1m", "x1d", function(entry) { // nothing to do here, we expect concurent callbacks to get // all notified, then the test finishes @@ -11,17 +14,29 @@ function run_test() var mc = new MultipleCallbacks(3, finish_cache2_test); - asyncOpenCacheEntry("http://x/", "disk", Ci.nsICacheStorage.OPEN_NORMALLY, null, + asyncOpenCacheEntry( + "http://x/", + "disk", + Ci.nsICacheStorage.OPEN_NORMALLY, + null, new OpenCallback(NORMAL, "x1m", "x1d", function(entry) { mc.fired(); }) ); - asyncOpenCacheEntry("http://x/", "disk", Ci.nsICacheStorage.OPEN_NORMALLY, null, + asyncOpenCacheEntry( + "http://x/", + "disk", + Ci.nsICacheStorage.OPEN_NORMALLY, + null, new OpenCallback(NORMAL, "x1m", "x1d", function(entry) { mc.fired(); }) ); - asyncOpenCacheEntry("http://x/", "disk", Ci.nsICacheStorage.OPEN_NORMALLY, null, + asyncOpenCacheEntry( + "http://x/", + "disk", + Ci.nsICacheStorage.OPEN_NORMALLY, + null, new OpenCallback(NORMAL, "x1m", "x1d", function(entry) { mc.fired(); }) diff --git a/netwerk/test/unit/test_cache2-14b-concurent-readers-complete.js b/netwerk/test/unit/test_cache2-14b-concurent-readers-complete.js index f5c0b36427c7..fda7d46ffd4a 100644 --- a/netwerk/test/unit/test_cache2-14b-concurent-readers-complete.js +++ b/netwerk/test/unit/test_cache2-14b-concurent-readers-complete.js @@ -1,8 +1,11 @@ -function run_test() -{ +function run_test() { do_get_profile(); - asyncOpenCacheEntry("http://x/", "disk", Ci.nsICacheStorage.OPEN_NORMALLY, null, + asyncOpenCacheEntry( + "http://x/", + "disk", + Ci.nsICacheStorage.OPEN_NORMALLY, + null, new OpenCallback(NEW, "x1m", "x1d", function(entry) { // nothing to do here, we expect concurent callbacks to get // all notified, then the test finishes @@ -13,18 +16,34 @@ function run_test() var order = 0; - asyncOpenCacheEntry("http://x/", "disk", Ci.nsICacheStorage.OPEN_NORMALLY, null, - new OpenCallback(NORMAL|COMPLETE|NOTIFYBEFOREREAD, "x1m", "x1d", function(entry, beforeReading) { - if (beforeReading) { - ++order; - Assert.equal(order, 3); - } else { - mc.fired(); + asyncOpenCacheEntry( + "http://x/", + "disk", + Ci.nsICacheStorage.OPEN_NORMALLY, + null, + new OpenCallback( + NORMAL | COMPLETE | NOTIFYBEFOREREAD, + "x1m", + "x1d", + function(entry, beforeReading) { + if (beforeReading) { + ++order; + Assert.equal(order, 3); + } else { + mc.fired(); + } } - }) + ) ); - asyncOpenCacheEntry("http://x/", "disk", Ci.nsICacheStorage.OPEN_NORMALLY, null, - new OpenCallback(NORMAL|NOTIFYBEFOREREAD, "x1m", "x1d", function(entry, beforeReading) { + asyncOpenCacheEntry( + "http://x/", + "disk", + Ci.nsICacheStorage.OPEN_NORMALLY, + null, + new OpenCallback(NORMAL | NOTIFYBEFOREREAD, "x1m", "x1d", function( + entry, + beforeReading + ) { if (beforeReading) { ++order; Assert.equal(order, 1); @@ -33,8 +52,15 @@ function run_test() } }) ); - asyncOpenCacheEntry("http://x/", "disk", Ci.nsICacheStorage.OPEN_NORMALLY, null, - new OpenCallback(NORMAL|NOTIFYBEFOREREAD, "x1m", "x1d", function(entry, beforeReading) { + asyncOpenCacheEntry( + "http://x/", + "disk", + Ci.nsICacheStorage.OPEN_NORMALLY, + null, + new OpenCallback(NORMAL | NOTIFYBEFOREREAD, "x1m", "x1d", function( + entry, + beforeReading + ) { if (beforeReading) { ++order; Assert.equal(order, 2); diff --git a/netwerk/test/unit/test_cache2-15-conditional-304.js b/netwerk/test/unit/test_cache2-15-conditional-304.js index 92381a73a1cd..7867676f0833 100644 --- a/netwerk/test/unit/test_cache2-15-conditional-304.js +++ b/netwerk/test/unit/test_cache2-15-conditional-304.js @@ -1,12 +1,19 @@ -function run_test() -{ +function run_test() { do_get_profile(); // Open for write, write - asyncOpenCacheEntry("http://304/", "disk", Ci.nsICacheStorage.OPEN_NORMALLY, null, + asyncOpenCacheEntry( + "http://304/", + "disk", + Ci.nsICacheStorage.OPEN_NORMALLY, + null, new OpenCallback(NEW, "31m", "31d", function(entry) { // Open normally but wait for validation from the server - asyncOpenCacheEntry("http://304/", "disk", Ci.nsICacheStorage.OPEN_NORMALLY, null, + asyncOpenCacheEntry( + "http://304/", + "disk", + Ci.nsICacheStorage.OPEN_NORMALLY, + null, new OpenCallback(REVAL, "31m", "31d", function(entry) { // emulate 304 from the server executeSoon(function() { @@ -17,17 +24,29 @@ function run_test() var mc = new MultipleCallbacks(3, finish_cache2_test); - asyncOpenCacheEntry("http://304/", "disk", Ci.nsICacheStorage.OPEN_NORMALLY, null, + asyncOpenCacheEntry( + "http://304/", + "disk", + Ci.nsICacheStorage.OPEN_NORMALLY, + null, new OpenCallback(NORMAL, "31m", "31d", function(entry) { mc.fired(); }) ); - asyncOpenCacheEntry("http://304/", "disk", Ci.nsICacheStorage.OPEN_NORMALLY, null, + asyncOpenCacheEntry( + "http://304/", + "disk", + Ci.nsICacheStorage.OPEN_NORMALLY, + null, new OpenCallback(NORMAL, "31m", "31d", function(entry) { mc.fired(); }) ); - asyncOpenCacheEntry("http://304/", "disk", Ci.nsICacheStorage.OPEN_NORMALLY, null, + asyncOpenCacheEntry( + "http://304/", + "disk", + Ci.nsICacheStorage.OPEN_NORMALLY, + null, new OpenCallback(NORMAL, "31m", "31d", function(entry) { mc.fired(); }) diff --git a/netwerk/test/unit/test_cache2-16-conditional-200.js b/netwerk/test/unit/test_cache2-16-conditional-200.js index ba1b84cf9f2e..d00a2faa400f 100644 --- a/netwerk/test/unit/test_cache2-16-conditional-200.js +++ b/netwerk/test/unit/test_cache2-16-conditional-200.js @@ -1,39 +1,66 @@ -function run_test() -{ +function run_test() { do_get_profile(); // Open for write, write - asyncOpenCacheEntry("http://200/", "disk", Ci.nsICacheStorage.OPEN_NORMALLY, null, + asyncOpenCacheEntry( + "http://200/", + "disk", + Ci.nsICacheStorage.OPEN_NORMALLY, + null, new OpenCallback(NEW, "21m", "21d", function(entry) { - asyncOpenCacheEntry("http://200/", "disk", Ci.nsICacheStorage.OPEN_NORMALLY, null, + asyncOpenCacheEntry( + "http://200/", + "disk", + Ci.nsICacheStorage.OPEN_NORMALLY, + null, new OpenCallback(NORMAL, "21m", "21d", function(entry) { // Open normally but wait for validation from the server - asyncOpenCacheEntry("http://200/", "disk", Ci.nsICacheStorage.OPEN_NORMALLY, null, + asyncOpenCacheEntry( + "http://200/", + "disk", + Ci.nsICacheStorage.OPEN_NORMALLY, + null, new OpenCallback(REVAL, "21m", "21d", function(entry) { // emulate 200 from server (new content) executeSoon(function() { var entry2 = entry.recreate(); // now fill the new entry, use OpenCallback directly for it - (new OpenCallback(NEW, "22m", "22d", function() {})) - .onCacheEntryAvailable(entry2, true, null, Cr.NS_OK); + new OpenCallback( + NEW, + "22m", + "22d", + function() {} + ).onCacheEntryAvailable(entry2, true, null, Cr.NS_OK); }); }) ); var mc = new MultipleCallbacks(3, finish_cache2_test); - asyncOpenCacheEntry("http://200/", "disk", Ci.nsICacheStorage.OPEN_NORMALLY, null, + asyncOpenCacheEntry( + "http://200/", + "disk", + Ci.nsICacheStorage.OPEN_NORMALLY, + null, new OpenCallback(NORMAL, "22m", "22d", function(entry) { mc.fired(); }) ); - asyncOpenCacheEntry("http://200/", "disk", Ci.nsICacheStorage.OPEN_NORMALLY, null, + asyncOpenCacheEntry( + "http://200/", + "disk", + Ci.nsICacheStorage.OPEN_NORMALLY, + null, new OpenCallback(NORMAL, "22m", "22d", function(entry) { mc.fired(); }) ); - asyncOpenCacheEntry("http://200/", "disk", Ci.nsICacheStorage.OPEN_NORMALLY, null, + asyncOpenCacheEntry( + "http://200/", + "disk", + Ci.nsICacheStorage.OPEN_NORMALLY, + null, new OpenCallback(NORMAL, "22m", "22d", function(entry) { mc.fired(); }) diff --git a/netwerk/test/unit/test_cache2-17-evict-all.js b/netwerk/test/unit/test_cache2-17-evict-all.js index 3033e42d6b14..0c87fa383f79 100644 --- a/netwerk/test/unit/test_cache2-17-evict-all.js +++ b/netwerk/test/unit/test_cache2-17-evict-all.js @@ -1,5 +1,4 @@ -function run_test() -{ +function run_test() { do_get_profile(); var svc = get_cache_service(); diff --git a/netwerk/test/unit/test_cache2-18-not-valid.js b/netwerk/test/unit/test_cache2-18-not-valid.js index 86d42b6f0dbc..df72439143a3 100644 --- a/netwerk/test/unit/test_cache2-18-not-valid.js +++ b/netwerk/test/unit/test_cache2-18-not-valid.js @@ -1,17 +1,28 @@ -function run_test() -{ +function run_test() { do_get_profile(); // Open for write, write but expect it to fail, since other callback will recreate (and doom) // the first entry before it opens output stream (note: in case of problems the DOOMED flag // can be removed, it is not the test failure when opening the output stream on recreated entry. - asyncOpenCacheEntry("http://nv/", "disk", Ci.nsICacheStorage.OPEN_NORMALLY, null, - new OpenCallback(NEW|DOOMED, "v1m", "v1d", function(entry) { + asyncOpenCacheEntry( + "http://nv/", + "disk", + Ci.nsICacheStorage.OPEN_NORMALLY, + null, + new OpenCallback(NEW | DOOMED, "v1m", "v1d", function(entry) { // Open for rewrite (don't validate), write different meta and data - asyncOpenCacheEntry("http://nv/", "disk", Ci.nsICacheStorage.OPEN_NORMALLY, null, - new OpenCallback(NOTVALID|RECREATE, "v2m", "v2d", function(entry) { + asyncOpenCacheEntry( + "http://nv/", + "disk", + Ci.nsICacheStorage.OPEN_NORMALLY, + null, + new OpenCallback(NOTVALID | RECREATE, "v2m", "v2d", function(entry) { // And check... - asyncOpenCacheEntry("http://nv/", "disk", Ci.nsICacheStorage.OPEN_NORMALLY, null, + asyncOpenCacheEntry( + "http://nv/", + "disk", + Ci.nsICacheStorage.OPEN_NORMALLY, + null, new OpenCallback(NORMAL, "v2m", "v2d", function(entry) { finish_cache2_test(); }) diff --git a/netwerk/test/unit/test_cache2-19-range-206.js b/netwerk/test/unit/test_cache2-19-range-206.js index 0139133eff48..866100492909 100644 --- a/netwerk/test/unit/test_cache2-19-range-206.js +++ b/netwerk/test/unit/test_cache2-19-range-206.js @@ -1,33 +1,57 @@ -function run_test() -{ +function run_test() { do_get_profile(); // Open for write, write - asyncOpenCacheEntry("http://r206/", "disk", Ci.nsICacheStorage.OPEN_NORMALLY, null, + asyncOpenCacheEntry( + "http://r206/", + "disk", + Ci.nsICacheStorage.OPEN_NORMALLY, + null, new OpenCallback(NEW, "206m", "206part1-", function(entry) { // Open normally but wait for validation from the server - asyncOpenCacheEntry("http://r206/", "disk", Ci.nsICacheStorage.OPEN_NORMALLY, null, + asyncOpenCacheEntry( + "http://r206/", + "disk", + Ci.nsICacheStorage.OPEN_NORMALLY, + null, new OpenCallback(PARTIAL, "206m", "206part1-", function(entry) { // emulate 206 from the server, i.e. resume transaction and write content to the output stream - (new OpenCallback(NEW|WAITFORWRITE|PARTIAL, "206m", "-part2", function(entry) { - entry.setValid(); - })).onCacheEntryAvailable(entry, true, null, Cr.NS_OK); + new OpenCallback( + NEW | WAITFORWRITE | PARTIAL, + "206m", + "-part2", + function(entry) { + entry.setValid(); + } + ).onCacheEntryAvailable(entry, true, null, Cr.NS_OK); }) ); var mc = new MultipleCallbacks(3, finish_cache2_test); - asyncOpenCacheEntry("http://r206/", "disk", Ci.nsICacheStorage.OPEN_NORMALLY, null, + asyncOpenCacheEntry( + "http://r206/", + "disk", + Ci.nsICacheStorage.OPEN_NORMALLY, + null, new OpenCallback(NORMAL, "206m", "206part1--part2", function(entry) { mc.fired(); }) ); - asyncOpenCacheEntry("http://r206/", "disk", Ci.nsICacheStorage.OPEN_NORMALLY, null, + asyncOpenCacheEntry( + "http://r206/", + "disk", + Ci.nsICacheStorage.OPEN_NORMALLY, + null, new OpenCallback(NORMAL, "206m", "206part1--part2", function(entry) { mc.fired(); }) ); - asyncOpenCacheEntry("http://r206/", "disk", Ci.nsICacheStorage.OPEN_NORMALLY, null, + asyncOpenCacheEntry( + "http://r206/", + "disk", + Ci.nsICacheStorage.OPEN_NORMALLY, + null, new OpenCallback(NORMAL, "206m", "206part1--part2", function(entry) { mc.fired(); }) diff --git a/netwerk/test/unit/test_cache2-20-range-200.js b/netwerk/test/unit/test_cache2-20-range-200.js index 15c1488d0f21..e4a37b529d8f 100644 --- a/netwerk/test/unit/test_cache2-20-range-200.js +++ b/netwerk/test/unit/test_cache2-20-range-200.js @@ -1,34 +1,58 @@ -function run_test() -{ +function run_test() { do_get_profile(); // Open for write, write - asyncOpenCacheEntry("http://r200/", "disk", Ci.nsICacheStorage.OPEN_NORMALLY, null, + asyncOpenCacheEntry( + "http://r200/", + "disk", + Ci.nsICacheStorage.OPEN_NORMALLY, + null, new OpenCallback(NEW, "200m1", "200part1a-", function(entry) { // Open normally but wait for validation from the server - asyncOpenCacheEntry("http://r200/", "disk", Ci.nsICacheStorage.OPEN_NORMALLY, null, + asyncOpenCacheEntry( + "http://r200/", + "disk", + Ci.nsICacheStorage.OPEN_NORMALLY, + null, new OpenCallback(PARTIAL, "200m1", "200part1a-", function(entry) { // emulate 200 from the server, i.e. recreate the entry, resume transaction and // write new content to the output stream - (new OpenCallback(NEW|WAITFORWRITE|RECREATE, "200m2", "200part1b--part2b", function(entry) { - entry.setValid(); - })).onCacheEntryAvailable(entry, true, null, Cr.NS_OK); + new OpenCallback( + NEW | WAITFORWRITE | RECREATE, + "200m2", + "200part1b--part2b", + function(entry) { + entry.setValid(); + } + ).onCacheEntryAvailable(entry, true, null, Cr.NS_OK); }) ); var mc = new MultipleCallbacks(3, finish_cache2_test); - asyncOpenCacheEntry("http://r200/", "disk", Ci.nsICacheStorage.OPEN_NORMALLY, null, + asyncOpenCacheEntry( + "http://r200/", + "disk", + Ci.nsICacheStorage.OPEN_NORMALLY, + null, new OpenCallback(NORMAL, "200m2", "200part1b--part2b", function(entry) { mc.fired(); }) ); - asyncOpenCacheEntry("http://r200/", "disk", Ci.nsICacheStorage.OPEN_NORMALLY, null, + asyncOpenCacheEntry( + "http://r200/", + "disk", + Ci.nsICacheStorage.OPEN_NORMALLY, + null, new OpenCallback(NORMAL, "200m2", "200part1b--part2b", function(entry) { mc.fired(); }) ); - asyncOpenCacheEntry("http://r200/", "disk", Ci.nsICacheStorage.OPEN_NORMALLY, null, + asyncOpenCacheEntry( + "http://r200/", + "disk", + Ci.nsICacheStorage.OPEN_NORMALLY, + null, new OpenCallback(NORMAL, "200m2", "200part1b--part2b", function(entry) { mc.fired(); }) diff --git a/netwerk/test/unit/test_cache2-21-anon-storage.js b/netwerk/test/unit/test_cache2-21-anon-storage.js index 176100fbe50f..771a9a402452 100644 --- a/netwerk/test/unit/test_cache2-21-anon-storage.js +++ b/netwerk/test/unit/test_cache2-21-anon-storage.js @@ -1,19 +1,38 @@ -function run_test() -{ +function run_test() { do_get_profile(); // Create and check an entry anon disk storage - asyncOpenCacheEntry("http://anon1/", "disk", Ci.nsICacheStorage.OPEN_NORMALLY, Services.loadContextInfo.anonymous, + asyncOpenCacheEntry( + "http://anon1/", + "disk", + Ci.nsICacheStorage.OPEN_NORMALLY, + Services.loadContextInfo.anonymous, new OpenCallback(NEW, "an1", "an1", function(entry) { - asyncOpenCacheEntry("http://anon1/", "disk", Ci.nsICacheStorage.OPEN_NORMALLY, Services.loadContextInfo.anonymous, + asyncOpenCacheEntry( + "http://anon1/", + "disk", + Ci.nsICacheStorage.OPEN_NORMALLY, + Services.loadContextInfo.anonymous, new OpenCallback(NORMAL, "an1", "an1", function(entry) { // Create and check an entry non-anon disk storage - asyncOpenCacheEntry("http://anon1/", "disk", Ci.nsICacheStorage.OPEN_NORMALLY, Services.loadContextInfo.default, + asyncOpenCacheEntry( + "http://anon1/", + "disk", + Ci.nsICacheStorage.OPEN_NORMALLY, + Services.loadContextInfo.default, new OpenCallback(NEW, "na1", "na1", function(entry) { - asyncOpenCacheEntry("http://anon1/", "disk", Ci.nsICacheStorage.OPEN_NORMALLY, Services.loadContextInfo.default, + asyncOpenCacheEntry( + "http://anon1/", + "disk", + Ci.nsICacheStorage.OPEN_NORMALLY, + Services.loadContextInfo.default, new OpenCallback(NORMAL, "na1", "na1", function(entry) { // check the anon entry is still there and intact - asyncOpenCacheEntry("http://anon1/", "disk", Ci.nsICacheStorage.OPEN_NORMALLY, Services.loadContextInfo.anonymous, + asyncOpenCacheEntry( + "http://anon1/", + "disk", + Ci.nsICacheStorage.OPEN_NORMALLY, + Services.loadContextInfo.anonymous, new OpenCallback(NORMAL, "an1", "an1", function(entry) { finish_cache2_test(); }) diff --git a/netwerk/test/unit/test_cache2-22-anon-visit.js b/netwerk/test/unit/test_cache2-22-anon-visit.js index 6be978c2d700..0890e7b70145 100644 --- a/netwerk/test/unit/test_cache2-22-anon-visit.js +++ b/netwerk/test/unit/test_cache2-22-anon-visit.js @@ -1,5 +1,4 @@ -function run_test() -{ +function run_test() { do_get_profile(); var mc = new MultipleCallbacks(2, function() { @@ -18,15 +17,22 @@ function run_test() ); }); - - asyncOpenCacheEntry("http://an2/", "disk", Ci.nsICacheStorage.OPEN_NORMALLY, Services.loadContextInfo.default, - new OpenCallback(NEW|WAITFORWRITE, "an2", "an2", function(entry) { + asyncOpenCacheEntry( + "http://an2/", + "disk", + Ci.nsICacheStorage.OPEN_NORMALLY, + Services.loadContextInfo.default, + new OpenCallback(NEW | WAITFORWRITE, "an2", "an2", function(entry) { mc.fired(); }) ); - asyncOpenCacheEntry("http://an2/", "disk", Ci.nsICacheStorage.OPEN_NORMALLY, Services.loadContextInfo.anonymous, - new OpenCallback(NEW|WAITFORWRITE, "an2", "an2", function(entry) { + asyncOpenCacheEntry( + "http://an2/", + "disk", + Ci.nsICacheStorage.OPEN_NORMALLY, + Services.loadContextInfo.anonymous, + new OpenCallback(NEW | WAITFORWRITE, "an2", "an2", function(entry) { mc.fired(); }) ); diff --git a/netwerk/test/unit/test_cache2-23-read-over-chunk.js b/netwerk/test/unit/test_cache2-23-read-over-chunk.js index 28126dfe83fc..324e9e493ecc 100644 --- a/netwerk/test/unit/test_cache2-23-read-over-chunk.js +++ b/netwerk/test/unit/test_cache2-23-read-over-chunk.js @@ -1,19 +1,23 @@ -function run_test() -{ +function run_test() { do_get_profile(); - const kChunkSize = (256 * 1024); + const kChunkSize = 256 * 1024; var payload = ""; - for (var i = 0; i < (kChunkSize + 10); ++i) { - if (i < (kChunkSize - 5)) + for (var i = 0; i < kChunkSize + 10; ++i) { + if (i < kChunkSize - 5) { payload += "0"; - else + } else { payload += String.fromCharCode(i + 65); + } } - asyncOpenCacheEntry("http://read/", "disk", Ci.nsICacheStorage.OPEN_TRUNCATE, Services.loadContextInfo.default, - new OpenCallback(NEW|WAITFORWRITE, "", payload, function(entry) { + asyncOpenCacheEntry( + "http://read/", + "disk", + Ci.nsICacheStorage.OPEN_TRUNCATE, + Services.loadContextInfo.default, + new OpenCallback(NEW | WAITFORWRITE, "", payload, function(entry) { var is = entry.openInputStream(0); pumpReadStream(is, function(read) { Assert.equal(read.length, kChunkSize + 10); diff --git a/netwerk/test/unit/test_cache2-24-exists.js b/netwerk/test/unit/test_cache2-24-exists.js index a8e244a9e155..adc82e8e8c23 100644 --- a/netwerk/test/unit/test_cache2-24-exists.js +++ b/netwerk/test/unit/test_cache2-24-exists.js @@ -1,5 +1,4 @@ -function run_test() -{ +function run_test() { do_get_profile(); var mc = new MultipleCallbacks(2, function() { @@ -10,18 +9,29 @@ function run_test() Assert.ok(mem.exists(createURI("http://m1/"), "")); Assert.ok(!mem.exists(createURI("http://m2/"), "")); Assert.ok(disk.exists(createURI("http://d1/"), "")); - do_check_throws_nsIException(() => disk.exists(createURI("http://d2/"), ""), 'NS_ERROR_NOT_AVAILABLE'); + do_check_throws_nsIException( + () => disk.exists(createURI("http://d2/"), ""), + "NS_ERROR_NOT_AVAILABLE" + ); finish_cache2_test(); }); - asyncOpenCacheEntry("http://d1/", "disk", Ci.nsICacheStorage.OPEN_NORMALLY, Services.loadContextInfo.default, + asyncOpenCacheEntry( + "http://d1/", + "disk", + Ci.nsICacheStorage.OPEN_NORMALLY, + Services.loadContextInfo.default, new OpenCallback(NEW | WAITFORWRITE, "meta", "data", function(entry) { mc.fired(); }) ); - asyncOpenCacheEntry("http://m1/", "memory", Ci.nsICacheStorage.OPEN_NORMALLY, Services.loadContextInfo.default, + asyncOpenCacheEntry( + "http://m1/", + "memory", + Ci.nsICacheStorage.OPEN_NORMALLY, + Services.loadContextInfo.default, new OpenCallback(NEW | WAITFORWRITE, "meta", "data", function(entry) { mc.fired(); }) diff --git a/netwerk/test/unit/test_cache2-25-chunk-memory-limit.js b/netwerk/test/unit/test_cache2-25-chunk-memory-limit.js index 1b92d5f62f10..e5c2ac45c7e6 100644 --- a/netwerk/test/unit/test_cache2-25-chunk-memory-limit.js +++ b/netwerk/test/unit/test_cache2-25-chunk-memory-limit.js @@ -1,9 +1,9 @@ -function gen_200k() -{ +function gen_200k() { var i; - var data="0123456789ABCDEFGHIJLKMNO"; - for (i=0; i<13; i++) - data+=data; + var data = "0123456789ABCDEFGHIJLKMNO"; + for (i = 0; i < 13; i++) { + data += data; + } return data; } @@ -12,28 +12,39 @@ function gen_200k() // second entry. var oStr; -function run_test() -{ +function run_test() { do_get_profile(); - var prefBranch = Cc["@mozilla.org/preferences-service;1"]. - getService(Ci.nsIPrefBranch); + var prefBranch = Cc["@mozilla.org/preferences-service;1"].getService( + Ci.nsIPrefBranch + ); // set max chunks memory so that only one full chunk fits within the limit prefBranch.setIntPref("browser.cache.disk.max_chunks_memory_usage", 300); - asyncOpenCacheEntry("http://a/", "disk", Ci.nsICacheStorage.OPEN_NORMALLY, null, + asyncOpenCacheEntry( + "http://a/", + "disk", + Ci.nsICacheStorage.OPEN_NORMALLY, + null, function(status, entry) { Assert.equal(status, Cr.NS_OK); var data = gen_200k(); oStr = entry.openOutputStream(0, data.length); Assert.equal(data.length, oStr.write(data, data.length)); - asyncOpenCacheEntry("http://b/", "disk", Ci.nsICacheStorage.OPEN_NORMALLY, null, + asyncOpenCacheEntry( + "http://b/", + "disk", + Ci.nsICacheStorage.OPEN_NORMALLY, + null, function(status, entry) { Assert.equal(status, Cr.NS_OK); var oStr2 = entry.openOutputStream(0, data.length); - do_check_throws_nsIException(() => oStr2.write(data, data.length), 'NS_ERROR_OUT_OF_MEMORY'); + do_check_throws_nsIException( + () => oStr2.write(data, data.length), + "NS_ERROR_OUT_OF_MEMORY" + ); finish_cache2_test(); } ); diff --git a/netwerk/test/unit/test_cache2-26-no-outputstream-open.js b/netwerk/test/unit/test_cache2-26-no-outputstream-open.js index 192cc62e9cbc..24588a399c7a 100644 --- a/netwerk/test/unit/test_cache2-26-no-outputstream-open.js +++ b/netwerk/test/unit/test_cache2-26-no-outputstream-open.js @@ -1,21 +1,33 @@ -function run_test() -{ +function run_test() { do_get_profile(); // Open for write, but never write and never mark valid - asyncOpenCacheEntry("http://no-data/", "disk", Ci.nsICacheStorage.OPEN_NORMALLY, null, - new OpenCallback(NEW|METAONLY|DONTSETVALID|WAITFORWRITE, "meta", "", function(entry) { - // Open again, we must get the callback and zero-length data - executeSoon(() => { - Cu.forceGC(); // invokes OnHandleClosed on the entry + asyncOpenCacheEntry( + "http://no-data/", + "disk", + Ci.nsICacheStorage.OPEN_NORMALLY, + null, + new OpenCallback( + NEW | METAONLY | DONTSETVALID | WAITFORWRITE, + "meta", + "", + function(entry) { + // Open again, we must get the callback and zero-length data + executeSoon(() => { + Cu.forceGC(); // invokes OnHandleClosed on the entry - asyncOpenCacheEntry("http://no-data/", "disk", Ci.nsICacheStorage.OPEN_NORMALLY, null, - new OpenCallback(NORMAL, "meta", "", function(entry) { - finish_cache2_test(); - }) - ); - }); - }) + asyncOpenCacheEntry( + "http://no-data/", + "disk", + Ci.nsICacheStorage.OPEN_NORMALLY, + null, + new OpenCallback(NORMAL, "meta", "", function(entry) { + finish_cache2_test(); + }) + ); + }); + } + ) ); do_test_pending(); diff --git a/netwerk/test/unit/test_cache2-27-force-valid-for.js b/netwerk/test/unit/test_cache2-27-force-valid-for.js index 6cc6b88fdaaa..e73f8bdaca2d 100644 --- a/netwerk/test/unit/test_cache2-27-force-valid-for.js +++ b/netwerk/test/unit/test_cache2-27-force-valid-for.js @@ -1,12 +1,15 @@ -function run_test() -{ +function run_test() { do_get_profile(); var mc = new MultipleCallbacks(2, function() { finish_cache2_test(); }); - asyncOpenCacheEntry("http://m1/", "memory", Ci.nsICacheStorage.OPEN_NORMALLY, Services.loadContextInfo.default, + asyncOpenCacheEntry( + "http://m1/", + "memory", + Ci.nsICacheStorage.OPEN_NORMALLY, + Services.loadContextInfo.default, new OpenCallback(NEW, "meta", "data", function(entry) { // Check the default equal(entry.isForcedValid, false); diff --git a/netwerk/test/unit/test_cache2-28-last-access-attrs.js b/netwerk/test/unit/test_cache2-28-last-access-attrs.js index 6b1054011eb7..c68efd3e8ae5 100644 --- a/netwerk/test/unit/test_cache2-28-last-access-attrs.js +++ b/netwerk/test/unit/test_cache2-28-last-access-attrs.js @@ -1,8 +1,7 @@ -function run_test() -{ +function run_test() { do_get_profile(); function NowSeconds() { - return parseInt((new Date()).getTime() / 1000); + return parseInt(new Date().getTime() / 1000); } function do_check_time(t, min, max) { Assert.ok(t >= min); @@ -11,18 +10,24 @@ function run_test() var timeStart = NowSeconds(); - asyncOpenCacheEntry("http://t/", "disk", Ci.nsICacheStorage.OPEN_NORMALLY, null, + asyncOpenCacheEntry( + "http://t/", + "disk", + Ci.nsICacheStorage.OPEN_NORMALLY, + null, new OpenCallback(NEW, "m", "d", function(entry) { - var firstOpen = NowSeconds(); Assert.equal(entry.fetchCount, 1); do_check_time(entry.lastFetched, timeStart, firstOpen); do_check_time(entry.lastModified, timeStart, firstOpen); do_timeout(2000, () => { - asyncOpenCacheEntry("http://t/", "disk", Ci.nsICacheStorage.OPEN_NORMALLY, null, + asyncOpenCacheEntry( + "http://t/", + "disk", + Ci.nsICacheStorage.OPEN_NORMALLY, + null, new OpenCallback(NORMAL, "m", "d", function(entry) { - var secondOpen = NowSeconds(); Assert.equal(entry.fetchCount, 2); do_check_time(entry.lastFetched, firstOpen, secondOpen); @@ -31,7 +36,7 @@ function run_test() finish_cache2_test(); }) ); - }) + }); }) ); diff --git a/netwerk/test/unit/test_cache2-28a-OPEN_SECRETLY.js b/netwerk/test/unit/test_cache2-28a-OPEN_SECRETLY.js index 7b14254039b3..3263560881ae 100644 --- a/netwerk/test/unit/test_cache2-28a-OPEN_SECRETLY.js +++ b/netwerk/test/unit/test_cache2-28a-OPEN_SECRETLY.js @@ -1,23 +1,29 @@ -function run_test() -{ +function run_test() { do_get_profile(); function NowSeconds() { - return parseInt((new Date()).getTime() / 1000); + return parseInt(new Date().getTime() / 1000); } function do_check_time(a, b) { Assert.ok(Math.abs(a - b) < 0.5); } - asyncOpenCacheEntry("http://t/", "disk", Ci.nsICacheStorage.OPEN_NORMALLY, null, + asyncOpenCacheEntry( + "http://t/", + "disk", + Ci.nsICacheStorage.OPEN_NORMALLY, + null, new OpenCallback(NEW, "m", "d", function(entry) { - var now1 = NowSeconds(); Assert.equal(entry.fetchCount, 1); do_check_time(entry.lastFetched, now1); do_check_time(entry.lastModified, now1); do_timeout(2000, () => { - asyncOpenCacheEntry("http://t/", "disk", Ci.nsICacheStorage.OPEN_SECRETLY, null, + asyncOpenCacheEntry( + "http://t/", + "disk", + Ci.nsICacheStorage.OPEN_SECRETLY, + null, new OpenCallback(NORMAL, "m", "d", function(entry) { Assert.equal(entry.fetchCount, 1); do_check_time(entry.lastFetched, now1); @@ -26,7 +32,7 @@ function run_test() finish_cache2_test(); }) ); - }) + }); }) ); diff --git a/netwerk/test/unit/test_cache2-29a-concurrent_read_resumable_entry_size_zero.js b/netwerk/test/unit/test_cache2-29a-concurrent_read_resumable_entry_size_zero.js index 54a0a924d413..3771d9e6a1c3 100644 --- a/netwerk/test/unit/test_cache2-29a-concurrent_read_resumable_entry_size_zero.js +++ b/netwerk/test/unit/test_cache2-29a-concurrent_read_resumable_entry_size_zero.js @@ -11,10 +11,11 @@ This test is using a resumable response. */ -const {HttpServer} = ChromeUtils.import("resource://testing-common/httpd.js"); +const { HttpServer } = ChromeUtils.import("resource://testing-common/httpd.js"); -var httpProtocolHandler = Cc["@mozilla.org/network/protocol;1?name=http"] - .getService(Ci.nsIHttpProtocolHandler); +var httpProtocolHandler = Cc[ + "@mozilla.org/network/protocol;1?name=http" +].getService(Ci.nsIHttpProtocolHandler); XPCOMUtils.defineLazyGetter(this, "URL", function() { return "http://localhost:" + httpServer.identity.primaryPort; @@ -23,27 +24,25 @@ XPCOMUtils.defineLazyGetter(this, "URL", function() { var httpServer = null; function make_channel(url, callback, ctx) { - return NetUtil.newChannel({uri: url, loadUsingSystemPrincipal: true}); + return NetUtil.newChannel({ uri: url, loadUsingSystemPrincipal: true }); } const responseBody = "response body"; -function contentHandler(metadata, response) -{ +function contentHandler(metadata, response) { response.setHeader("Content-Type", "text/plain"); response.setHeader("ETag", "Just testing"); response.setHeader("Cache-Control", "max-age=99999"); response.setHeader("Accept-Ranges", "bytes"); response.setHeader("Content-Length", "" + responseBody.length); if (metadata.hasHeader("If-Range")) { - response.setStatusLine(metadata.httpVersion, 206, "Partial Content"); - response.setHeader("Content-Range", "0-12/13"); + response.setStatusLine(metadata.httpVersion, 206, "Partial Content"); + response.setHeader("Content-Range", "0-12/13"); } response.bodyOutputStream.write(responseBody, responseBody.length); } -function run_test() -{ +function run_test() { do_get_profile(); Services.prefs.setIntPref("browser.cache.disk.max_entry_size", 0); @@ -63,13 +62,11 @@ function run_test() do_test_pending(); } -function firstTimeThrough(request, buffer) -{ +function firstTimeThrough(request, buffer) { Assert.equal(buffer, responseBody); } -function secondTimeThrough(request, buffer) -{ +function secondTimeThrough(request, buffer) { Assert.equal(buffer, responseBody); httpServer.stop(do_test_finished); } diff --git a/netwerk/test/unit/test_cache2-29b-concurrent_read_non-resumable_entry_size_zero.js b/netwerk/test/unit/test_cache2-29b-concurrent_read_non-resumable_entry_size_zero.js index a62ee6baa8a9..c649bc6282df 100644 --- a/netwerk/test/unit/test_cache2-29b-concurrent_read_non-resumable_entry_size_zero.js +++ b/netwerk/test/unit/test_cache2-29b-concurrent_read_non-resumable_entry_size_zero.js @@ -13,10 +13,11 @@ This test is using a non-resumable response. */ -const {HttpServer} = ChromeUtils.import("resource://testing-common/httpd.js"); +const { HttpServer } = ChromeUtils.import("resource://testing-common/httpd.js"); -var httpProtocolHandler = Cc["@mozilla.org/network/protocol;1?name=http"] - .getService(Ci.nsIHttpProtocolHandler); +var httpProtocolHandler = Cc[ + "@mozilla.org/network/protocol;1?name=http" +].getService(Ci.nsIHttpProtocolHandler); XPCOMUtils.defineLazyGetter(this, "URL", function() { return "http://localhost:" + httpServer.identity.primaryPort; @@ -25,14 +26,13 @@ XPCOMUtils.defineLazyGetter(this, "URL", function() { var httpServer = null; function make_channel(url, callback, ctx) { - return NetUtil.newChannel({uri: url, loadUsingSystemPrincipal: true}); + return NetUtil.newChannel({ uri: url, loadUsingSystemPrincipal: true }); } const responseBody = "c\r\ndata reached\r\n3\r\nhej\r\n0\r\n\r\n"; const responseBodyDecoded = "data reachedhej"; -function contentHandler(metadata, response) -{ +function contentHandler(metadata, response) { response.seizePower(); response.write("HTTP/1.1 200 OK\r\n"); response.write("Content-Type: text/plain\r\n"); @@ -42,8 +42,7 @@ function contentHandler(metadata, response) response.finish(); } -function run_test() -{ +function run_test() { do_get_profile(); Services.prefs.setIntPref("browser.cache.disk.max_entry_size", 0); @@ -55,21 +54,23 @@ function run_test() httpProtocolHandler.EnsureHSTSDataReady().then(function() { var chan1 = make_channel(URL + "/content"); - chan1.asyncOpen(new ChannelListener(firstTimeThrough, null, CL_ALLOW_UNKNOWN_CL)); + chan1.asyncOpen( + new ChannelListener(firstTimeThrough, null, CL_ALLOW_UNKNOWN_CL) + ); var chan2 = make_channel(URL + "/content"); - chan2.asyncOpen(new ChannelListener(secondTimeThrough, null, CL_ALLOW_UNKNOWN_CL)); + chan2.asyncOpen( + new ChannelListener(secondTimeThrough, null, CL_ALLOW_UNKNOWN_CL) + ); }); do_test_pending(); } -function firstTimeThrough(request, buffer) -{ +function firstTimeThrough(request, buffer) { Assert.equal(buffer, responseBodyDecoded); } -function secondTimeThrough(request, buffer) -{ +function secondTimeThrough(request, buffer) { Assert.equal(buffer, responseBodyDecoded); httpServer.stop(do_test_finished); } diff --git a/netwerk/test/unit/test_cache2-29c-concurrent_read_half-interrupted.js b/netwerk/test/unit/test_cache2-29c-concurrent_read_half-interrupted.js index 72e4e01f6f13..77f41aebadf6 100644 --- a/netwerk/test/unit/test_cache2-29c-concurrent_read_half-interrupted.js +++ b/netwerk/test/unit/test_cache2-29c-concurrent_read_half-interrupted.js @@ -13,10 +13,11 @@ This test is using a resumable response. */ -const {HttpServer} = ChromeUtils.import("resource://testing-common/httpd.js"); +const { HttpServer } = ChromeUtils.import("resource://testing-common/httpd.js"); -var httpProtocolHandler = Cc["@mozilla.org/network/protocol;1?name=http"] - .getService(Ci.nsIHttpProtocolHandler); +var httpProtocolHandler = Cc[ + "@mozilla.org/network/protocol;1?name=http" +].getService(Ci.nsIHttpProtocolHandler); XPCOMUtils.defineLazyGetter(this, "URL", function() { return "http://localhost:" + httpServer.identity.primaryPort; @@ -25,7 +26,7 @@ XPCOMUtils.defineLazyGetter(this, "URL", function() { var httpServer = null; function make_channel(url, callback, ctx) { - return NetUtil.newChannel({uri: url, loadUsingSystemPrincipal: true}); + return NetUtil.newChannel({ uri: url, loadUsingSystemPrincipal: true }); } // need something bigger than 1024 bytes @@ -42,24 +43,22 @@ const responseBody = "0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef" + "0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef"; -function contentHandler(metadata, response) -{ +function contentHandler(metadata, response) { response.setHeader("Content-Type", "text/plain"); response.setHeader("ETag", "Just testing"); response.setHeader("Cache-Control", "max-age=99999"); response.setHeader("Accept-Ranges", "bytes"); response.setHeader("Content-Length", "" + responseBody.length); if (metadata.hasHeader("If-Range")) { - response.setStatusLine(metadata.httpVersion, 206, "Partial Content"); + response.setStatusLine(metadata.httpVersion, 206, "Partial Content"); let len = responseBody.length; - response.setHeader("Content-Range", "0-" + (len - 1) + "/" + len); + response.setHeader("Content-Range", "0-" + (len - 1) + "/" + len); } response.bodyOutputStream.write(responseBody, responseBody.length); } -function run_test() -{ +function run_test() { // Static check Assert.ok(responseBody.length > 1024); @@ -82,13 +81,11 @@ function run_test() do_test_pending(); } -function firstTimeThrough(request, buffer) -{ +function firstTimeThrough(request, buffer) { Assert.equal(buffer, responseBody); } -function secondTimeThrough(request, buffer) -{ +function secondTimeThrough(request, buffer) { Assert.equal(buffer, responseBody); httpServer.stop(do_test_finished); } diff --git a/netwerk/test/unit/test_cache2-29d-concurrent_read_half-corrupted-206.js b/netwerk/test/unit/test_cache2-29d-concurrent_read_half-corrupted-206.js index 6d54acf943c2..0ebf1f060dc6 100644 --- a/netwerk/test/unit/test_cache2-29d-concurrent_read_half-corrupted-206.js +++ b/netwerk/test/unit/test_cache2-29d-concurrent_read_half-corrupted-206.js @@ -14,10 +14,11 @@ This test is using a resumable response. */ -const {HttpServer} = ChromeUtils.import("resource://testing-common/httpd.js"); +const { HttpServer } = ChromeUtils.import("resource://testing-common/httpd.js"); -var httpProtocolHandler = Cc["@mozilla.org/network/protocol;1?name=http"] - .getService(Ci.nsIHttpProtocolHandler); +var httpProtocolHandler = Cc[ + "@mozilla.org/network/protocol;1?name=http" +].getService(Ci.nsIHttpProtocolHandler); XPCOMUtils.defineLazyGetter(this, "URL", function() { return "http://localhost:" + httpServer.identity.primaryPort; @@ -26,7 +27,7 @@ XPCOMUtils.defineLazyGetter(this, "URL", function() { var httpServer = null; function make_channel(url, callback, ctx) { - return NetUtil.newChannel({uri: url, loadUsingSystemPrincipal: true}); + return NetUtil.newChannel({ uri: url, loadUsingSystemPrincipal: true }); } // need something bigger than 1024 bytes @@ -43,23 +44,21 @@ const responseBody = "0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef" + "0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef"; -function contentHandler(metadata, response) -{ +function contentHandler(metadata, response) { response.setHeader("Content-Type", "text/plain"); response.setHeader("ETag", "Just testing"); response.setHeader("Cache-Control", "max-age=99999"); response.setHeader("Accept-Ranges", "bytes"); response.setHeader("Content-Length", "" + responseBody.length); if (metadata.hasHeader("If-Range")) { - response.setStatusLine(metadata.httpVersion, 206, "Partial Content"); + response.setStatusLine(metadata.httpVersion, 206, "Partial Content"); // Deliberately broken response header to trigger corrupted content error on the second channel - response.setHeader("Content-Range", "0-1/2"); + response.setHeader("Content-Range", "0-1/2"); } response.bodyOutputStream.write(responseBody, responseBody.length); } -function run_test() -{ +function run_test() { // Static check Assert.ok(responseBody.length > 1024); @@ -76,18 +75,18 @@ function run_test() var chan1 = make_channel(URL + "/content"); chan1.asyncOpen(new ChannelListener(firstTimeThrough, null)); var chan2 = make_channel(URL + "/content"); - chan2.asyncOpen(new ChannelListener(secondTimeThrough, null, CL_EXPECT_FAILURE)); + chan2.asyncOpen( + new ChannelListener(secondTimeThrough, null, CL_EXPECT_FAILURE) + ); }); do_test_pending(); } -function firstTimeThrough(request, buffer) -{ +function firstTimeThrough(request, buffer) { Assert.equal(buffer, responseBody); } -function secondTimeThrough(request, buffer) -{ +function secondTimeThrough(request, buffer) { httpServer.stop(do_test_finished); } diff --git a/netwerk/test/unit/test_cache2-29e-concurrent_read_half-non-206-response.js b/netwerk/test/unit/test_cache2-29e-concurrent_read_half-non-206-response.js index 017fdaa0cc95..4537d4511c78 100644 --- a/netwerk/test/unit/test_cache2-29e-concurrent_read_half-non-206-response.js +++ b/netwerk/test/unit/test_cache2-29e-concurrent_read_half-non-206-response.js @@ -14,10 +14,11 @@ This test is using a resumable response. */ -const {HttpServer} = ChromeUtils.import("resource://testing-common/httpd.js"); +const { HttpServer } = ChromeUtils.import("resource://testing-common/httpd.js"); -var httpProtocolHandler = Cc["@mozilla.org/network/protocol;1?name=http"] - .getService(Ci.nsIHttpProtocolHandler); +var httpProtocolHandler = Cc[ + "@mozilla.org/network/protocol;1?name=http" +].getService(Ci.nsIHttpProtocolHandler); XPCOMUtils.defineLazyGetter(this, "URL", function() { return "http://localhost:" + httpServer.identity.primaryPort; @@ -26,7 +27,7 @@ XPCOMUtils.defineLazyGetter(this, "URL", function() { var httpServer = null; function make_channel(url, callback, ctx) { - return NetUtil.newChannel({uri: url, loadUsingSystemPrincipal: true}); + return NetUtil.newChannel({ uri: url, loadUsingSystemPrincipal: true }); } // need something bigger than 1024 bytes @@ -43,8 +44,7 @@ const responseBody = "0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef" + "0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef"; -function contentHandler(metadata, response) -{ +function contentHandler(metadata, response) { response.setHeader("Content-Type", "text/plain"); response.setHeader("ETag", "Just testing"); response.setHeader("Cache-Control", "max-age=99999"); @@ -53,8 +53,7 @@ function contentHandler(metadata, response) response.bodyOutputStream.write(responseBody, responseBody.length); } -function run_test() -{ +function run_test() { // Static check Assert.ok(responseBody.length > 1024); @@ -71,18 +70,18 @@ function run_test() var chan1 = make_channel(URL + "/content"); chan1.asyncOpen(new ChannelListener(firstTimeThrough, null)); var chan2 = make_channel(URL + "/content"); - chan2.asyncOpen(new ChannelListener(secondTimeThrough, null, CL_EXPECT_FAILURE)); + chan2.asyncOpen( + new ChannelListener(secondTimeThrough, null, CL_EXPECT_FAILURE) + ); }); do_test_pending(); } -function firstTimeThrough(request, buffer) -{ +function firstTimeThrough(request, buffer) { Assert.equal(buffer, responseBody); } -function secondTimeThrough(request, buffer) -{ +function secondTimeThrough(request, buffer) { httpServer.stop(do_test_finished); } diff --git a/netwerk/test/unit/test_cache2-30a-entry-pinning.js b/netwerk/test/unit/test_cache2-30a-entry-pinning.js index 8cc39c78061f..4f00db5e225c 100644 --- a/netwerk/test/unit/test_cache2-30a-entry-pinning.js +++ b/netwerk/test/unit/test_cache2-30a-entry-pinning.js @@ -1,24 +1,33 @@ -function run_test() -{ +function run_test() { do_get_profile(); // Open for write, write - asyncOpenCacheEntry("http://a/", "pin", Ci.nsICacheStorage.OPEN_TRUNCATE, Services.loadContextInfo.default, - new OpenCallback(NEW|WAITFORWRITE, "a1m", "a1d", function(entry) { + asyncOpenCacheEntry( + "http://a/", + "pin", + Ci.nsICacheStorage.OPEN_TRUNCATE, + Services.loadContextInfo.default, + new OpenCallback(NEW | WAITFORWRITE, "a1m", "a1d", function(entry) { // Open for read and check - asyncOpenCacheEntry("http://a/", "disk", Ci.nsICacheStorage.OPEN_NORMALLY, Services.loadContextInfo.default, + asyncOpenCacheEntry( + "http://a/", + "disk", + Ci.nsICacheStorage.OPEN_NORMALLY, + Services.loadContextInfo.default, new OpenCallback(NORMAL, "a1m", "a1d", function(entry) { - // Now clear the whole cache get_cache_service().clear(); // The pinned entry should be intact - asyncOpenCacheEntry("http://a/", "disk", Ci.nsICacheStorage.OPEN_NORMALLY, Services.loadContextInfo.default, + asyncOpenCacheEntry( + "http://a/", + "disk", + Ci.nsICacheStorage.OPEN_NORMALLY, + Services.loadContextInfo.default, new OpenCallback(NORMAL, "a1m", "a1d", function(entry) { finish_cache2_test(); }) ); - }) ); }) diff --git a/netwerk/test/unit/test_cache2-30b-pinning-storage-clear.js b/netwerk/test/unit/test_cache2-30b-pinning-storage-clear.js index a8b14e8f6e58..09844b63aa0f 100644 --- a/netwerk/test/unit/test_cache2-30b-pinning-storage-clear.js +++ b/netwerk/test/unit/test_cache2-30b-pinning-storage-clear.js @@ -1,31 +1,39 @@ -function run_test() -{ +function run_test() { do_get_profile(); var lci = Services.loadContextInfo.default; // Open a pinned entry for write, write - asyncOpenCacheEntry("http://a/", "pin", Ci.nsICacheStorage.OPEN_TRUNCATE, lci, - new OpenCallback(NEW|WAITFORWRITE, "a1m", "a1d", function(entry) { - + asyncOpenCacheEntry( + "http://a/", + "pin", + Ci.nsICacheStorage.OPEN_TRUNCATE, + lci, + new OpenCallback(NEW | WAITFORWRITE, "a1m", "a1d", function(entry) { // Now clear the disk storage, that should leave the pinned entry in the cache var diskStorage = getCacheStorage("disk", lci); diskStorage.asyncEvictStorage(null); // Open for read and check, it should still be there - asyncOpenCacheEntry("http://a/", "disk", Ci.nsICacheStorage.OPEN_NORMALLY, lci, + asyncOpenCacheEntry( + "http://a/", + "disk", + Ci.nsICacheStorage.OPEN_NORMALLY, + lci, new OpenCallback(NORMAL, "a1m", "a1d", function(entry) { - // Now clear the pinning storage, entry should be gone var pinningStorage = getCacheStorage("pin", lci); pinningStorage.asyncEvictStorage(null); - asyncOpenCacheEntry("http://a/", "disk", Ci.nsICacheStorage.OPEN_NORMALLY, lci, + asyncOpenCacheEntry( + "http://a/", + "disk", + Ci.nsICacheStorage.OPEN_NORMALLY, + lci, new OpenCallback(NEW, "", "", function(entry) { finish_cache2_test(); }) ); - }) ); }) diff --git a/netwerk/test/unit/test_cache2-30c-pinning-deferred-doom.js b/netwerk/test/unit/test_cache2-30c-pinning-deferred-doom.js index 1b1a88f2efe3..78163a98eb3d 100644 --- a/netwerk/test/unit/test_cache2-30c-pinning-deferred-doom.js +++ b/netwerk/test/unit/test_cache2-30c-pinning-deferred-doom.js @@ -21,34 +21,43 @@ This is a complex test checking the internal "deferred doom" functionality in bo const kENTRYCOUNT = 10; -function log_(msg) { if (true) dump(">>>>>>>>>>>>> " + msg + "\n"); } +function log_(msg) { + if (true) { + dump(">>>>>>>>>>>>> " + msg + "\n"); + } +} -function run_test() -{ +function run_test() { do_get_profile(); var lci = Services.loadContextInfo.default; var testingInterface = get_cache_service().QueryInterface(Ci.nsICacheTesting); Assert.ok(testingInterface); - var mc = new MultipleCallbacks(1, function() { - // (2) + var mc = new MultipleCallbacks( + 1, + function() { + // (2) - mc = new MultipleCallbacks(1, finish_cache2_test); - // Release all references to cache entries so that they can be purged - // Calling gc() four times is needed to force it to actually release - // entries that are obviously unreferenced. Yeah, I know, this is wacky... - gc(); - gc(); - executeSoon(() => { + mc = new MultipleCallbacks(1, finish_cache2_test); + // Release all references to cache entries so that they can be purged + // Calling gc() four times is needed to force it to actually release + // entries that are obviously unreferenced. Yeah, I know, this is wacky... gc(); gc(); - log_("purging"); + executeSoon(() => { + gc(); + gc(); + log_("purging"); - // Invokes cacheservice:purge-memory-pools when done. - get_cache_service().purgeFromMemory(Ci.nsICacheStorageService.PURGE_EVERYTHING); // goes to (3) - }); - }, true); + // Invokes cacheservice:purge-memory-pools when done. + get_cache_service().purgeFromMemory( + Ci.nsICacheStorageService.PURGE_EVERYTHING + ); // goes to (3) + }); + }, + true + ); // (1), here we start @@ -58,73 +67,120 @@ function run_test() // Callbacks 1-20 mc.add(); - asyncOpenCacheEntry("http://pinned" + i + "/", "pin", Ci.nsICacheStorage.OPEN_TRUNCATE, lci, - new OpenCallback(NEW|WAITFORWRITE, "m" + i, "p" + i, function(entry) { mc.fired(); })); + asyncOpenCacheEntry( + "http://pinned" + i + "/", + "pin", + Ci.nsICacheStorage.OPEN_TRUNCATE, + lci, + new OpenCallback(NEW | WAITFORWRITE, "m" + i, "p" + i, function(entry) { + mc.fired(); + }) + ); mc.add(); - asyncOpenCacheEntry("http://common" + i + "/", "disk", Ci.nsICacheStorage.OPEN_TRUNCATE, lci, - new OpenCallback(NEW|WAITFORWRITE, "m" + i, "d" + i, function(entry) { mc.fired(); })); + asyncOpenCacheEntry( + "http://common" + i + "/", + "disk", + Ci.nsICacheStorage.OPEN_TRUNCATE, + lci, + new OpenCallback(NEW | WAITFORWRITE, "m" + i, "d" + i, function(entry) { + mc.fired(); + }) + ); } mc.fired(); // Goes to (2) - var os = Cc["@mozilla.org/observer-service;1"].getService(Ci.nsIObserverService); - os.addObserver({ - observe(subject, topic, data) + var os = Cc["@mozilla.org/observer-service;1"].getService( + Ci.nsIObserverService + ); + os.addObserver( { - // (3) + observe(subject, topic, data) { + // (3) - log_("after purge, second set of opens"); - // Prevent the I/O thread from reading the data. We first want to schedule clear of the cache. - // This deterministically emulates a slow hard drive. - testingInterface.suspendCacheIOThread(3); + log_("after purge, second set of opens"); + // Prevent the I/O thread from reading the data. We first want to schedule clear of the cache. + // This deterministically emulates a slow hard drive. + testingInterface.suspendCacheIOThread(3); - // All entries should load - // Callbacks 21-40 - for (i = 0; i < kENTRYCOUNT; ++i) { - mc.add(); - asyncOpenCacheEntry("http://pinned" + i + "/", "disk", Ci.nsICacheStorage.OPEN_NORMALLY, lci, - new OpenCallback(NORMAL, "m" + i, "p" + i, function(entry) { mc.fired(); })); + // All entries should load + // Callbacks 21-40 + for (i = 0; i < kENTRYCOUNT; ++i) { + mc.add(); + asyncOpenCacheEntry( + "http://pinned" + i + "/", + "disk", + Ci.nsICacheStorage.OPEN_NORMALLY, + lci, + new OpenCallback(NORMAL, "m" + i, "p" + i, function(entry) { + mc.fired(); + }) + ); - // Unfortunately we cannot ensure that entries existing in the cache will be delivered to the consumer - // when soon after are evicted by some cache API call. It's better to not ensure getting an entry - // than allowing to get an entry that was just evicted from the cache. Entries may be delievered - // as new, but are already doomed. Output stream cannot be openned, or the file handle is already - // writing to a doomed file. - // - // The API now just ensures that entries removed by any of the cache eviction APIs are never more - // available to consumers. - mc.add(); - asyncOpenCacheEntry("http://common" + i + "/", "disk", Ci.nsICacheStorage.OPEN_NORMALLY, lci, - new OpenCallback(MAYBE_NEW|DOOMED, "m" + i, "d" + i, function(entry) { mc.fired(); })); - } + // Unfortunately we cannot ensure that entries existing in the cache will be delivered to the consumer + // when soon after are evicted by some cache API call. It's better to not ensure getting an entry + // than allowing to get an entry that was just evicted from the cache. Entries may be delievered + // as new, but are already doomed. Output stream cannot be openned, or the file handle is already + // writing to a doomed file. + // + // The API now just ensures that entries removed by any of the cache eviction APIs are never more + // available to consumers. + mc.add(); + asyncOpenCacheEntry( + "http://common" + i + "/", + "disk", + Ci.nsICacheStorage.OPEN_NORMALLY, + lci, + new OpenCallback(MAYBE_NEW | DOOMED, "m" + i, "d" + i, function( + entry + ) { + mc.fired(); + }) + ); + } - log_("clearing"); - // Now clear everything except pinned, all entries are in state of reading - get_cache_service().clear(); - log_("cleared"); + log_("clearing"); + // Now clear everything except pinned, all entries are in state of reading + get_cache_service().clear(); + log_("cleared"); - // Resume reading the cache data, only now the pinning status on entries will be discovered, - // the deferred dooming code will trigger. - testingInterface.resumeCacheIOThread(); + // Resume reading the cache data, only now the pinning status on entries will be discovered, + // the deferred dooming code will trigger. + testingInterface.resumeCacheIOThread(); - log_("third set of opens"); - // Now open again. Pinned entries should be there, disk entries should be the renewed entries. - // Callbacks 41-60 - for (i = 0; i < kENTRYCOUNT; ++i) { - mc.add(); - asyncOpenCacheEntry("http://pinned" + i + "/", "disk", Ci.nsICacheStorage.OPEN_NORMALLY, lci, - new OpenCallback(NORMAL, "m" + i, "p" + i, function(entry) { mc.fired(); })); + log_("third set of opens"); + // Now open again. Pinned entries should be there, disk entries should be the renewed entries. + // Callbacks 41-60 + for (i = 0; i < kENTRYCOUNT; ++i) { + mc.add(); + asyncOpenCacheEntry( + "http://pinned" + i + "/", + "disk", + Ci.nsICacheStorage.OPEN_NORMALLY, + lci, + new OpenCallback(NORMAL, "m" + i, "p" + i, function(entry) { + mc.fired(); + }) + ); - mc.add(); - asyncOpenCacheEntry("http://common" + i + "/", "disk", Ci.nsICacheStorage.OPEN_NORMALLY, lci, - new OpenCallback(NEW, "m2" + i, "d2" + i, function(entry) { mc.fired(); })); - } - - mc.fired(); // Finishes this test - } - }, "cacheservice:purge-memory-pools"); + mc.add(); + asyncOpenCacheEntry( + "http://common" + i + "/", + "disk", + Ci.nsICacheStorage.OPEN_NORMALLY, + lci, + new OpenCallback(NEW, "m2" + i, "d2" + i, function(entry) { + mc.fired(); + }) + ); + } + mc.fired(); // Finishes this test + }, + }, + "cacheservice:purge-memory-pools" + ); do_test_pending(); } diff --git a/netwerk/test/unit/test_cache2-30d-pinning-WasEvicted-API.js b/netwerk/test/unit/test_cache2-30d-pinning-WasEvicted-API.js index 36841027e6ad..a208753897f2 100644 --- a/netwerk/test/unit/test_cache2-30d-pinning-WasEvicted-API.js +++ b/netwerk/test/unit/test_cache2-30d-pinning-WasEvicted-API.js @@ -17,94 +17,133 @@ This test exercises the CacheFileContextEvictor::WasEvicted API and code using i const kENTRYCOUNT = 10; -function log_(msg) { if (true) dump(">>>>>>>>>>>>> " + msg + "\n"); } +function log_(msg) { + if (true) { + dump(">>>>>>>>>>>>> " + msg + "\n"); + } +} -function run_test() -{ +function run_test() { do_get_profile(); var lci = Services.loadContextInfo.default; var testingInterface = get_cache_service().QueryInterface(Ci.nsICacheTesting); Assert.ok(testingInterface); - var mc = new MultipleCallbacks(1, function() { - // (2) + var mc = new MultipleCallbacks( + 1, + function() { + // (2) - mc = new MultipleCallbacks(1, finish_cache2_test); - // Release all references to cache entries so that they can be purged - // Calling gc() four times is needed to force it to actually release - // entries that are obviously unreferenced. Yeah, I know, this is wacky... - gc(); - gc(); - executeSoon(() => { + mc = new MultipleCallbacks(1, finish_cache2_test); + // Release all references to cache entries so that they can be purged + // Calling gc() four times is needed to force it to actually release + // entries that are obviously unreferenced. Yeah, I know, this is wacky... gc(); gc(); - log_("purging"); + executeSoon(() => { + gc(); + gc(); + log_("purging"); - // Invokes cacheservice:purge-memory-pools when done. - get_cache_service().purgeFromMemory(Ci.nsICacheStorageService.PURGE_EVERYTHING); // goes to (3) - }); - }, true); + // Invokes cacheservice:purge-memory-pools when done. + get_cache_service().purgeFromMemory( + Ci.nsICacheStorageService.PURGE_EVERYTHING + ); // goes to (3) + }); + }, + true + ); // (1), here we start log_("first set of opens"); var i; for (i = 0; i < kENTRYCOUNT; ++i) { - // Callbacks 1-20 mc.add(); - asyncOpenCacheEntry("http://pinned" + i + "/", "pin", Ci.nsICacheStorage.OPEN_TRUNCATE, lci, - new OpenCallback(NEW|WAITFORWRITE, "m" + i, "p" + i, function(entry) { mc.fired(); })); + asyncOpenCacheEntry( + "http://pinned" + i + "/", + "pin", + Ci.nsICacheStorage.OPEN_TRUNCATE, + lci, + new OpenCallback(NEW | WAITFORWRITE, "m" + i, "p" + i, function(entry) { + mc.fired(); + }) + ); mc.add(); - asyncOpenCacheEntry("http://common" + i + "/", "disk", Ci.nsICacheStorage.OPEN_TRUNCATE, lci, - new OpenCallback(NEW|WAITFORWRITE, "m" + i, "d" + i, function(entry) { mc.fired(); })); + asyncOpenCacheEntry( + "http://common" + i + "/", + "disk", + Ci.nsICacheStorage.OPEN_TRUNCATE, + lci, + new OpenCallback(NEW | WAITFORWRITE, "m" + i, "d" + i, function(entry) { + mc.fired(); + }) + ); } mc.fired(); // Goes to (2) - var os = Cc["@mozilla.org/observer-service;1"].getService(Ci.nsIObserverService); - os.addObserver({ - observe(subject, topic, data) + var os = Cc["@mozilla.org/observer-service;1"].getService( + Ci.nsIObserverService + ); + os.addObserver( { - // (3) + observe(subject, topic, data) { + // (3) - log_("after purge"); - // Prevent the I/O thread from evicting physically the data. We first want to re-open the entries. - // This deterministically emulates a slow hard drive. - testingInterface.suspendCacheIOThread(7); + log_("after purge"); + // Prevent the I/O thread from evicting physically the data. We first want to re-open the entries. + // This deterministically emulates a slow hard drive. + testingInterface.suspendCacheIOThread(7); - log_("clearing"); - // Now clear everything except pinned. Stores the "ce_*" file and schedules background eviction. - get_cache_service().clear(); - log_("cleared"); + log_("clearing"); + // Now clear everything except pinned. Stores the "ce_*" file and schedules background eviction. + get_cache_service().clear(); + log_("cleared"); - log_("second set of opens"); - // Now open again. Pinned entries should be there, disk entries should be the renewed entries. - // Callbacks 21-40 - for (i = 0; i < kENTRYCOUNT; ++i) { - mc.add(); - asyncOpenCacheEntry("http://pinned" + i + "/", "disk", Ci.nsICacheStorage.OPEN_NORMALLY, lci, - new OpenCallback(NORMAL, "m" + i, "p" + i, function(entry) { mc.fired(); })); + log_("second set of opens"); + // Now open again. Pinned entries should be there, disk entries should be the renewed entries. + // Callbacks 21-40 + for (i = 0; i < kENTRYCOUNT; ++i) { + mc.add(); + asyncOpenCacheEntry( + "http://pinned" + i + "/", + "disk", + Ci.nsICacheStorage.OPEN_NORMALLY, + lci, + new OpenCallback(NORMAL, "m" + i, "p" + i, function(entry) { + mc.fired(); + }) + ); - mc.add(); - asyncOpenCacheEntry("http://common" + i + "/", "disk", Ci.nsICacheStorage.OPEN_NORMALLY, lci, - new OpenCallback(NEW, "m2" + i, "d2" + i, function(entry) { mc.fired(); })); - } + mc.add(); + asyncOpenCacheEntry( + "http://common" + i + "/", + "disk", + Ci.nsICacheStorage.OPEN_NORMALLY, + lci, + new OpenCallback(NEW, "m2" + i, "d2" + i, function(entry) { + mc.fired(); + }) + ); + } - // Resume IO, this will just pop-off the CacheFileContextEvictor::EvictEntries() because of - // an early check on CacheIOThread::YieldAndRerun() in that method. - // CacheFileIOManager::OpenFileInternal should now run and CacheFileContextEvictor::WasEvicted - // should be checked on. - log_("resuming"); - testingInterface.resumeCacheIOThread(); - log_("resumed"); - - mc.fired(); // Finishes this test - } - }, "cacheservice:purge-memory-pools"); + // Resume IO, this will just pop-off the CacheFileContextEvictor::EvictEntries() because of + // an early check on CacheIOThread::YieldAndRerun() in that method. + // CacheFileIOManager::OpenFileInternal should now run and CacheFileContextEvictor::WasEvicted + // should be checked on. + log_("resuming"); + testingInterface.resumeCacheIOThread(); + log_("resumed"); + mc.fired(); // Finishes this test + }, + }, + "cacheservice:purge-memory-pools" + ); do_test_pending(); } diff --git a/netwerk/test/unit/test_cache2-31-visit-all.js b/netwerk/test/unit/test_cache2-31-visit-all.js index fb612fdf94af..00b8d57d7d42 100644 --- a/netwerk/test/unit/test_cache2-31-visit-all.js +++ b/netwerk/test/unit/test_cache2-31-visit-all.js @@ -1,46 +1,61 @@ -function run_test() -{ +function run_test() { var storage = getCacheStorage("disk"); - var lcis = [Services.loadContextInfo.default, - Services.loadContextInfo.custom(false, { userContextId: 1 }), - Services.loadContextInfo.custom(false, { userContextId: 2 }), - Services.loadContextInfo.custom(false, { userContextId: 3 })]; + var lcis = [ + Services.loadContextInfo.default, + Services.loadContextInfo.custom(false, { userContextId: 1 }), + Services.loadContextInfo.custom(false, { userContextId: 2 }), + Services.loadContextInfo.custom(false, { userContextId: 3 }), + ]; do_get_profile(); - var mc = new MultipleCallbacks(8, function() { - executeSoon(function() { - var expectedConsumption = 8192; - var entries = [{ uri: "http://a/", lci: lcis[0] }, // default - { uri: "http://b/", lci: lcis[0] }, // default - { uri: "http://a/", lci: lcis[1] }, // user Context 1 - { uri: "http://b/", lci: lcis[1] }, // user Context 1 - { uri: "http://a/", lci: lcis[2] }, // user Context 2 - { uri: "http://b/", lci: lcis[2] }, // user Context 2 - { uri: "http://a/", lci: lcis[3] }, // user Context 3 - { uri: "http://b/", lci: lcis[3] }]; // user Context 3 + var mc = new MultipleCallbacks( + 8, + function() { + executeSoon(function() { + var expectedConsumption = 8192; + var entries = [ + { uri: "http://a/", lci: lcis[0] }, // default + { uri: "http://b/", lci: lcis[0] }, // default + { uri: "http://a/", lci: lcis[1] }, // user Context 1 + { uri: "http://b/", lci: lcis[1] }, // user Context 1 + { uri: "http://a/", lci: lcis[2] }, // user Context 2 + { uri: "http://b/", lci: lcis[2] }, // user Context 2 + { uri: "http://a/", lci: lcis[3] }, // user Context 3 + { uri: "http://b/", lci: lcis[3] }, + ]; // user Context 3 - get_cache_service().asyncVisitAllStorages( - // Test should store 8 entries across 4 originAttributes - new VisitCallback(8, expectedConsumption, entries, function() { - get_cache_service().asyncVisitAllStorages( - // Still 8 entries expected, now don't walk them - new VisitCallback(8, expectedConsumption, null, function() { - finish_cache2_test(); - }), - false - ); - }), - true - ); - }); - }, true); + get_cache_service().asyncVisitAllStorages( + // Test should store 8 entries across 4 originAttributes + new VisitCallback(8, expectedConsumption, entries, function() { + get_cache_service().asyncVisitAllStorages( + // Still 8 entries expected, now don't walk them + new VisitCallback(8, expectedConsumption, null, function() { + finish_cache2_test(); + }), + false + ); + }), + true + ); + }); + }, + true + ); // Add two cache entries for each originAttributes. - for (var i = 0 ; i < lcis.length; i++) { - asyncOpenCacheEntry("http://a/", "disk", Ci.nsICacheStorage.OPEN_NORMALLY, lcis[i], + for (var i = 0; i < lcis.length; i++) { + asyncOpenCacheEntry( + "http://a/", + "disk", + Ci.nsICacheStorage.OPEN_NORMALLY, + lcis[i], new OpenCallback(NEW, "a1m", "a1d", function(entry) { - asyncOpenCacheEntry("http://a/", "disk", Ci.nsICacheStorage.OPEN_NORMALLY, lcis[i], + asyncOpenCacheEntry( + "http://a/", + "disk", + Ci.nsICacheStorage.OPEN_NORMALLY, + lcis[i], new OpenCallback(NORMAL, "a1m", "a1d", function(entry) { mc.fired(); }) @@ -48,9 +63,17 @@ function run_test() }) ); - asyncOpenCacheEntry("http://b/", "disk", Ci.nsICacheStorage.OPEN_NORMALLY, lcis[i], + asyncOpenCacheEntry( + "http://b/", + "disk", + Ci.nsICacheStorage.OPEN_NORMALLY, + lcis[i], new OpenCallback(NEW, "b1m", "b1d", function(entry) { - asyncOpenCacheEntry("http://b/", "disk", Ci.nsICacheStorage.OPEN_NORMALLY, lcis[i], + asyncOpenCacheEntry( + "http://b/", + "disk", + Ci.nsICacheStorage.OPEN_NORMALLY, + lcis[i], new OpenCallback(NORMAL, "b1m", "b1d", function(entry) { mc.fired(); }) diff --git a/netwerk/test/unit/test_cache2-32-clear-origin.js b/netwerk/test/unit/test_cache2-32-clear-origin.js index 1f2ab7fdf6f9..8ed3f4d4508f 100644 --- a/netwerk/test/unit/test_cache2-32-clear-origin.js +++ b/netwerk/test/unit/test_cache2-32-clear-origin.js @@ -1,26 +1,52 @@ const URL = "http://example.net"; const URL2 = "http://foo.bar"; -function run_test() -{ +function run_test() { do_get_profile(); - asyncOpenCacheEntry(URL + "/a", "disk", Ci.nsICacheStorage.OPEN_NORMALLY, null, + asyncOpenCacheEntry( + URL + "/a", + "disk", + Ci.nsICacheStorage.OPEN_NORMALLY, + null, new OpenCallback(NEW, "e1m", "e1d", function(entry) { - asyncOpenCacheEntry(URL + "/a", "disk", Ci.nsICacheStorage.OPEN_NORMALLY, null, + asyncOpenCacheEntry( + URL + "/a", + "disk", + Ci.nsICacheStorage.OPEN_NORMALLY, + null, new OpenCallback(NORMAL, "e1m", "e1d", function(entry) { - asyncOpenCacheEntry(URL2 + "/a", "disk", Ci.nsICacheStorage.OPEN_NORMALLY, null, + asyncOpenCacheEntry( + URL2 + "/a", + "disk", + Ci.nsICacheStorage.OPEN_NORMALLY, + null, new OpenCallback(NEW, "f1m", "f1d", function(entry) { - asyncOpenCacheEntry(URL2 + "/a", "disk", Ci.nsICacheStorage.OPEN_NORMALLY, null, + asyncOpenCacheEntry( + URL2 + "/a", + "disk", + Ci.nsICacheStorage.OPEN_NORMALLY, + null, new OpenCallback(NORMAL, "f1m", "f1d", function(entry) { var url = Services.io.newURI(URL); - var principal = Services.scriptSecurityManager.createCodebasePrincipal(url, {}); + var principal = Services.scriptSecurityManager.createCodebasePrincipal( + url, + {} + ); get_cache_service().clearOrigin(principal); - asyncOpenCacheEntry(URL + "/a", "disk", Ci.nsICacheStorage.OPEN_NORMALLY, null, + asyncOpenCacheEntry( + URL + "/a", + "disk", + Ci.nsICacheStorage.OPEN_NORMALLY, + null, new OpenCallback(NEW, "e1m", "e1d", function(entry) { - asyncOpenCacheEntry(URL2 + "/a", "disk", Ci.nsICacheStorage.OPEN_NORMALLY, null, + asyncOpenCacheEntry( + URL2 + "/a", + "disk", + Ci.nsICacheStorage.OPEN_NORMALLY, + null, new OpenCallback(NORMAL, "f1m", "f1d", function(entry) { finish_cache2_test(); }) diff --git a/netwerk/test/unit/test_cacheForOfflineUse_no-store.js b/netwerk/test/unit/test_cacheForOfflineUse_no-store.js index 6c791fe9990a..b2015c17adbd 100644 --- a/netwerk/test/unit/test_cacheForOfflineUse_no-store.js +++ b/netwerk/test/unit/test_cacheForOfflineUse_no-store.js @@ -1,7 +1,7 @@ "use strict"; // https://bugzilla.mozilla.org/show_bug.cgi?id=760955 -const {HttpServer} = ChromeUtils.import("resource://testing-common/httpd.js"); +const { HttpServer } = ChromeUtils.import("resource://testing-common/httpd.js"); var httpServer = null; const testFileName = "test_nsHttpChannel_CacheForOfflineUse-no-store"; @@ -19,36 +19,40 @@ var cacheUpdateObserver = null; var appCache = null; function make_channel_for_offline_use(url, callback, ctx) { - var chan = NetUtil.newChannel({uri: url, loadUsingSystemPrincipal: true}); + var chan = NetUtil.newChannel({ uri: url, loadUsingSystemPrincipal: true }); - var cacheService = Cc["@mozilla.org/network/application-cache-service;1"]. - getService(Ci.nsIApplicationCacheService); + var cacheService = Cc[ + "@mozilla.org/network/application-cache-service;1" + ].getService(Ci.nsIApplicationCacheService); appCache = cacheService.getApplicationCache(cacheClientID); - + var appCacheChan = chan.QueryInterface(Ci.nsIApplicationCacheChannel); appCacheChan.applicationCacheForWrite = appCache; return chan; } function make_uri(url) { - var ios = Cc["@mozilla.org/network/io-service;1"]. - getService(Ci.nsIIOService); + var ios = Cc["@mozilla.org/network/io-service;1"].getService(Ci.nsIIOService); return ios.newURI(url); } const responseBody = "response body"; // A HTTP channel for updating the offline cache should normally succeed. -function normalHandler(metadata, response) -{ +function normalHandler(metadata, response) { info("normalHandler"); response.setHeader("Content-Type", "text/plain"); response.bodyOutputStream.write(responseBody, responseBody.length); } -function checkNormal(request, buffer) -{ +function checkNormal(request, buffer) { Assert.equal(buffer, responseBody); - asyncCheckCacheEntryPresence(baseURI + normalEntry, "appcache", true, run_next_test, appCache); + asyncCheckCacheEntryPresence( + baseURI + normalEntry, + "appcache", + true, + run_next_test, + appCache + ); } add_test(function test_normal() { var chan = make_channel_for_offline_use(baseURI + normalEntry); @@ -57,17 +61,21 @@ add_test(function test_normal() { // An HTTP channel for updating the offline cache should fail when it gets a // response with Cache-Control: no-store. -function noStoreHandler(metadata, response) -{ +function noStoreHandler(metadata, response) { info("noStoreHandler"); response.setHeader("Content-Type", "text/plain"); response.setHeader("Cache-Control", "no-store"); response.bodyOutputStream.write(responseBody, responseBody.length); } -function checkNoStore(request, buffer) -{ +function checkNoStore(request, buffer) { Assert.equal(buffer, ""); - asyncCheckCacheEntryPresence(baseURI + noStoreEntry, "appcache", false, run_next_test, appCache); + asyncCheckCacheEntryPresence( + baseURI + noStoreEntry, + "appcache", + false, + run_next_test, + appCache + ); } add_test(function test_noStore() { var chan = make_channel_for_offline_use(baseURI + noStoreEntry); @@ -75,8 +83,7 @@ add_test(function test_noStore() { chan.asyncOpen(new ChannelListener(checkNoStore, chan, CL_EXPECT_FAILURE)); }); -function run_test() -{ +function run_test() { do_get_profile(); httpServer = new HttpServer(); @@ -86,7 +93,6 @@ function run_test() run_next_test(); } -function finish_test(request, buffer) -{ +function finish_test(request, buffer) { httpServer.stop(do_test_finished); } diff --git a/netwerk/test/unit/test_cache_jar.js b/netwerk/test/unit/test_cache_jar.js index 178145697e64..c00ed376ffc5 100644 --- a/netwerk/test/unit/test_cache_jar.js +++ b/netwerk/test/unit/test_cache_jar.js @@ -1,4 +1,4 @@ -const {HttpServer} = ChromeUtils.import("resource://testing-common/httpd.js"); +const { HttpServer } = ChromeUtils.import("resource://testing-common/httpd.js"); XPCOMUtils.defineLazyGetter(this, "URL", function() { return "http://localhost:" + httpserv.identity.primaryPort + "/cached"; @@ -17,21 +17,17 @@ function cached_handler(metadata, response) { } function makeChan(url, inIsolatedMozBrowser, userContextId) { - var chan = NetUtil.newChannel({uri: url, loadUsingSystemPrincipal: true}) - .QueryInterface(Ci.nsIHttpChannel); - chan.loadInfo.originAttributes = { inIsolatedMozBrowser, - userContextId, - }; + var chan = NetUtil.newChannel({ + uri: url, + loadUsingSystemPrincipal: true, + }).QueryInterface(Ci.nsIHttpChannel); + chan.loadInfo.originAttributes = { inIsolatedMozBrowser, userContextId }; return chan; } // [inIsolatedMozBrowser, userContextId, expected_handlers_called] -var firstTests = [ - [false, 0, 1], [true, 0, 1], [false, 1, 1], [true, 1, 1], -]; -var secondTests = [ - [false, 0, 0], [true, 0, 0], [false, 1, 1], [true, 1, 0], -]; +var firstTests = [[false, 0, 1], [true, 0, 1], [false, 1, 1], [true, 1, 1]]; +var secondTests = [[false, 0, 0], [true, 0, 0], [false, 1, 1], [true, 1, 0]]; async function run_all_tests() { for (let test of firstTests) { @@ -41,11 +37,15 @@ async function run_all_tests() { // We can't easily cause webapp data to be cleared from the child process, so skip // the rest of these tests. - let procType = Cc["@mozilla.org/xre/runtime;1"].getService(Ci.nsIXULRuntime).processType; - if (procType != Ci.nsIXULRuntime.PROCESS_TYPE_DEFAULT) + let procType = Cc["@mozilla.org/xre/runtime;1"].getService(Ci.nsIXULRuntime) + .processType; + if (procType != Ci.nsIXULRuntime.PROCESS_TYPE_DEFAULT) { return; + } - Services.clearData.deleteDataFromOriginAttributesPattern({ userContextId: 1 }); + Services.clearData.deleteDataFromOriginAttributesPattern({ + userContextId: 1, + }); for (let test of secondTests) { handlers_called = 0; @@ -71,7 +71,9 @@ function run_test() { function test_channel(inIsolatedMozBrowser, userContextId, expected) { return new Promise(resolve => { var chan = makeChan(URL, inIsolatedMozBrowser, userContextId); - chan.asyncOpen(new ChannelListener(doneFirstLoad.bind(null, resolve), expected)); + chan.asyncOpen( + new ChannelListener(doneFirstLoad.bind(null, resolve), expected) + ); }); } @@ -79,7 +81,9 @@ function doneFirstLoad(resolve, req, buffer, expected) { // Load it again, make sure it hits the cache var oa = req.loadInfo.originAttributes; var chan = makeChan(URL, oa.isInIsolatedMozBrowserElement, oa.userContextId); - chan.asyncOpen(new ChannelListener(doneSecondLoad.bind(null, resolve), expected)); + chan.asyncOpen( + new ChannelListener(doneSecondLoad.bind(null, resolve), expected) + ); } function doneSecondLoad(resolve, req, buffer, expected) { diff --git a/netwerk/test/unit/test_cacheflags.js b/netwerk/test/unit/test_cacheflags.js index 623be597bc0e..fff7965ed87d 100644 --- a/netwerk/test/unit/test_cacheflags.js +++ b/netwerk/test/unit/test_cacheflags.js @@ -1,5 +1,5 @@ -const {HttpServer} = ChromeUtils.import("resource://testing-common/httpd.js"); -var {Services} = ChromeUtils.import('resource://gre/modules/Services.jsm'); +const { HttpServer } = ChromeUtils.import("resource://testing-common/httpd.js"); +var { Services } = ChromeUtils.import("resource://gre/modules/Services.jsm"); var httpserver = new HttpServer(); httpserver.start(-1); @@ -22,13 +22,16 @@ function make_channel(url, flags, usePrivateBrowsing) { var securityFlags = Ci.nsILoadInfo.SEC_ALLOW_CROSS_ORIGIN_DATA_IS_NULL; var uri = Services.io.newURI(url); - var principal = Services.scriptSecurityManager.createCodebasePrincipal(uri, - { privateBrowsingId : usePrivateBrowsing ? 1 : 0 }); + var principal = Services.scriptSecurityManager.createCodebasePrincipal(uri, { + privateBrowsingId: usePrivateBrowsing ? 1 : 0, + }); - var req = NetUtil.newChannel({uri, - loadingPrincipal: principal, - securityFlags, - contentPolicyType: Ci.nsIContentPolicy.TYPE_OTHER}); + var req = NetUtil.newChannel({ + uri, + loadingPrincipal: principal, + securityFlags, + contentPolicyType: Ci.nsIContentPolicy.TYPE_OTHER, + }); req.loadFlags = flags; if (usePrivateBrowsing) { @@ -37,8 +40,14 @@ function make_channel(url, flags, usePrivateBrowsing) { return req; } -function Test(path, flags, expectSuccess, readFromCache, hitServer, - usePrivateBrowsing /* defaults to false */) { +function Test( + path, + flags, + expectSuccess, + readFromCache, + hitServer, + usePrivateBrowsing /* defaults to false */ +) { this.path = path; this.flags = flags; this.expectSuccess = expectSuccess; @@ -56,7 +65,10 @@ Test.prototype = { _buffer: "", _isFromCache: false, - QueryInterface: ChromeUtils.generateQI(["nsIStreamListener", "nsIRequestObserver"]), + QueryInterface: ChromeUtils.generateQI([ + "nsIStreamListener", + "nsIRequestObserver", + ]), onStartRequest(request) { var cachingChannel = request.QueryInterface(Ci.nsICacheInfoChannel); @@ -76,113 +88,173 @@ Test.prototype = { }, run() { - dump("Running:" + - "\n " + this.path + - "\n " + this.flags + - "\n " + this.expectSuccess + - "\n " + this.readFromCache + - "\n " + this.hitServer + "\n"); + dump( + "Running:" + + "\n " + + this.path + + "\n " + + this.flags + + "\n " + + this.expectSuccess + + "\n " + + this.readFromCache + + "\n " + + this.hitServer + + "\n" + ); gHitServer = false; var channel = make_channel(this.path, this.flags, this.usePrivateBrowsing); channel.asyncOpen(this); - } + }, }; var gHitServer = false; var gTests = [ + new Test( + httpBase + shortexpPath, + 0, + true, // expect success + false, // read from cache + true, // hit server + true + ), // USE PRIVATE BROWSING, so not cached for later requests + new Test( + httpBase + shortexpPath, + 0, + true, // expect success + false, // read from cache + true + ), // hit server + new Test( + httpBase + shortexpPath, + 0, + true, // expect success + true, // read from cache + true + ), // hit server + new Test( + httpBase + shortexpPath, + Ci.nsIRequest.LOAD_BYPASS_CACHE, + true, // expect success + false, // read from cache + true + ), // hit server + new Test( + httpBase + shortexpPath, + Ci.nsICachingChannel.LOAD_ONLY_FROM_CACHE, + false, // expect success + false, // read from cache + false + ), // hit server + new Test( + httpBase + shortexpPath, + Ci.nsICachingChannel.LOAD_ONLY_FROM_CACHE | Ci.nsIRequest.VALIDATE_NEVER, + true, // expect success + true, // read from cache + false + ), // hit server + new Test( + httpBase + shortexpPath, + Ci.nsIRequest.LOAD_FROM_CACHE, + true, // expect success + true, // read from cache + false + ), // hit server - new Test(httpBase + shortexpPath, 0, - true, // expect success - false, // read from cache - true, // hit server - true), // USE PRIVATE BROWSING, so not cached for later requests - new Test(httpBase + shortexpPath, 0, - true, // expect success - false, // read from cache - true), // hit server - new Test(httpBase + shortexpPath, 0, - true, // expect success - true, // read from cache - true), // hit server - new Test(httpBase + shortexpPath, Ci.nsIRequest.LOAD_BYPASS_CACHE, - true, // expect success - false, // read from cache - true), // hit server - new Test(httpBase + shortexpPath, Ci.nsICachingChannel.LOAD_ONLY_FROM_CACHE, - false, // expect success - false, // read from cache - false), // hit server - new Test(httpBase + shortexpPath, - Ci.nsICachingChannel.LOAD_ONLY_FROM_CACHE | - Ci.nsIRequest.VALIDATE_NEVER, - true, // expect success - true, // read from cache - false), // hit server - new Test(httpBase + shortexpPath, Ci.nsIRequest.LOAD_FROM_CACHE, - true, // expect success - true, // read from cache - false), // hit server + new Test( + httpBase + longexpPath, + 0, + true, // expect success + false, // read from cache + true + ), // hit server + new Test( + httpBase + longexpPath, + 0, + true, // expect success + true, // read from cache + false + ), // hit server + new Test( + httpBase + longexpPath, + Ci.nsIRequest.LOAD_BYPASS_CACHE, + true, // expect success + false, // read from cache + true + ), // hit server + new Test( + httpBase + longexpPath, + Ci.nsIRequest.VALIDATE_ALWAYS, + true, // expect success + true, // read from cache + true + ), // hit server + new Test( + httpBase + longexpPath, + Ci.nsICachingChannel.LOAD_ONLY_FROM_CACHE, + true, // expect success + true, // read from cache + false + ), // hit server + new Test( + httpBase + longexpPath, + Ci.nsICachingChannel.LOAD_ONLY_FROM_CACHE | Ci.nsIRequest.VALIDATE_NEVER, + true, // expect success + true, // read from cache + false + ), // hit server + new Test( + httpBase + longexpPath, + Ci.nsICachingChannel.LOAD_ONLY_FROM_CACHE | Ci.nsIRequest.VALIDATE_ALWAYS, + false, // expect success + false, // read from cache + false + ), // hit server + new Test( + httpBase + longexpPath, + Ci.nsIRequest.LOAD_FROM_CACHE, + true, // expect success + true, // read from cache + false + ), // hit server - new Test(httpBase + longexpPath, 0, - true, // expect success - false, // read from cache - true), // hit server - new Test(httpBase + longexpPath, 0, - true, // expect success - true, // read from cache - false), // hit server - new Test(httpBase + longexpPath, Ci.nsIRequest.LOAD_BYPASS_CACHE, - true, // expect success - false, // read from cache - true), // hit server - new Test(httpBase + longexpPath, - Ci.nsIRequest.VALIDATE_ALWAYS, - true, // expect success - true, // read from cache - true), // hit server - new Test(httpBase + longexpPath, Ci.nsICachingChannel.LOAD_ONLY_FROM_CACHE, - true, // expect success - true, // read from cache - false), // hit server - new Test(httpBase + longexpPath, - Ci.nsICachingChannel.LOAD_ONLY_FROM_CACHE | - Ci.nsIRequest.VALIDATE_NEVER, - true, // expect success - true, // read from cache - false), // hit server - new Test(httpBase + longexpPath, - Ci.nsICachingChannel.LOAD_ONLY_FROM_CACHE | - Ci.nsIRequest.VALIDATE_ALWAYS, - false, // expect success - false, // read from cache - false), // hit server - new Test(httpBase + longexpPath, Ci.nsIRequest.LOAD_FROM_CACHE, - true, // expect success - true, // read from cache - false), // hit server + new Test( + httpBase + longexp2Path, + 0, + true, // expect success + false, // read from cache + true + ), // hit server + new Test( + httpBase + longexp2Path, + 0, + true, // expect success + true, // read from cache + false + ), // hit server - new Test(httpBase + longexp2Path, 0, - true, // expect success - false, // read from cache - true), // hit server - new Test(httpBase + longexp2Path, 0, - true, // expect success - true, // read from cache - false), // hit server - - new Test(httpBase + nocachePath, 0, - true, // expect success - false, // read from cache - true), // hit server - new Test(httpBase + nocachePath, 0, - true, // expect success - true, // read from cache - true), // hit server - new Test(httpBase + nocachePath, Ci.nsICachingChannel.LOAD_ONLY_FROM_CACHE, - false, // expect success - false, // read from cache - false), // hit server + new Test( + httpBase + nocachePath, + 0, + true, // expect success + false, // read from cache + true + ), // hit server + new Test( + httpBase + nocachePath, + 0, + true, // expect success + true, // read from cache + true + ), // hit server + new Test( + httpBase + nocachePath, + Ci.nsICachingChannel.LOAD_ONLY_FROM_CACHE, + false, // expect success + false, // read from cache + false + ), // hit server // CACHE2: mayhemer - entry is doomed... I think the logic is wrong, we should not doom them // as they are not valid, but take them as they need to reval @@ -195,12 +267,13 @@ var gTests = [ // LOAD_ONLY_FROM_CACHE would normally fail (because no-cache forces // a validation), but VALIDATE_NEVER should override that. - new Test(httpBase + nocachePath, - Ci.nsICachingChannel.LOAD_ONLY_FROM_CACHE | - Ci.nsIRequest.VALIDATE_NEVER, - true, // expect success - true, // read from cache - false), // hit server + new Test( + httpBase + nocachePath, + Ci.nsICachingChannel.LOAD_ONLY_FROM_CACHE | Ci.nsIRequest.VALIDATE_NEVER, + true, // expect success + true, // read from cache + false + ), // hit server // ... however, no-cache over ssl should act like no-store and force // a validation (and therefore failure) even if VALIDATE_NEVER is @@ -215,52 +288,76 @@ var gTests = [ false) // hit server */ - new Test(httpBase + nostorePath, 0, - true, // expect success - false, // read from cache - true), // hit server - new Test(httpBase + nostorePath, 0, - true, // expect success - false, // read from cache - true), // hit server - new Test(httpBase + nostorePath, Ci.nsICachingChannel.LOAD_ONLY_FROM_CACHE, - false, // expect success - false, // read from cache - false), // hit server - new Test(httpBase + nostorePath, Ci.nsIRequest.LOAD_FROM_CACHE, - true, // expect success - true, // read from cache - false), // hit server + new Test( + httpBase + nostorePath, + 0, + true, // expect success + false, // read from cache + true + ), // hit server + new Test( + httpBase + nostorePath, + 0, + true, // expect success + false, // read from cache + true + ), // hit server + new Test( + httpBase + nostorePath, + Ci.nsICachingChannel.LOAD_ONLY_FROM_CACHE, + false, // expect success + false, // read from cache + false + ), // hit server + new Test( + httpBase + nostorePath, + Ci.nsIRequest.LOAD_FROM_CACHE, + true, // expect success + true, // read from cache + false + ), // hit server // no-store should force the validation (and therefore failure, with // LOAD_ONLY_FROM_CACHE) even if VALIDATE_NEVER is set. - new Test(httpBase + nostorePath, - Ci.nsICachingChannel.LOAD_ONLY_FROM_CACHE | - Ci.nsIRequest.VALIDATE_NEVER, - false, // expect success - false, // read from cache - false), // hit server + new Test( + httpBase + nostorePath, + Ci.nsICachingChannel.LOAD_ONLY_FROM_CACHE | Ci.nsIRequest.VALIDATE_NEVER, + false, // expect success + false, // read from cache + false + ), // hit server - new Test(httpBase + test410Path, 0, - true, // expect success - false, // read from cache - true), // hit server - new Test(httpBase + test410Path, 0, - true, // expect success - true, // read from cache - false), // hit server + new Test( + httpBase + test410Path, + 0, + true, // expect success + false, // read from cache + true + ), // hit server + new Test( + httpBase + test410Path, + 0, + true, // expect success + true, // read from cache + false + ), // hit server - new Test(httpBase + test404Path, 0, - true, // expect success - false, // read from cache - true), // hit server - new Test(httpBase + test404Path, 0, - true, // expect success - false, // read from cache - true) // hit server + new Test( + httpBase + test404Path, + 0, + true, // expect success + false, // read from cache + true + ), // hit server + new Test( + httpBase + test404Path, + 0, + true, // expect success + false, // read from cache + true + ), // hit server ]; -function run_next_test() -{ +function run_next_test() { if (gTests.length == 0) { httpserver.stop(do_test_finished); return; @@ -274,7 +371,7 @@ function handler(httpStatus, metadata, response) { gHitServer = true; try { var etag = metadata.getHeader("If-None-Match"); - } catch(ex) { + } catch (ex) { var etag = ""; } if (etag == "testtag") { diff --git a/netwerk/test/unit/test_captive_portal_service.js b/netwerk/test/unit/test_captive_portal_service.js index 2f88528f4289..6cd3f50b6c5f 100644 --- a/netwerk/test/unit/test_captive_portal_service.js +++ b/netwerk/test/unit/test_captive_portal_service.js @@ -1,6 +1,6 @@ "use strict"; -const {HttpServer} = ChromeUtils.import("resource://testing-common/httpd.js"); +const { HttpServer } = ChromeUtils.import("resource://testing-common/httpd.js"); let httpserver = null; XPCOMUtils.defineLazyGetter(this, "cpURI", function() { @@ -9,8 +9,7 @@ XPCOMUtils.defineLazyGetter(this, "cpURI", function() { const SUCCESS_STRING = "success\n"; let cpResponse = SUCCESS_STRING; -function contentHandler(metadata, response) -{ +function contentHandler(metadata, response) { response.setHeader("Content-Type", "text/plain"); response.bodyOutputStream.write(cpResponse, cpResponse.length); } @@ -22,8 +21,9 @@ const PREF_CAPTIVE_MINTIME = "network.captive-portal-service.minInterval"; const PREF_CAPTIVE_MAXTIME = "network.captive-portal-service.maxInterval"; const PREF_DNS_NATIVE_IS_LOCALHOST = "network.dns.native-is-localhost"; -const cps = Cc["@mozilla.org/network/captive-portal-service;1"] - .getService(Ci.nsICaptivePortalService); +const cps = Cc["@mozilla.org/network/captive-portal-service;1"].getService( + Ci.nsICaptivePortalService +); registerCleanupFunction(async () => { Services.prefs.clearUserPref(PREF_CAPTIVE_ENABLED); @@ -47,13 +47,13 @@ function observerPromise(topic) { Services.obs.removeObserver(observer, topic); resolve(aData); } - } - } + }, + }; Services.obs.addObserver(observer, topic); }); } -add_task(function setup(){ +add_task(function setup() { httpserver = new HttpServer(); httpserver.registerPathHandler("/captive.txt", contentHandler); httpserver.start(-1); @@ -65,8 +65,7 @@ add_task(function setup(){ Services.prefs.setBoolPref(PREF_DNS_NATIVE_IS_LOCALHOST, true); }); -add_task(async function test_simple() -{ +add_task(async function test_simple() { Services.prefs.setBoolPref(PREF_CAPTIVE_ENABLED, false); equal(cps.state, Ci.nsICaptivePortalService.UNKNOWN); @@ -95,8 +94,7 @@ add_task(async function test_simple() // This test redirects to another URL which returns the same content. // It should still be interpreted as a captive portal. -add_task(async function test_redirect_success() -{ +add_task(async function test_redirect_success() { Services.prefs.setBoolPref(PREF_CAPTIVE_ENABLED, false); equal(cps.state, Ci.nsICaptivePortalService.UNKNOWN); @@ -106,16 +104,27 @@ add_task(async function test_redirect_success() }); httpserver.registerPathHandler("/captive.txt", (metadata, response) => { response.setStatusLine(metadata.httpVersion, 307, "Moved Temporarily"); - response.setHeader("Location", `http://localhost:${httpserver.identity.primaryPort}/succ.txt`); + response.setHeader( + "Location", + `http://localhost:${httpserver.identity.primaryPort}/succ.txt` + ); }); - let notification = observerPromise("captive-portal-login").then(() => "login"); - let succNotif = observerPromise("network:captive-portal-connectivity").then(() => "connectivity"); + let notification = observerPromise("captive-portal-login").then( + () => "login" + ); + let succNotif = observerPromise("network:captive-portal-connectivity").then( + () => "connectivity" + ); Services.prefs.setBoolPref(PREF_CAPTIVE_ENABLED, true); let winner = await Promise.race([notification, succNotif]); equal(winner, "login", "This should have been a login, not a success"); - equal(cps.state, Ci.nsICaptivePortalService.LOCKED_PORTAL, "Should be locked after redirect to same text"); + equal( + cps.state, + Ci.nsICaptivePortalService.LOCKED_PORTAL, + "Should be locked after redirect to same text" + ); }); // This redirects to another URI with a different content. @@ -131,14 +140,21 @@ add_task(async function test_redirect_bad() { httpserver.registerPathHandler("/captive.txt", (metadata, response) => { response.setStatusLine(metadata.httpVersion, 307, "Moved Temporarily"); - response.setHeader("Location", `http://localhost:${httpserver.identity.primaryPort}/bad.txt`); + response.setHeader( + "Location", + `http://localhost:${httpserver.identity.primaryPort}/bad.txt` + ); }); let notification = observerPromise("captive-portal-login"); Services.prefs.setBoolPref(PREF_CAPTIVE_ENABLED, true); await notification; - equal(cps.state, Ci.nsICaptivePortalService.LOCKED_PORTAL, "Should be locked after redirect to bad text"); + equal( + cps.state, + Ci.nsICaptivePortalService.LOCKED_PORTAL, + "Should be locked after redirect to bad text" + ); }); // This redirects to the same URI. @@ -167,8 +183,8 @@ add_task(async function test_redirect_https() { equal(cps.state, Ci.nsICaptivePortalService.UNKNOWN); let h2Port = Cc["@mozilla.org/process/environment;1"] - .getService(Ci.nsIEnvironment) - .get("MOZHTTP2_PORT"); + .getService(Ci.nsIEnvironment) + .get("MOZHTTP2_PORT"); Assert.notEqual(h2Port, null); Assert.notEqual(h2Port, ""); @@ -182,6 +198,10 @@ add_task(async function test_redirect_https() { Services.prefs.setBoolPref(PREF_CAPTIVE_ENABLED, true); await notification; - equal(cps.state, Ci.nsICaptivePortalService.LOCKED_PORTAL, "Should be locked after redirect to https"); + equal( + cps.state, + Ci.nsICaptivePortalService.LOCKED_PORTAL, + "Should be locked after redirect to https" + ); Services.prefs.setBoolPref(PREF_CAPTIVE_ENABLED, false); }); diff --git a/netwerk/test/unit/test_channel_close.js b/netwerk/test/unit/test_channel_close.js index 548a448dfab8..82b73e3189b4 100644 --- a/netwerk/test/unit/test_channel_close.js +++ b/netwerk/test/unit/test_channel_close.js @@ -1,7 +1,8 @@ -const {HttpServer} = ChromeUtils.import("resource://testing-common/httpd.js"); +const { HttpServer } = ChromeUtils.import("resource://testing-common/httpd.js"); -var httpProtocolHandler = Cc["@mozilla.org/network/protocol;1?name=http"] - .getService(Ci.nsIHttpProtocolHandler); +var httpProtocolHandler = Cc[ + "@mozilla.org/network/protocol;1?name=http" +].getService(Ci.nsIHttpProtocolHandler); XPCOMUtils.defineLazyGetter(this, "URL", function() { return "http://localhost:" + httpserver.identity.primaryPort; @@ -32,7 +33,9 @@ function run_test() { // Opened channel that has remaining references on shutdown live_channels.push(setupChannel(testpath)); - live_channels[1].asyncOpen(new ChannelListener(checkRequestFinish, live_channels[1])); + live_channels[1].asyncOpen( + new ChannelListener(checkRequestFinish, live_channels[1]) + ); }); do_test_pending(); @@ -41,7 +44,7 @@ function run_test() { function setupChannel(path) { var chan = NetUtil.newChannel({ uri: URL + path, - loadUsingSystemPrincipal: true + loadUsingSystemPrincipal: true, }); chan.QueryInterface(Ci.nsIHttpChannel); chan.requestMethod = "GET"; diff --git a/netwerk/test/unit/test_channel_priority.js b/netwerk/test/unit/test_channel_priority.js index 41ebf8cdeffe..896a5e78a109 100644 --- a/netwerk/test/unit/test_channel_priority.js +++ b/netwerk/test/unit/test_channel_priority.js @@ -6,11 +6,11 @@ /* globals runningInParent, do_send_remote_message */ /* globals ChannelListener */ -'use strict'; +"use strict"; /* globals NetUtil*/ /* globals HttpServer */ -const {HttpServer} = ChromeUtils.import('resource://testing-common/httpd.js'); +const { HttpServer } = ChromeUtils.import("resource://testing-common/httpd.js"); let httpserver; let port; @@ -18,17 +18,17 @@ let port; function startHttpServer() { httpserver = new HttpServer(); - httpserver.registerPathHandler('/resource', (metadata, response) => { - response.setStatusLine(metadata.httpVersion, 200, 'OK'); - response.setHeader('Content-Type', 'text/plain', false); - response.setHeader('Cache-Control', 'no-cache', false); + httpserver.registerPathHandler("/resource", (metadata, response) => { + response.setStatusLine(metadata.httpVersion, 200, "OK"); + response.setHeader("Content-Type", "text/plain", false); + response.setHeader("Cache-Control", "no-cache", false); response.bodyOutputStream.write("data", 4); }); - httpserver.registerPathHandler('/redirect', (metadata, response) => { - response.setStatusLine(metadata.httpVersion, 302, 'Redirect'); - response.setHeader('Location', '/resource', false); - response.setHeader('Cache-Control', 'no-cache', false); + httpserver.registerPathHandler("/redirect", (metadata, response) => { + response.setStatusLine(metadata.httpVersion, 302, "Redirect"); + response.setHeader("Location", "/resource", false); + response.setHeader("Cache-Control", "no-cache", false); }); httpserver.start(-1); @@ -36,11 +36,14 @@ function startHttpServer() { } function stopHttpServer() { - httpserver.stop(()=>{}); + httpserver.stop(() => {}); } function makeRequest(uri) { - let requestChannel = NetUtil.newChannel({uri, loadUsingSystemPrincipal: true}); + let requestChannel = NetUtil.newChannel({ + uri, + loadUsingSystemPrincipal: true, + }); requestChannel.QueryInterface(Ci.nsISupportsPriority); requestChannel.priority = Ci.nsISupportsPriority.PRIORITY_HIGHEST; requestChannel.asyncOpen(new ChannelListener(checkResponse, requestChannel)); @@ -48,11 +51,17 @@ function makeRequest(uri) { function checkResponse(request, buffer, requestChannel) { requestChannel.QueryInterface(Ci.nsISupportsPriority); - Assert.equal(requestChannel.priority, Ci.nsISupportsPriority.PRIORITY_HIGHEST); + Assert.equal( + requestChannel.priority, + Ci.nsISupportsPriority.PRIORITY_HIGHEST + ); // the response channel can be different (if it was redirected) let responseChannel = request.QueryInterface(Ci.nsISupportsPriority); - Assert.equal(responseChannel.priority, Ci.nsISupportsPriority.PRIORITY_HIGHEST); + Assert.equal( + responseChannel.priority, + Ci.nsISupportsPriority.PRIORITY_HIGHEST + ); run_next_test(); } @@ -65,12 +74,13 @@ add_test(function test_redirect() { makeRequest(`http://localhost:${port}/redirect`); }); -function run_test() { // jshint ignore:line +function run_test() { + // jshint ignore:line if (!runningInParent) { // add a task to report test finished to parent process at the end of test queue, // since do_register_cleanup is not available in child xpcshell test script. - add_test(function () { - do_send_remote_message('finished'); + add_test(function() { + do_send_remote_message("finished"); run_next_test(); }); @@ -84,7 +94,8 @@ function run_test() { // jshint ignore:line } // This is used by unit_ipc/test_channel_priority_wrap.js for e10s XPCShell test -function configPort(serverPort) { // jshint ignore:line +function configPort(serverPort) { + // jshint ignore:line port = serverPort; run_next_test(); } diff --git a/netwerk/test/unit/test_chunked_responses.js b/netwerk/test/unit/test_chunked_responses.js index 2ed811530866..59adf3f485d6 100644 --- a/netwerk/test/unit/test_chunked_responses.js +++ b/netwerk/test/unit/test_chunked_responses.js @@ -11,7 +11,7 @@ "use strict"; -const {HttpServer} = ChromeUtils.import("resource://testing-common/httpd.js"); +const { HttpServer } = ChromeUtils.import("resource://testing-common/httpd.js"); Services.prefs.setBoolPref("security.allow_eval_with_system_principal", true); registerCleanupFunction(() => { @@ -27,47 +27,43 @@ var index = 0; var test_flags = new Array(); var testPathBase = "/chunked_hdrs"; -function run_test() -{ +function run_test() { httpserver.start(-1); do_test_pending(); run_test_number(1); } -function run_test_number(num) -{ +function run_test_number(num) { var testPath = testPathBase + num; httpserver.registerPathHandler(testPath, eval("handler" + num)); var channel = setupChannel(testPath); - var flags = test_flags[num]; // OK if flags undefined for test - channel.asyncOpen(new ChannelListener(eval("completeTest" + num), - channel, flags)); + var flags = test_flags[num]; // OK if flags undefined for test + channel.asyncOpen( + new ChannelListener(eval("completeTest" + num), channel, flags) + ); } -function setupChannel(url) -{ +function setupChannel(url) { var chan = NetUtil.newChannel({ uri: URL + url, - loadUsingSystemPrincipal: true + loadUsingSystemPrincipal: true, }); var httpChan = chan.QueryInterface(Ci.nsIHttpChannel); return httpChan; } -function endTests() -{ +function endTests() { httpserver.stop(do_test_finished); } //////////////////////////////////////////////////////////////////////////////// // Test 1: FAIL because of overflowed chunked size. The parser uses long so // the test case uses >64bit to fail on all platforms. -test_flags[1] = CL_EXPECT_LATE_FAILURE|CL_ALLOW_UNKNOWN_CL; +test_flags[1] = CL_EXPECT_LATE_FAILURE | CL_ALLOW_UNKNOWN_CL; -function handler1(metadata, response) -{ +function handler1(metadata, response) { var body = "12345678123456789\r\ndata never reached"; response.seizePower(); @@ -79,8 +75,7 @@ function handler1(metadata, response) response.finish(); } -function completeTest1(request, data, ctx) -{ +function completeTest1(request, data, ctx) { Assert.equal(request.status, Cr.NS_ERROR_UNEXPECTED); run_test_number(2); @@ -89,10 +84,9 @@ function completeTest1(request, data, ctx) //////////////////////////////////////////////////////////////////////////////// // Test 2: FAIL because of non-hex in chunked length -test_flags[2] = CL_EXPECT_LATE_FAILURE|CL_ALLOW_UNKNOWN_CL; +test_flags[2] = CL_EXPECT_LATE_FAILURE | CL_ALLOW_UNKNOWN_CL; -function handler2(metadata, response) -{ +function handler2(metadata, response) { var body = "junkintheway 123\r\ndata never reached"; response.seizePower(); @@ -104,8 +98,7 @@ function handler2(metadata, response) response.finish(); } -function completeTest2(request, data, ctx) -{ +function completeTest2(request, data, ctx) { Assert.equal(request.status, Cr.NS_ERROR_UNEXPECTED); run_test_number(3); } @@ -115,8 +108,7 @@ function completeTest2(request, data, ctx) test_flags[3] = CL_ALLOW_UNKNOWN_CL; -function handler3(metadata, response) -{ +function handler3(metadata, response) { var body = "c junkafter\r\ndata reached\r\n0\r\n\r\n"; response.seizePower(); @@ -128,8 +120,7 @@ function handler3(metadata, response) response.finish(); } -function completeTest3(request, data, ctx) -{ +function completeTest3(request, data, ctx) { Assert.equal(request.status, 0); run_test_number(4); } @@ -139,8 +130,7 @@ function completeTest3(request, data, ctx) test_flags[4] = CL_ALLOW_UNKNOWN_CL; -function handler4(metadata, response) -{ +function handler4(metadata, response) { var body = "c\r\ndata reached\r\n3\r\nhej\r\n0\r\n\r\n"; response.seizePower(); @@ -152,8 +142,7 @@ function handler4(metadata, response) response.finish(); } -function completeTest4(request, data, ctx) -{ +function completeTest4(request, data, ctx) { Assert.equal(request.status, 0); run_test_number(5); } @@ -162,10 +151,9 @@ function completeTest4(request, data, ctx) // Test 5: A chunk size larger than 32 bit but smaller than 64bit also fails // This is probabaly subject to get improved at some point. -test_flags[5] = CL_EXPECT_LATE_FAILURE|CL_ALLOW_UNKNOWN_CL; +test_flags[5] = CL_EXPECT_LATE_FAILURE | CL_ALLOW_UNKNOWN_CL; -function handler5(metadata, response) -{ +function handler5(metadata, response) { var body = "123456781\r\ndata never reached"; response.seizePower(); @@ -177,9 +165,8 @@ function handler5(metadata, response) response.finish(); } -function completeTest5(request, data, ctx) -{ +function completeTest5(request, data, ctx) { Assert.equal(request.status, Cr.NS_ERROR_UNEXPECTED); endTests(); -// run_test_number(6); + // run_test_number(6); } diff --git a/netwerk/test/unit/test_compareURIs.js b/netwerk/test/unit/test_compareURIs.js index 6a978b36f5c9..4826e77b281d 100644 --- a/netwerk/test/unit/test_compareURIs.js +++ b/netwerk/test/unit/test_compareURIs.js @@ -1,48 +1,58 @@ - function do_info(text, stack) { - if (!stack) + if (!stack) { stack = Components.stack.caller; + } - dump("TEST-INFO | " + stack.filename + " | [" + stack.name + " : " + - stack.lineNumber + "] " + text + "\n"); + dump( + "TEST-INFO | " + + stack.filename + + " | [" + + stack.name + + " : " + + stack.lineNumber + + "] " + + text + + "\n" + ); } -function run_test() -{ - var tests = [ - [ "http://mozilla.org/", "http://mozilla.org/somewhere/there", true ], - [ "http://mozilla.org/", "http://www.mozilla.org/", false ], - [ "http://mozilla.org/", "http://mozilla.org:80", true ], - [ "http://mozilla.org/", "http://mozilla.org:90", false ], - [ "http://mozilla.org", "https://mozilla.org", false ], - [ "http://mozilla.org", "https://mozilla.org:80", false ], - [ "http://mozilla.org:443", "https://mozilla.org", false ], - [ "https://mozilla.org:443", "https://mozilla.org", true ], - [ "https://mozilla.org:443", "https://mozilla.org/somewhere/", true ], - [ "about:", "about:", false ], - [ "data:text/plain,text", "data:text/plain,text", false ], - [ "about:blank", "about:blank", false ], - [ "about:", "http://mozilla.org/", false ], - [ "about:", "about:config", false ], - [ "about:text/plain,text", "data:text/plain,text", false ], - [ "jar:http://mozilla.org/!/", "http://mozilla.org/", true ], - [ "view-source:http://mozilla.org/", "http://mozilla.org/", true ] - ]; +function run_test() { + var tests = [ + ["http://mozilla.org/", "http://mozilla.org/somewhere/there", true], + ["http://mozilla.org/", "http://www.mozilla.org/", false], + ["http://mozilla.org/", "http://mozilla.org:80", true], + ["http://mozilla.org/", "http://mozilla.org:90", false], + ["http://mozilla.org", "https://mozilla.org", false], + ["http://mozilla.org", "https://mozilla.org:80", false], + ["http://mozilla.org:443", "https://mozilla.org", false], + ["https://mozilla.org:443", "https://mozilla.org", true], + ["https://mozilla.org:443", "https://mozilla.org/somewhere/", true], + ["about:", "about:", false], + ["data:text/plain,text", "data:text/plain,text", false], + ["about:blank", "about:blank", false], + ["about:", "http://mozilla.org/", false], + ["about:", "about:config", false], + ["about:text/plain,text", "data:text/plain,text", false], + ["jar:http://mozilla.org/!/", "http://mozilla.org/", true], + ["view-source:http://mozilla.org/", "http://mozilla.org/", true], + ]; - var secman = Cc["@mozilla.org/scriptsecuritymanager;1"].getService(Ci.nsIScriptSecurityManager); + var secman = Cc["@mozilla.org/scriptsecuritymanager;1"].getService( + Ci.nsIScriptSecurityManager + ); - tests.forEach(function(aTest) { - do_info("Comparing " + aTest[0] + " to " + aTest[1]); + tests.forEach(function(aTest) { + do_info("Comparing " + aTest[0] + " to " + aTest[1]); - var uri1 = NetUtil.newURI(aTest[0]); - var uri2 = NetUtil.newURI(aTest[1]); + var uri1 = NetUtil.newURI(aTest[0]); + var uri2 = NetUtil.newURI(aTest[1]); - var equal; - try { - secman.checkSameOriginURI(uri1, uri2, false, false); - equal = true; - } catch (e) { - equal = false - } - Assert.equal(equal, aTest[2]); - }); + var equal; + try { + secman.checkSameOriginURI(uri1, uri2, false, false); + equal = true; + } catch (e) { + equal = false; + } + Assert.equal(equal, aTest[2]); + }); } diff --git a/netwerk/test/unit/test_compressappend.js b/netwerk/test/unit/test_compressappend.js index df45b08f7bcb..75c570af71d4 100644 --- a/netwerk/test/unit/test_compressappend.js +++ b/netwerk/test/unit/test_compressappend.js @@ -1,20 +1,24 @@ // -// Test that data can be appended to a cache entry even when the data is +// Test that data can be appended to a cache entry even when the data is // compressed by the cache compression feature - bug 648429. // -function write_and_check(str, data, len) -{ +function write_and_check(str, data, len) { var written = str.write(data, len); if (written != len) { - do_throw("str.write has not written all data!\n" + - " Expected: " + len + "\n" + - " Actual: " + written + "\n"); + do_throw( + "str.write has not written all data!\n" + + " Expected: " + + len + + "\n" + + " Actual: " + + written + + "\n" + ); } } -function TestAppend(compress, callback) -{ +function TestAppend(compress, callback) { this._compress = compress; this._callback = callback; this.run(); @@ -26,22 +30,31 @@ TestAppend.prototype = { run() { evict_cache_entries(); - asyncOpenCacheEntry("http://data/", - "disk", Ci.nsICacheStorage.OPEN_NORMALLY, null, - this.writeData.bind(this)); + asyncOpenCacheEntry( + "http://data/", + "disk", + Ci.nsICacheStorage.OPEN_NORMALLY, + null, + this.writeData.bind(this) + ); }, writeData(status, entry) { Assert.equal(status, Cr.NS_OK); - if (this._compress) + if (this._compress) { entry.setMetaDataElement("uncompressed-len", "0"); + } var os = entry.openOutputStream(0, 5); write_and_check(os, "12345", 5); os.close(); entry.close(); - asyncOpenCacheEntry("http://data/", - "disk", Ci.nsICacheStorage.OPEN_NORMALLY, null, - this.appendData.bind(this)); + asyncOpenCacheEntry( + "http://data/", + "disk", + Ci.nsICacheStorage.OPEN_NORMALLY, + null, + this.appendData.bind(this) + ); }, appendData(status, entry) { @@ -51,9 +64,13 @@ TestAppend.prototype = { os.close(); entry.close(); - asyncOpenCacheEntry("http://data/", - "disk", Ci.nsICacheStorage.OPEN_READONLY, null, - this.checkData.bind(this)); + asyncOpenCacheEntry( + "http://data/", + "disk", + Ci.nsICacheStorage.OPEN_READONLY, + null, + this.checkData.bind(this) + ); }, checkData(status, entry) { @@ -66,7 +83,7 @@ TestAppend.prototype = { executeSoon(self._callback); }); - } + }, }; function run_test() { diff --git a/netwerk/test/unit/test_content_encoding_gzip.js b/netwerk/test/unit/test_content_encoding_gzip.js index 28b71323e0b0..cb4412ef817d 100644 --- a/netwerk/test/unit/test_content_encoding_gzip.js +++ b/netwerk/test/unit/test_content_encoding_gzip.js @@ -1,113 +1,208 @@ -const {HttpServer} = ChromeUtils.import("resource://testing-common/httpd.js"); +const { HttpServer } = ChromeUtils.import("resource://testing-common/httpd.js"); var httpserver = new HttpServer(); var index = 0; var tests = [ - {url: "/test/cegzip1", - flags: CL_EXPECT_GZIP, - ce: "gzip", - body: [ - 0x1f, 0x8b, 0x08, 0x08, 0x5a, 0xa0, 0x31, 0x4f, 0x00, 0x03, 0x74, 0x78, 0x74, 0x00, 0x2b, 0xc9, - 0xc8, 0x2c, 0x56, 0x00, 0xa2, 0x92, 0xd4, 0xe2, 0x12, 0x43, 0x2e, 0x00, 0xb9, 0x23, 0xd7, 0x3b, - 0x0e, 0x00, 0x00, 0x00], - datalen: 14 // the data length of the uncompressed document - }, + { + url: "/test/cegzip1", + flags: CL_EXPECT_GZIP, + ce: "gzip", + body: [ + 0x1f, + 0x8b, + 0x08, + 0x08, + 0x5a, + 0xa0, + 0x31, + 0x4f, + 0x00, + 0x03, + 0x74, + 0x78, + 0x74, + 0x00, + 0x2b, + 0xc9, + 0xc8, + 0x2c, + 0x56, + 0x00, + 0xa2, + 0x92, + 0xd4, + 0xe2, + 0x12, + 0x43, + 0x2e, + 0x00, + 0xb9, + 0x23, + 0xd7, + 0x3b, + 0x0e, + 0x00, + 0x00, + 0x00, + ], + datalen: 14, // the data length of the uncompressed document + }, - {url: "/test/cegzip2", - flags: CL_EXPECT_GZIP, - ce: "gzip, gzip", - body: [ - 0x1f, 0x8b, 0x08, 0x00, 0x72, 0xa1, 0x31, 0x4f, 0x00, 0x03, 0x93, 0xef, 0xe6, 0xe0, 0x88, 0x5a, - 0x60, 0xe8, 0xcf, 0xc0, 0x5c, 0x52, 0x51, 0xc2, 0xa0, 0x7d, 0xf2, 0x84, 0x4e, 0x18, 0xc3, 0xa2, - 0x49, 0x57, 0x1e, 0x09, 0x39, 0xeb, 0x31, 0xec, 0x54, 0xbe, 0x6e, 0xcd, 0xc7, 0xc0, 0xc0, 0x00, - 0x00, 0x6e, 0x90, 0x7a, 0x85, 0x24, 0x00, 0x00, 0x00], - datalen: 14 // the data length of the uncompressed document - }, + { + url: "/test/cegzip2", + flags: CL_EXPECT_GZIP, + ce: "gzip, gzip", + body: [ + 0x1f, + 0x8b, + 0x08, + 0x00, + 0x72, + 0xa1, + 0x31, + 0x4f, + 0x00, + 0x03, + 0x93, + 0xef, + 0xe6, + 0xe0, + 0x88, + 0x5a, + 0x60, + 0xe8, + 0xcf, + 0xc0, + 0x5c, + 0x52, + 0x51, + 0xc2, + 0xa0, + 0x7d, + 0xf2, + 0x84, + 0x4e, + 0x18, + 0xc3, + 0xa2, + 0x49, + 0x57, + 0x1e, + 0x09, + 0x39, + 0xeb, + 0x31, + 0xec, + 0x54, + 0xbe, + 0x6e, + 0xcd, + 0xc7, + 0xc0, + 0xc0, + 0x00, + 0x00, + 0x6e, + 0x90, + 0x7a, + 0x85, + 0x24, + 0x00, + 0x00, + 0x00, + ], + datalen: 14, // the data length of the uncompressed document + }, - {url: "/test/cebrotli1", - flags: CL_EXPECT_GZIP, - ce: "br", - body: [0x0B, 0x02, 0x80, 0x74, 0x65, 0x73, 0x74, 0x0A, 0x03], + { + url: "/test/cebrotli1", + flags: CL_EXPECT_GZIP, + ce: "br", + body: [0x0b, 0x02, 0x80, 0x74, 0x65, 0x73, 0x74, 0x0a, 0x03], - datalen: 5 // the data length of the uncompressed document - }, + datalen: 5, // the data length of the uncompressed document + }, - // this is not a brotli document - {url: "/test/cebrotli2", - flags: CL_EXPECT_GZIP | CL_EXPECT_FAILURE, - ce: "br", - body: [0x0B, 0x0A, 0x09], - datalen: 3 - }, + // this is not a brotli document + { + url: "/test/cebrotli2", + flags: CL_EXPECT_GZIP | CL_EXPECT_FAILURE, + ce: "br", + body: [0x0b, 0x0a, 0x09], + datalen: 3, + }, - // this is brotli but should come through as identity due to prefs - {url: "/test/cebrotli3", - flags: 0, - ce: "br", - body: [0x0B, 0x02, 0x80, 0x74, 0x65, 0x73, 0x74, 0x0A, 0x03], + // this is brotli but should come through as identity due to prefs + { + url: "/test/cebrotli3", + flags: 0, + ce: "br", + body: [0x0b, 0x02, 0x80, 0x74, 0x65, 0x73, 0x74, 0x0a, 0x03], - datalen: 9 - }, + datalen: 9, + }, ]; function setupChannel(url) { - return NetUtil.newChannel({ - uri: "http://localhost:" + httpserver.identity.primaryPort + url, - loadUsingSystemPrincipal: true - }); + return NetUtil.newChannel({ + uri: "http://localhost:" + httpserver.identity.primaryPort + url, + loadUsingSystemPrincipal: true, + }); } function startIter() { - if (tests[index].url === "/test/cebrotli3") { - // this test wants to make sure we don't do brotli when not in a-e - prefs.setCharPref("network.http.accept-encoding", "gzip, deflate"); - } - var channel = setupChannel(tests[index].url); - channel.asyncOpen(new ChannelListener(completeIter, channel, tests[index].flags)); + if (tests[index].url === "/test/cebrotli3") { + // this test wants to make sure we don't do brotli when not in a-e + prefs.setCharPref("network.http.accept-encoding", "gzip, deflate"); + } + var channel = setupChannel(tests[index].url); + channel.asyncOpen( + new ChannelListener(completeIter, channel, tests[index].flags) + ); } function completeIter(request, data, ctx) { - if (!(tests[index].flags & CL_EXPECT_FAILURE)) { - Assert.equal(data.length, tests[index].datalen); - } - if (++index < tests.length) { - startIter(); - } else { - httpserver.stop(do_test_finished); - prefs.setCharPref("network.http.accept-encoding", cePref); - } + if (!(tests[index].flags & CL_EXPECT_FAILURE)) { + Assert.equal(data.length, tests[index].datalen); + } + if (++index < tests.length) { + startIter(); + } else { + httpserver.stop(do_test_finished); + prefs.setCharPref("network.http.accept-encoding", cePref); + } } var prefs; var cePref; function run_test() { - prefs = Cc["@mozilla.org/preferences-service;1"].getService(Ci.nsIPrefBranch); - cePref = prefs.getCharPref("network.http.accept-encoding"); - prefs.setCharPref("network.http.accept-encoding", "gzip, deflate, br"); + prefs = Cc["@mozilla.org/preferences-service;1"].getService(Ci.nsIPrefBranch); + cePref = prefs.getCharPref("network.http.accept-encoding"); + prefs.setCharPref("network.http.accept-encoding", "gzip, deflate, br"); - httpserver.registerPathHandler("/test/cegzip1", handler); - httpserver.registerPathHandler("/test/cegzip2", handler); - httpserver.registerPathHandler("/test/cebrotli1", handler); - httpserver.registerPathHandler("/test/cebrotli2", handler); - httpserver.registerPathHandler("/test/cebrotli3", handler); - httpserver.start(-1); + httpserver.registerPathHandler("/test/cegzip1", handler); + httpserver.registerPathHandler("/test/cegzip2", handler); + httpserver.registerPathHandler("/test/cebrotli1", handler); + httpserver.registerPathHandler("/test/cebrotli2", handler); + httpserver.registerPathHandler("/test/cebrotli3", handler); + httpserver.start(-1); - startIter(); - do_test_pending(); + startIter(); + do_test_pending(); } function handler(metadata, response) { - response.setStatusLine(metadata.httpVersion, 200, "OK"); - response.setHeader("Content-Type", "text/plain", false); - response.setHeader("Content-Encoding", tests[index].ce, false); - response.setHeader("Content-Length", "" + tests[index].body.length, false); - - var bos = Cc["@mozilla.org/binaryoutputstream;1"] - .createInstance(Ci.nsIBinaryOutputStream); - bos.setOutputStream(response.bodyOutputStream); + response.setStatusLine(metadata.httpVersion, 200, "OK"); + response.setHeader("Content-Type", "text/plain", false); + response.setHeader("Content-Encoding", tests[index].ce, false); + response.setHeader("Content-Length", "" + tests[index].body.length, false); - response.processAsync(); - bos.writeByteArray(tests[index].body, tests[index].body.length); - response.finish(); + var bos = Cc["@mozilla.org/binaryoutputstream;1"].createInstance( + Ci.nsIBinaryOutputStream + ); + bos.setOutputStream(response.bodyOutputStream); + + response.processAsync(); + bos.writeByteArray(tests[index].body, tests[index].body.length); + response.finish(); } - diff --git a/netwerk/test/unit/test_content_length_underrun.js b/netwerk/test/unit/test_content_length_underrun.js index b848e03d7348..83fd5c7b865c 100644 --- a/netwerk/test/unit/test_content_length_underrun.js +++ b/netwerk/test/unit/test_content_length_underrun.js @@ -5,7 +5,7 @@ //////////////////////////////////////////////////////////////////////////////// // Test infrastructure -const {HttpServer} = ChromeUtils.import("resource://testing-common/httpd.js"); +const { HttpServer } = ChromeUtils.import("resource://testing-common/httpd.js"); XPCOMUtils.defineLazyGetter(this, "URL", function() { return "http://localhost:" + httpserver.identity.primaryPort; @@ -26,13 +26,13 @@ registerCleanupFunction(() => { Services.prefs.clearUserPref("security.allow_eval_with_system_principal"); }); -function run_test() -{ +function run_test() { prefs = Cc["@mozilla.org/preferences-service;1"].getService(Ci.nsIPrefBranch); enforcePrefStrict = prefs.getBoolPref("network.http.enforce-framing.http1"); enforcePrefSoft = prefs.getBoolPref("network.http.enforce-framing.soft"); enforcePrefStrictChunked = prefs.getBoolPref( - "network.http.enforce-framing.strict_chunked_encoding"); + "network.http.enforce-framing.strict_chunked_encoding" + ); prefs.setBoolPref("network.http.enforce-framing.http1", true); @@ -42,19 +42,18 @@ function run_test() run_test_number(1); } -function run_test_number(num) -{ +function run_test_number(num) { testPath = testPathBase + num; httpserver.registerPathHandler(testPath, eval("handler" + num)); var channel = setupChannel(testPath); - flags = test_flags[num]; // OK if flags undefined for test - channel.asyncOpen(new ChannelListener(eval("completeTest" + num), - channel, flags)); + flags = test_flags[num]; // OK if flags undefined for test + channel.asyncOpen( + new ChannelListener(eval("completeTest" + num), channel, flags) + ); } -function run_gzip_test(num) -{ +function run_gzip_test(num) { testPath = testPathBase + num; httpserver.registerPathHandler(testPath, eval("handler" + num)); @@ -63,7 +62,10 @@ function run_gzip_test(num) function StreamListener() {} StreamListener.prototype = { - QueryInterface: ChromeUtils.generateQI(["nsIStreamListener", "nsIRequestObserver"]), + QueryInterface: ChromeUtils.generateQI([ + "nsIStreamListener", + "nsIRequestObserver", + ]), onStartRequest(aRequest) {}, @@ -71,35 +73,34 @@ function run_gzip_test(num) // Make sure we catch the error NS_ERROR_NET_PARTIAL_TRANSFER here. Assert.equal(aStatusCode, Cr.NS_ERROR_NET_PARTIAL_TRANSFER); // do_test_finished(); - endTests(); + endTests(); }, - onDataAvailable(request, stream, offset, count) {} + onDataAvailable(request, stream, offset, count) {}, }; let listener = new StreamListener(); - - channel.asyncOpen(listener); + channel.asyncOpen(listener); } -function setupChannel(url) -{ +function setupChannel(url) { var chan = NetUtil.newChannel({ uri: URL + url, - loadUsingSystemPrincipal: true + loadUsingSystemPrincipal: true, }); var httpChan = chan.QueryInterface(Ci.nsIHttpChannel); return httpChan; } -function endTests() -{ +function endTests() { // restore the prefs to pre-test values prefs.setBoolPref("network.http.enforce-framing.http1", enforcePrefStrict); prefs.setBoolPref("network.http.enforce-framing.soft", enforcePrefSoft); - prefs.setBoolPref("network.http.enforce-framing.strict_chunked_encoding", - enforcePrefStrictChunked); + prefs.setBoolPref( + "network.http.enforce-framing.strict_chunked_encoding", + enforcePrefStrictChunked + ); httpserver.stop(do_test_finished); } @@ -107,8 +108,7 @@ function endTests() // Test 1: FAIL because of Content-Length underrun with HTTP 1.1 test_flags[1] = CL_EXPECT_LATE_FAILURE; -function handler1(metadata, response) -{ +function handler1(metadata, response) { var body = "blablabla"; response.seizePower(); @@ -120,8 +120,7 @@ function handler1(metadata, response) response.finish(); } -function completeTest1(request, data, ctx) -{ +function completeTest1(request, data, ctx) { Assert.equal(request.status, Cr.NS_ERROR_NET_PARTIAL_TRANSFER); run_test_number(11); @@ -131,8 +130,7 @@ function completeTest1(request, data, ctx) // Test 11: PASS because of Content-Length underrun with HTTP 1.1 but non 2xx test_flags[11] = CL_IGNORE_CL; -function handler11(metadata, response) -{ +function handler11(metadata, response) { var body = "blablabla"; response.seizePower(); @@ -144,8 +142,7 @@ function handler11(metadata, response) response.finish(); } -function completeTest11(request, data, ctx) -{ +function completeTest11(request, data, ctx) { Assert.equal(request.status, Cr.NS_OK); run_test_number(2); } @@ -155,8 +152,7 @@ function completeTest11(request, data, ctx) test_flags[2] = CL_IGNORE_CL; -function handler2(metadata, response) -{ +function handler2(metadata, response) { var body = "short content"; response.seizePower(); @@ -168,15 +164,16 @@ function handler2(metadata, response) response.finish(); } -function completeTest2(request, data, ctx) -{ +function completeTest2(request, data, ctx) { Assert.equal(request.status, Cr.NS_OK); // test 3 requires the enforce-framing prefs to be false prefs.setBoolPref("network.http.enforce-framing.http1", false); prefs.setBoolPref("network.http.enforce-framing.soft", false); - prefs.setBoolPref("network.http.enforce-framing.strict_chunked_encoding", - false); + prefs.setBoolPref( + "network.http.enforce-framing.strict_chunked_encoding", + false + ); run_test_number(3); } @@ -184,8 +181,7 @@ function completeTest2(request, data, ctx) // Test 3: SUCCEED with bad Content-Length because pref allows it test_flags[3] = CL_IGNORE_CL; -function handler3(metadata, response) -{ +function handler3(metadata, response) { var body = "blablabla"; response.seizePower(); @@ -197,8 +193,7 @@ function handler3(metadata, response) response.finish(); } -function completeTest3(request, data, ctx) -{ +function completeTest3(request, data, ctx) { Assert.equal(request.status, Cr.NS_OK); prefs.setBoolPref("network.http.enforce-framing.soft", true); run_test_number(4); @@ -208,11 +203,11 @@ function completeTest3(request, data, ctx) // Test 4: Succeed because a cut off deflate stream can't be detected test_flags[4] = CL_IGNORE_CL; -function handler4(metadata, response) -{ - // this is the beginning of a deflate compressed response body - - var body = "\xcd\x57\xcd\x6e\x1b\x37\x10\xbe\x07\xc8\x3b\x0c\x36\x68\x72\xd1" + +function handler4(metadata, response) { + // this is the beginning of a deflate compressed response body + + var body = + "\xcd\x57\xcd\x6e\x1b\x37\x10\xbe\x07\xc8\x3b\x0c\x36\x68\x72\xd1" + "\xbf\x92\x22\xb1\x57\x0a\x64\x4b\x6a\x0c\x28\xb6\x61\xa9\x41\x73" + "\x2a\xb8\xbb\x94\x44\x98\xfb\x03\x92\x92\xec\x06\x7d\x97\x1e\xeb" + "\xbe\x86\x5e\xac\xc3\x25\x97\xa2\x64\xb9\x75\x0b\x14\xe8\x69\x87" + @@ -238,8 +233,7 @@ function handler4(metadata, response) response.finish(); } -function completeTest4(request, data, ctx) -{ +function completeTest4(request, data, ctx) { Assert.equal(request.status, Cr.NS_OK); prefs.setBoolPref("network.http.enforce-framing.http1", true); @@ -252,11 +246,11 @@ function completeTest4(request, data, ctx) // Note that test 99 here is run completely different than the other tests in // this file so if you add more tests here, consider adding them before this. -function handler99(metadata, response) -{ +function handler99(metadata, response) { // this is the beginning of a gzip compressed response body - - var body = "\x1f\x8b\x08\x00\x80\xb9\x25\x53\x00\x03\xd4\xd9\x79\xb8\x8e\xe5" + + + var body = + "\x1f\x8b\x08\x00\x80\xb9\x25\x53\x00\x03\xd4\xd9\x79\xb8\x8e\xe5" + "\xba\x00\xf0\x65\x19\x33\x24\x15\x29\xf3\x50\x52\xc6\xac\x85\x10" + "\x8b\x12\x22\x45\xe6\xb6\x21\x9a\x96\x84\x4c\x69\x32\xec\x84\x92" + "\xcc\x99\x6a\xd9\x32\xa5\xd0\x40\xd9\xc6\x14\x15\x95\x28\x62\x9b" + diff --git a/netwerk/test/unit/test_content_sniffer.js b/netwerk/test/unit/test_content_sniffer.js index 5aad4fc25b2e..7060fe76c8a6 100644 --- a/netwerk/test/unit/test_content_sniffer.js +++ b/netwerk/test/unit/test_content_sniffer.js @@ -1,6 +1,6 @@ // This file tests nsIContentSniffer, introduced in bug 324985 -const {HttpServer} = ChromeUtils.import("resource://testing-common/httpd.js"); +const { HttpServer } = ChromeUtils.import("resource://testing-common/httpd.js"); const unknownType = "application/x-unknown-content-type"; const sniffedType = "application/x-sniffed"; @@ -18,31 +18,44 @@ var sniffing_enabled = true; var sniffer = { QueryInterface: ChromeUtils.generateQI(["nsIFactory", "nsIContentSniffer"]), createInstance: function sniffer_ci(outer, iid) { - if (outer) + if (outer) { throw Cr.NS_ERROR_NO_AGGREGATION; + } return this.QueryInterface(iid); }, lockFactory: function sniffer_lockf(lock) { throw Cr.NS_ERROR_NOT_IMPLEMENTED; }, - getMIMETypeFromContent (request, data, length) { + getMIMETypeFromContent(request, data, length) { return sniffedType; - } + }, }; var listener = { onStartRequest: function test_onStartR(request) { try { var chan = request.QueryInterface(Ci.nsIChannel); - if (chan.contentType == unknownType) + if (chan.contentType == unknownType) { do_throw("Type should not be unknown!"); - if (sniffing_enabled && this._iteration > 2 && - chan.contentType != sniffedType) { - do_throw("Expecting <" + sniffedType +"> but got <" + - chan.contentType + "> for " + chan.URI.spec); + } + if ( + sniffing_enabled && + this._iteration > 2 && + chan.contentType != sniffedType + ) { + do_throw( + "Expecting <" + + sniffedType + + "> but got <" + + chan.contentType + + "> for " + + chan.URI.spec + ); } else if (!sniffing_enabled && chan.contentType == sniffedType) { - do_throw("Sniffing not enabled but sniffer called for " + chan.URI.spec); + do_throw( + "Sniffing not enabled but sniffer called for " + chan.URI.spec + ); } } catch (e) { do_throw("Unexpected exception: " + e); @@ -60,13 +73,14 @@ var listener = { do_test_finished(); }, - _iteration: 1 + _iteration: 1, }; function makeChan(url) { - var chan = NetUtil.newChannel({ uri: url, loadUsingSystemPrincipal: true}); - if (sniffing_enabled) + var chan = NetUtil.newChannel({ uri: url, loadUsingSystemPrincipal: true }); + if (sniffing_enabled) { chan.loadFlags |= Ci.nsIChannel.LOAD_CALL_CONTENT_SNIFFERS; + } return chan; } @@ -79,16 +93,20 @@ function run_test() { httpserv.start(-1); urls = [ - // NOTE: First URL here runs without our content sniffer - "data:" + unknownType + ", Some text", - "data:" + unknownType + ", Text", // Make sure sniffing works even if we - // used the unknown content sniffer too - "data:text/plain, Some more text", - "http://localhost:" + httpserv.identity.primaryPort -]; + // NOTE: First URL here runs without our content sniffer + "data:" + unknownType + ", Some text", + "data:" + unknownType + ", Text", // Make sure sniffing works even if we + // used the unknown content sniffer too + "data:text/plain, Some more text", + "http://localhost:" + httpserv.identity.primaryPort, + ]; - Components.manager.nsIComponentRegistrar.registerFactory(snifferCID, - "Unit test content sniffer", snifferContract, sniffer); + Components.manager.nsIComponentRegistrar.registerFactory( + snifferCID, + "Unit test content sniffer", + snifferContract, + sniffer + ); run_test_iteration(1); } @@ -96,22 +114,28 @@ function run_test() { function run_test_iteration(index) { if (index > urls.length) { if (sniffing_enabled) { - sniffing_enabled = false; - index = listener._iteration = 1; + sniffing_enabled = false; + index = listener._iteration = 1; } else { - do_test_pending(); - httpserv.stop(do_test_finished); - return; // we're done + do_test_pending(); + httpserv.stop(do_test_finished); + return; // we're done } } if (sniffing_enabled && index == 2) { // Register our sniffer only here // This also makes sure that dynamic registration is working - var catMan = Cc["@mozilla.org/categorymanager;1"] - .getService(Ci.nsICategoryManager); - catMan.nsICategoryManager.addCategoryEntry(categoryName, "unit test", - snifferContract, false, true); + var catMan = Cc["@mozilla.org/categorymanager;1"].getService( + Ci.nsICategoryManager + ); + catMan.nsICategoryManager.addCategoryEntry( + categoryName, + "unit test", + snifferContract, + false, + true + ); } var chan = makeChan(urls[index - 1]); @@ -121,4 +145,3 @@ function run_test_iteration(index) { do_test_pending(); } - diff --git a/netwerk/test/unit/test_cookie_blacklist.js b/netwerk/test/unit/test_cookie_blacklist.js index 1387ac7a1c8a..2bcd98e577b1 100644 --- a/netwerk/test/unit/test_cookie_blacklist.js +++ b/netwerk/test/unit/test_cookie_blacklist.js @@ -5,13 +5,49 @@ function run_test() { var ios = Cc["@mozilla.org/network/io-service;1"].getService(Ci.nsIIOService); var cookieURI = ios.newURI("http://mozilla.org/test_cookie_blacklist.js"); - var cookieService = Cc["@mozilla.org/cookieService;1"] - .getService(Ci.nsICookieService); - cookieService.setCookieStringFromHttp(cookieURI, cookieURI, null, "BadCookie1=\x01", null, null); - cookieService.setCookieStringFromHttp(cookieURI, cookieURI, null, "BadCookie2=\v", null, null); - cookieService.setCookieStringFromHttp(cookieURI, cookieURI, null, "Bad\x07Name=illegal", null, null); - cookieService.setCookieStringFromHttp(cookieURI, cookieURI, null, GOOD_COOKIE, null, null); - cookieService.setCookieStringFromHttp(cookieURI, cookieURI, null, SPACEY_COOKIE, null, null); + var cookieService = Cc["@mozilla.org/cookieService;1"].getService( + Ci.nsICookieService + ); + cookieService.setCookieStringFromHttp( + cookieURI, + cookieURI, + null, + "BadCookie1=\x01", + null, + null + ); + cookieService.setCookieStringFromHttp( + cookieURI, + cookieURI, + null, + "BadCookie2=\v", + null, + null + ); + cookieService.setCookieStringFromHttp( + cookieURI, + cookieURI, + null, + "Bad\x07Name=illegal", + null, + null + ); + cookieService.setCookieStringFromHttp( + cookieURI, + cookieURI, + null, + GOOD_COOKIE, + null, + null + ); + cookieService.setCookieStringFromHttp( + cookieURI, + cookieURI, + null, + SPACEY_COOKIE, + null, + null + ); var storedCookie = cookieService.getCookieString(cookieURI, null); Assert.equal(storedCookie, GOOD_COOKIE + "; " + SPACEY_COOKIE); diff --git a/netwerk/test/unit/test_cookie_header.js b/netwerk/test/unit/test_cookie_header.js index 276e8d0044f0..46d0beea67a1 100644 --- a/netwerk/test/unit/test_cookie_header.js +++ b/netwerk/test/unit/test_cookie_header.js @@ -1,15 +1,16 @@ // This file tests bug 250375 -const {HttpServer} = ChromeUtils.import("resource://testing-common/httpd.js"); +const { HttpServer } = ChromeUtils.import("resource://testing-common/httpd.js"); XPCOMUtils.defineLazyGetter(this, "URL", function() { return "http://localhost:" + httpserv.identity.primaryPort + "/"; }); function inChildProcess() { - return Cc["@mozilla.org/xre/app-info;1"] - .getService(Ci.nsIXULRuntime) - .processType != Ci.nsIXULRuntime.PROCESS_TYPE_DEFAULT; + return ( + Cc["@mozilla.org/xre/app-info;1"].getService(Ci.nsIXULRuntime) + .processType != Ci.nsIXULRuntime.PROCESS_TYPE_DEFAULT + ); } function check_request_header(chan, name, value) { @@ -17,7 +18,12 @@ function check_request_header(chan, name, value) { try { chanValue = chan.getRequestHeader(name); } catch (e) { - do_throw("Expected to find header '" + name + "' but didn't find it, got exception: " + e); + do_throw( + "Expected to find header '" + + name + + "' but didn't find it, got exception: " + + e + ); } dump("Value for header '" + name + "' is '" + chanValue + "'\n"); Assert.equal(chanValue, value); @@ -51,12 +57,14 @@ var listener = { do_test_finished(); }, - _iteration: 1 + _iteration: 1, }; function makeChan() { - return NetUtil.newChannel({uri: URL, loadUsingSystemPrincipal: true}) - .QueryInterface(Ci.nsIHttpChannel); + return NetUtil.newChannel({ + uri: URL, + loadUsingSystemPrincipal: true, + }).QueryInterface(Ci.nsIHttpChannel); } var httpserv = null; @@ -65,7 +73,10 @@ function run_test() { // Allow all cookies if the pref service is available in this process. if (!inChildProcess()) { Services.prefs.setIntPref("network.cookie.cookieBehavior", 0); - Services.prefs.setBoolPref("network.cookieSettings.unblocked_for_testing", true); + Services.prefs.setBoolPref( + "network.cookieSettings.unblocked_for_testing", + true + ); } httpserv = new HttpServer(); @@ -83,8 +94,9 @@ function run_test() { function run_test_continued() { var chan = makeChan(); - var cookServ = Cc["@mozilla.org/cookieService;1"] - .getService(Ci.nsICookieService); + var cookServ = Cc["@mozilla.org/cookieService;1"].getService( + Ci.nsICookieService + ); var cookie2 = "C2=V2"; cookServ.setCookieString(chan.URI, null, cookie2, chan); chan.setRequestHeader("Cookie", cookieVal, false); diff --git a/netwerk/test/unit/test_cookiejars.js b/netwerk/test/unit/test_cookiejars.js index 24cd536678b1..39dd02f5b6e2 100644 --- a/netwerk/test/unit/test_cookiejars.js +++ b/netwerk/test/unit/test_cookiejars.js @@ -5,13 +5,13 @@ /* * Test that channels with different LoadInfo * are stored in separate namespaces ("cookie jars") - */ + */ XPCOMUtils.defineLazyGetter(this, "URL", function() { return "http://localhost:" + httpserver.identity.primaryPort; }); -const {HttpServer} = ChromeUtils.import("resource://testing-common/httpd.js"); +const { HttpServer } = ChromeUtils.import("resource://testing-common/httpd.js"); var httpserver = new HttpServer(); @@ -19,35 +19,46 @@ var cookieSetPath = "/setcookie"; var cookieCheckPath = "/checkcookie"; function inChildProcess() { - return Cc["@mozilla.org/xre/app-info;1"] - .getService(Ci.nsIXULRuntime) - .processType != Ci.nsIXULRuntime.PROCESS_TYPE_DEFAULT; + return ( + Cc["@mozilla.org/xre/app-info;1"].getService(Ci.nsIXULRuntime) + .processType != Ci.nsIXULRuntime.PROCESS_TYPE_DEFAULT + ); } // Test array: -// - element 0: name for cookie, used both to set and later to check +// - element 0: name for cookie, used both to set and later to check // - element 1: loadInfo (determines cookie namespace) // // TODO: bug 722850: make private browsing work per-app, and add tests. For now // all values are 'false' for PB. var tests = [ - { cookieName: 'LCC_App0_BrowF_PrivF', - originAttributes: new OriginAttributes(0, false, 0) }, - { cookieName: 'LCC_App0_BrowT_PrivF', - originAttributes: new OriginAttributes(0, true, 0) }, - { cookieName: 'LCC_App1_BrowF_PrivF', - originAttributes: new OriginAttributes(1, false, 0) }, - { cookieName: 'LCC_App1_BrowT_PrivF', - originAttributes: new OriginAttributes(1, true, 0) }, + { + cookieName: "LCC_App0_BrowF_PrivF", + originAttributes: new OriginAttributes(0, false, 0), + }, + { + cookieName: "LCC_App0_BrowT_PrivF", + originAttributes: new OriginAttributes(0, true, 0), + }, + { + cookieName: "LCC_App1_BrowF_PrivF", + originAttributes: new OriginAttributes(1, false, 0), + }, + { + cookieName: "LCC_App1_BrowT_PrivF", + originAttributes: new OriginAttributes(1, true, 0), + }, ]; // test number: index into 'tests' array var i = 0; -function setupChannel(path) -{ - var chan = NetUtil.newChannel({uri: URL + path, loadUsingSystemPrincipal: true}); +function setupChannel(path) { + var chan = NetUtil.newChannel({ + uri: URL + path, + loadUsingSystemPrincipal: true, + }); chan.loadInfo.originAttributes = tests[i].originAttributes; chan.QueryInterface(Ci.nsIHttpChannel); return chan; @@ -59,8 +70,7 @@ function setCookie() { channel.asyncOpen(new ChannelListener(setNextCookie, null)); } -function setNextCookie(request, data, context) -{ +function setNextCookie(request, data, context) { if (++i == tests.length) { // all cookies set: switch to checking them i = 0; @@ -73,8 +83,7 @@ function setNextCookie(request, data, context) // Open channel that should send one and only one correct Cookie: header to // server, corresponding to it's namespace -function checkCookie() -{ +function checkCookie() { var channel = setupChannel(cookieCheckPath); channel.asyncOpen(new ChannelListener(completeCheckCookie, null)); } @@ -89,20 +98,33 @@ function completeCheckCookie(request, data, context) { var j; for (j = 0; j < tests.length; j++) { var cookieToCheck = tests[j].cookieName; - found = (cookiesSeen.includes(cookieToCheck)); + found = cookiesSeen.includes(cookieToCheck); if (found && expectedCookie != cookieToCheck) { - do_throw("test index " + i + ": found unexpected cookie '" - + cookieToCheck + "': in '" + cookiesSeen + "'"); + do_throw( + "test index " + + i + + ": found unexpected cookie '" + + cookieToCheck + + "': in '" + + cookiesSeen + + "'" + ); } else if (!found && expectedCookie == cookieToCheck) { - do_throw("test index " + i + ": missing expected cookie '" - + expectedCookie + "': in '" + cookiesSeen + "'"); + do_throw( + "test index " + + i + + ": missing expected cookie '" + + expectedCookie + + "': in '" + + cookiesSeen + + "'" + ); } } // If we get here we're good. info("Saw only correct cookie '" + expectedCookie + "'"); Assert.ok(true); - if (++i == tests.length) { // end of tests httpserver.stop(do_test_finished); @@ -111,12 +133,14 @@ function completeCheckCookie(request, data, context) { } } -function run_test() -{ +function run_test() { // Allow all cookies if the pref service is available in this process. if (!inChildProcess()) { Services.prefs.setIntPref("network.cookie.cookieBehavior", 0); - Services.prefs.setBoolPref("network.cookieSettings.unblocked_for_testing", true); + Services.prefs.setBoolPref( + "network.cookieSettings.unblocked_for_testing", + true + ); } httpserver.registerPathHandler(cookieSetPath, cookieSetHandler); @@ -127,8 +151,7 @@ function run_test() do_test_pending(); } -function cookieSetHandler(metadata, response) -{ +function cookieSetHandler(metadata, response) { var cookieName = metadata.getHeader("foo-set-cookie"); response.setStatusLine(metadata.httpVersion, 200, "Ok"); @@ -137,8 +160,7 @@ function cookieSetHandler(metadata, response) response.bodyOutputStream.write("Ok", "Ok".length); } -function cookieCheckHandler(metadata, response) -{ +function cookieCheckHandler(metadata, response) { var cookies = metadata.getHeader("Cookie"); response.setStatusLine(metadata.httpVersion, 200, "Ok"); @@ -146,4 +168,3 @@ function cookieCheckHandler(metadata, response) response.setHeader("Content-Type", "text/plain"); response.bodyOutputStream.write("Ok", "Ok".length); } - diff --git a/netwerk/test/unit/test_cookiejars_safebrowsing.js b/netwerk/test/unit/test_cookiejars_safebrowsing.js index 8d4ed986439a..75dc8f2c8579 100644 --- a/netwerk/test/unit/test_cookiejars_safebrowsing.js +++ b/netwerk/test/unit/test_cookiejars_safebrowsing.js @@ -23,15 +23,17 @@ * actually get stored in the correct jar). */ -const {HttpServer} = ChromeUtils.import("resource://testing-common/httpd.js"); - +const { HttpServer } = ChromeUtils.import("resource://testing-common/httpd.js"); XPCOMUtils.defineLazyGetter(this, "URL", function() { return "http://localhost:" + httpserver.identity.primaryPort; }); -ChromeUtils.defineModuleGetter(this, "SafeBrowsing", - "resource://gre/modules/SafeBrowsing.jsm"); +ChromeUtils.defineModuleGetter( + this, + "SafeBrowsing", + "resource://gre/modules/SafeBrowsing.jsm" +); var setCookiePath = "/setcookie"; var checkCookiePath = "/checkcookie"; @@ -40,8 +42,10 @@ var safebrowsingGethashPath = "/safebrowsingGethash"; var httpserver; function inChildProcess() { - return Cc["@mozilla.org/xre/app-info;1"].getService(Ci.nsIXULRuntime) - .processType != Ci.nsIXULRuntime.PROCESS_TYPE_DEFAULT; + return ( + Cc["@mozilla.org/xre/app-info;1"].getService(Ci.nsIXULRuntime) + .processType != Ci.nsIXULRuntime.PROCESS_TYPE_DEFAULT + ); } function cookieSetHandler(metadata, response) { @@ -79,28 +83,39 @@ function safebrowsingGethashHandler(metadata, response) { } function setupChannel(path, originAttributes) { - var channel = NetUtil.newChannel({uri: URL + path, loadUsingSystemPrincipal: true}); + var channel = NetUtil.newChannel({ + uri: URL + path, + loadUsingSystemPrincipal: true, + }); channel.loadInfo.originAttributes = originAttributes; channel.QueryInterface(Ci.nsIHttpChannel); return channel; } function run_test() { - // Set up a profile do_get_profile(); // Allow all cookies if the pref service is available in this process. if (!inChildProcess()) { Services.prefs.setIntPref("network.cookie.cookieBehavior", 0); - Services.prefs.setBoolPref("network.cookieSettings.unblocked_for_testing", true); + Services.prefs.setBoolPref( + "network.cookieSettings.unblocked_for_testing", + true + ); } httpserver = new HttpServer(); httpserver.registerPathHandler(setCookiePath, cookieSetHandler); httpserver.registerPathHandler(checkCookiePath, cookieCheckHandler); - httpserver.registerPathHandler(safebrowsingUpdatePath, safebrowsingUpdateHandler); - httpserver.registerPathHandler(safebrowsingGethashPath, safebrowsingGethashHandler); + httpserver.registerPathHandler( + safebrowsingUpdatePath, + safebrowsingUpdateHandler + ); + httpserver.registerPathHandler( + safebrowsingGethashPath, + safebrowsingGethashHandler + ); httpserver.start(-1); run_next_test(); @@ -109,11 +124,12 @@ function run_test() { // this test does not emulate a response in the body, // rather we only set the cookies in the header of response. add_test(function test_safebrowsing_update() { - - var dbservice = Cc["@mozilla.org/url-classifier/dbservice;1"] - .getService(Ci.nsIUrlClassifierDBService); - var streamUpdater = Cc["@mozilla.org/url-classifier/streamupdater;1"] - .getService(Ci.nsIUrlClassifierStreamUpdater); + var dbservice = Cc["@mozilla.org/url-classifier/dbservice;1"].getService( + Ci.nsIUrlClassifierDBService + ); + var streamUpdater = Cc[ + "@mozilla.org/url-classifier/streamupdater;1" + ].getService(Ci.nsIUrlClassifierStreamUpdater); function onSuccess() { run_next_test(); @@ -125,30 +141,39 @@ add_test(function test_safebrowsing_update() { do_throw("ERROR: received onDownloadError!"); } - streamUpdater.downloadUpdates("test-phish-simple,test-malware-simple", "", - true, URL + safebrowsingUpdatePath, onSuccess, onUpdateError, onDownloadError); + streamUpdater.downloadUpdates( + "test-phish-simple,test-malware-simple", + "", + true, + URL + safebrowsingUpdatePath, + onSuccess, + onUpdateError, + onDownloadError + ); }); add_test(function test_safebrowsing_gethash() { - var hashCompleter = Cc["@mozilla.org/url-classifier/hashcompleter;1"] - .getService(Ci.nsIUrlClassifierHashCompleter); + var hashCompleter = Cc[ + "@mozilla.org/url-classifier/hashcompleter;1" + ].getService(Ci.nsIUrlClassifierHashCompleter); - hashCompleter.complete("aaaa", - URL + safebrowsingGethashPath, - "test-phish-simple", { - completionV2(hash, table, chunkId) { - }, + hashCompleter.complete( + "aaaa", + URL + safebrowsingGethashPath, + "test-phish-simple", + { + completionV2(hash, table, chunkId) {}, - completionFinished(status) { - Assert.equal(status, Cr.NS_OK); - run_next_test(); - }, - }); + completionFinished(status) { + Assert.equal(status, Cr.NS_OK); + run_next_test(); + }, + } + ); }); add_test(function test_non_safebrowsing_cookie() { - - var cookieName = 'regCookie_id0'; + var cookieName = "regCookie_id0"; var originAttributes = new OriginAttributes(0, false, 0); function setNonSafeBrowsingCookie() { @@ -159,7 +184,9 @@ add_test(function test_non_safebrowsing_cookie() { function checkNonSafeBrowsingCookie() { var channel = setupChannel(checkCookiePath, originAttributes); - channel.asyncOpen(new ChannelListener(completeCheckNonSafeBrowsingCookie, null)); + channel.asyncOpen( + new ChannelListener(completeCheckNonSafeBrowsingCookie, null) + ); } function completeCheckNonSafeBrowsingCookie(request, data, context) { @@ -175,8 +202,7 @@ add_test(function test_non_safebrowsing_cookie() { }); add_test(function test_safebrowsing_cookie() { - - var cookieName = 'sbCookie_id4294967294'; + var cookieName = "sbCookie_id4294967294"; var originAttributes = new OriginAttributes(0, false, 0); originAttributes.firstPartyDomain = "safebrowsing.86868755-6b82-4842-b301-72671a0db32e.mozilla"; @@ -189,7 +215,9 @@ add_test(function test_safebrowsing_cookie() { function checkSafeBrowsingCookie() { var channel = setupChannel(checkCookiePath, originAttributes); - channel.asyncOpen(new ChannelListener(completeCheckSafeBrowsingCookie, null)); + channel.asyncOpen( + new ChannelListener(completeCheckSafeBrowsingCookie, null) + ); } function completeCheckSafeBrowsingCookie(request, data, context) { diff --git a/netwerk/test/unit/test_cookies_async_failure.js b/netwerk/test/unit/test_cookies_async_failure.js index 6e6124958305..6d9da33bebfe 100644 --- a/netwerk/test/unit/test_cookies_async_failure.js +++ b/netwerk/test/unit/test_cookies_async_failure.js @@ -46,8 +46,18 @@ function* do_run_test() { // Create a cookie object for testing. this.now = Date.now() * 1000; this.futureExpiry = Math.round(this.now / 1e6 + 1000); - this.cookie = new Cookie("oh", "hai", "bar.com", "/", this.futureExpiry, - this.now, this.now, false, false, false); + this.cookie = new Cookie( + "oh", + "hai", + "bar.com", + "/", + this.futureExpiry, + this.now, + this.now, + false, + false, + false + ); this.sub_generator = run_test_1(test_generator); sub_generator.next(); @@ -72,22 +82,19 @@ function* do_run_test() { finish_test(); } -function do_get_backup_file(profile) -{ +function do_get_backup_file(profile) { let file = profile.clone(); file.append("cookies.sqlite.bak"); return file; } -function do_get_rebuild_backup_file(profile) -{ +function do_get_rebuild_backup_file(profile) { let file = profile.clone(); file.append("cookies.sqlite.bak-rebuild"); return file; } -function do_corrupt_db(file) -{ +function do_corrupt_db(file) { // Sanity check: the database size should be larger than 450k, since we've // written about 460k of data. If it's not, let's make it obvious now. let size = file.fileSize; @@ -101,8 +108,9 @@ function do_corrupt_db(file) // database file will be larger than the actual content requires, since the // cookie service uses a large growth increment. So we calculate the offset // based on the expected size of the content, not just the file size.) - let ostream = Cc["@mozilla.org/network/file-output-stream;1"]. - createInstance(Ci.nsIFileOutputStream); + let ostream = Cc["@mozilla.org/network/file-output-stream;1"].createInstance( + Ci.nsIFileOutputStream + ); ostream.init(file, 2, -1, 0); let sstream = ostream.QueryInterface(Ci.nsISeekableStream); let n = size - 450e3 + 20e3; @@ -117,8 +125,7 @@ function do_corrupt_db(file) return size; } -function* run_test_1(generator) -{ +function* run_test_1(generator) { // Load the profile and populate it. let uri = NetUtil.newURI("http://foo.com/"); Services.cookies.setCookieString(uri, null, "oh=hai; max-age=1000", null); @@ -156,15 +163,24 @@ function* run_test_1(generator) db.close(); // Attempt to insert a cookie with the same (name, host, path) triplet. - Services.cookiemgr.add(cookie.host, cookie.path, cookie.name, "hallo", - cookie.isSecure, cookie.isHttpOnly, cookie.isSession, cookie.expiry, {}, - Ci.nsICookie.SAMESITE_NONE); + Services.cookiemgr.add( + cookie.host, + cookie.path, + cookie.name, + "hallo", + cookie.isSecure, + cookie.isHttpOnly, + cookie.isSession, + cookie.expiry, + {}, + Ci.nsICookie.SAMESITE_NONE + ); // Check that the cookie service accepted the new cookie. Assert.equal(Services.cookiemgr.countCookiesFromHost(cookie.host), 1); let isRebuildingDone = false; - let rebuildingObserve = function (subject, topic, data) { + let rebuildingObserve = function(subject, topic, data) { isRebuildingDone = true; Services.obs.removeObserver(rebuildingObserve, "cookie-db-rebuilding"); }; @@ -176,7 +192,9 @@ function* run_test_1(generator) // the chaos status. for (let i = 0; i < 10; ++i) { Assert.equal(Services.cookiemgr.countCookiesFromHost(cookie.host), 1); - executeSoon(function() { do_run_generator(sub_generator); }); + executeSoon(function() { + do_run_generator(sub_generator); + }); yield; } @@ -186,7 +204,9 @@ function* run_test_1(generator) new _observer(sub_generator, "cookie-db-rebuilding"); yield; } - executeSoon(function() { do_run_generator(sub_generator); }); + executeSoon(function() { + do_run_generator(sub_generator); + }); yield; // At this point, the cookies should still be in memory. @@ -227,11 +247,10 @@ function* run_test_1(generator) do_run_generator(generator); } -function* run_test_2(generator) -{ +function* run_test_2(generator) { // Load the profile and populate it. do_load_profile(); - Services.cookies.runInTransaction(_=>{ + Services.cookies.runInTransaction(_ => { for (let i = 0; i < 3000; ++i) { let uri = NetUtil.newURI("http://" + i + ".com/"); Services.cookies.setCookieString(uri, null, "oh=hai; max-age=1000", null); @@ -282,24 +301,31 @@ function* run_test_2(generator) do_run_generator(generator); } -function* run_test_3(generator) -{ +function* run_test_3(generator) { // Set the maximum cookies per base domain limit to a large value, so that // corrupting the database is easier. Services.prefs.setIntPref("network.cookie.maxPerHost", 3000); // Load the profile and populate it. do_load_profile(); - Services.cookies.runInTransaction(_=>{ + Services.cookies.runInTransaction(_ => { for (let i = 0; i < 10; ++i) { let uri = NetUtil.newURI("http://hither.com/"); - Services.cookies.setCookieString(uri, null, "oh" + i + "=hai; max-age=1000", - null); + Services.cookies.setCookieString( + uri, + null, + "oh" + i + "=hai; max-age=1000", + null + ); } for (let i = 10; i < 3000; ++i) { let uri = NetUtil.newURI("http://haithur.com/"); - Services.cookies.setCookieString(uri, null, "oh" + i + "=hai; max-age=1000", - null); + Services.cookies.setCookieString( + uri, + null, + "oh" + i + "=hai; max-age=1000", + null + ); } }); @@ -363,11 +389,10 @@ function* run_test_3(generator) do_run_generator(generator); } -function* run_test_4(generator) -{ +function* run_test_4(generator) { // Load the profile and populate it. do_load_profile(); - Services.cookies.runInTransaction(_=>{ + Services.cookies.runInTransaction(_ => { for (let i = 0; i < 3000; ++i) { let uri = NetUtil.newURI("http://" + i + ".com/"); Services.cookies.setCookieString(uri, null, "oh=hai; max-age=1000", null); @@ -425,14 +450,17 @@ function* run_test_4(generator) do_run_generator(generator); } -function* run_test_5(generator) -{ +function* run_test_5(generator) { // Load the profile and populate it. do_load_profile(); - Services.cookies.runInTransaction(_=>{ + Services.cookies.runInTransaction(_ => { let uri = NetUtil.newURI("http://bar.com/"); - Services.cookies.setCookieString(uri, null, "oh=hai; path=/; max-age=1000", - null); + Services.cookies.setCookieString( + uri, + null, + "oh=hai; path=/; max-age=1000", + null + ); for (let i = 0; i < 3000; ++i) { let uri = NetUtil.newURI("http://" + i + ".com/"); Services.cookies.setCookieString(uri, null, "oh=hai; max-age=1000", null); @@ -489,4 +517,3 @@ function* run_test_5(generator) Assert.ok(!do_get_backup_file(profile).exists()); do_run_generator(generator); } - diff --git a/netwerk/test/unit/test_cookies_persistence.js b/netwerk/test/unit/test_cookies_persistence.js index f95fa1865afc..9abef63de43e 100644 --- a/netwerk/test/unit/test_cookies_persistence.js +++ b/netwerk/test/unit/test_cookies_persistence.js @@ -29,8 +29,14 @@ function* do_run_test() { var spec2 = "http://bar.com/bar.html"; var uri1 = NetUtil.newURI(spec1); var uri2 = NetUtil.newURI(spec2); - var channel1 = NetUtil.newChannel({uri: uri1, loadUsingSystemPrincipal: true}); - var channel2 = NetUtil.newChannel({uri: uri2, loadUsingSystemPrincipal: true}); + var channel1 = NetUtil.newChannel({ + uri: uri1, + loadUsingSystemPrincipal: true, + }); + var channel2 = NetUtil.newChannel({ + uri: uri2, + loadUsingSystemPrincipal: true, + }); // Force the channel URI to be used when determining the originating URI of // the channel. @@ -75,4 +81,3 @@ function* do_run_test() { finish_test(); } - diff --git a/netwerk/test/unit/test_cookies_privatebrowsing.js b/netwerk/test/unit/test_cookies_privatebrowsing.js index a8902855849e..c6e5015874a9 100644 --- a/netwerk/test/unit/test_cookies_privatebrowsing.js +++ b/netwerk/test/unit/test_cookies_privatebrowsing.js @@ -18,8 +18,10 @@ function finish_test() { } function make_channel(url) { - return NetUtil.newChannel({uri: url, loadUsingSystemPrincipal: true}) - .QueryInterface(Ci.nsIHttpChannel); + return NetUtil.newChannel({ + uri: url, + loadUsingSystemPrincipal: true, + }).QueryInterface(Ci.nsIHttpChannel); } function* do_run_test() { @@ -27,7 +29,10 @@ function* do_run_test() { let profile = do_get_profile(); // We don't want to have CookieSettings blocking this test. - Services.prefs.setBoolPref("network.cookieSettings.unblocked_for_testing", true); + Services.prefs.setBoolPref( + "network.cookieSettings.unblocked_for_testing", + true + ); // Test with cookies enabled. Services.prefs.setIntPref("network.cookie.cookieBehavior", 0); diff --git a/netwerk/test/unit/test_cookies_profile_close.js b/netwerk/test/unit/test_cookies_profile_close.js index 83f62a84f4d9..236b6f010637 100644 --- a/netwerk/test/unit/test_cookies_profile_close.js +++ b/netwerk/test/unit/test_cookies_profile_close.js @@ -42,7 +42,14 @@ function* do_run_test() { Assert.equal(Services.cookies.getCookieString(uri, null), ""); Assert.equal(Services.cookies.getCookieStringFromHttp(uri, null, null), ""); Services.cookies.setCookieString(uri, null, "oh2=hai", null); - Services.cookies.setCookieStringFromHttp(uri, null, null, "oh3=hai", null, null); + Services.cookies.setCookieStringFromHttp( + uri, + null, + null, + "oh3=hai", + null, + null + ); Assert.equal(Services.cookies.getCookieString(uri, null), ""); do_check_throws(function() { @@ -54,8 +61,18 @@ function* do_run_test() { }, Cr.NS_ERROR_NOT_AVAILABLE); do_check_throws(function() { - Services.cookiemgr.add("foo.com", "", "oh4", "hai", false, false, false, 0, {}, - Ci.nsICookie.SAMESITE_NONE); + Services.cookiemgr.add( + "foo.com", + "", + "oh4", + "hai", + false, + false, + false, + 0, + {}, + Ci.nsICookie.SAMESITE_NONE + ); }, Cr.NS_ERROR_NOT_AVAILABLE); do_check_throws(function() { @@ -86,8 +103,9 @@ function* do_run_test() { // Load the profile and check that the API is available. do_load_profile(); - Assert.ok(Services.cookiemgr.cookieExists(cookie.host, cookie.path, cookie.name, {})); + Assert.ok( + Services.cookiemgr.cookieExists(cookie.host, cookie.path, cookie.name, {}) + ); finish_test(); } - diff --git a/netwerk/test/unit/test_cookies_read.js b/netwerk/test/unit/test_cookies_read.js index 7733aa3b67ff..0038a82bccf5 100644 --- a/netwerk/test/unit/test_cookies_read.js +++ b/netwerk/test/unit/test_cookies_read.js @@ -5,7 +5,7 @@ var test_generator = do_run_test(); -var CMAX = 1000; // # of cookies to create +var CMAX = 1000; // # of cookies to create function run_test() { do_test_pending(); @@ -120,4 +120,3 @@ function* do_run_test() { finish_test(); } - diff --git a/netwerk/test/unit/test_cookies_sync_failure.js b/netwerk/test/unit/test_cookies_sync_failure.js index b923eaaef3e3..82985bdeb871 100644 --- a/netwerk/test/unit/test_cookies_sync_failure.js +++ b/netwerk/test/unit/test_cookies_sync_failure.js @@ -52,8 +52,18 @@ function* do_run_test() { // Create a cookie object for testing. this.now = Date.now() * 1000; this.futureExpiry = Math.round(this.now / 1e6 + 1000); - this.cookie = new Cookie("oh", "hai", "bar.com", "/", this.futureExpiry, - this.now, this.now, false, false, false); + this.cookie = new Cookie( + "oh", + "hai", + "bar.com", + "/", + this.futureExpiry, + this.now, + this.now, + false, + false, + false + ); this.sub_generator = run_test_1(test_generator); sub_generator.next(); @@ -67,7 +77,10 @@ function* do_run_test() { sub_generator.next(); yield; - this.sub_generator = run_test_3(test_generator, COOKIE_DATABASE_SCHEMA_CURRENT); + this.sub_generator = run_test_3( + test_generator, + COOKIE_DATABASE_SCHEMA_CURRENT + ); sub_generator.next(); yield; @@ -79,13 +92,19 @@ function* do_run_test() { sub_generator.next(); yield; - this.sub_generator = run_test_4_exists(test_generator, 1, - "ALTER TABLE moz_cookies ADD lastAccessed INTEGER"); + this.sub_generator = run_test_4_exists( + test_generator, + 1, + "ALTER TABLE moz_cookies ADD lastAccessed INTEGER" + ); sub_generator.next(); yield; - this.sub_generator = run_test_4_exists(test_generator, 2, - "ALTER TABLE moz_cookies ADD baseDomain TEXT"); + this.sub_generator = run_test_4_exists( + test_generator, + 2, + "ALTER TABLE moz_cookies ADD baseDomain TEXT" + ); sub_generator.next(); yield; @@ -93,32 +112,37 @@ function* do_run_test() { sub_generator.next(); yield; - this.sub_generator = run_test_4_exists(test_generator, 3, - "ALTER TABLE moz_cookies ADD creationTime INTEGER"); + this.sub_generator = run_test_4_exists( + test_generator, + 3, + "ALTER TABLE moz_cookies ADD creationTime INTEGER" + ); sub_generator.next(); yield; - this.sub_generator = run_test_4_exists(test_generator, 3, - "CREATE UNIQUE INDEX moz_uniqueid ON moz_cookies (name, host, path)"); + this.sub_generator = run_test_4_exists( + test_generator, + 3, + "CREATE UNIQUE INDEX moz_uniqueid ON moz_cookies (name, host, path)" + ); sub_generator.next(); yield; finish_test(); - } const garbage = "hello thar!"; -function create_garbage_file(file) -{ +function create_garbage_file(file) { // Create an empty database file. file.create(Ci.nsIFile.NORMAL_FILE_TYPE, -1); Assert.ok(file.exists()); Assert.equal(file.fileSize, 0); // Write some garbage to it. - let ostream = Cc["@mozilla.org/network/file-output-stream;1"]. - createInstance(Ci.nsIFileOutputStream); + let ostream = Cc["@mozilla.org/network/file-output-stream;1"].createInstance( + Ci.nsIFileOutputStream + ); ostream.init(file, -1, -1, 0); ostream.write(garbage, garbage.length); ostream.flush(); @@ -128,16 +152,14 @@ function create_garbage_file(file) Assert.equal(file.fileSize, garbage.length); } -function check_garbage_file(file) -{ +function check_garbage_file(file) { Assert.ok(file.exists()); Assert.equal(file.fileSize, garbage.length); file.remove(false); Assert.ok(!file.exists()); } -function* run_test_1(generator) -{ +function* run_test_1(generator) { // Create a garbage database file. create_garbage_file(cookieFile); @@ -165,8 +187,7 @@ function* run_test_1(generator) do_run_generator(generator); } -function* run_test_2(generator) -{ +function* run_test_2(generator) { // Load the profile and populate it. do_load_profile(); let uri = NetUtil.newURI("http://foo.com/"); @@ -196,8 +217,7 @@ function* run_test_2(generator) do_run_generator(generator); } -function* run_test_3(generator, schema) -{ +function* run_test_3(generator, schema) { // Manually create a schema 2 database, populate it, and set the schema // version to the desired number. let schema2db = new CookieDatabaseConnection(do_get_cookie_file(profile), 2); @@ -224,8 +244,7 @@ function* run_test_3(generator, schema) do_run_generator(generator); } -function* run_test_4_exists(generator, schema, stmt) -{ +function* run_test_4_exists(generator, schema, stmt) { // Manually create a database, populate it, and add the desired column. let db = new CookieDatabaseConnection(do_get_cookie_file(profile), schema); db.insertCookie(cookie); @@ -254,12 +273,21 @@ function* run_test_4_exists(generator, schema, stmt) do_run_generator(generator); } -function* run_test_4_baseDomain(generator) -{ +function* run_test_4_baseDomain(generator) { // Manually create a database and populate it with a bad host. let db = new CookieDatabaseConnection(do_get_cookie_file(profile), 2); - let badCookie = new Cookie("oh", "hai", ".", "/", this.futureExpiry, this.now, - this.now, false, false, false); + let badCookie = new Cookie( + "oh", + "hai", + ".", + "/", + this.futureExpiry, + this.now, + this.now, + false, + false, + false + ); db.insertCookie(badCookie); db.close(); diff --git a/netwerk/test/unit/test_cookies_thirdparty.js b/netwerk/test/unit/test_cookies_thirdparty.js index b9c8df792686..07b9db606cae 100644 --- a/netwerk/test/unit/test_cookies_thirdparty.js +++ b/netwerk/test/unit/test_cookies_thirdparty.js @@ -6,7 +6,10 @@ // 2) with channel, but with no docshell parent function run_test() { - Services.prefs.setBoolPref("network.cookieSettings.unblocked_for_testing", true); + Services.prefs.setBoolPref( + "network.cookieSettings.unblocked_for_testing", + true + ); // Create URIs and channels pointing to foo.com and bar.com. // We will use these to put foo.com into first and third party contexts. @@ -15,12 +18,18 @@ function run_test() { let uri1 = NetUtil.newURI(spec1); let uri2 = NetUtil.newURI(spec2); - // test with cookies enabled + // test with cookies enabled { Services.prefs.setIntPref("network.cookie.cookieBehavior", 0); - let channel1 = NetUtil.newChannel({uri: uri1, loadUsingSystemPrincipal: true}); - let channel2 = NetUtil.newChannel({uri: uri2, loadUsingSystemPrincipal: true}); + let channel1 = NetUtil.newChannel({ + uri: uri1, + loadUsingSystemPrincipal: true, + }); + let channel2 = NetUtil.newChannel({ + uri: uri2, + loadUsingSystemPrincipal: true, + }); do_set_cookies(uri1, channel1, true, [1, 2, 3, 4]); Services.cookies.removeAll(); @@ -32,8 +41,14 @@ function run_test() { { Services.prefs.setIntPref("network.cookie.cookieBehavior", 1); - let channel1 = NetUtil.newChannel({uri: uri1, loadUsingSystemPrincipal: true}); - let channel2 = NetUtil.newChannel({uri: uri2, loadUsingSystemPrincipal: true}); + let channel1 = NetUtil.newChannel({ + uri: uri1, + loadUsingSystemPrincipal: true, + }); + let channel2 = NetUtil.newChannel({ + uri: uri2, + loadUsingSystemPrincipal: true, + }); do_set_cookies(uri1, channel1, true, [0, 0, 0, 0]); Services.cookies.removeAll(); @@ -49,11 +64,17 @@ function run_test() { { Services.prefs.setIntPref("network.cookie.cookieBehavior", 0); - let channel1 = NetUtil.newChannel({uri: uri1, loadUsingSystemPrincipal: true}); + let channel1 = NetUtil.newChannel({ + uri: uri1, + loadUsingSystemPrincipal: true, + }); let httpchannel1 = channel1.QueryInterface(Ci.nsIHttpChannelInternal); httpchannel1.forceAllowThirdPartyCookie = true; - let channel2 = NetUtil.newChannel({uri: uri2, loadUsingSystemPrincipal: true}); + let channel2 = NetUtil.newChannel({ + uri: uri2, + loadUsingSystemPrincipal: true, + }); let httpchannel2 = channel2.QueryInterface(Ci.nsIHttpChannelInternal); httpchannel2.forceAllowThirdPartyCookie = true; @@ -67,11 +88,17 @@ function run_test() { { Services.prefs.setIntPref("network.cookie.cookieBehavior", 1); - let channel1 = NetUtil.newChannel({uri: uri1, loadUsingSystemPrincipal: true}); + let channel1 = NetUtil.newChannel({ + uri: uri1, + loadUsingSystemPrincipal: true, + }); let httpchannel1 = channel1.QueryInterface(Ci.nsIHttpChannelInternal); httpchannel1.forceAllowThirdPartyCookie = true; - let channel2 = NetUtil.newChannel({uri: uri2, loadUsingSystemPrincipal: true}); + let channel2 = NetUtil.newChannel({ + uri: uri2, + loadUsingSystemPrincipal: true, + }); let httpchannel2 = channel2.QueryInterface(Ci.nsIHttpChannelInternal); httpchannel2.forceAllowThirdPartyCookie = true; @@ -85,11 +112,17 @@ function run_test() { { Services.prefs.setIntPref("network.cookie.cookieBehavior", 3); - let channel1 = NetUtil.newChannel({uri: uri1, loadUsingSystemPrincipal: true}); + let channel1 = NetUtil.newChannel({ + uri: uri1, + loadUsingSystemPrincipal: true, + }); let httpchannel1 = channel1.QueryInterface(Ci.nsIHttpChannelInternal); httpchannel1.forceAllowThirdPartyCookie = true; - let channel2 = NetUtil.newChannel({uri: uri2, loadUsingSystemPrincipal: true}); + let channel2 = NetUtil.newChannel({ + uri: uri2, + loadUsingSystemPrincipal: true, + }); let httpchannel2 = channel2.QueryInterface(Ci.nsIHttpChannelInternal); httpchannel2.forceAllowThirdPartyCookie = true; diff --git a/netwerk/test/unit/test_cookies_thirdparty_nonsecure_session.js b/netwerk/test/unit/test_cookies_thirdparty_nonsecure_session.js index c964f0e96ff6..68257d56c180 100644 --- a/netwerk/test/unit/test_cookies_thirdparty_nonsecure_session.js +++ b/netwerk/test/unit/test_cookies_thirdparty_nonsecure_session.js @@ -26,7 +26,10 @@ function* do_run_test() { let profile = do_get_profile(); // We don't want to have CookieSettings blocking this test. - Services.prefs.setBoolPref("network.cookieSettings.unblocked_for_testing", true); + Services.prefs.setBoolPref( + "network.cookieSettings.unblocked_for_testing", + true + ); // Create URIs and channels pointing to foo.com and bar.com. // We will use these to put foo.com into first and third party contexts. @@ -34,8 +37,14 @@ function* do_run_test() { var spec2 = "https://bar.com/bar.html"; var uri1 = NetUtil.newURI(spec1); var uri2 = NetUtil.newURI(spec2); - var channel1 = NetUtil.newChannel({uri: uri1, loadUsingSystemPrincipal: true}); - var channel2 = NetUtil.newChannel({uri: uri2, loadUsingSystemPrincipal: true}); + var channel1 = NetUtil.newChannel({ + uri: uri1, + loadUsingSystemPrincipal: true, + }); + var channel2 = NetUtil.newChannel({ + uri: uri2, + loadUsingSystemPrincipal: true, + }); // Force the channel URI to be used when determining the originating URI of // the channel. @@ -46,7 +55,10 @@ function* do_run_test() { // test with cookies enabled and nonsecure third party cookies persistent. Services.prefs.setIntPref("network.cookie.cookieBehavior", 0); - Services.prefs.setBoolPref("network.cookie.thirdparty.nonsecureSessionOnly", false); + Services.prefs.setBoolPref( + "network.cookie.thirdparty.nonsecureSessionOnly", + false + ); do_set_cookies(uri1, channel2, false, [1, 2, 3, 4]); // third-party HTTP do_set_cookies(uri2, channel1, false, [1, 2, 3, 4]); // third-party HTTPS @@ -58,7 +70,10 @@ function* do_run_test() { Assert.equal(Services.cookies.countCookiesFromHost(uri2.host), 4); // HTTPS cookies OK // test with nonsecure third party cookies for session only. - Services.prefs.setBoolPref("network.cookie.thirdparty.nonsecureSessionOnly", true); + Services.prefs.setBoolPref( + "network.cookie.thirdparty.nonsecureSessionOnly", + true + ); Services.cookies.removeAll(); do_set_cookies(uri1, channel2, false, [1, 2, 3, 4]); // third-party HTTP do_set_cookies(uri2, channel1, false, [1, 2, 3, 4]); // third-party HTTPS diff --git a/netwerk/test/unit/test_cookies_thirdparty_session.js b/netwerk/test/unit/test_cookies_thirdparty_session.js index a8137aafc59b..596640ebc34f 100644 --- a/netwerk/test/unit/test_cookies_thirdparty_session.js +++ b/netwerk/test/unit/test_cookies_thirdparty_session.js @@ -24,7 +24,10 @@ function* do_run_test() { let profile = do_get_profile(); // We don't want to have CookieSettings blocking this test. - Services.prefs.setBoolPref("network.cookieSettings.unblocked_for_testing", true); + Services.prefs.setBoolPref( + "network.cookieSettings.unblocked_for_testing", + true + ); // Create URIs and channels pointing to foo.com and bar.com. // We will use these to put foo.com into first and third party contexts. @@ -32,8 +35,14 @@ function* do_run_test() { var spec2 = "http://bar.com/bar.html"; var uri1 = NetUtil.newURI(spec1); var uri2 = NetUtil.newURI(spec2); - var channel1 = NetUtil.newChannel({uri: uri1, loadUsingSystemPrincipal: true}); - var channel2 = NetUtil.newChannel({uri: uri2, loadUsingSystemPrincipal: true}); + var channel1 = NetUtil.newChannel({ + uri: uri1, + loadUsingSystemPrincipal: true, + }); + var channel2 = NetUtil.newChannel({ + uri: uri2, + loadUsingSystemPrincipal: true, + }); // Force the channel URI to be used when determining the originating URI of // the channel. diff --git a/netwerk/test/unit/test_data_protocol.js b/netwerk/test/unit/test_data_protocol.js index 623da40616be..bdc87bd89299 100644 --- a/netwerk/test/unit/test_data_protocol.js +++ b/netwerk/test/unit/test_data_protocol.js @@ -5,27 +5,39 @@ // - Other content strips unescaped spaces // - Base64 content strips escaped and unescaped spaces var urls = [ - ["data:,", "text/plain", ""], - ["data:,foo", "text/plain", "foo"], - ["data:application/octet-stream,foo bar", "application/octet-stream", "foobar"], - ["data:application/octet-stream,foo%20bar", "application/octet-stream", "foo bar"], - ["data:application/xhtml+xml,foo bar", "application/xhtml+xml", "foo bar"], - ["data:application/xhtml+xml,foo%20bar", "application/xhtml+xml", "foo bar"], - ["data:text/plain,foo%00 bar", "text/plain", "foo\x00 bar"], - ["data:text/plain;x=y,foo%00 bar", "text/plain", "foo\x00 bar"], - ["data:;x=y,foo%00 bar", "text/plain", "foo\x00 bar"], - ["data:text/plain;base64,Zm9 vI%20GJ%0Dhc%0Ag==", "text/plain", "foo bar"], - ["DATA:TEXT/PLAIN;BASE64,Zm9 vI%20GJ%0Dhc%0Ag==", "text/plain", "foo bar"], - ["DaTa:;BaSe64,Zm9 vI%20GJ%0Dhc%0Ag==", "text/plain", "foo bar"], - ["data:;x=y;base64,Zm9 vI%20GJ%0Dhc%0Ag==", "text/plain", "foo bar"], + ["data:,", "text/plain", ""], + ["data:,foo", "text/plain", "foo"], + [ + "data:application/octet-stream,foo bar", + "application/octet-stream", + "foobar", + ], + [ + "data:application/octet-stream,foo%20bar", + "application/octet-stream", + "foo bar", + ], + ["data:application/xhtml+xml,foo bar", "application/xhtml+xml", "foo bar"], + ["data:application/xhtml+xml,foo%20bar", "application/xhtml+xml", "foo bar"], + ["data:text/plain,foo%00 bar", "text/plain", "foo\x00 bar"], + ["data:text/plain;x=y,foo%00 bar", "text/plain", "foo\x00 bar"], + ["data:;x=y,foo%00 bar", "text/plain", "foo\x00 bar"], + ["data:text/plain;base64,Zm9 vI%20GJ%0Dhc%0Ag==", "text/plain", "foo bar"], + ["DATA:TEXT/PLAIN;BASE64,Zm9 vI%20GJ%0Dhc%0Ag==", "text/plain", "foo bar"], + ["DaTa:;BaSe64,Zm9 vI%20GJ%0Dhc%0Ag==", "text/plain", "foo bar"], + ["data:;x=y;base64,Zm9 vI%20GJ%0Dhc%0Ag==", "text/plain", "foo bar"], // Bug 774240 - ["data:application/octet-stream;base64=y,foobar", "application/octet-stream", "foobar"], + [ + "data:application/octet-stream;base64=y,foobar", + "application/octet-stream", + "foobar", + ], // Bug 781693 - ["data:text/plain;base64;x=y,dGVzdA==", "text/plain", "test"], - ["data:text/plain;x=y;base64,dGVzdA==", "text/plain", "test"], - ["data:text/plain;x=y;base64,", "text/plain", ""], - ["data: ;charset=x ; base64,WA", "text/plain", "X", "x"], - ["data:base64,WA", "text/plain", "WA", "US-ASCII"], + ["data:text/plain;base64;x=y,dGVzdA==", "text/plain", "test"], + ["data:text/plain;x=y;base64,dGVzdA==", "text/plain", "test"], + ["data:text/plain;x=y;base64,", "text/plain", ""], + ["data: ;charset=x ; base64,WA", "text/plain", "X", "x"], + ["data:base64,WA", "text/plain", "WA", "US-ASCII"], ]; function run_test() { @@ -34,30 +46,46 @@ function run_test() { function on_read_complete(request, data, idx) { dump("*** run_test.on_read_complete\n"); - if (request.nsIChannel.contentType != urls[idx][1]) - do_throw("Type mismatch! Is <" + chan.contentType + ">, should be <" + urls[idx][1] + ">"); + if (request.nsIChannel.contentType != urls[idx][1]) { + do_throw( + "Type mismatch! Is <" + + chan.contentType + + ">, should be <" + + urls[idx][1] + + ">" + ); + } if (urls[idx][3] && request.nsIChannel.contentCharset !== urls[idx][3]) { - do_throw(`Charset mismatch! Test <${urls[idx][0]}> - Is <${request.nsIChannel.contentCharset}>, should be <${urls[idx][3]}>`); + do_throw( + `Charset mismatch! Test <${urls[idx][0]}> - Is <${ + request.nsIChannel.contentCharset + }>, should be <${urls[idx][3]}>` + ); } /* read completed successfully. now compare the data. */ - if (data != urls[idx][2]) - do_throw("Stream contents do not match with direct read! Is <" + data + ">, should be <" + urls[idx][2] + ">"); + if (data != urls[idx][2]) { + do_throw( + "Stream contents do not match with direct read! Is <" + + data + + ">, should be <" + + urls[idx][2] + + ">" + ); + } do_test_finished(); } - var ios = Cc["@mozilla.org/network/io-service;1"]. - getService(Ci.nsIIOService); + var ios = Cc["@mozilla.org/network/io-service;1"].getService(Ci.nsIIOService); for (var i = 0; i < urls.length; ++i) { dump("*** opening channel " + i + "\n"); do_test_pending(); var chan = NetUtil.newChannel({ uri: urls[i][0], - loadUsingSystemPrincipal: true + loadUsingSystemPrincipal: true, }); chan.contentType = "foo/bar"; // should be ignored chan.asyncOpen(new ChannelListener(on_read_complete, i)); } } - diff --git a/netwerk/test/unit/test_disabled_ftp.js b/netwerk/test/unit/test_disabled_ftp.js index 1c192983c286..f385e67eaa2d 100644 --- a/netwerk/test/unit/test_disabled_ftp.js +++ b/netwerk/test/unit/test_disabled_ftp.js @@ -6,7 +6,14 @@ add_task(async function ftp_disabled() { Services.prefs.setBoolPref("network.ftp.enabled", false); let chan = null; - Assert.throws(() => { chan = NetUtil.newChannel({uri: "ftp://ftp.de.debian.org/", loadUsingSystemPrincipal: true}) - .QueryInterface(Ci.nsIHttpChannel); }, - /NS_ERROR_UNKNOWN_PROTOCOL/, "creating the FTP channel must throw"); + Assert.throws( + () => { + chan = NetUtil.newChannel({ + uri: "ftp://ftp.de.debian.org/", + loadUsingSystemPrincipal: true, + }).QueryInterface(Ci.nsIHttpChannel); + }, + /NS_ERROR_UNKNOWN_PROTOCOL/, + "creating the FTP channel must throw" + ); }); diff --git a/netwerk/test/unit/test_dns_cancel.js b/netwerk/test/unit/test_dns_cancel.js index c3cd97d4c106..7b9b241d2629 100644 --- a/netwerk/test/unit/test_dns_cancel.js +++ b/netwerk/test/unit/test_dns_cancel.js @@ -4,7 +4,7 @@ var hostname1 = ""; var hostname2 = ""; var possible = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"; -for( var i=0; i < 20; i++ ) { +for (var i = 0; i < 20; i++) { hostname1 += possible.charAt(Math.floor(Math.random() * possible.length)); hostname2 += possible.charAt(Math.floor(Math.random() * possible.length)); } @@ -26,7 +26,7 @@ var listener1 = { do_test_finished(); } }, - QueryInterface: ChromeUtils.generateQI(["nsIDNSListener"]) + QueryInterface: ChromeUtils.generateQI(["nsIDNSListener"]), }; var listener2 = { @@ -39,39 +39,71 @@ var listener2 = { do_test_finished(); } }, - QueryInterface: ChromeUtils.generateQI(["nsIDNSListener"]) + QueryInterface: ChromeUtils.generateQI(["nsIDNSListener"]), }; const defaultOriginAttributes = {}; function run_test() { - var threadManager = Cc["@mozilla.org/thread-manager;1"].getService(Ci.nsIThreadManager); + var threadManager = Cc["@mozilla.org/thread-manager;1"].getService( + Ci.nsIThreadManager + ); var mainThread = threadManager.currentThread; var flags = Ci.nsIDNSService.RESOLVE_BYPASS_CACHE; // This one will be canceled with cancelAsyncResolve. - requestList1Canceled1 = dns.asyncResolve(hostname2, flags, listener1, - mainThread, defaultOriginAttributes); - dns.cancelAsyncResolve(hostname2, flags, listener1, - Cr.NS_ERROR_ABORT, defaultOriginAttributes); + requestList1Canceled1 = dns.asyncResolve( + hostname2, + flags, + listener1, + mainThread, + defaultOriginAttributes + ); + dns.cancelAsyncResolve( + hostname2, + flags, + listener1, + Cr.NS_ERROR_ABORT, + defaultOriginAttributes + ); // This one will not be canceled. - requestList1NotCanceled = dns.asyncResolve(hostname1, flags, listener1, - mainThread, defaultOriginAttributes); + requestList1NotCanceled = dns.asyncResolve( + hostname1, + flags, + listener1, + mainThread, + defaultOriginAttributes + ); // This one will be canceled with cancel(Cr.NS_ERROR_ABORT). - requestList1Canceled2 = dns.asyncResolve(hostname1, flags, listener1, - mainThread, defaultOriginAttributes); + requestList1Canceled2 = dns.asyncResolve( + hostname1, + flags, + listener1, + mainThread, + defaultOriginAttributes + ); requestList1Canceled2.cancel(Cr.NS_ERROR_ABORT); // This one will not be canceled. - requestList2NotCanceled = dns.asyncResolve(hostname1, flags, listener2, - mainThread, defaultOriginAttributes); + requestList2NotCanceled = dns.asyncResolve( + hostname1, + flags, + listener2, + mainThread, + defaultOriginAttributes + ); // This one will be canceled with cancel(Cr.NS_ERROR_ABORT). - requestList2Canceled = dns.asyncResolve(hostname2, flags, listener2, - mainThread, defaultOriginAttributes); + requestList2Canceled = dns.asyncResolve( + hostname2, + flags, + listener2, + mainThread, + defaultOriginAttributes + ); requestList2Canceled.cancel(Cr.NS_ERROR_ABORT); do_test_pending(); diff --git a/netwerk/test/unit/test_dns_disable_ipv4.js b/netwerk/test/unit/test_dns_disable_ipv4.js index 411f811561e2..8a148159e50a 100644 --- a/netwerk/test/unit/test_dns_disable_ipv4.js +++ b/netwerk/test/unit/test_dns_disable_ipv4.js @@ -4,7 +4,9 @@ // var dns = Cc["@mozilla.org/network/dns-service;1"].getService(Ci.nsIDNSService); -var ioService = Cc["@mozilla.org/network/io-service;1"].getService(Ci.nsIIOService); +var ioService = Cc["@mozilla.org/network/io-service;1"].getService( + Ci.nsIIOService +); var listener = { onLookupComplete(inRequest, inRecord, inStatus) { @@ -19,13 +21,13 @@ var listener = { var answer = inRecord.getNextAddrAsString(); // If there is an answer it should be an IPv6 address dump(answer); - Assert.ok(answer.includes(':')); + Assert.ok(answer.includes(":")); } catch (e) { break; } } do_test_finished(); - } + }, }; const defaultOriginAttributes = {}; @@ -33,8 +35,13 @@ const defaultOriginAttributes = {}; function run_test() { do_test_pending(); try { - dns.asyncResolve("example.org", Ci.nsIDNSService.RESOLVE_DISABLE_IPV4, - listener, null, defaultOriginAttributes); + dns.asyncResolve( + "example.org", + Ci.nsIDNSService.RESOLVE_DISABLE_IPV4, + listener, + null, + defaultOriginAttributes + ); } catch (e) { dump(e); Assert.ok(false); diff --git a/netwerk/test/unit/test_dns_disable_ipv6.js b/netwerk/test/unit/test_dns_disable_ipv6.js index 3b8d20482db5..dc29ab74c039 100644 --- a/netwerk/test/unit/test_dns_disable_ipv6.js +++ b/netwerk/test/unit/test_dns_disable_ipv6.js @@ -4,7 +4,9 @@ // var dns = Cc["@mozilla.org/network/dns-service;1"].getService(Ci.nsIDNSService); -var ioService = Cc["@mozilla.org/network/io-service;1"].getService(Ci.nsIIOService); +var ioService = Cc["@mozilla.org/network/io-service;1"].getService( + Ci.nsIIOService +); var listener = { onLookupComplete(inRequest, inRecord, inStatus) { @@ -19,14 +21,14 @@ var listener = { var answer = inRecord.getNextAddrAsString(); // If there is an answer it should be an IPv4 address dump(answer); - Assert.ok(!answer.includes(':')); - Assert.ok(answer.includes('.')); + Assert.ok(!answer.includes(":")); + Assert.ok(answer.includes(".")); } catch (e) { break; } } do_test_finished(); - } + }, }; const defaultOriginAttributes = {}; @@ -34,8 +36,13 @@ const defaultOriginAttributes = {}; function run_test() { do_test_pending(); try { - dns.asyncResolve("example.com", Ci.nsIDNSService.RESOLVE_DISABLE_IPV6, - listener, null, defaultOriginAttributes); + dns.asyncResolve( + "example.com", + Ci.nsIDNSService.RESOLVE_DISABLE_IPV6, + listener, + null, + defaultOriginAttributes + ); } catch (e) { dump(e); Assert.ok(false); diff --git a/netwerk/test/unit/test_dns_localredirect.js b/netwerk/test/unit/test_dns_localredirect.js index 58d6c5146d4b..53f11e350f06 100644 --- a/netwerk/test/unit/test_dns_localredirect.js +++ b/netwerk/test/unit/test_dns_localredirect.js @@ -1,5 +1,7 @@ var dns = Cc["@mozilla.org/network/dns-service;1"].getService(Ci.nsIDNSService); -var prefs = Cc["@mozilla.org/preferences-service;1"].getService(Ci.nsIPrefBranch); +var prefs = Cc["@mozilla.org/preferences-service;1"].getService( + Ci.nsIPrefBranch +); var nextTest; @@ -11,7 +13,7 @@ var listener = { nextTest(); do_test_finished(); }, - QueryInterface: ChromeUtils.generateQI(["nsIDNSListener"]) + QueryInterface: ChromeUtils.generateQI(["nsIDNSListener"]), }; const defaultOriginAttributes = {}; @@ -19,21 +21,36 @@ const defaultOriginAttributes = {}; function run_test() { prefs.setCharPref("network.dns.localDomains", "local.vingtetun.org"); - var threadManager = Cc["@mozilla.org/thread-manager;1"].getService(Ci.nsIThreadManager); + var threadManager = Cc["@mozilla.org/thread-manager;1"].getService( + Ci.nsIThreadManager + ); var mainThread = threadManager.currentThread; nextTest = do_test_2; - dns.asyncResolve("local.vingtetun.org", 0, listener, - mainThread, defaultOriginAttributes); + dns.asyncResolve( + "local.vingtetun.org", + 0, + listener, + mainThread, + defaultOriginAttributes + ); do_test_pending(); } function do_test_2() { - var threadManager = Cc["@mozilla.org/thread-manager;1"].getService(Ci.nsIThreadManager); + var threadManager = Cc["@mozilla.org/thread-manager;1"].getService( + Ci.nsIThreadManager + ); var mainThread = threadManager.currentThread; nextTest = testsDone; prefs.setCharPref("network.dns.forceResolve", "localhost"); - dns.asyncResolve("www.example.com", 0, listener, mainThread, defaultOriginAttributes); + dns.asyncResolve( + "www.example.com", + 0, + listener, + mainThread, + defaultOriginAttributes + ); do_test_pending(); } @@ -42,4 +59,3 @@ function testsDone() { prefs.clearUserPref("network.dns.localDomains"); prefs.clearUserPref("network.dns.forceResolve"); } - diff --git a/netwerk/test/unit/test_dns_offline.js b/netwerk/test/unit/test_dns_offline.js index 42773c9f5ac5..15abfa193932 100644 --- a/netwerk/test/unit/test_dns_offline.js +++ b/netwerk/test/unit/test_dns_offline.js @@ -1,7 +1,13 @@ var dns = Cc["@mozilla.org/network/dns-service;1"].getService(Ci.nsIDNSService); -var ioService = Cc["@mozilla.org/network/io-service;1"].getService(Ci.nsIIOService); -var prefs = Cc["@mozilla.org/preferences-service;1"].getService(Ci.nsIPrefBranch); -var threadManager = Cc["@mozilla.org/thread-manager;1"].getService(Ci.nsIThreadManager); +var ioService = Cc["@mozilla.org/network/io-service;1"].getService( + Ci.nsIIOService +); +var prefs = Cc["@mozilla.org/preferences-service;1"].getService( + Ci.nsIPrefBranch +); +var threadManager = Cc["@mozilla.org/thread-manager;1"].getService( + Ci.nsIThreadManager +); var mainThread = threadManager.currentThread; var listener1 = { @@ -9,7 +15,7 @@ var listener1 = { Assert.equal(inStatus, Cr.NS_ERROR_OFFLINE); test2(); do_test_finished(); - } + }, }; var listener2 = { @@ -19,7 +25,7 @@ var listener2 = { Assert.ok(answer == "127.0.0.1" || answer == "::1"); test3(); do_test_finished(); - } + }, }; var listener3 = { @@ -29,7 +35,7 @@ var listener3 = { Assert.ok(answer == "127.0.0.1" || answer == "::1"); cleanup(); do_test_finished(); - } + }, }; const defaultOriginAttributes = {}; @@ -39,11 +45,17 @@ function run_test() { prefs.setBoolPref("network.dns.offline-localhost", false); ioService.offline = true; try { - dns.asyncResolve("localhost", 0, listener1, mainThread, defaultOriginAttributes); + dns.asyncResolve( + "localhost", + 0, + listener1, + mainThread, + defaultOriginAttributes + ); } catch (e) { - Assert.equal(e.result, Cr.NS_ERROR_OFFLINE); - test2(); - do_test_finished(); + Assert.equal(e.result, Cr.NS_ERROR_OFFLINE); + test2(); + do_test_finished(); } } @@ -57,7 +69,13 @@ function test2() { } function test2Continued() { - dns.asyncResolve("localhost", 0, listener2, mainThread, defaultOriginAttributes); + dns.asyncResolve( + "localhost", + 0, + listener2, + mainThread, + defaultOriginAttributes + ); } function test3() { @@ -68,7 +86,13 @@ function test3() { } function test3Continued() { - dns.asyncResolve("localhost", 0, listener3, mainThread, defaultOriginAttributes); + dns.asyncResolve( + "localhost", + 0, + listener3, + mainThread, + defaultOriginAttributes + ); } function cleanup() { diff --git a/netwerk/test/unit/test_dns_onion.js b/netwerk/test/unit/test_dns_onion.js index 590b70152818..f5b7f91c3878 100644 --- a/netwerk/test/unit/test_dns_onion.js +++ b/netwerk/test/unit/test_dns_onion.js @@ -1,10 +1,14 @@ var dns = Cc["@mozilla.org/network/dns-service;1"].getService(Ci.nsIDNSService); -var threadManager = Cc["@mozilla.org/thread-manager;1"].getService(Ci.nsIThreadManager); +var threadManager = Cc["@mozilla.org/thread-manager;1"].getService( + Ci.nsIThreadManager +); var mainThread = threadManager.currentThread; var onionPref; var localdomainPref; -var prefs = Cc["@mozilla.org/preferences-service;1"].getService(Ci.nsIPrefBranch); +var prefs = Cc["@mozilla.org/preferences-service;1"].getService( + Ci.nsIPrefBranch +); // check that we don't lookup .onion var listenerBlock = { @@ -12,7 +16,7 @@ var listenerBlock = { Assert.ok(!Components.isSuccessCode(inStatus)); do_test_dontBlock(); }, - QueryInterface: ChromeUtils.generateQI(["nsIDNSListener"]) + QueryInterface: ChromeUtils.generateQI(["nsIDNSListener"]), }; // check that we do lookup .onion (via pref) @@ -22,22 +26,32 @@ var listenerDontBlock = { Assert.ok(answer == "127.0.0.1" || answer == "::1"); all_done(); }, - QueryInterface: ChromeUtils.generateQI(["nsIDNSListener"]) + QueryInterface: ChromeUtils.generateQI(["nsIDNSListener"]), }; const defaultOriginAttributes = {}; function do_test_dontBlock() { prefs.setBoolPref("network.dns.blockDotOnion", false); - dns.asyncResolve("private.onion", 0, listenerDontBlock, - mainThread, defaultOriginAttributes); + dns.asyncResolve( + "private.onion", + 0, + listenerDontBlock, + mainThread, + defaultOriginAttributes + ); } function do_test_block() { prefs.setBoolPref("network.dns.blockDotOnion", true); try { - dns.asyncResolve("private.onion", 0, listenerBlock, - mainThread, defaultOriginAttributes); + dns.asyncResolve( + "private.onion", + 0, + listenerBlock, + mainThread, + defaultOriginAttributes + ); } catch (e) { // it is ok for this negative test to fail fast Assert.ok(true); @@ -59,4 +73,3 @@ function run_test() { do_test_block(); do_test_pending(); } - diff --git a/netwerk/test/unit/test_dns_originAttributes.js b/netwerk/test/unit/test_dns_originAttributes.js index a59e8d04cfc1..b87b6b44fecb 100644 --- a/netwerk/test/unit/test_dns_originAttributes.js +++ b/netwerk/test/unit/test_dns_originAttributes.js @@ -1,5 +1,7 @@ var dns = Cc["@mozilla.org/network/dns-service;1"].getService(Ci.nsIDNSService); -var threadManager = Cc["@mozilla.org/thread-manager;1"].getService(Ci.nsIThreadManager); +var threadManager = Cc["@mozilla.org/thread-manager;1"].getService( + Ci.nsIThreadManager +); var mainThread = threadManager.currentThread; var listener1 = { @@ -9,7 +11,7 @@ var listener1 = { Assert.ok(answer == "127.0.0.1" || answer == "::1"); test2(); do_test_finished(); - } + }, }; var listener2 = { @@ -19,31 +21,42 @@ var listener2 = { Assert.ok(answer == "127.0.0.1" || answer == "::1"); test3(); do_test_finished(); - } + }, }; var listener3 = { onLookupComplete(inRequest, inRecord, inStatus) { Assert.equal(inStatus, Cr.NS_ERROR_OFFLINE); do_test_finished(); - } + }, }; -const firstOriginAttributes = { userContextId: 1 }; +const firstOriginAttributes = { userContextId: 1 }; const secondOriginAttributes = { userContextId: 2 }; // First, we resolve the address normally for first originAttributes. function run_test() { do_test_pending(); - dns.asyncResolve("localhost", 0, listener1, mainThread, firstOriginAttributes); + dns.asyncResolve( + "localhost", + 0, + listener1, + mainThread, + firstOriginAttributes + ); } // Second, we resolve the same address offline to see whether its DNS cache works // correctly. function test2() { do_test_pending(); - dns.asyncResolve("localhost", Ci.nsIDNSService.RESOLVE_OFFLINE, listener2, - mainThread, firstOriginAttributes); + dns.asyncResolve( + "localhost", + Ci.nsIDNSService.RESOLVE_OFFLINE, + listener2, + mainThread, + firstOriginAttributes + ); } // Third, we resolve the same address offline again with different originAttributes. @@ -52,10 +65,15 @@ function test2() { function test3() { do_test_pending(); try { - dns.asyncResolve("localhost", Ci.nsIDNSService.RESOLVE_OFFLINE, listener3, - mainThread, secondOriginAttributes); + dns.asyncResolve( + "localhost", + Ci.nsIDNSService.RESOLVE_OFFLINE, + listener3, + mainThread, + secondOriginAttributes + ); } catch (e) { - Assert.equal(e.result, Cr.NS_ERROR_OFFLINE); - do_test_finished(); + Assert.equal(e.result, Cr.NS_ERROR_OFFLINE); + do_test_finished(); } } diff --git a/netwerk/test/unit/test_dns_proxy_bypass.js b/netwerk/test/unit/test_dns_proxy_bypass.js index 1e7e25c470f3..666b4fed6ce3 100644 --- a/netwerk/test/unit/test_dns_proxy_bypass.js +++ b/netwerk/test/unit/test_dns_proxy_bypass.js @@ -2,18 +2,21 @@ * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ -var ioService = Cc["@mozilla.org/network/io-service;1"]. - getService(Ci.nsIIOService); +var ioService = Cc["@mozilla.org/network/io-service;1"].getService( + Ci.nsIIOService +); -var prefs = Cc["@mozilla.org/preferences-service;1"]. - getService(Ci.nsIPrefBranch); +var prefs = Cc["@mozilla.org/preferences-service;1"].getService( + Ci.nsIPrefBranch +); var url = "ws://dnsleak.example.com"; var dnsRequestObserver = { register() { - this.obs = Cc["@mozilla.org/observer-service;1"]. - getService(Ci.nsIObserverService); + this.obs = Cc["@mozilla.org/observer-service;1"].getService( + Ci.nsIObserverService + ); this.obs.addObserver(this, "dns-resolution-request"); }, @@ -32,7 +35,7 @@ var dnsRequestObserver = { } catch (e) {} } } - } + }, }; var listener = { @@ -49,7 +52,7 @@ var listener = { prefs.clearUserPref("network.dns.notifyResolution"); dnsRequestObserver.unregister(); do_test_finished(); - } + }, }; function run_test() { @@ -59,17 +62,19 @@ function run_test() { prefs.setIntPref("network.proxy.socks_port", 9000); prefs.setIntPref("network.proxy.type", 1); prefs.setBoolPref("network.proxy.socks_remote_dns", true); - var chan = Cc["@mozilla.org/network/protocol;1?name=ws"]. - createInstance(Ci.nsIWebSocketChannel); + var chan = Cc["@mozilla.org/network/protocol;1?name=ws"].createInstance( + Ci.nsIWebSocketChannel + ); - chan.initLoadInfo(null, // aLoadingNode - Services.scriptSecurityManager.getSystemPrincipal(), - null, // aTriggeringPrincipal - Ci.nsILoadInfo.SEC_ALLOW_CROSS_ORIGIN_DATA_IS_NULL, - Ci.nsIContentPolicy.TYPE_WEBSOCKET); + chan.initLoadInfo( + null, // aLoadingNode + Services.scriptSecurityManager.getSystemPrincipal(), + null, // aTriggeringPrincipal + Ci.nsILoadInfo.SEC_ALLOW_CROSS_ORIGIN_DATA_IS_NULL, + Ci.nsIContentPolicy.TYPE_WEBSOCKET + ); var uri = ioService.newURI(url); chan.asyncOpen(uri, url, 0, listener, null); do_test_pending(); } - diff --git a/netwerk/test/unit/test_dns_service.js b/netwerk/test/unit/test_dns_service.js index b45c6241856c..5dcedd389fa2 100644 --- a/netwerk/test/unit/test_dns_service.js +++ b/netwerk/test/unit/test_dns_service.js @@ -7,16 +7,23 @@ var listener = { do_test_finished(); }, - QueryInterface: ChromeUtils.generateQI(["nsIDNSListener"]) + QueryInterface: ChromeUtils.generateQI(["nsIDNSListener"]), }; const defaultOriginAttributes = {}; function run_test() { - var threadManager = Cc["@mozilla.org/thread-manager;1"].getService(Ci.nsIThreadManager); + var threadManager = Cc["@mozilla.org/thread-manager;1"].getService( + Ci.nsIThreadManager + ); var mainThread = threadManager.currentThread; - dns.asyncResolve("localhost", 0, listener, mainThread, defaultOriginAttributes); + dns.asyncResolve( + "localhost", + 0, + listener, + mainThread, + defaultOriginAttributes + ); do_test_pending(); } - diff --git a/netwerk/test/unit/test_domain_eviction.js b/netwerk/test/unit/test_domain_eviction.js index dc5659bfcea4..40b41523f4fd 100644 --- a/netwerk/test/unit/test_domain_eviction.js +++ b/netwerk/test/unit/test_domain_eviction.js @@ -6,19 +6,16 @@ var test_generator = do_run_test(); -function run_test() -{ +function run_test() { do_test_pending(); do_run_generator(test_generator); } -function continue_test() -{ +function continue_test() { do_run_generator(test_generator); } -function* do_run_test() -{ +function* do_run_test() { // Set quotaPerHost to maxPerHost - 1, so there is only one cookie // will be evicted everytime. Services.prefs.setIntPref("network.cookie.quotaPerHost", 49); @@ -60,24 +57,48 @@ function* do_run_test() Assert.equal(countCookies("horse.radish", "horse.radish"), 50); for (let cookie of Services.cookiemgr.enumerator) { - if (cookie.host == "horse.radish") + if (cookie.host == "horse.radish") { do_throw("cookies not evicted by lastAccessed order"); + } } // Test that expired cookies for a domain are evicted before live ones. let shortExpiry = Math.floor(Date.now() / 1000 + 2); setCookies("captchart.com", 49, futureExpiry); - Services.cookiemgr.add("captchart.com", "", "test100", "eviction", - false, false, false, shortExpiry, {}, Ci.nsICookie.SAMESITE_NONE); + Services.cookiemgr.add( + "captchart.com", + "", + "test100", + "eviction", + false, + false, + false, + shortExpiry, + {}, + Ci.nsICookie.SAMESITE_NONE + ); do_timeout(2100, continue_test); yield; Assert.equal(countCookies("captchart.com", "captchart.com"), 50); - Services.cookiemgr.add("captchart.com", "", "test200", "eviction", - false, false, false, futureExpiry, {}, Ci.nsICookie.SAMESITE_NONE); + Services.cookiemgr.add( + "captchart.com", + "", + "test200", + "eviction", + false, + false, + false, + futureExpiry, + {}, + Ci.nsICookie.SAMESITE_NONE + ); Assert.equal(countCookies("captchart.com", "captchart.com"), 50); - for (let cookie of Services.cookiemgr.getCookiesFromHost("captchart.com", {})) { + for (let cookie of Services.cookiemgr.getCookiesFromHost( + "captchart.com", + {} + )) { Assert.ok(cookie.expiry == futureExpiry); } @@ -85,12 +106,21 @@ function* do_run_test() } // set 'aNumber' cookies with host 'aHost', with distinct names. -function -setCookies(aHost, aNumber, aExpiry) -{ - for (let i = 0; i < aNumber; ++i) - Services.cookiemgr.add(aHost, "", "test" + i, "eviction", - false, false, false, aExpiry, {}, Ci.nsICookie.SAMESITE_NONE); +function setCookies(aHost, aNumber, aExpiry) { + for (let i = 0; i < aNumber; ++i) { + Services.cookiemgr.add( + aHost, + "", + "test" + i, + "eviction", + false, + false, + false, + aExpiry, + {}, + Ci.nsICookie.SAMESITE_NONE + ); + } } // count how many cookies are within domain 'aBaseDomain', using three @@ -99,27 +129,32 @@ setCookies(aHost, aNumber, aExpiry) // 2) 'countCookiesFromHost', which returns the number of cookies within the // base domain of 'aHost', // 3) 'getCookiesFromHost', which returns an enumerator of 2). -function -countCookies(aBaseDomain, aHost) -{ +function countCookies(aBaseDomain, aHost) { // count how many cookies are within domain 'aBaseDomain' using the cookie // enumerator. let cookies = []; for (let cookie of Services.cookiemgr.enumerator) { - if (cookie.host.length >= aBaseDomain.length && - cookie.host.slice(cookie.host.length - aBaseDomain.length) == aBaseDomain) + if ( + cookie.host.length >= aBaseDomain.length && + cookie.host.slice(cookie.host.length - aBaseDomain.length) == aBaseDomain + ) { cookies.push(cookie); + } } // confirm the count using countCookiesFromHost and getCookiesFromHost. let result = cookies.length; - Assert.equal(Services.cookiemgr.countCookiesFromHost(aBaseDomain), - cookies.length); + Assert.equal( + Services.cookiemgr.countCookiesFromHost(aBaseDomain), + cookies.length + ); Assert.equal(Services.cookiemgr.countCookiesFromHost(aHost), cookies.length); for (let cookie of Services.cookiemgr.getCookiesFromHost(aHost, {})) { - if (cookie.host.length >= aBaseDomain.length && - cookie.host.slice(cookie.host.length - aBaseDomain.length) == aBaseDomain) { + if ( + cookie.host.length >= aBaseDomain.length && + cookie.host.slice(cookie.host.length - aBaseDomain.length) == aBaseDomain + ) { let found = false; for (let i = 0; i < cookies.length; ++i) { if (cookies[i].host == cookie.host && cookies[i].name == cookie.name) { @@ -129,11 +164,13 @@ countCookies(aBaseDomain, aHost) } } - if (!found) + if (!found) { do_throw("cookie " + cookie.name + " not found in master enumerator"); - + } } else { - do_throw("cookie host " + cookie.host + " not within domain " + aBaseDomain); + do_throw( + "cookie host " + cookie.host + " not within domain " + aBaseDomain + ); } } @@ -141,4 +178,3 @@ countCookies(aBaseDomain, aHost) return result; } - diff --git a/netwerk/test/unit/test_doomentry.js b/netwerk/test/unit/test_doomentry.js index 2105ed14fe7a..1fc0fca5e808 100644 --- a/netwerk/test/unit/test_doomentry.js +++ b/netwerk/test/unit/test_doomentry.js @@ -6,36 +6,44 @@ * - an existent active entry */ -function doom(url, callback) -{ +function doom(url, callback) { get_cache_service() - .diskCacheStorage(Services.loadContextInfo.default, false) - .asyncDoomURI(createURI(url), "", { - onCacheEntryDoomed(result) { - callback(result); - } - }); + .diskCacheStorage(Services.loadContextInfo.default, false) + .asyncDoomURI(createURI(url), "", { + onCacheEntryDoomed(result) { + callback(result); + }, + }); } -function write_and_check(str, data, len) -{ +function write_and_check(str, data, len) { var written = str.write(data, len); if (written != len) { - do_throw("str.write has not written all data!\n" + - " Expected: " + len + "\n" + - " Actual: " + written + "\n"); + do_throw( + "str.write has not written all data!\n" + + " Expected: " + + len + + "\n" + + " Actual: " + + written + + "\n" + ); } } -function write_entry() -{ - asyncOpenCacheEntry("http://testentry/", "disk", Ci.nsICacheStorage.OPEN_TRUNCATE, null, function(status, entry) { - write_entry_cont(entry, entry.openOutputStream(0, -1)); - }); +function write_entry() { + asyncOpenCacheEntry( + "http://testentry/", + "disk", + Ci.nsICacheStorage.OPEN_TRUNCATE, + null, + function(status, entry) { + write_entry_cont(entry, entry.openOutputStream(0, -1)); + } + ); } -function write_entry_cont(entry, ostream) -{ +function write_entry_cont(entry, ostream) { var data = "testdata"; write_and_check(ostream, data, data.length); ostream.close(); @@ -43,24 +51,27 @@ function write_entry_cont(entry, ostream) doom("http://testentry/", check_doom1); } -function check_doom1(status) -{ +function check_doom1(status) { Assert.equal(status, Cr.NS_OK); doom("http://nonexistententry/", check_doom2); } -function check_doom2(status) -{ +function check_doom2(status) { Assert.equal(status, Cr.NS_ERROR_NOT_AVAILABLE); - asyncOpenCacheEntry("http://testentry/", "disk", Ci.nsICacheStorage.OPEN_TRUNCATE, null, function(status, entry) { - write_entry2(entry, entry.openOutputStream(0, -1)); - }); + asyncOpenCacheEntry( + "http://testentry/", + "disk", + Ci.nsICacheStorage.OPEN_TRUNCATE, + null, + function(status, entry) { + write_entry2(entry, entry.openOutputStream(0, -1)); + } + ); } var gEntry; var gOstream; -function write_entry2(entry, ostream) -{ +function write_entry2(entry, ostream) { // write some data and doom the entry while it is active var data = "testdata"; write_and_check(ostream, data, data.length); @@ -69,8 +80,7 @@ function write_entry2(entry, ostream) doom("http://testentry/", check_doom3); } -function check_doom3(status) -{ +function check_doom3(status) { Assert.equal(status, Cr.NS_OK); // entry was doomed but writing should still succeed var data = "testdata"; @@ -81,8 +91,7 @@ function check_doom3(status) doom("http://testentry/", check_doom4); } -function check_doom4(status) -{ +function check_doom4(status) { Assert.equal(status, Cr.NS_ERROR_NOT_AVAILABLE); do_test_finished(); } diff --git a/netwerk/test/unit/test_duplicate_headers.js b/netwerk/test/unit/test_duplicate_headers.js index 5ac327095606..3b59432887de 100644 --- a/netwerk/test/unit/test_duplicate_headers.js +++ b/netwerk/test/unit/test_duplicate_headers.js @@ -6,7 +6,7 @@ //////////////////////////////////////////////////////////////////////////////// // Test infrastructure -const {HttpServer} = ChromeUtils.import("resource://testing-common/httpd.js"); +const { HttpServer } = ChromeUtils.import("resource://testing-common/httpd.js"); XPCOMUtils.defineLazyGetter(this, "URL", function() { return "http://localhost:" + httpserver.identity.primaryPort; @@ -17,37 +17,34 @@ var index = 0; var test_flags = new Array(); var testPathBase = "/dupe_hdrs"; -function run_test() -{ +function run_test() { httpserver.start(-1); do_test_pending(); run_test_number(1); } -function run_test_number(num) -{ +function run_test_number(num) { testPath = testPathBase + num; httpserver.registerPathHandler(testPath, this["handler" + num]); var channel = setupChannel(testPath); - flags = test_flags[num]; // OK if flags undefined for test - channel.asyncOpen(new ChannelListener(this["completeTest" + num], - channel, flags)); + flags = test_flags[num]; // OK if flags undefined for test + channel.asyncOpen( + new ChannelListener(this["completeTest" + num], channel, flags) + ); } -function setupChannel(url) -{ +function setupChannel(url) { var chan = NetUtil.newChannel({ uri: URL + url, - loadUsingSystemPrincipal: true + loadUsingSystemPrincipal: true, }); var httpChan = chan.QueryInterface(Ci.nsIHttpChannel); return httpChan; } -function endTests() -{ +function endTests() { httpserver.stop(do_test_finished); } @@ -55,8 +52,7 @@ function endTests() // Test 1: FAIL because of conflicting Content-Length headers test_flags[1] = CL_EXPECT_FAILURE; -function handler1(metadata, response) -{ +function handler1(metadata, response) { var body = "012345678901234567890123456789"; // Comrades! We must seize power from the petty-bourgeois running dogs of // httpd.js in order to reply with multiple instances of the same header! @@ -70,9 +66,7 @@ function handler1(metadata, response) response.finish(); } - -function completeTest1(request, data, ctx) -{ +function completeTest1(request, data, ctx) { Assert.equal(request.status, Cr.NS_ERROR_CORRUPTED_CONTENT); run_test_number(2); @@ -81,8 +75,7 @@ function completeTest1(request, data, ctx) //////////////////////////////////////////////////////////////////////////////// // Test 2: OK to have duplicate same Content-Length headers -function handler2(metadata, response) -{ +function handler2(metadata, response) { var body = "012345678901234567890123456789"; response.seizePower(); response.write("HTTP/1.0 200 OK\r\n"); @@ -94,8 +87,7 @@ function handler2(metadata, response) response.finish(); } -function completeTest2(request, data, ctx) -{ +function completeTest2(request, data, ctx) { Assert.equal(request.status, 0); run_test_number(3); } @@ -104,8 +96,7 @@ function completeTest2(request, data, ctx) // Test 3: FAIL: 2nd Content-length is blank test_flags[3] = CL_EXPECT_FAILURE; -function handler3(metadata, response) -{ +function handler3(metadata, response) { var body = "012345678901234567890123456789"; response.seizePower(); response.write("HTTP/1.0 200 OK\r\n"); @@ -117,20 +108,18 @@ function handler3(metadata, response) response.finish(); } -function completeTest3(request, data, ctx) -{ +function completeTest3(request, data, ctx) { Assert.equal(request.status, Cr.NS_ERROR_CORRUPTED_CONTENT); run_test_number(4); } //////////////////////////////////////////////////////////////////////////////// -// Test 4: ensure that blank C-len header doesn't allow attacker to reset Clen, +// Test 4: ensure that blank C-len header doesn't allow attacker to reset Clen, // then insert CRLF attack test_flags[4] = CL_EXPECT_FAILURE; -function handler4(metadata, response) -{ +function handler4(metadata, response) { var body = "012345678901234567890123456789"; response.seizePower(); @@ -147,20 +136,17 @@ function handler4(metadata, response) response.finish(); } -function completeTest4(request, data, ctx) -{ +function completeTest4(request, data, ctx) { Assert.equal(request.status, Cr.NS_ERROR_CORRUPTED_CONTENT); run_test_number(5); } - //////////////////////////////////////////////////////////////////////////////// // Test 5: ensure that we take 1st instance of duplicate, nonmerged headers that // are permitted : (ex: Referrer) -function handler5(metadata, response) -{ +function handler5(metadata, response) { var body = "012345678901234567890123456789"; response.seizePower(); response.write("HTTP/1.0 200 OK\r\n"); @@ -173,8 +159,7 @@ function handler5(metadata, response) response.finish(); } -function completeTest5(request, data, ctx) -{ +function completeTest5(request, data, ctx) { try { referer = request.getResponseHeader("Referer"); Assert.equal(referer, "naive.org"); @@ -190,8 +175,7 @@ function completeTest5(request, data, ctx) // - needed to prevent CRLF injection attacks test_flags[6] = CL_EXPECT_FAILURE; -function handler6(metadata, response) -{ +function handler6(metadata, response) { var body = "012345678901234567890123456789"; response.seizePower(); response.write("HTTP/1.0 301 Moved\r\n"); @@ -205,19 +189,17 @@ function handler6(metadata, response) response.finish(); } -function completeTest6(request, data, ctx) -{ +function completeTest6(request, data, ctx) { Assert.equal(request.status, Cr.NS_ERROR_CORRUPTED_CONTENT); -// run_test_number(7); // Test 7 leaking under e10s: unrelated bug? + // run_test_number(7); // Test 7 leaking under e10s: unrelated bug? run_test_number(8); } //////////////////////////////////////////////////////////////////////////////// // Test 7: OK to have multiple Location: headers with same value -function handler7(metadata, response) -{ +function handler7(metadata, response) { var body = "012345678901234567890123456789"; response.seizePower(); response.write("HTTP/1.0 301 Moved\r\n"); @@ -232,8 +214,7 @@ function handler7(metadata, response) response.finish(); } -function completeTest7(request, data, ctx) -{ +function completeTest7(request, data, ctx) { // for some reason need this here request.QueryInterface(Ci.nsIHttpChannel); @@ -251,8 +232,7 @@ function completeTest7(request, data, ctx) // FAIL if 2nd Location: headers blank test_flags[8] = CL_EXPECT_FAILURE; -function handler8(metadata, response) -{ +function handler8(metadata, response) { var body = "012345678901234567890123456789"; response.seizePower(); response.write("HTTP/1.0 301 Moved\r\n"); @@ -267,26 +247,24 @@ function handler8(metadata, response) response.finish(); } -function completeTest8(request, data, ctx) -{ +function completeTest8(request, data, ctx) { Assert.equal(request.status, Cr.NS_ERROR_CORRUPTED_CONTENT); run_test_number(9); } //////////////////////////////////////////////////////////////////////////////// -// Test 9: ensure that blank Location header doesn't allow attacker to reset, +// Test 9: ensure that blank Location header doesn't allow attacker to reset, // then insert an evil one test_flags[9] = CL_EXPECT_FAILURE; -function handler9(metadata, response) -{ +function handler9(metadata, response) { var body = "012345678901234567890123456789"; response.seizePower(); response.write("HTTP/1.0 301 Moved\r\n"); response.write("Content-Type: text/plain\r\n"); response.write("Content-Length: 30\r\n"); - // redirect to previous test handler that completes OK: test 2 + // redirect to previous test handler that completes OK: test 2 response.write("Location: " + URL + testPathBase + "2\r\n"); response.write("Location:\r\n"); // redirect to previous test handler that completes OK: test 4 @@ -297,8 +275,7 @@ function handler9(metadata, response) response.finish(); } -function completeTest9(request, data, ctx) -{ +function completeTest9(request, data, ctx) { // All redirection should fail: Assert.equal(request.status, Cr.NS_ERROR_CORRUPTED_CONTENT); @@ -306,11 +283,10 @@ function completeTest9(request, data, ctx) } //////////////////////////////////////////////////////////////////////////////// -// Test 10: FAIL: if conflicting values for Content-Dispo +// Test 10: FAIL: if conflicting values for Content-Dispo test_flags[10] = CL_EXPECT_FAILURE; -function handler10(metadata, response) -{ +function handler10(metadata, response) { var body = "012345678901234567890123456789"; response.seizePower(); response.write("HTTP/1.0 200 OK\r\n"); @@ -324,9 +300,7 @@ function handler10(metadata, response) response.finish(); } - -function completeTest10(request, data, ctx) -{ +function completeTest10(request, data, ctx) { Assert.equal(request.status, Cr.NS_ERROR_CORRUPTED_CONTENT); run_test_number(11); @@ -335,8 +309,7 @@ function completeTest10(request, data, ctx) //////////////////////////////////////////////////////////////////////////////// // Test 11: OK to have duplicate same Content-Disposition headers -function handler11(metadata, response) -{ +function handler11(metadata, response) { var body = "012345678901234567890123456789"; response.seizePower(); response.write("HTTP/1.0 200 OK\r\n"); @@ -349,8 +322,7 @@ function handler11(metadata, response) response.finish(); } -function completeTest11(request, data, ctx) -{ +function completeTest11(request, data, ctx) { Assert.equal(request.status, 0); try { @@ -368,8 +340,7 @@ function completeTest11(request, data, ctx) //////////////////////////////////////////////////////////////////////////////// // Bug 716801 OK for Location: header to be blank -function handler12(metadata, response) -{ +function handler12(metadata, response) { var body = "012345678901234567890123456789"; response.seizePower(); response.write("HTTP/1.0 200 OK\r\n"); @@ -382,8 +353,7 @@ function handler12(metadata, response) response.finish(); } -function completeTest12(request, data, ctx) -{ +function completeTest12(request, data, ctx) { Assert.equal(request.status, Cr.NS_OK); Assert.equal(30, data.length); @@ -394,8 +364,7 @@ function completeTest12(request, data, ctx) // Negative content length is ok test_flags[13] = CL_ALLOW_UNKNOWN_CL; -function handler13(metadata, response) -{ +function handler13(metadata, response) { var body = "012345678901234567890123456789"; response.seizePower(); response.write("HTTP/1.0 200 OK\r\n"); @@ -407,8 +376,7 @@ function handler13(metadata, response) response.finish(); } -function completeTest13(request, data, ctx) -{ +function completeTest13(request, data, ctx) { Assert.equal(request.status, Cr.NS_OK); Assert.equal(30, data.length); @@ -420,8 +388,7 @@ function completeTest13(request, data, ctx) test_flags[14] = CL_EXPECT_FAILURE | CL_ALLOW_UNKNOWN_CL; -function handler14(metadata, response) -{ +function handler14(metadata, response) { var body = "012345678901234567890123456789"; response.seizePower(); response.write("HTTP/1.0 200 OK\r\n"); @@ -434,8 +401,7 @@ function handler14(metadata, response) response.finish(); } -function completeTest14(request, data, ctx) -{ +function completeTest14(request, data, ctx) { Assert.equal(request.status, Cr.NS_ERROR_CORRUPTED_CONTENT); run_test_number(15); @@ -446,8 +412,7 @@ function completeTest14(request, data, ctx) test_flags[15] = CL_EXPECT_FAILURE | CL_ALLOW_UNKNOWN_CL; -function handler15(metadata, response) -{ +function handler15(metadata, response) { var body = "012345678901234567890123456789"; response.seizePower(); response.write("HTTP/1.0 200 OK\r\n"); @@ -460,8 +425,7 @@ function handler15(metadata, response) response.finish(); } -function completeTest15(request, data, ctx) -{ +function completeTest15(request, data, ctx) { Assert.equal(request.status, Cr.NS_ERROR_CORRUPTED_CONTENT); run_test_number(16); @@ -472,8 +436,7 @@ function completeTest15(request, data, ctx) test_flags[16] = CL_ALLOW_UNKNOWN_CL; reran16 = false; -function handler16(metadata, response) -{ +function handler16(metadata, response) { var body = "012345678901234567890123456789"; response.seizePower(); response.write("HTTP/1.0 200 OK\r\n"); @@ -486,26 +449,23 @@ function handler16(metadata, response) response.finish(); } -function completeTest16(request, data, ctx) -{ +function completeTest16(request, data, ctx) { Assert.equal(request.status, Cr.NS_OK); Assert.equal(30, data.length); if (!reran16) { reran16 = true; run_test_number(16); + } else { + run_test_number(17); } - else { - run_test_number(17); - } } //////////////////////////////////////////////////////////////////////////////// // empty content length paired with non empty is not ok test_flags[17] = CL_EXPECT_FAILURE | CL_ALLOW_UNKNOWN_CL; -function handler17(metadata, response) -{ +function handler17(metadata, response) { var body = "012345678901234567890123456789"; response.seizePower(); response.write("HTTP/1.0 200 OK\r\n"); @@ -518,8 +478,7 @@ function handler17(metadata, response) response.finish(); } -function completeTest17(request, data, ctx) -{ +function completeTest17(request, data, ctx) { Assert.equal(request.status, Cr.NS_ERROR_CORRUPTED_CONTENT); run_test_number(18); @@ -529,8 +488,7 @@ function completeTest17(request, data, ctx) // alpha content-length is just like -1 test_flags[18] = CL_ALLOW_UNKNOWN_CL; -function handler18(metadata, response) -{ +function handler18(metadata, response) { var body = "012345678901234567890123456789"; response.seizePower(); response.write("HTTP/1.0 200 OK\r\n"); @@ -542,8 +500,7 @@ function handler18(metadata, response) response.finish(); } -function completeTest18(request, data, ctx) -{ +function completeTest18(request, data, ctx) { Assert.equal(request.status, Cr.NS_OK); Assert.equal(30, data.length); @@ -554,8 +511,7 @@ function completeTest18(request, data, ctx) // semi-colons are ok too in the content-length test_flags[19] = CL_ALLOW_UNKNOWN_CL; -function handler19(metadata, response) -{ +function handler19(metadata, response) { var body = "012345678901234567890123456789"; response.seizePower(); response.write("HTTP/1.0 200 OK\r\n"); @@ -567,8 +523,7 @@ function handler19(metadata, response) response.finish(); } -function completeTest19(request, data, ctx) -{ +function completeTest19(request, data, ctx) { Assert.equal(request.status, Cr.NS_OK); Assert.equal(30, data.length); @@ -579,8 +534,7 @@ function completeTest19(request, data, ctx) // FAIL if 1st Location: header is blank, followed by non-blank test_flags[20] = CL_EXPECT_FAILURE; -function handler20(metadata, response) -{ +function handler20(metadata, response) { var body = "012345678901234567890123456789"; response.seizePower(); response.write("HTTP/1.0 301 Moved\r\n"); @@ -595,10 +549,8 @@ function handler20(metadata, response) response.finish(); } -function completeTest20(request, data, ctx) -{ +function completeTest20(request, data, ctx) { Assert.equal(request.status, Cr.NS_ERROR_CORRUPTED_CONTENT); endTests(); } - diff --git a/netwerk/test/unit/test_esni_dns_fetch.js b/netwerk/test/unit/test_esni_dns_fetch.js index 9ccb97fd82c4..a26f11c5f8ed 100644 --- a/netwerk/test/unit/test_esni_dns_fetch.js +++ b/netwerk/test/unit/test_esni_dns_fetch.js @@ -5,13 +5,17 @@ var h2Port; var listen; var dns = Cc["@mozilla.org/network/dns-service;1"].getService(Ci.nsIDNSService); -var threadManager = Cc["@mozilla.org/thread-manager;1"].getService(Ci.nsIThreadManager); +var threadManager = Cc["@mozilla.org/thread-manager;1"].getService( + Ci.nsIThreadManager +); var mainThread = threadManager.currentThread; const defaultOriginAttributes = {}; function run_test() { - var env = Cc["@mozilla.org/process/environment;1"].getService(Ci.nsIEnvironment); + var env = Cc["@mozilla.org/process/environment;1"].getService( + Ci.nsIEnvironment + ); h2Port = env.get("MOZHTTP2_PORT"); Assert.notEqual(h2Port, null); Assert.notEqual(h2Port, ""); @@ -37,8 +41,9 @@ function run_test() { // The moz-http2 cert is for foo.example.com and is signed by http2-ca.pem // so add that cert to the trust list as a signing cert. // the foo.example.com domain name. - let certdb = Cc["@mozilla.org/security/x509certdb;1"] - .getService(Ci.nsIX509CertDB); + let certdb = Cc["@mozilla.org/security/x509certdb;1"].getService( + Ci.nsIX509CertDB + ); addCertFromFile(certdb, "http2-ca.pem", "CTu,u,u"); do_test_pending(); run_dns_tests(); @@ -60,11 +65,10 @@ registerCleanupFunction(() => { prefs.clearUserPref("network.trr.bootstrapAddress"); prefs.clearUserPref("network.trr.blacklist-duration"); prefs.clearUserPref("network.trr.request-timeout"); - }); -var test_answer="bXkgdm9pY2UgaXMgbXkgcGFzc3dvcmQ="; -var test_answer_addr="127.0.0.1"; +var test_answer = "bXkgdm9pY2UgaXMgbXkgcGFzc3dvcmQ="; +var test_answer_addr = "127.0.0.1"; // check that we do lookup by type fine var listenerEsni = { @@ -77,7 +81,7 @@ var listenerEsni = { run_dns_tests(); } }, - QueryInterface: ChromeUtils.generateQI(["nsIDNSListener"]) + QueryInterface: ChromeUtils.generateQI(["nsIDNSListener"]), }; // check that we do lookup for A record is fine @@ -91,52 +95,70 @@ var listenerAddr = { run_dns_tests(); } }, - QueryInterface: ChromeUtils.generateQI(["nsIDNSListener"]) + QueryInterface: ChromeUtils.generateQI(["nsIDNSListener"]), }; -function testEsniRequest() -{ +function testEsniRequest() { // use the h2 server as DOH provider - prefs.setCharPref("network.trr.uri", "https://foo.example.com:" + h2Port + "/esni-dns"); - listen = dns.asyncResolveByType("_esni.example.com", dns.RESOLVE_TYPE_TXT, 0, listenerEsni, mainThread, defaultOriginAttributes); + prefs.setCharPref( + "network.trr.uri", + "https://foo.example.com:" + h2Port + "/esni-dns" + ); + listen = dns.asyncResolveByType( + "_esni.example.com", + dns.RESOLVE_TYPE_TXT, + 0, + listenerEsni, + mainThread, + defaultOriginAttributes + ); } // verify esni record pushed on a A record request -function testEsniPushPart1() -{ - prefs.setCharPref("network.trr.uri", "https://foo.example.com:" + h2Port + "/esni-dns-push"); - listen = dns.asyncResolve("_esni_push.example.com", 0, listenerAddr, mainThread, defaultOriginAttributes); +function testEsniPushPart1() { + prefs.setCharPref( + "network.trr.uri", + "https://foo.example.com:" + h2Port + "/esni-dns-push" + ); + listen = dns.asyncResolve( + "_esni_push.example.com", + 0, + listenerAddr, + mainThread, + defaultOriginAttributes + ); } // verify the esni pushed record -function testEsniPushPart2() -{ +function testEsniPushPart2() { // At this point the second host name should've been pushed and we can resolve it using // cache only. Set back the URI to a path that fails. - prefs.setCharPref("network.trr.uri", "https://foo.example.com:" + h2Port + "/404"); - listen = dns.asyncResolveByType("_esni_push.example.com", dns.RESOLVE_TYPE_TXT, 0, listenerEsni, mainThread, defaultOriginAttributes); + prefs.setCharPref( + "network.trr.uri", + "https://foo.example.com:" + h2Port + "/404" + ); + listen = dns.asyncResolveByType( + "_esni_push.example.com", + dns.RESOLVE_TYPE_TXT, + 0, + listenerEsni, + mainThread, + defaultOriginAttributes + ); } -function testsDone() -{ +function testsDone() { do_test_finished(); do_test_finished(); } -var tests = [testEsniRequest, - testEsniPushPart1, - testEsniPushPart2, - testsDone - ]; +var tests = [testEsniRequest, testEsniPushPart1, testEsniPushPart2, testsDone]; var current_test = 0; -function run_dns_tests() -{ +function run_dns_tests() { if (current_test < tests.length) { dump("starting test " + current_test + "\n"); do_test_pending(); tests[current_test++](); } } - - diff --git a/netwerk/test/unit/test_event_sink.js b/netwerk/test/unit/test_event_sink.js index 5dbf6623ffc0..271f856ccd84 100644 --- a/netwerk/test/unit/test_event_sink.js +++ b/netwerk/test/unit/test_event_sink.js @@ -1,6 +1,6 @@ // This file tests channel event sinks (bug 315598 et al) -const {HttpServer} = ChromeUtils.import("resource://testing-common/httpd.js"); +const { HttpServer } = ChromeUtils.import("resource://testing-common/httpd.js"); XPCOMUtils.defineLazyGetter(this, "URL", function() { return "http://localhost:" + httpserv.identity.primaryPort; @@ -19,27 +19,34 @@ const categoryName = "net-channel-event-sinks"; var eventsink = { QueryInterface: ChromeUtils.generateQI(["nsIFactory", "nsIChannelEventSink"]), createInstance: function eventsink_ci(outer, iid) { - if (outer) + if (outer) { throw Cr.NS_ERROR_NO_AGGREGATION; + } return this.QueryInterface(iid); }, lockFactory: function eventsink_lockf(lock) { throw Cr.NS_ERROR_NOT_IMPLEMENTED; }, - asyncOnChannelRedirect: function eventsink_onredir(oldChan, newChan, flags, callback) { + asyncOnChannelRedirect: function eventsink_onredir( + oldChan, + newChan, + flags, + callback + ) { // veto this.called = true; throw Cr.NS_BINDING_ABORTED; }, getInterface: function eventsink_gi(iid) { - if (iid.equals(Ci.nsIChannelEventSink)) + if (iid.equals(Ci.nsIChannelEventSink)) { return this; + } throw Cr.NS_ERROR_NO_INTERFACE; }, - called: false + called: false, }; var listener = { @@ -53,10 +60,18 @@ var listener = { // The current URI must be the original URI, as all redirects have been // cancelled - if (!(request instanceof Ci.nsIChannel) || - !request.URI.equals(request.originalURI)) - do_throw("Wrong URI: Is <" + request.URI.spec + ">, should be <" + - request.originalURI.spec + ">"); + if ( + !(request instanceof Ci.nsIChannel) || + !request.URI.equals(request.originalURI) + ) { + do_throw( + "Wrong URI: Is <" + + request.URI.spec + + ">, should be <" + + request.originalURI.spec + + ">" + ); + } if (request instanceof Ci.nsIHttpChannel) { // As we expect a blocked redirect, verify that we have a 3xx status @@ -86,11 +101,11 @@ var listener = { do_test_finished(); }, - _iteration: 1 + _iteration: 1, }; function makeChan(url) { - return NetUtil.newChannel({uri: url, loadUsingSystemPrincipal: true}); + return NetUtil.newChannel({ uri: url, loadUsingSystemPrincipal: true }); } var httpserv = null; @@ -101,8 +116,12 @@ function run_test() { httpserv.registerPathHandler("/redirectfile", redirectfile); httpserv.start(-1); - Components.manager.nsIComponentRegistrar.registerFactory(sinkCID, - "Unit test Event sink", sinkContract, eventsink); + Components.manager.nsIComponentRegistrar.registerFactory( + sinkCID, + "Unit test Event sink", + sinkContract, + eventsink + ); // Step 1: Set the callbacks on the listener itself var chan = makeChan(URL + "/redirect"); @@ -116,19 +135,28 @@ function run_test() { function run_test_continued() { eventsink.called = false; - var catMan = Cc["@mozilla.org/categorymanager;1"] - .getService(Ci.nsICategoryManager); + var catMan = Cc["@mozilla.org/categorymanager;1"].getService( + Ci.nsICategoryManager + ); var chan; if (listener._iteration == 1) { // Step 2: Category entry - catMan.nsICategoryManager.addCategoryEntry(categoryName, "unit test", - sinkContract, false, true); - chan = makeChan(URL + "/redirect") + catMan.nsICategoryManager.addCategoryEntry( + categoryName, + "unit test", + sinkContract, + false, + true + ); + chan = makeChan(URL + "/redirect"); } else { // Step 3: Global contract id - catMan.nsICategoryManager.deleteCategoryEntry(categoryName, "unit test", - false); + catMan.nsICategoryManager.deleteCategoryEntry( + categoryName, + "unit test", + false + ); listener.expectSinkCall = false; chan = makeChan(URL + "/redirectfile"); } @@ -144,9 +172,11 @@ function run_test_continued() { // /redirect function redirect(metadata, response) { response.setStatusLine(metadata.httpVersion, 301, "Moved Permanently"); - response.setHeader("Location", - "http://localhost:" + metadata.port + "/", - false); + response.setHeader( + "Location", + "http://localhost:" + metadata.port + "/", + false + ); var body = "Moved\n"; response.bodyOutputStream.write(body, body.length); diff --git a/netwerk/test/unit/test_eviction.js b/netwerk/test/unit/test_eviction.js index 026b59d89180..67845ba89a96 100644 --- a/netwerk/test/unit/test_eviction.js +++ b/netwerk/test/unit/test_eviction.js @@ -5,19 +5,16 @@ var test_generator = do_run_test(); -function run_test() -{ +function run_test() { do_test_pending(); do_run_generator(test_generator); } -function continue_test() -{ +function continue_test() { do_run_generator(test_generator); } -function repeat_test() -{ +function repeat_test() { // The test is probably going to fail because setting a batch of cookies took // a significant fraction of 'gPurgeAge'. Compensate by rerunning the // test with a larger purge age. @@ -41,20 +38,17 @@ var gShortExpiry = 2; // Required delay to ensure a purge occurs, in milliseconds. This must be at // least gPurgeAge + 10%, and includes a little fuzz to account for timer // resolution and possible differences between PR_Now() and Date.now(). -function get_purge_delay() -{ +function get_purge_delay() { return gPurgeAge * 1100 + 100; } // Required delay to ensure a cookie set with an expiry time 'gShortExpiry' into // the future will have expired. -function get_expiry_delay() -{ +function get_expiry_delay() { return gShortExpiry * 1000 + 100; } -function* do_run_test() -{ +function* do_run_test() { // Set up a profile. let profile = do_get_profile(); @@ -191,18 +185,28 @@ function* do_run_test() // Set 'end - begin' total cookies, with consecutively increasing hosts numbered // 'begin' to 'end'. -function set_cookies(begin, end, expiry) -{ +function set_cookies(begin, end, expiry) { Assert.ok(begin != end); let beginTime; for (let i = begin; i < end; ++i) { let host = "eviction." + i + ".tests"; - Services.cookiemgr.add(host, "", "test", "eviction", false, false, false, - expiry, {}, Ci.nsICookie.SAMESITE_NONE); + Services.cookiemgr.add( + host, + "", + "test", + "eviction", + false, + false, + false, + expiry, + {}, + Ci.nsICookie.SAMESITE_NONE + ); - if (i == begin) + if (i == begin) { beginTime = get_creationTime(i); + } } let endTime = get_creationTime(end - 1); @@ -216,8 +220,7 @@ function set_cookies(begin, end, expiry) return true; } -function get_creationTime(i) -{ +function get_creationTime(i) { let host = "eviction." + i + ".tests"; let enumerator = Services.cookiemgr.getCookiesFromHost(host, {}); Assert.ok(enumerator.hasMoreElements()); @@ -238,7 +241,9 @@ function check_remaining_cookies(aNumberTotal, aNumberOld, aNumberToExpect) { if (aNumberTotal != aNumberToExpect) { // make sure the cookie is one of the batch we expect was purged. var hostNumber = new Number(cookie.rawHost.split(".")[1]); - if (hostNumber < (aNumberOld - aNumberToExpect)) break; + if (hostNumber < aNumberOld - aNumberToExpect) { + break; + } } } diff --git a/netwerk/test/unit/test_extract_charset_from_content_type.js b/netwerk/test/unit/test_extract_charset_from_content_type.js index 9b687e834de4..b0eeee388829 100644 --- a/netwerk/test/unit/test_extract_charset_from_content_type.js +++ b/netwerk/test/unit/test_extract_charset_from_content_type.js @@ -24,140 +24,220 @@ function check(aHadCharset, aCharset, aCharsetStart, aCharsetEnd) { } function run_test() { - var netutil = Cc["@mozilla.org/network/util;1"] - .getService(Ci.nsINetUtil); - hadCharset = - netutil.extractCharsetFromContentType("text/html", charset, charsetStart, - charsetEnd); + var netutil = Cc["@mozilla.org/network/util;1"].getService(Ci.nsINetUtil); + hadCharset = netutil.extractCharsetFromContentType( + "text/html", + charset, + charsetStart, + charsetEnd + ); check(false, "", 9, 9); - hadCharset = - netutil.extractCharsetFromContentType("TEXT/HTML", charset, charsetStart, - charsetEnd); + hadCharset = netutil.extractCharsetFromContentType( + "TEXT/HTML", + charset, + charsetStart, + charsetEnd + ); check(false, "", 9, 9); - hadCharset = - netutil.extractCharsetFromContentType("text/html, text/html", charset, - charsetStart, charsetEnd); + hadCharset = netutil.extractCharsetFromContentType( + "text/html, text/html", + charset, + charsetStart, + charsetEnd + ); check(false, "", 9, 9); - hadCharset = - netutil.extractCharsetFromContentType("text/html, text/plain", - charset, charsetStart, charsetEnd); + hadCharset = netutil.extractCharsetFromContentType( + "text/html, text/plain", + charset, + charsetStart, + charsetEnd + ); check(false, "", 21, 21); - hadCharset = - netutil.extractCharsetFromContentType('text/html, ', charset, charsetStart, - charsetEnd); + hadCharset = netutil.extractCharsetFromContentType( + "text/html, ", + charset, + charsetStart, + charsetEnd + ); check(false, "", 9, 9); - hadCharset = - netutil.extractCharsetFromContentType('text/html, */*', charset, - charsetStart, charsetEnd); + hadCharset = netutil.extractCharsetFromContentType( + "text/html, */*", + charset, + charsetStart, + charsetEnd + ); check(false, "", 9, 9); - hadCharset = - netutil.extractCharsetFromContentType('text/html, foo', charset, - charsetStart, charsetEnd); + hadCharset = netutil.extractCharsetFromContentType( + "text/html, foo", + charset, + charsetStart, + charsetEnd + ); check(false, "", 9, 9); - hadCharset = - netutil.extractCharsetFromContentType("text/html; charset=ISO-8859-1", - charset, charsetStart, charsetEnd); + hadCharset = netutil.extractCharsetFromContentType( + "text/html; charset=ISO-8859-1", + charset, + charsetStart, + charsetEnd + ); check(true, "ISO-8859-1", 9, 29); - hadCharset = - netutil.extractCharsetFromContentType("text/html ; charset=ISO-8859-1", - charset, charsetStart, charsetEnd); + hadCharset = netutil.extractCharsetFromContentType( + "text/html ; charset=ISO-8859-1", + charset, + charsetStart, + charsetEnd + ); check(true, "ISO-8859-1", 11, 34); - hadCharset = - netutil.extractCharsetFromContentType("text/html ; charset=ISO-8859-1 ", - charset, charsetStart, charsetEnd); + hadCharset = netutil.extractCharsetFromContentType( + "text/html ; charset=ISO-8859-1 ", + charset, + charsetStart, + charsetEnd + ); check(true, "ISO-8859-1", 11, 36); - hadCharset = - netutil.extractCharsetFromContentType("text/html ; charset=ISO-8859-1 ; ", - charset, charsetStart, charsetEnd); + hadCharset = netutil.extractCharsetFromContentType( + "text/html ; charset=ISO-8859-1 ; ", + charset, + charsetStart, + charsetEnd + ); check(true, "ISO-8859-1", 11, 35); - hadCharset = - netutil.extractCharsetFromContentType('text/html; charset="ISO-8859-1"', - charset, charsetStart, charsetEnd); + hadCharset = netutil.extractCharsetFromContentType( + 'text/html; charset="ISO-8859-1"', + charset, + charsetStart, + charsetEnd + ); check(true, "ISO-8859-1", 9, 31); - hadCharset = - netutil.extractCharsetFromContentType("text/html; charset='ISO-8859-1'", - charset, charsetStart, charsetEnd); + hadCharset = netutil.extractCharsetFromContentType( + "text/html; charset='ISO-8859-1'", + charset, + charsetStart, + charsetEnd + ); check(true, "'ISO-8859-1'", 9, 31); - hadCharset = - netutil.extractCharsetFromContentType("text/html; charset=\"ISO-8859-1\", text/html", - charset, charsetStart, charsetEnd); + hadCharset = netutil.extractCharsetFromContentType( + 'text/html; charset="ISO-8859-1", text/html', + charset, + charsetStart, + charsetEnd + ); check(true, "ISO-8859-1", 9, 31); - hadCharset = - netutil.extractCharsetFromContentType("text/html; charset=\"ISO-8859-1\", text/html; charset=UTF8", - charset, charsetStart, charsetEnd); + hadCharset = netutil.extractCharsetFromContentType( + 'text/html; charset="ISO-8859-1", text/html; charset=UTF8', + charset, + charsetStart, + charsetEnd + ); check(true, "UTF8", 42, 56); - hadCharset = - netutil.extractCharsetFromContentType("text/html; charset=ISO-8859-1, TEXT/HTML", - charset, charsetStart, charsetEnd); + hadCharset = netutil.extractCharsetFromContentType( + "text/html; charset=ISO-8859-1, TEXT/HTML", + charset, + charsetStart, + charsetEnd + ); check(true, "ISO-8859-1", 9, 29); - hadCharset = - netutil.extractCharsetFromContentType("text/html; charset=ISO-8859-1, TEXT/plain", - charset, charsetStart, charsetEnd); + hadCharset = netutil.extractCharsetFromContentType( + "text/html; charset=ISO-8859-1, TEXT/plain", + charset, + charsetStart, + charsetEnd + ); check(false, "", 41, 41); - hadCharset = - netutil.extractCharsetFromContentType("text/plain, TEXT/HTML; charset=\"ISO-8859-1\", text/html, TEXT/HTML", - charset, charsetStart, charsetEnd); + hadCharset = netutil.extractCharsetFromContentType( + 'text/plain, TEXT/HTML; charset="ISO-8859-1", text/html, TEXT/HTML', + charset, + charsetStart, + charsetEnd + ); check(true, "ISO-8859-1", 21, 43); - hadCharset = - netutil.extractCharsetFromContentType('text/plain, TEXT/HTML; param="charset=UTF8"; charset="ISO-8859-1"; param2="charset=UTF16", text/html, TEXT/HTML', - charset, charsetStart, charsetEnd); + hadCharset = netutil.extractCharsetFromContentType( + 'text/plain, TEXT/HTML; param="charset=UTF8"; charset="ISO-8859-1"; param2="charset=UTF16", text/html, TEXT/HTML', + charset, + charsetStart, + charsetEnd + ); check(true, "ISO-8859-1", 43, 65); - hadCharset = - netutil.extractCharsetFromContentType('text/plain, TEXT/HTML; param=charset=UTF8; charset="ISO-8859-1"; param2=charset=UTF16, text/html, TEXT/HTML', - charset, charsetStart, charsetEnd); + hadCharset = netutil.extractCharsetFromContentType( + 'text/plain, TEXT/HTML; param=charset=UTF8; charset="ISO-8859-1"; param2=charset=UTF16, text/html, TEXT/HTML', + charset, + charsetStart, + charsetEnd + ); check(true, "ISO-8859-1", 41, 63); - hadCharset = - netutil.extractCharsetFromContentType("text/plain; param= , text/html", - charset, charsetStart, charsetEnd); + hadCharset = netutil.extractCharsetFromContentType( + "text/plain; param= , text/html", + charset, + charsetStart, + charsetEnd + ); check(false, "", 30, 30); - hadCharset = - netutil.extractCharsetFromContentType('text/plain; param=", text/html"', - charset, charsetStart, charsetEnd); + hadCharset = netutil.extractCharsetFromContentType( + 'text/plain; param=", text/html"', + charset, + charsetStart, + charsetEnd + ); check(false, "", 10, 10); - hadCharset = - netutil.extractCharsetFromContentType('text/plain; param=", \\" , text/html"', - charset, charsetStart, charsetEnd); + hadCharset = netutil.extractCharsetFromContentType( + 'text/plain; param=", \\" , text/html"', + charset, + charsetStart, + charsetEnd + ); check(false, "", 10, 10); - hadCharset = - netutil.extractCharsetFromContentType('text/plain; param=", \\" , text/html , "', - charset, charsetStart, charsetEnd); + hadCharset = netutil.extractCharsetFromContentType( + 'text/plain; param=", \\" , text/html , "', + charset, + charsetStart, + charsetEnd + ); check(false, "", 10, 10); - hadCharset = - netutil.extractCharsetFromContentType('text/plain param=", \\" , text/html , "', - charset, charsetStart, charsetEnd); + hadCharset = netutil.extractCharsetFromContentType( + 'text/plain param=", \\" , text/html , "', + charset, + charsetStart, + charsetEnd + ); check(false, "", 38, 38); - hadCharset = - netutil.extractCharsetFromContentType('text/plain charset=UTF8', - charset, charsetStart, charsetEnd); + hadCharset = netutil.extractCharsetFromContentType( + "text/plain charset=UTF8", + charset, + charsetStart, + charsetEnd + ); check(false, "", 23, 23); - hadCharset = - netutil.extractCharsetFromContentType('text/plain, TEXT/HTML; param="charset=UTF8"; ; param2="charset=UTF16", text/html, TEXT/HTML', - charset, charsetStart, charsetEnd); + hadCharset = netutil.extractCharsetFromContentType( + 'text/plain, TEXT/HTML; param="charset=UTF8"; ; param2="charset=UTF16", text/html, TEXT/HTML', + charset, + charsetStart, + charsetEnd + ); check(false, "", 21, 21); } diff --git a/netwerk/test/unit/test_fallback_no-cache-entry_canceled.js b/netwerk/test/unit/test_fallback_no-cache-entry_canceled.js index 7bed08c51ee3..b5a77f380306 100644 --- a/netwerk/test/unit/test_fallback_no-cache-entry_canceled.js +++ b/netwerk/test/unit/test_fallback_no-cache-entry_canceled.js @@ -1,5 +1,4 @@ -const {HttpServer} = ChromeUtils.import("resource://testing-common/httpd.js"); - +const { HttpServer } = ChromeUtils.import("resource://testing-common/httpd.js"); var httpServer = null; // Need to randomize, because apparently no one clears our cache @@ -12,99 +11,118 @@ XPCOMUtils.defineLazyGetter(this, "randomURI", function() { var cacheUpdateObserver = null; function make_channel(url, callback, ctx) { - return NetUtil.newChannel({uri: url, loadUsingSystemPrincipal: true}); + return NetUtil.newChannel({ uri: url, loadUsingSystemPrincipal: true }); } function make_uri(url) { - var ios = Cc["@mozilla.org/network/io-service;1"]. - getService(Ci.nsIIOService); + var ios = Cc["@mozilla.org/network/io-service;1"].getService(Ci.nsIIOService); return ios.newURI(url); } var responseBody = "Content body"; // start the test with loading this master entry referencing the manifest -function masterEntryHandler(metadata, response) -{ +function masterEntryHandler(metadata, response) { var masterEntryContent = ""; response.setHeader("Content-Type", "text/html"); - response.bodyOutputStream.write(masterEntryContent, masterEntryContent.length); + response.bodyOutputStream.write( + masterEntryContent, + masterEntryContent.length + ); } // manifest defines fallback namespace from any /redirect path to /content -function manifestHandler(metadata, response) -{ +function manifestHandler(metadata, response) { var manifestContent = "CACHE MANIFEST\nFALLBACK:\nredirect /content\n"; response.setHeader("Content-Type", "text/cache-manifest"); response.bodyOutputStream.write(manifestContent, manifestContent.length); } // content handler correctly returns some plain text data -function contentHandler(metadata, response) -{ +function contentHandler(metadata, response) { response.setHeader("Content-Type", "text/plain"); response.bodyOutputStream.write(responseBody, responseBody.length); } // finally check we got fallback content -function finish_test(request, buffer) -{ +function finish_test(request, buffer) { Assert.equal(buffer, ""); httpServer.stop(do_test_finished); } -function run_test() -{ +function run_test() { httpServer = new HttpServer(); httpServer.registerPathHandler("/masterEntry", masterEntryHandler); httpServer.registerPathHandler("/manifest", manifestHandler); httpServer.registerPathHandler("/content", contentHandler); httpServer.start(-1); - var pm = Cc["@mozilla.org/permissionmanager;1"] - .getService(Ci.nsIPermissionManager); - var ssm = Cc["@mozilla.org/scriptsecuritymanager;1"] - .getService(Ci.nsIScriptSecurityManager); + var pm = Cc["@mozilla.org/permissionmanager;1"].getService( + Ci.nsIPermissionManager + ); + var ssm = Cc["@mozilla.org/scriptsecuritymanager;1"].getService( + Ci.nsIScriptSecurityManager + ); var uri = make_uri("http://localhost:" + httpServer.identity.primaryPort); var principal = ssm.createCodebasePrincipal(uri, {}); if (pm.testPermissionFromPrincipal(principal, "offline-app") != 0) { - dump("Previous test failed to clear offline-app permission! Expect failures.\n"); + dump( + "Previous test failed to clear offline-app permission! Expect failures.\n" + ); } - pm.addFromPrincipal(principal, "offline-app", Ci.nsIPermissionManager.ALLOW_ACTION); + pm.addFromPrincipal( + principal, + "offline-app", + Ci.nsIPermissionManager.ALLOW_ACTION + ); - var ps = Cc["@mozilla.org/preferences-service;1"] - .getService(Ci.nsIPrefBranch); + var ps = Cc["@mozilla.org/preferences-service;1"].getService( + Ci.nsIPrefBranch + ); dump(ps.getBoolPref("browser.cache.offline.enable")); ps.setBoolPref("browser.cache.offline.enable", true); - ps.setComplexValue("browser.cache.offline.parent_directory", Ci.nsIFile, do_get_profile()); + ps.setComplexValue( + "browser.cache.offline.parent_directory", + Ci.nsIFile, + do_get_profile() + ); - cacheUpdateObserver = {observe() { - dump("got offline-cache-update-completed\n"); - // offline cache update completed. - // In this test the randomURI doesn't exists - var chan = make_channel(randomURI); - chan.loadFlags = (Ci.nsIRequest.INHIBIT_CACHING | - Ci.nsIRequest.LOAD_FROM_CACHE | - Ci.nsICachingChannel.LOAD_ONLY_FROM_CACHE); - chan.notificationCallbacks = new ChannelEventSink(ES_ABORT_REDIRECT); - var chanac = chan.QueryInterface(Ci.nsIApplicationCacheChannel); - chanac.chooseApplicationCache = true; - chan.asyncOpen(new ChannelListener(finish_test, null, CL_EXPECT_FAILURE)); - }} + cacheUpdateObserver = { + observe() { + dump("got offline-cache-update-completed\n"); + // offline cache update completed. + // In this test the randomURI doesn't exists + var chan = make_channel(randomURI); + chan.loadFlags = + Ci.nsIRequest.INHIBIT_CACHING | + Ci.nsIRequest.LOAD_FROM_CACHE | + Ci.nsICachingChannel.LOAD_ONLY_FROM_CACHE; + chan.notificationCallbacks = new ChannelEventSink(ES_ABORT_REDIRECT); + var chanac = chan.QueryInterface(Ci.nsIApplicationCacheChannel); + chanac.chooseApplicationCache = true; + chan.asyncOpen(new ChannelListener(finish_test, null, CL_EXPECT_FAILURE)); + }, + }; - var os = Cc["@mozilla.org/observer-service;1"]. - getService(Ci.nsIObserverService); + var os = Cc["@mozilla.org/observer-service;1"].getService( + Ci.nsIObserverService + ); os.addObserver(cacheUpdateObserver, "offline-cache-update-completed"); - var us = Cc["@mozilla.org/offlinecacheupdate-service;1"]. - getService(Ci.nsIOfflineCacheUpdateService); - us.scheduleUpdate(make_uri("http://localhost:" + - httpServer.identity.primaryPort + "/manifest"), - make_uri("http://localhost:" + - httpServer.identity.primaryPort + "/masterEntry"), - Services.scriptSecurityManager.getSystemPrincipal(), - null); + var us = Cc["@mozilla.org/offlinecacheupdate-service;1"].getService( + Ci.nsIOfflineCacheUpdateService + ); + us.scheduleUpdate( + make_uri( + "http://localhost:" + httpServer.identity.primaryPort + "/manifest" + ), + make_uri( + "http://localhost:" + httpServer.identity.primaryPort + "/masterEntry" + ), + Services.scriptSecurityManager.getSystemPrincipal(), + null + ); do_test_pending(); } diff --git a/netwerk/test/unit/test_fallback_no-cache-entry_passing.js b/netwerk/test/unit/test_fallback_no-cache-entry_passing.js index 23d0ae994cd5..1883dc8218af 100644 --- a/netwerk/test/unit/test_fallback_no-cache-entry_passing.js +++ b/netwerk/test/unit/test_fallback_no-cache-entry_passing.js @@ -1,4 +1,4 @@ -const {HttpServer} = ChromeUtils.import("resource://testing-common/httpd.js"); +const { HttpServer } = ChromeUtils.import("resource://testing-common/httpd.js"); var httpServer = null; // Need to randomize, because apparently no one clears our cache @@ -11,98 +11,117 @@ XPCOMUtils.defineLazyGetter(this, "randomURI", function() { var cacheUpdateObserver = null; function make_channel(url, callback, ctx) { - return NetUtil.newChannel({uri: url, loadUsingSystemPrincipal: true}); + return NetUtil.newChannel({ uri: url, loadUsingSystemPrincipal: true }); } function make_uri(url) { - var ios = Cc["@mozilla.org/network/io-service;1"]. - getService(Ci.nsIIOService); + var ios = Cc["@mozilla.org/network/io-service;1"].getService(Ci.nsIIOService); return ios.newURI(url); } var responseBody = "Content body"; // start the test with loading this master entry referencing the manifest -function masterEntryHandler(metadata, response) -{ +function masterEntryHandler(metadata, response) { var masterEntryContent = ""; response.setHeader("Content-Type", "text/html"); - response.bodyOutputStream.write(masterEntryContent, masterEntryContent.length); + response.bodyOutputStream.write( + masterEntryContent, + masterEntryContent.length + ); } // manifest defines fallback namespace from any /redirect path to /content -function manifestHandler(metadata, response) -{ +function manifestHandler(metadata, response) { var manifestContent = "CACHE MANIFEST\nFALLBACK:\nredirect /content\n"; response.setHeader("Content-Type", "text/cache-manifest"); response.bodyOutputStream.write(manifestContent, manifestContent.length); } // content handler correctly returns some plain text data -function contentHandler(metadata, response) -{ +function contentHandler(metadata, response) { response.setHeader("Content-Type", "text/plain"); response.bodyOutputStream.write(responseBody, responseBody.length); } // finally check we got fallback content -function finish_test(request, buffer) -{ +function finish_test(request, buffer) { Assert.equal(buffer, responseBody); httpServer.stop(do_test_finished); } -function run_test() -{ +function run_test() { httpServer = new HttpServer(); httpServer.registerPathHandler("/masterEntry", masterEntryHandler); httpServer.registerPathHandler("/manifest", manifestHandler); httpServer.registerPathHandler("/content", contentHandler); httpServer.start(-1); - var pm = Cc["@mozilla.org/permissionmanager;1"] - .getService(Ci.nsIPermissionManager); - var ssm = Cc["@mozilla.org/scriptsecuritymanager;1"] - .getService(Ci.nsIScriptSecurityManager); + var pm = Cc["@mozilla.org/permissionmanager;1"].getService( + Ci.nsIPermissionManager + ); + var ssm = Cc["@mozilla.org/scriptsecuritymanager;1"].getService( + Ci.nsIScriptSecurityManager + ); var uri = make_uri("http://localhost:" + httpServer.identity.primaryPort); var principal = ssm.createCodebasePrincipal(uri, {}); if (pm.testPermissionFromPrincipal(principal, "offline-app") != 0) { - dump("Previous test failed to clear offline-app permission! Expect failures.\n"); + dump( + "Previous test failed to clear offline-app permission! Expect failures.\n" + ); } - pm.addFromPrincipal(principal, "offline-app", Ci.nsIPermissionManager.ALLOW_ACTION); + pm.addFromPrincipal( + principal, + "offline-app", + Ci.nsIPermissionManager.ALLOW_ACTION + ); - var ps = Cc["@mozilla.org/preferences-service;1"] - .getService(Ci.nsIPrefBranch); + var ps = Cc["@mozilla.org/preferences-service;1"].getService( + Ci.nsIPrefBranch + ); dump(ps.getBoolPref("browser.cache.offline.enable")); ps.setBoolPref("browser.cache.offline.enable", true); - ps.setComplexValue("browser.cache.offline.parent_directory", Ci.nsIFile, do_get_profile()); + ps.setComplexValue( + "browser.cache.offline.parent_directory", + Ci.nsIFile, + do_get_profile() + ); - cacheUpdateObserver = {observe() { - dump("got offline-cache-update-completed\n"); - // offline cache update completed. - // In this test the randomURI doesn't exists - var chan = make_channel(randomURI); - chan.loadFlags = (Ci.nsIRequest.INHIBIT_CACHING | - Ci.nsIRequest.LOAD_FROM_CACHE | - Ci.nsICachingChannel.LOAD_ONLY_FROM_CACHE); - var chanac = chan.QueryInterface(Ci.nsIApplicationCacheChannel); - chanac.chooseApplicationCache = true; - chan.asyncOpen(new ChannelListener(finish_test)); - }} + cacheUpdateObserver = { + observe() { + dump("got offline-cache-update-completed\n"); + // offline cache update completed. + // In this test the randomURI doesn't exists + var chan = make_channel(randomURI); + chan.loadFlags = + Ci.nsIRequest.INHIBIT_CACHING | + Ci.nsIRequest.LOAD_FROM_CACHE | + Ci.nsICachingChannel.LOAD_ONLY_FROM_CACHE; + var chanac = chan.QueryInterface(Ci.nsIApplicationCacheChannel); + chanac.chooseApplicationCache = true; + chan.asyncOpen(new ChannelListener(finish_test)); + }, + }; - var os = Cc["@mozilla.org/observer-service;1"]. - getService(Ci.nsIObserverService); + var os = Cc["@mozilla.org/observer-service;1"].getService( + Ci.nsIObserverService + ); os.addObserver(cacheUpdateObserver, "offline-cache-update-completed"); - var us = Cc["@mozilla.org/offlinecacheupdate-service;1"]. - getService(Ci.nsIOfflineCacheUpdateService); - us.scheduleUpdate(make_uri("http://localhost:" + - httpServer.identity.primaryPort + "/manifest"), - make_uri("http://localhost:" + - httpServer.identity.primaryPort + "/masterEntry"), - Services.scriptSecurityManager.getSystemPrincipal(), - null); + var us = Cc["@mozilla.org/offlinecacheupdate-service;1"].getService( + Ci.nsIOfflineCacheUpdateService + ); + us.scheduleUpdate( + make_uri( + "http://localhost:" + httpServer.identity.primaryPort + "/manifest" + ), + make_uri( + "http://localhost:" + httpServer.identity.primaryPort + "/masterEntry" + ), + Services.scriptSecurityManager.getSystemPrincipal(), + null + ); do_test_pending(); } diff --git a/netwerk/test/unit/test_fallback_redirect-to-different-origin_canceled.js b/netwerk/test/unit/test_fallback_redirect-to-different-origin_canceled.js index b88145ee8e85..0d280e0030ed 100644 --- a/netwerk/test/unit/test_fallback_redirect-to-different-origin_canceled.js +++ b/netwerk/test/unit/test_fallback_redirect-to-different-origin_canceled.js @@ -1,4 +1,4 @@ -const {HttpServer} = ChromeUtils.import("resource://testing-common/httpd.js"); +const { HttpServer } = ChromeUtils.import("resource://testing-common/httpd.js"); var httpServer = null; // Need to randomize, because apparently no one clears our cache @@ -11,56 +11,52 @@ XPCOMUtils.defineLazyGetter(this, "randomURI", function() { var cacheUpdateObserver = null; function make_channel(url, callback, ctx) { - return NetUtil.newChannel({uri: url, loadUsingSystemPrincipal: true}); + return NetUtil.newChannel({ uri: url, loadUsingSystemPrincipal: true }); } function make_uri(url) { - var ios = Cc["@mozilla.org/network/io-service;1"]. - getService(Ci.nsIIOService); + var ios = Cc["@mozilla.org/network/io-service;1"].getService(Ci.nsIIOService); return ios.newURI(url); } const responseBody = "Content body"; // start the test with loading this master entry referencing the manifest -function masterEntryHandler(metadata, response) -{ +function masterEntryHandler(metadata, response) { var masterEntryContent = ""; response.setHeader("Content-Type", "text/html"); - response.bodyOutputStream.write(masterEntryContent, masterEntryContent.length); + response.bodyOutputStream.write( + masterEntryContent, + masterEntryContent.length + ); } // manifest defines fallback namespace from any /redirect path to /content -function manifestHandler(metadata, response) -{ +function manifestHandler(metadata, response) { var manifestContent = "CACHE MANIFEST\nFALLBACK:\nredirect /content\n"; response.setHeader("Content-Type", "text/cache-manifest"); response.bodyOutputStream.write(manifestContent, manifestContent.length); } // content handler correctly returns some plain text data -function contentHandler(metadata, response) -{ +function contentHandler(metadata, response) { response.setHeader("Content-Type", "text/plain"); response.bodyOutputStream.write(responseBody, responseBody.length); } // redirect handler returns redirect -function redirectHandler(metadata, response) -{ +function redirectHandler(metadata, response) { response.setStatusLine(metadata.httpVersion, 301, "Moved"); response.setHeader("Location", "http://example.com/", false); } // finally check we got fallback content -function finish_test(request, buffer) -{ +function finish_test(request, buffer) { Assert.equal(buffer, ""); httpServer.stop(do_test_finished); } -function run_test() -{ +function run_test() { httpServer = new HttpServer(); httpServer.registerPathHandler("/masterEntry", masterEntryHandler); httpServer.registerPathHandler("/manifest", manifestHandler); @@ -68,46 +64,67 @@ function run_test() httpServer.registerPathHandler(randomPath, redirectHandler); httpServer.start(-1); - var pm = Cc["@mozilla.org/permissionmanager;1"] - .getService(Ci.nsIPermissionManager); - var ssm = Cc["@mozilla.org/scriptsecuritymanager;1"] - .getService(Ci.nsIScriptSecurityManager); + var pm = Cc["@mozilla.org/permissionmanager;1"].getService( + Ci.nsIPermissionManager + ); + var ssm = Cc["@mozilla.org/scriptsecuritymanager;1"].getService( + Ci.nsIScriptSecurityManager + ); var uri = make_uri("http://localhost:" + httpServer.identity.primaryPort); var principal = ssm.createCodebasePrincipal(uri, {}); if (pm.testPermissionFromPrincipal(principal, "offline-app") != 0) { - dump("Previous test failed to clear offline-app permission! Expect failures.\n"); + dump( + "Previous test failed to clear offline-app permission! Expect failures.\n" + ); } - pm.addFromPrincipal(principal, "offline-app", Ci.nsIPermissionManager.ALLOW_ACTION); + pm.addFromPrincipal( + principal, + "offline-app", + Ci.nsIPermissionManager.ALLOW_ACTION + ); - var ps = Cc["@mozilla.org/preferences-service;1"] - .getService(Ci.nsIPrefBranch); + var ps = Cc["@mozilla.org/preferences-service;1"].getService( + Ci.nsIPrefBranch + ); dump(ps.getBoolPref("browser.cache.offline.enable")); ps.setBoolPref("browser.cache.offline.enable", true); - ps.setComplexValue("browser.cache.offline.parent_directory", Ci.nsIFile, do_get_profile()); + ps.setComplexValue( + "browser.cache.offline.parent_directory", + Ci.nsIFile, + do_get_profile() + ); - cacheUpdateObserver = {observe() { - dump("got offline-cache-update-completed\n"); - // offline cache update completed. - var chan = make_channel(randomURI); - chan.notificationCallbacks = new ChannelEventSink(ES_ABORT_REDIRECT); - var chanac = chan.QueryInterface(Ci.nsIApplicationCacheChannel); - chanac.chooseApplicationCache = true; - chan.asyncOpen(new ChannelListener(finish_test, null, CL_EXPECT_FAILURE)); - }} + cacheUpdateObserver = { + observe() { + dump("got offline-cache-update-completed\n"); + // offline cache update completed. + var chan = make_channel(randomURI); + chan.notificationCallbacks = new ChannelEventSink(ES_ABORT_REDIRECT); + var chanac = chan.QueryInterface(Ci.nsIApplicationCacheChannel); + chanac.chooseApplicationCache = true; + chan.asyncOpen(new ChannelListener(finish_test, null, CL_EXPECT_FAILURE)); + }, + }; - var os = Cc["@mozilla.org/observer-service;1"]. - getService(Ci.nsIObserverService); + var os = Cc["@mozilla.org/observer-service;1"].getService( + Ci.nsIObserverService + ); os.addObserver(cacheUpdateObserver, "offline-cache-update-completed"); - var us = Cc["@mozilla.org/offlinecacheupdate-service;1"]. - getService(Ci.nsIOfflineCacheUpdateService); - us.scheduleUpdate(make_uri("http://localhost:" + - httpServer.identity.primaryPort + "/manifest"), - make_uri("http://localhost:" + - httpServer.identity.primaryPort + "/masterEntry"), - Services.scriptSecurityManager.getSystemPrincipal(), - null); + var us = Cc["@mozilla.org/offlinecacheupdate-service;1"].getService( + Ci.nsIOfflineCacheUpdateService + ); + us.scheduleUpdate( + make_uri( + "http://localhost:" + httpServer.identity.primaryPort + "/manifest" + ), + make_uri( + "http://localhost:" + httpServer.identity.primaryPort + "/masterEntry" + ), + Services.scriptSecurityManager.getSystemPrincipal(), + null + ); do_test_pending(); } diff --git a/netwerk/test/unit/test_fallback_redirect-to-different-origin_passing.js b/netwerk/test/unit/test_fallback_redirect-to-different-origin_passing.js index 549ba2cf8f86..d8ad05aafb11 100644 --- a/netwerk/test/unit/test_fallback_redirect-to-different-origin_passing.js +++ b/netwerk/test/unit/test_fallback_redirect-to-different-origin_passing.js @@ -1,4 +1,4 @@ -const {HttpServer} = ChromeUtils.import("resource://testing-common/httpd.js"); +const { HttpServer } = ChromeUtils.import("resource://testing-common/httpd.js"); var httpServer = null; // Need to randomize, because apparently no one clears our cache @@ -11,56 +11,52 @@ XPCOMUtils.defineLazyGetter(this, "randomURI", function() { var cacheUpdateObserver = null; function make_channel(url, callback, ctx) { - return NetUtil.newChannel({uri: url, loadUsingSystemPrincipal: true}); + return NetUtil.newChannel({ uri: url, loadUsingSystemPrincipal: true }); } function make_uri(url) { - var ios = Cc["@mozilla.org/network/io-service;1"]. - getService(Ci.nsIIOService); + var ios = Cc["@mozilla.org/network/io-service;1"].getService(Ci.nsIIOService); return ios.newURI(url); } var responseBody = "Content body"; // start the test with loading this master entry referencing the manifest -function masterEntryHandler(metadata, response) -{ +function masterEntryHandler(metadata, response) { var masterEntryContent = ""; response.setHeader("Content-Type", "text/html"); - response.bodyOutputStream.write(masterEntryContent, masterEntryContent.length); + response.bodyOutputStream.write( + masterEntryContent, + masterEntryContent.length + ); } // manifest defines fallback namespace from any /redirect path to /content -function manifestHandler(metadata, response) -{ +function manifestHandler(metadata, response) { var manifestContent = "CACHE MANIFEST\nFALLBACK:\nredirect /content\n"; response.setHeader("Content-Type", "text/cache-manifest"); response.bodyOutputStream.write(manifestContent, manifestContent.length); } // content handler correctly returns some plain text data -function contentHandler(metadata, response) -{ +function contentHandler(metadata, response) { response.setHeader("Content-Type", "text/plain"); response.bodyOutputStream.write(responseBody, responseBody.length); } // redirect handler returns redirect -function redirectHandler(metadata, response) -{ +function redirectHandler(metadata, response) { response.setStatusLine(metadata.httpVersion, 301, "Moved"); response.setHeader("Location", "http://example.com/", false); } // finally check we got fallback content -function finish_test(request, buffer) -{ +function finish_test(request, buffer) { Assert.equal(buffer, responseBody); httpServer.stop(do_test_finished); } -function run_test() -{ +function run_test() { httpServer = new HttpServer(); httpServer.registerPathHandler("/masterEntry", masterEntryHandler); httpServer.registerPathHandler("/manifest", manifestHandler); @@ -68,45 +64,66 @@ function run_test() httpServer.registerPathHandler(randomPath, redirectHandler); httpServer.start(-1); - var pm = Cc["@mozilla.org/permissionmanager;1"] - .getService(Ci.nsIPermissionManager); - var ssm = Cc["@mozilla.org/scriptsecuritymanager;1"] - .getService(Ci.nsIScriptSecurityManager); + var pm = Cc["@mozilla.org/permissionmanager;1"].getService( + Ci.nsIPermissionManager + ); + var ssm = Cc["@mozilla.org/scriptsecuritymanager;1"].getService( + Ci.nsIScriptSecurityManager + ); var uri = make_uri("http://localhost:" + httpServer.identity.primaryPort); var principal = ssm.createCodebasePrincipal(uri, {}); if (pm.testPermissionFromPrincipal(principal, "offline-app") != 0) { - dump("Previous test failed to clear offline-app permission! Expect failures.\n"); + dump( + "Previous test failed to clear offline-app permission! Expect failures.\n" + ); } - pm.addFromPrincipal(principal, "offline-app", Ci.nsIPermissionManager.ALLOW_ACTION); + pm.addFromPrincipal( + principal, + "offline-app", + Ci.nsIPermissionManager.ALLOW_ACTION + ); - var ps = Cc["@mozilla.org/preferences-service;1"] - .getService(Ci.nsIPrefBranch); + var ps = Cc["@mozilla.org/preferences-service;1"].getService( + Ci.nsIPrefBranch + ); dump(ps.getBoolPref("browser.cache.offline.enable")); ps.setBoolPref("browser.cache.offline.enable", true); - ps.setComplexValue("browser.cache.offline.parent_directory", Ci.nsIFile, do_get_profile()); + ps.setComplexValue( + "browser.cache.offline.parent_directory", + Ci.nsIFile, + do_get_profile() + ); - cacheUpdateObserver = {observe() { - dump("got offline-cache-update-completed\n"); - // offline cache update completed. - var chan = make_channel(randomURI); - var chanac = chan.QueryInterface(Ci.nsIApplicationCacheChannel); - chanac.chooseApplicationCache = true; - chan.asyncOpen(new ChannelListener(finish_test)); - }} + cacheUpdateObserver = { + observe() { + dump("got offline-cache-update-completed\n"); + // offline cache update completed. + var chan = make_channel(randomURI); + var chanac = chan.QueryInterface(Ci.nsIApplicationCacheChannel); + chanac.chooseApplicationCache = true; + chan.asyncOpen(new ChannelListener(finish_test)); + }, + }; - var os = Cc["@mozilla.org/observer-service;1"]. - getService(Ci.nsIObserverService); + var os = Cc["@mozilla.org/observer-service;1"].getService( + Ci.nsIObserverService + ); os.addObserver(cacheUpdateObserver, "offline-cache-update-completed"); - var us = Cc["@mozilla.org/offlinecacheupdate-service;1"]. - getService(Ci.nsIOfflineCacheUpdateService); - us.scheduleUpdate(make_uri("http://localhost:" + - httpServer.identity.primaryPort + "/manifest"), - make_uri("http://localhost:" + - httpServer.identity.primaryPort + "/masterEntry"), - Services.scriptSecurityManager.getSystemPrincipal(), - null); + var us = Cc["@mozilla.org/offlinecacheupdate-service;1"].getService( + Ci.nsIOfflineCacheUpdateService + ); + us.scheduleUpdate( + make_uri( + "http://localhost:" + httpServer.identity.primaryPort + "/manifest" + ), + make_uri( + "http://localhost:" + httpServer.identity.primaryPort + "/masterEntry" + ), + Services.scriptSecurityManager.getSystemPrincipal(), + null + ); do_test_pending(); } diff --git a/netwerk/test/unit/test_fallback_request-error_canceled.js b/netwerk/test/unit/test_fallback_request-error_canceled.js index 5c3b0fadc649..27fac1e13547 100644 --- a/netwerk/test/unit/test_fallback_request-error_canceled.js +++ b/netwerk/test/unit/test_fallback_request-error_canceled.js @@ -1,4 +1,4 @@ -const {HttpServer} = ChromeUtils.import("resource://testing-common/httpd.js"); +const { HttpServer } = ChromeUtils.import("resource://testing-common/httpd.js"); var httpServer = null; // Need to randomize, because apparently no one clears our cache @@ -11,109 +11,127 @@ XPCOMUtils.defineLazyGetter(this, "randomURI", function() { var cacheUpdateObserver = null; function make_channel(url, callback, ctx) { - return NetUtil.newChannel({uri: url, loadUsingSystemPrincipal: true}); + return NetUtil.newChannel({ uri: url, loadUsingSystemPrincipal: true }); } function make_uri(url) { - var ios = Cc["@mozilla.org/network/io-service;1"]. - getService(Ci.nsIIOService); + var ios = Cc["@mozilla.org/network/io-service;1"].getService(Ci.nsIIOService); return ios.newURI(url); } var responseBody = "Content body"; // start the test with loading this master entry referencing the manifest -function masterEntryHandler(metadata, response) -{ +function masterEntryHandler(metadata, response) { var masterEntryContent = ""; response.setHeader("Content-Type", "text/html"); - response.bodyOutputStream.write(masterEntryContent, masterEntryContent.length); + response.bodyOutputStream.write( + masterEntryContent, + masterEntryContent.length + ); } // manifest defines fallback namespace from any /redirect path to /content -function manifestHandler(metadata, response) -{ +function manifestHandler(metadata, response) { var manifestContent = "CACHE MANIFEST\nFALLBACK:\nredirect /content\n"; response.setHeader("Content-Type", "text/cache-manifest"); response.bodyOutputStream.write(manifestContent, manifestContent.length); } // content handler correctly returns some plain text data -function contentHandler(metadata, response) -{ +function contentHandler(metadata, response) { response.setHeader("Content-Type", "text/plain"); response.bodyOutputStream.write(responseBody, responseBody.length); } // redirect handler returns redirect -function redirectHandler(metadata, response) -{ +function redirectHandler(metadata, response) { response.setStatusLine(metadata.httpVersion, 301, "Moved"); response.setHeader("Location", "http://example.com/", false); } // finally check we got fallback content -function finish_test(request, buffer) -{ +function finish_test(request, buffer) { Assert.equal(buffer, ""); do_test_finished(); } -function run_test() -{ +function run_test() { httpServer = new HttpServer(); httpServer.registerPathHandler("/masterEntry", masterEntryHandler); httpServer.registerPathHandler("/manifest", manifestHandler); httpServer.registerPathHandler("/content", contentHandler); httpServer.start(-1); - var pm = Cc["@mozilla.org/permissionmanager;1"] - .getService(Ci.nsIPermissionManager); - var ssm = Cc["@mozilla.org/scriptsecuritymanager;1"] - .getService(Ci.nsIScriptSecurityManager); + var pm = Cc["@mozilla.org/permissionmanager;1"].getService( + Ci.nsIPermissionManager + ); + var ssm = Cc["@mozilla.org/scriptsecuritymanager;1"].getService( + Ci.nsIScriptSecurityManager + ); var uri = make_uri("http://localhost:" + httpServer.identity.primaryPort); var principal = ssm.createCodebasePrincipal(uri, {}); if (pm.testPermissionFromPrincipal(principal, "offline-app") != 0) { - dump("Previous test failed to clear offline-app permission! Expect failures.\n"); + dump( + "Previous test failed to clear offline-app permission! Expect failures.\n" + ); } - pm.addFromPrincipal(principal, "offline-app", Ci.nsIPermissionManager.ALLOW_ACTION); + pm.addFromPrincipal( + principal, + "offline-app", + Ci.nsIPermissionManager.ALLOW_ACTION + ); - var ps = Cc["@mozilla.org/preferences-service;1"] - .getService(Ci.nsIPrefBranch); + var ps = Cc["@mozilla.org/preferences-service;1"].getService( + Ci.nsIPrefBranch + ); dump(ps.getBoolPref("browser.cache.offline.enable")); ps.setBoolPref("browser.cache.offline.enable", true); - ps.setComplexValue("browser.cache.offline.parent_directory", Ci.nsIFile, do_get_profile()); + ps.setComplexValue( + "browser.cache.offline.parent_directory", + Ci.nsIFile, + do_get_profile() + ); - cacheUpdateObserver = {observe() { - dump("got offline-cache-update-completed\n"); - // offline cache update completed. + cacheUpdateObserver = { + observe() { + dump("got offline-cache-update-completed\n"); + // offline cache update completed. - // doing this to eval the lazy getter, otherwise the make_channel call would hang - randomURI; - httpServer.stop(function() { - // Now shut the server down to have an error in onStartRequest - var chan = make_channel(randomURI); - chan.notificationCallbacks = new ChannelEventSink(ES_ABORT_REDIRECT); - var chanac = chan.QueryInterface(Ci.nsIApplicationCacheChannel); - chanac.chooseApplicationCache = true; - chan.asyncOpen(new ChannelListener(finish_test, null, CL_EXPECT_FAILURE)); - }); - }} + // doing this to eval the lazy getter, otherwise the make_channel call would hang + randomURI; + httpServer.stop(function() { + // Now shut the server down to have an error in onStartRequest + var chan = make_channel(randomURI); + chan.notificationCallbacks = new ChannelEventSink(ES_ABORT_REDIRECT); + var chanac = chan.QueryInterface(Ci.nsIApplicationCacheChannel); + chanac.chooseApplicationCache = true; + chan.asyncOpen( + new ChannelListener(finish_test, null, CL_EXPECT_FAILURE) + ); + }); + }, + }; - - var os = Cc["@mozilla.org/observer-service;1"]. - getService(Ci.nsIObserverService); + var os = Cc["@mozilla.org/observer-service;1"].getService( + Ci.nsIObserverService + ); os.addObserver(cacheUpdateObserver, "offline-cache-update-completed"); - var us = Cc["@mozilla.org/offlinecacheupdate-service;1"]. - getService(Ci.nsIOfflineCacheUpdateService); - us.scheduleUpdate(make_uri("http://localhost:" + - httpServer.identity.primaryPort + "/manifest"), - make_uri("http://localhost:" + - httpServer.identity.primaryPort + "/masterEntry"), - Services.scriptSecurityManager.getSystemPrincipal(), - null); + var us = Cc["@mozilla.org/offlinecacheupdate-service;1"].getService( + Ci.nsIOfflineCacheUpdateService + ); + us.scheduleUpdate( + make_uri( + "http://localhost:" + httpServer.identity.primaryPort + "/manifest" + ), + make_uri( + "http://localhost:" + httpServer.identity.primaryPort + "/masterEntry" + ), + Services.scriptSecurityManager.getSystemPrincipal(), + null + ); do_test_pending(); } diff --git a/netwerk/test/unit/test_fallback_request-error_passing.js b/netwerk/test/unit/test_fallback_request-error_passing.js index 03f4e64b397e..6604b27d1d2b 100644 --- a/netwerk/test/unit/test_fallback_request-error_passing.js +++ b/netwerk/test/unit/test_fallback_request-error_passing.js @@ -1,4 +1,4 @@ -const {HttpServer} = ChromeUtils.import("resource://testing-common/httpd.js"); +const { HttpServer } = ChromeUtils.import("resource://testing-common/httpd.js"); var httpServer = null; // Need to randomize, because apparently no one clears our cache @@ -12,106 +12,122 @@ var cacheUpdateObserver = null; var systemPrincipal = Services.scriptSecurityManager.getSystemPrincipal(); function make_channel(url, callback, ctx) { - return NetUtil.newChannel({uri: url, loadUsingSystemPrincipal: true}); + return NetUtil.newChannel({ uri: url, loadUsingSystemPrincipal: true }); } function make_uri(url) { - var ios = Cc["@mozilla.org/network/io-service;1"]. - getService(Ci.nsIIOService); + var ios = Cc["@mozilla.org/network/io-service;1"].getService(Ci.nsIIOService); return ios.newURI(url); } var responseBody = "Content body"; // start the test with loading this master entry referencing the manifest -function masterEntryHandler(metadata, response) -{ +function masterEntryHandler(metadata, response) { var masterEntryContent = ""; response.setHeader("Content-Type", "text/html"); - response.bodyOutputStream.write(masterEntryContent, masterEntryContent.length); + response.bodyOutputStream.write( + masterEntryContent, + masterEntryContent.length + ); } // manifest defines fallback namespace from any /redirect path to /content -function manifestHandler(metadata, response) -{ +function manifestHandler(metadata, response) { var manifestContent = "CACHE MANIFEST\nFALLBACK:\nredirect /content\n"; response.setHeader("Content-Type", "text/cache-manifest"); response.bodyOutputStream.write(manifestContent, manifestContent.length); } // content handler correctly returns some plain text data -function contentHandler(metadata, response) -{ +function contentHandler(metadata, response) { response.setHeader("Content-Type", "text/plain"); response.bodyOutputStream.write(responseBody, responseBody.length); } // redirect handler returns redirect -function redirectHandler(metadata, response) -{ +function redirectHandler(metadata, response) { response.setStatusLine(metadata.httpVersion, 301, "Moved"); response.setHeader("Location", "http://example.com/", false); } // finally check we got fallback content -function finish_test(request, buffer) -{ +function finish_test(request, buffer) { Assert.equal(buffer, responseBody); do_test_finished(); } -function run_test() -{ +function run_test() { httpServer = new HttpServer(); httpServer.registerPathHandler("/masterEntry", masterEntryHandler); httpServer.registerPathHandler("/manifest", manifestHandler); httpServer.registerPathHandler("/content", contentHandler); httpServer.start(-1); - var pm = Cc["@mozilla.org/permissionmanager;1"] - .getService(Ci.nsIPermissionManager); - var ssm = Cc["@mozilla.org/scriptsecuritymanager;1"] - .getService(Ci.nsIScriptSecurityManager); + var pm = Cc["@mozilla.org/permissionmanager;1"].getService( + Ci.nsIPermissionManager + ); + var ssm = Cc["@mozilla.org/scriptsecuritymanager;1"].getService( + Ci.nsIScriptSecurityManager + ); var uri = make_uri("http://localhost:" + httpServer.identity.primaryPort); var principal = ssm.createCodebasePrincipal(uri, {}); if (pm.testPermissionFromPrincipal(principal, "offline-app") != 0) { - dump("Previous test failed to clear offline-app permission! Expect failures.\n"); + dump( + "Previous test failed to clear offline-app permission! Expect failures.\n" + ); } - pm.addFromPrincipal(principal, "offline-app", Ci.nsIPermissionManager.ALLOW_ACTION); + pm.addFromPrincipal( + principal, + "offline-app", + Ci.nsIPermissionManager.ALLOW_ACTION + ); - var ps = Cc["@mozilla.org/preferences-service;1"] - .getService(Ci.nsIPrefBranch); + var ps = Cc["@mozilla.org/preferences-service;1"].getService( + Ci.nsIPrefBranch + ); dump(ps.getBoolPref("browser.cache.offline.enable")); ps.setBoolPref("browser.cache.offline.enable", true); - ps.setComplexValue("browser.cache.offline.parent_directory", Ci.nsIFile, do_get_profile()); + ps.setComplexValue( + "browser.cache.offline.parent_directory", + Ci.nsIFile, + do_get_profile() + ); - cacheUpdateObserver = {observe() { - dump("got offline-cache-update-completed\n"); - // offline cache update completed. - var _x = randomURI; // doing this so the lazy value gets computed - httpServer.stop(function() { - // Now shut the server down to have an error in onstartrequest - var chan = make_channel(randomURI); - var chanac = chan.QueryInterface(Ci.nsIApplicationCacheChannel); - chanac.chooseApplicationCache = true; - chan.asyncOpen(new ChannelListener(finish_test)); - }); - }} + cacheUpdateObserver = { + observe() { + dump("got offline-cache-update-completed\n"); + // offline cache update completed. + var _x = randomURI; // doing this so the lazy value gets computed + httpServer.stop(function() { + // Now shut the server down to have an error in onstartrequest + var chan = make_channel(randomURI); + var chanac = chan.QueryInterface(Ci.nsIApplicationCacheChannel); + chanac.chooseApplicationCache = true; + chan.asyncOpen(new ChannelListener(finish_test)); + }); + }, + }; - - var os = Cc["@mozilla.org/observer-service;1"]. - getService(Ci.nsIObserverService); + var os = Cc["@mozilla.org/observer-service;1"].getService( + Ci.nsIObserverService + ); os.addObserver(cacheUpdateObserver, "offline-cache-update-completed"); - var us = Cc["@mozilla.org/offlinecacheupdate-service;1"]. - getService(Ci.nsIOfflineCacheUpdateService); - us.scheduleUpdate(make_uri("http://localhost:" + - httpServer.identity.primaryPort + "/manifest"), - make_uri("http://localhost:" + - httpServer.identity.primaryPort + "/masterEntry"), - systemPrincipal, - null); + var us = Cc["@mozilla.org/offlinecacheupdate-service;1"].getService( + Ci.nsIOfflineCacheUpdateService + ); + us.scheduleUpdate( + make_uri( + "http://localhost:" + httpServer.identity.primaryPort + "/manifest" + ), + make_uri( + "http://localhost:" + httpServer.identity.primaryPort + "/masterEntry" + ), + systemPrincipal, + null + ); do_test_pending(); } diff --git a/netwerk/test/unit/test_fallback_response-error_canceled.js b/netwerk/test/unit/test_fallback_response-error_canceled.js index 7928497fd09d..e968a25eb879 100644 --- a/netwerk/test/unit/test_fallback_response-error_canceled.js +++ b/netwerk/test/unit/test_fallback_response-error_canceled.js @@ -1,5 +1,4 @@ -const {HttpServer} = ChromeUtils.import("resource://testing-common/httpd.js"); - +const { HttpServer } = ChromeUtils.import("resource://testing-common/httpd.js"); var httpServer = null; // Need to randomize, because apparently no one clears our cache @@ -13,55 +12,51 @@ var cacheUpdateObserver = null; var systemPrincipal = Services.scriptSecurityManager.getSystemPrincipal(); function make_channel(url, callback, ctx) { - return NetUtil.newChannel({uri: url, loadUsingSystemPrincipal: true}); + return NetUtil.newChannel({ uri: url, loadUsingSystemPrincipal: true }); } function make_uri(url) { - var ios = Cc["@mozilla.org/network/io-service;1"]. - getService(Ci.nsIIOService); + var ios = Cc["@mozilla.org/network/io-service;1"].getService(Ci.nsIIOService); return ios.newURI(url); } var responseBody = "Content body"; // start the test with loading this master entry referencing the manifest -function masterEntryHandler(metadata, response) -{ +function masterEntryHandler(metadata, response) { var masterEntryContent = ""; response.setHeader("Content-Type", "text/html"); - response.bodyOutputStream.write(masterEntryContent, masterEntryContent.length); + response.bodyOutputStream.write( + masterEntryContent, + masterEntryContent.length + ); } // manifest defines fallback namespace from any /error path to /content -function manifestHandler(metadata, response) -{ +function manifestHandler(metadata, response) { var manifestContent = "CACHE MANIFEST\nFALLBACK:\nerror /content\n"; response.setHeader("Content-Type", "text/cache-manifest"); response.bodyOutputStream.write(manifestContent, manifestContent.length); } // content handler correctly returns some plain text data -function contentHandler(metadata, response) -{ +function contentHandler(metadata, response) { response.setHeader("Content-Type", "text/plain"); response.bodyOutputStream.write(responseBody, responseBody.length); } // error handler returns error -function errorHandler(metadata, response) -{ +function errorHandler(metadata, response) { response.setStatusLine(metadata.httpVersion, 404, "Bad request"); } // finally check we got fallback content -function finish_test(request, buffer) -{ +function finish_test(request, buffer) { Assert.equal(buffer, ""); httpServer.stop(do_test_finished); } -function run_test() -{ +function run_test() { httpServer = new HttpServer(); httpServer.registerPathHandler("/masterEntry", masterEntryHandler); httpServer.registerPathHandler("/manifest", manifestHandler); @@ -69,46 +64,67 @@ function run_test() httpServer.registerPathHandler(randomPath, errorHandler); httpServer.start(-1); - var pm = Cc["@mozilla.org/permissionmanager;1"] - .getService(Ci.nsIPermissionManager); - var ssm = Cc["@mozilla.org/scriptsecuritymanager;1"] - .getService(Ci.nsIScriptSecurityManager); + var pm = Cc["@mozilla.org/permissionmanager;1"].getService( + Ci.nsIPermissionManager + ); + var ssm = Cc["@mozilla.org/scriptsecuritymanager;1"].getService( + Ci.nsIScriptSecurityManager + ); var uri = make_uri("http://localhost:" + httpServer.identity.primaryPort); var principal = ssm.createCodebasePrincipal(uri, {}); if (pm.testPermissionFromPrincipal(principal, "offline-app") != 0) { - dump("Previous test failed to clear offline-app permission! Expect failures.\n"); + dump( + "Previous test failed to clear offline-app permission! Expect failures.\n" + ); } - pm.addFromPrincipal(principal, "offline-app", Ci.nsIPermissionManager.ALLOW_ACTION); + pm.addFromPrincipal( + principal, + "offline-app", + Ci.nsIPermissionManager.ALLOW_ACTION + ); - var ps = Cc["@mozilla.org/preferences-service;1"] - .getService(Ci.nsIPrefBranch); + var ps = Cc["@mozilla.org/preferences-service;1"].getService( + Ci.nsIPrefBranch + ); dump(ps.getBoolPref("browser.cache.offline.enable")); ps.setBoolPref("browser.cache.offline.enable", true); - ps.setComplexValue("browser.cache.offline.parent_directory", Ci.nsIFile, do_get_profile()); + ps.setComplexValue( + "browser.cache.offline.parent_directory", + Ci.nsIFile, + do_get_profile() + ); - cacheUpdateObserver = {observe() { - dump("got offline-cache-update-completed\n"); - // offline cache update completed. - var chan = make_channel(randomURI); - chan.notificationCallbacks = new ChannelEventSink(ES_ABORT_REDIRECT); - var chanac = chan.QueryInterface(Ci.nsIApplicationCacheChannel); - chanac.chooseApplicationCache = true; - chan.asyncOpen(new ChannelListener(finish_test, null, CL_EXPECT_FAILURE)); - }} + cacheUpdateObserver = { + observe() { + dump("got offline-cache-update-completed\n"); + // offline cache update completed. + var chan = make_channel(randomURI); + chan.notificationCallbacks = new ChannelEventSink(ES_ABORT_REDIRECT); + var chanac = chan.QueryInterface(Ci.nsIApplicationCacheChannel); + chanac.chooseApplicationCache = true; + chan.asyncOpen(new ChannelListener(finish_test, null, CL_EXPECT_FAILURE)); + }, + }; - var os = Cc["@mozilla.org/observer-service;1"]. - getService(Ci.nsIObserverService); + var os = Cc["@mozilla.org/observer-service;1"].getService( + Ci.nsIObserverService + ); os.addObserver(cacheUpdateObserver, "offline-cache-update-completed"); - var us = Cc["@mozilla.org/offlinecacheupdate-service;1"]. - getService(Ci.nsIOfflineCacheUpdateService); - us.scheduleUpdate(make_uri("http://localhost:" + - httpServer.identity.primaryPort + "/manifest"), - make_uri("http://localhost:" + - httpServer.identity.primaryPort + "/masterEntry"), - systemPrincipal, - null); + var us = Cc["@mozilla.org/offlinecacheupdate-service;1"].getService( + Ci.nsIOfflineCacheUpdateService + ); + us.scheduleUpdate( + make_uri( + "http://localhost:" + httpServer.identity.primaryPort + "/manifest" + ), + make_uri( + "http://localhost:" + httpServer.identity.primaryPort + "/masterEntry" + ), + systemPrincipal, + null + ); do_test_pending(); } diff --git a/netwerk/test/unit/test_fallback_response-error_passing.js b/netwerk/test/unit/test_fallback_response-error_passing.js index b757f4b2754f..84956c6ea5d4 100644 --- a/netwerk/test/unit/test_fallback_response-error_passing.js +++ b/netwerk/test/unit/test_fallback_response-error_passing.js @@ -1,4 +1,4 @@ -const {HttpServer} = ChromeUtils.import("resource://testing-common/httpd.js"); +const { HttpServer } = ChromeUtils.import("resource://testing-common/httpd.js"); var httpServer = null; // Need to randomize, because apparently no one clears our cache @@ -12,55 +12,51 @@ var cacheUpdateObserver = null; var systemPrincipal = Services.scriptSecurityManager.getSystemPrincipal(); function make_channel(url, callback, ctx) { - return NetUtil.newChannel({uri: url, loadUsingSystemPrincipal: true}); + return NetUtil.newChannel({ uri: url, loadUsingSystemPrincipal: true }); } function make_uri(url) { - var ios = Cc["@mozilla.org/network/io-service;1"]. - getService(Ci.nsIIOService); + var ios = Cc["@mozilla.org/network/io-service;1"].getService(Ci.nsIIOService); return ios.newURI(url); } var responseBody = "Content body"; // start the test with loading this master entry referencing the manifest -function masterEntryHandler(metadata, response) -{ +function masterEntryHandler(metadata, response) { var masterEntryContent = ""; response.setHeader("Content-Type", "text/html"); - response.bodyOutputStream.write(masterEntryContent, masterEntryContent.length); + response.bodyOutputStream.write( + masterEntryContent, + masterEntryContent.length + ); } // manifest defines fallback namespace from any /error path to /content -function manifestHandler(metadata, response) -{ +function manifestHandler(metadata, response) { var manifestContent = "CACHE MANIFEST\nFALLBACK:\nerror /content\n"; response.setHeader("Content-Type", "text/cache-manifest"); response.bodyOutputStream.write(manifestContent, manifestContent.length); } // content handler correctly returns some plain text data -function contentHandler(metadata, response) -{ +function contentHandler(metadata, response) { response.setHeader("Content-Type", "text/plain"); response.bodyOutputStream.write(responseBody, responseBody.length); } // error handler returns error -function errorHandler(metadata, response) -{ +function errorHandler(metadata, response) { response.setStatusLine(metadata.httpVersion, 404, "Bad request"); } // finally check we got fallback content -function finish_test(request, buffer) -{ +function finish_test(request, buffer) { Assert.equal(buffer, responseBody); httpServer.stop(do_test_finished); } -function run_test() -{ +function run_test() { httpServer = new HttpServer(); httpServer.registerPathHandler("/masterEntry", masterEntryHandler); httpServer.registerPathHandler("/manifest", manifestHandler); @@ -68,45 +64,66 @@ function run_test() httpServer.registerPathHandler(randomPath, errorHandler); httpServer.start(-1); - var pm = Cc["@mozilla.org/permissionmanager;1"] - .getService(Ci.nsIPermissionManager); - var ssm = Cc["@mozilla.org/scriptsecuritymanager;1"] - .getService(Ci.nsIScriptSecurityManager); + var pm = Cc["@mozilla.org/permissionmanager;1"].getService( + Ci.nsIPermissionManager + ); + var ssm = Cc["@mozilla.org/scriptsecuritymanager;1"].getService( + Ci.nsIScriptSecurityManager + ); var uri = make_uri("http://localhost:" + httpServer.identity.primaryPort); var principal = ssm.createCodebasePrincipal(uri, {}); if (pm.testPermissionFromPrincipal(principal, "offline-app") != 0) { - dump("Previous test failed to clear offline-app permission! Expect failures.\n"); + dump( + "Previous test failed to clear offline-app permission! Expect failures.\n" + ); } - pm.addFromPrincipal(principal, "offline-app", Ci.nsIPermissionManager.ALLOW_ACTION); + pm.addFromPrincipal( + principal, + "offline-app", + Ci.nsIPermissionManager.ALLOW_ACTION + ); - var ps = Cc["@mozilla.org/preferences-service;1"] - .getService(Ci.nsIPrefBranch); + var ps = Cc["@mozilla.org/preferences-service;1"].getService( + Ci.nsIPrefBranch + ); dump(ps.getBoolPref("browser.cache.offline.enable")); ps.setBoolPref("browser.cache.offline.enable", true); - ps.setComplexValue("browser.cache.offline.parent_directory", Ci.nsIFile, do_get_profile()); + ps.setComplexValue( + "browser.cache.offline.parent_directory", + Ci.nsIFile, + do_get_profile() + ); - cacheUpdateObserver = {observe() { - dump("got offline-cache-update-completed\n"); - // offline cache update completed. - var chan = make_channel(randomURI); - var chanac = chan.QueryInterface(Ci.nsIApplicationCacheChannel); - chanac.chooseApplicationCache = true; - chan.asyncOpen(new ChannelListener(finish_test)); - }} + cacheUpdateObserver = { + observe() { + dump("got offline-cache-update-completed\n"); + // offline cache update completed. + var chan = make_channel(randomURI); + var chanac = chan.QueryInterface(Ci.nsIApplicationCacheChannel); + chanac.chooseApplicationCache = true; + chan.asyncOpen(new ChannelListener(finish_test)); + }, + }; - var os = Cc["@mozilla.org/observer-service;1"]. - getService(Ci.nsIObserverService); + var os = Cc["@mozilla.org/observer-service;1"].getService( + Ci.nsIObserverService + ); os.addObserver(cacheUpdateObserver, "offline-cache-update-completed"); - var us = Cc["@mozilla.org/offlinecacheupdate-service;1"]. - getService(Ci.nsIOfflineCacheUpdateService); - us.scheduleUpdate(make_uri("http://localhost:" + - httpServer.identity.primaryPort + "/manifest"), - make_uri("http://localhost:" + - httpServer.identity.primaryPort + "/masterEntry"), - systemPrincipal, - null); + var us = Cc["@mozilla.org/offlinecacheupdate-service;1"].getService( + Ci.nsIOfflineCacheUpdateService + ); + us.scheduleUpdate( + make_uri( + "http://localhost:" + httpServer.identity.primaryPort + "/manifest" + ), + make_uri( + "http://localhost:" + httpServer.identity.primaryPort + "/masterEntry" + ), + systemPrincipal, + null + ); do_test_pending(); } diff --git a/netwerk/test/unit/test_file_protocol.js b/netwerk/test/unit/test_file_protocol.js index c4ab7e81d449..420c541eb5c5 100644 --- a/netwerk/test/unit/test_file_protocol.js +++ b/netwerk/test/unit/test_file_protocol.js @@ -1,7 +1,6 @@ /* run some tests on the file:// protocol handler */ - -const PR_RDONLY = 0x1; // see prio.h +const PR_RDONLY = 0x1; // see prio.h const special_type = "application/x-our-special-type"; @@ -11,37 +10,37 @@ const special_type = "application/x-our-special-type"; test_read_dir_2, test_upload_file, test_load_replace, - do_test_finished + do_test_finished, ].forEach(f => add_test(f)); function getFile(key) { - var dirSvc = Cc["@mozilla.org/file/directory_service;1"] - .getService(Ci.nsIProperties); + var dirSvc = Cc["@mozilla.org/file/directory_service;1"].getService( + Ci.nsIProperties + ); return dirSvc.get(key, Ci.nsIFile); } function new_file_input_stream(file, buffered) { - var stream = - Cc["@mozilla.org/network/file-input-stream;1"]. - createInstance(Ci.nsIFileInputStream); + var stream = Cc["@mozilla.org/network/file-input-stream;1"].createInstance( + Ci.nsIFileInputStream + ); stream.init(file, PR_RDONLY, 0, 0); - if (!buffered) + if (!buffered) { return stream; + } - var buffer = - Cc["@mozilla.org/network/buffered-input-stream;1"]. - createInstance(Ci.nsIBufferedInputStream); + var buffer = Cc[ + "@mozilla.org/network/buffered-input-stream;1" + ].createInstance(Ci.nsIBufferedInputStream); buffer.init(stream, 4096); return buffer; } function new_file_channel(file) { - var ios = - Cc["@mozilla.org/network/io-service;1"]. - getService(Ci.nsIIOService); + var ios = Cc["@mozilla.org/network/io-service;1"].getService(Ci.nsIIOService); return NetUtil.newChannel({ uri: ios.newFileURI(file), - loadUsingSystemPrincipal: true + loadUsingSystemPrincipal: true, }); } @@ -65,49 +64,63 @@ FileStreamListener.prototype = { return request.file.isDirectory(); }, - QueryInterface: ChromeUtils.generateQI(["nsIStreamListener", "nsIRequestObserver"]), + QueryInterface: ChromeUtils.generateQI([ + "nsIStreamListener", + "nsIRequestObserver", + ]), onStartRequest(request) { - if (this._got_onstartrequest) + if (this._got_onstartrequest) { do_throw("Got second onStartRequest event!"); + } this._got_onstartrequest = true; if (!this._isDir(request)) { request.QueryInterface(Ci.nsIChannel); this._contentLen = request.contentLength; - if (this._contentLen == -1) + if (this._contentLen == -1) { do_throw("Content length is unknown in onStartRequest!"); + } } }, onDataAvailable(request, stream, offset, count) { - if (!this._got_onstartrequest) + if (!this._got_onstartrequest) { do_throw("onDataAvailable without onStartRequest event!"); - if (this._got_onstoprequest) + } + if (this._got_onstoprequest) { do_throw("onDataAvailable after onStopRequest event!"); - if (!request.isPending()) + } + if (!request.isPending()) { do_throw("request reports itself as not pending from onStartRequest!"); + } this._buffer = this._buffer.concat(read_stream(stream, count)); }, onStopRequest(request, status) { - if (!this._got_onstartrequest) + if (!this._got_onstartrequest) { do_throw("onStopRequest without onStartRequest event!"); - if (this._got_onstoprequest) + } + if (this._got_onstoprequest) { do_throw("Got second onStopRequest event!"); + } this._got_onstoprequest = true; - if (!Components.isSuccessCode(status)) + if (!Components.isSuccessCode(status)) { do_throw("Failed to load file: " + status.toString(16)); - if (status != request.status) + } + if (status != request.status) { do_throw("request.status does not match status arg to onStopRequest!"); - if (request.isPending()) + } + if (request.isPending()) { do_throw("request reports itself as pending from onStopRequest!"); - if (this._contentLen != -1 && this._buffer.length != this._contentLen) + } + if (this._contentLen != -1 && this._buffer.length != this._contentLen) { do_throw("did not read nsIChannel.contentLength number of bytes!"); + } this._closure(this._buffer); - } + }, }; function test_read_file() { @@ -120,16 +133,23 @@ function test_read_file() { dump("*** test_read_file.on_read_complete\n"); // bug 326693 - if (chan.contentType != special_type) - do_throw("Type mismatch! Is <" + chan.contentType + ">, should be <" + - special_type + ">") + if (chan.contentType != special_type) { + do_throw( + "Type mismatch! Is <" + + chan.contentType + + ">, should be <" + + special_type + + ">" + ); + } /* read completed successfully. now read data directly from file, and compare the result. */ - var stream = new_file_input_stream(file, false); + var stream = new_file_input_stream(file, false); var result = read_stream(stream, stream.available()); - if (result != data) + if (result != data) { do_throw("Stream contents do not match with direct read!"); + } run_next_test(); } @@ -144,18 +164,31 @@ function do_test_read_dir(set_type, expected_type) { var chan = new_file_channel(file); function on_read_complete(data) { - dump("*** test_read_dir.on_read_complete(" + set_type + ", " + expected_type + ")\n"); + dump( + "*** test_read_dir.on_read_complete(" + + set_type + + ", " + + expected_type + + ")\n" + ); // bug 326693 - if (chan.contentType != expected_type) - do_throw("Type mismatch! Is <" + chan.contentType + ">, should be <" + - expected_type + ">") + if (chan.contentType != expected_type) { + do_throw( + "Type mismatch! Is <" + + chan.contentType + + ">, should be <" + + expected_type + + ">" + ); + } run_next_test(); } - if (set_type) + if (set_type) { chan.contentType = expected_type; + } chan.asyncOpen(new FileStreamListener(on_read_complete)); } @@ -171,7 +204,7 @@ function test_upload_file() { dump("*** test_upload_file\n"); var file = do_get_file("../unit/data/test_readline6.txt"); // file to upload - var dest = do_get_tempdir(); // file upload destination + var dest = do_get_tempdir(); // file upload destination dest.append("junk.dat"); dest.createUnique(dest.NORMAL_FILE_TYPE, 0o600); @@ -185,20 +218,28 @@ function test_upload_file() { dump("*** test_upload_file.on_upload_complete\n"); // bug 326693 - if (chan.contentType != special_type) - do_throw("Type mismatch! Is <" + chan.contentType + ">, should be <" + - special_type + ">") + if (chan.contentType != special_type) { + do_throw( + "Type mismatch! Is <" + + chan.contentType + + ">, should be <" + + special_type + + ">" + ); + } /* upload of file completed successfully. */ - if (data.length != 0) + if (data.length != 0) { do_throw("Upload resulted in data!"); + } - var oldstream = new_file_input_stream(file, false); - var newstream = new_file_input_stream(dest, false); + var oldstream = new_file_input_stream(file, false); + var newstream = new_file_input_stream(dest, false); var olddata = read_stream(oldstream, oldstream.available()); var newdata = read_stream(newstream, newstream.available()); - if (olddata != newdata) + if (olddata != newdata) { do_throw("Stream contents do not match after file copy!"); + } oldstream.close(); newstream.close(); @@ -210,7 +251,7 @@ function test_upload_file() { dump(e + "\n"); do_throw("Unable to remove uploaded file!\n"); } - + run_next_test(); } @@ -229,9 +270,13 @@ function test_load_replace() { Assert.notEqual(chan.URI.pathQueryRef, chan.originalURI.pathQueryRef); // The original URI path should be the same as the lnk file path - var ios = Cc["@mozilla.org/network/io-service;1"]. - getService(Ci.nsIIOService); - Assert.equal(chan.originalURI.pathQueryRef, ios.newFileURI(file).pathQueryRef); + var ios = Cc["@mozilla.org/network/io-service;1"].getService( + Ci.nsIIOService + ); + Assert.equal( + chan.originalURI.pathQueryRef, + ios.newFileURI(file).pathQueryRef + ); } run_next_test(); } diff --git a/netwerk/test/unit/test_filestreams.js b/netwerk/test/unit/test_filestreams.js index 2c39badd1f29..7ee3ea0ba087 100644 --- a/netwerk/test/unit/test_filestreams.js +++ b/netwerk/test/unit/test_filestreams.js @@ -6,7 +6,8 @@ do_get_profile(); const OUTPUT_STREAM_CONTRACT_ID = "@mozilla.org/network/file-output-stream;1"; -const SAFE_OUTPUT_STREAM_CONTRACT_ID = "@mozilla.org/network/safe-file-output-stream;1"; +const SAFE_OUTPUT_STREAM_CONTRACT_ID = + "@mozilla.org/network/safe-file-output-stream;1"; //////////////////////////////////////////////////////////////////////////////// //// Helper Methods @@ -19,13 +20,12 @@ const SAFE_OUTPUT_STREAM_CONTRACT_ID = "@mozilla.org/network/safe-file-output-st * @param aFile * The file to modify in order for it to have a unique leafname. */ -function ensure_unique(aFile) -{ +function ensure_unique(aFile) { ensure_unique.fileIndex = ensure_unique.fileIndex || 0; var leafName = aFile.leafName; while (aFile.clone().exists()) { - aFile.leafName = leafName + "_" + (ensure_unique.fileIndex++); + aFile.leafName = leafName + "_" + ensure_unique.fileIndex++; } } @@ -47,20 +47,24 @@ function ensure_unique(aFile) * the actual open. The stream should have a clone, so changes to the file * object after Init and before Open should not affect it. */ -function check_access(aContractId, aDeferOpen, aTrickDeferredOpen) -{ +function check_access(aContractId, aDeferOpen, aTrickDeferredOpen) { const LEAF_NAME = "filestreams-test-file.tmp"; const TRICKY_LEAF_NAME = "BetYouDidNotExpectThat.tmp"; - let file = Cc["@mozilla.org/file/directory_service;1"]. - getService(Ci.nsIProperties). - get("ProfD", Ci.nsIFile); + let file = Cc["@mozilla.org/file/directory_service;1"] + .getService(Ci.nsIProperties) + .get("ProfD", Ci.nsIFile); file.append(LEAF_NAME); // Writing ensure_unique(file); let ostream = Cc[aContractId].createInstance(Ci.nsIFileOutputStream); - ostream.init(file, -1, -1, aDeferOpen ? Ci.nsIFileOutputStream.DEFER_OPEN : 0); + ostream.init( + file, + -1, + -1, + aDeferOpen ? Ci.nsIFileOutputStream.DEFER_OPEN : 0 + ); Assert.equal(aDeferOpen, !file.clone().exists()); // If defer, should not exist and vice versa if (aDeferOpen) { // File should appear when we do write to it. @@ -80,23 +84,28 @@ function check_access(aContractId, aDeferOpen, aTrickDeferredOpen) // Reading ensure_unique(file); - let istream = Cc["@mozilla.org/network/file-input-stream;1"]. - createInstance(Ci.nsIFileInputStream); + let istream = Cc["@mozilla.org/network/file-input-stream;1"].createInstance( + Ci.nsIFileInputStream + ); var initOk, getOk; try { - istream.init(file, -1, 0, aDeferOpen ? Ci.nsIFileInputStream.DEFER_OPEN : 0); + istream.init( + file, + -1, + 0, + aDeferOpen ? Ci.nsIFileInputStream.DEFER_OPEN : 0 + ); initOk = true; - } - catch(e) { + } catch (e) { initOk = false; } try { - let fstream = Cc["@mozilla.org/network/file-input-stream;1"]. - createInstance(Ci.nsIFileInputStream); + let fstream = Cc["@mozilla.org/network/file-input-stream;1"].createInstance( + Ci.nsIFileInputStream + ); fstream.init(aFile, -1, 0, 0); getOk = true; - } - catch(e) { + } catch (e) { getOk = false; } @@ -104,8 +113,9 @@ function check_access(aContractId, aDeferOpen, aTrickDeferredOpen) // intend to read does not exist, and then trying to read from it should // fail. The other case is where the open is not deferred, and there we should // get an error when we Init (and also when we try to read). - Assert.ok( (aDeferOpen && initOk && !getOk) || - (!aDeferOpen && !initOk && !getOk) ); + Assert.ok( + (aDeferOpen && initOk && !getOk) || (!aDeferOpen && !initOk && !getOk) + ); istream.close(); } @@ -116,33 +126,40 @@ function check_access(aContractId, aDeferOpen, aTrickDeferredOpen) * @param aDeferOpen * Whether to use DEFER_OPEN in the streams. */ -function sync_operations(aDeferOpen) -{ +function sync_operations(aDeferOpen) { const TEST_DATA = "this is a test string"; const LEAF_NAME = "filestreams-test-file.tmp"; - let file = Cc["@mozilla.org/file/directory_service;1"]. - getService(Ci.nsIProperties). - get("ProfD", Ci.nsIFile); + let file = Cc["@mozilla.org/file/directory_service;1"] + .getService(Ci.nsIProperties) + .get("ProfD", Ci.nsIFile); file.append(LEAF_NAME); file.createUnique(Ci.nsIFile.NORMAL_FILE_TYPE, 0o666); - let ostream = Cc[OUTPUT_STREAM_CONTRACT_ID]. - createInstance(Ci.nsIFileOutputStream); - ostream.init(file, -1, -1, aDeferOpen ? Ci.nsIFileOutputStream.DEFER_OPEN : 0); + let ostream = Cc[OUTPUT_STREAM_CONTRACT_ID].createInstance( + Ci.nsIFileOutputStream + ); + ostream.init( + file, + -1, + -1, + aDeferOpen ? Ci.nsIFileOutputStream.DEFER_OPEN : 0 + ); ostream.write(TEST_DATA, TEST_DATA.length); ostream.close(); - let fstream = Cc["@mozilla.org/network/file-input-stream;1"]. - createInstance(Ci.nsIFileInputStream); + let fstream = Cc["@mozilla.org/network/file-input-stream;1"].createInstance( + Ci.nsIFileInputStream + ); fstream.init(file, -1, 0, aDeferOpen ? Ci.nsIFileInputStream.DEFER_OPEN : 0); - let cstream = Cc["@mozilla.org/intl/converter-input-stream;1"]. - createInstance(Ci.nsIConverterInputStream); + let cstream = Cc["@mozilla.org/intl/converter-input-stream;1"].createInstance( + Ci.nsIConverterInputStream + ); cstream.init(fstream, "UTF-8", 0, 0); - let string = {}; + let string = {}; cstream.readString(-1, string); cstream.close(); fstream.close(); @@ -153,85 +170,80 @@ function sync_operations(aDeferOpen) //////////////////////////////////////////////////////////////////////////////// //// Tests -function test_access() -{ +function test_access() { check_access(OUTPUT_STREAM_CONTRACT_ID, false, false); } -function test_access_trick() -{ +function test_access_trick() { check_access(OUTPUT_STREAM_CONTRACT_ID, false, true); } -function test_access_defer() -{ +function test_access_defer() { check_access(OUTPUT_STREAM_CONTRACT_ID, true, false); } -function test_access_defer_trick() -{ +function test_access_defer_trick() { check_access(OUTPUT_STREAM_CONTRACT_ID, true, true); } -function test_access_safe() -{ +function test_access_safe() { check_access(SAFE_OUTPUT_STREAM_CONTRACT_ID, false, false); } -function test_access_safe_trick() -{ +function test_access_safe_trick() { check_access(SAFE_OUTPUT_STREAM_CONTRACT_ID, false, true); } -function test_access_safe_defer() -{ +function test_access_safe_defer() { check_access(SAFE_OUTPUT_STREAM_CONTRACT_ID, true, false); } -function test_access_safe_defer_trick() -{ +function test_access_safe_defer_trick() { check_access(SAFE_OUTPUT_STREAM_CONTRACT_ID, true, true); } -function test_sync_operations() -{ +function test_sync_operations() { sync_operations(); } -function test_sync_operations_deferred() -{ +function test_sync_operations_deferred() { sync_operations(true); } -function do_test_zero_size_buffered(disableBuffering) -{ +function do_test_zero_size_buffered(disableBuffering) { const LEAF_NAME = "filestreams-test-file.tmp"; const BUFFERSIZE = 4096; - let file = Cc["@mozilla.org/file/directory_service;1"]. - getService(Ci.nsIProperties). - get("ProfD", Ci.nsIFile); + let file = Cc["@mozilla.org/file/directory_service;1"] + .getService(Ci.nsIProperties) + .get("ProfD", Ci.nsIFile); file.append(LEAF_NAME); file.createUnique(Ci.nsIFile.NORMAL_FILE_TYPE, 0o666); - let fstream = Cc["@mozilla.org/network/file-input-stream;1"]. - createInstance(Ci.nsIFileInputStream); - fstream.init(file, -1, 0, - Ci.nsIFileInputStream.CLOSE_ON_EOF | - Ci.nsIFileInputStream.REOPEN_ON_REWIND); + let fstream = Cc["@mozilla.org/network/file-input-stream;1"].createInstance( + Ci.nsIFileInputStream + ); + fstream.init( + file, + -1, + 0, + Ci.nsIFileInputStream.CLOSE_ON_EOF | Ci.nsIFileInputStream.REOPEN_ON_REWIND + ); - var buffered = Cc["@mozilla.org/network/buffered-input-stream;1"]. - createInstance(Ci.nsIBufferedInputStream); + var buffered = Cc[ + "@mozilla.org/network/buffered-input-stream;1" + ].createInstance(Ci.nsIBufferedInputStream); buffered.init(fstream, BUFFERSIZE); if (disableBuffering) { - buffered.QueryInterface(Ci.nsIStreamBufferAccess).disableBuffering(); + buffered.QueryInterface(Ci.nsIStreamBufferAccess).disableBuffering(); } // Scriptable input streams clamp read sizes to the return value of // available(), so don't quite do what we want here. - let cstream = Cc["@mozilla.org/intl/converter-input-stream;1"]. - createInstance(Ci.nsIConverterInputStream); + let cstream = Cc["@mozilla.org/intl/converter-input-stream;1"].createInstance( + Ci.nsIConverterInputStream + ); cstream.init(buffered, "UTF-8", 0, 0); Assert.equal(buffered.available(), 0); @@ -263,10 +275,9 @@ function do_test_zero_size_buffered(disableBuffering) Assert.ok(!exceptionThrown); } -function test_zero_size_buffered() -{ - do_test_zero_size_buffered(false); - do_test_zero_size_buffered(true); +function test_zero_size_buffered() { + do_test_zero_size_buffered(false); + do_test_zero_size_buffered(true); } //////////////////////////////////////////////////////////////////////////////// @@ -286,10 +297,8 @@ var tests = [ test_zero_size_buffered, ]; -function run_test() -{ +function run_test() { tests.forEach(function(test) { test(); }); } - diff --git a/netwerk/test/unit/test_freshconnection.js b/netwerk/test/unit/test_freshconnection.js index ea1ebe4ea97e..f811bd97c465 100644 --- a/netwerk/test/unit/test_freshconnection.js +++ b/netwerk/test/unit/test_freshconnection.js @@ -3,8 +3,7 @@ // assertions in necko. var listener = { - onStartRequest: function test_onStartR(request) { - }, + onStartRequest: function test_onStartR(request) {}, onDataAvailable: function test_ODA() { do_throw("Should not get any data!"); @@ -18,12 +17,12 @@ var listener = { function run_test() { var chan = NetUtil.newChannel({ uri: "http://localhost:4444", - loadUsingSystemPrincipal: true + loadUsingSystemPrincipal: true, }); - chan.loadFlags = Ci.nsIRequest.LOAD_FRESH_CONNECTION | - Ci.nsIChannel.LOAD_INITIAL_DOCUMENT_URI; + chan.loadFlags = + Ci.nsIRequest.LOAD_FRESH_CONNECTION | + Ci.nsIChannel.LOAD_INITIAL_DOCUMENT_URI; chan.QueryInterface(Ci.nsIHttpChannel); chan.asyncOpen(listener); do_test_pending(); } - diff --git a/netwerk/test/unit/test_getHost.js b/netwerk/test/unit/test_getHost.js index fd9e83929d99..b2ade368a14b 100644 --- a/netwerk/test/unit/test_getHost.js +++ b/netwerk/test/unit/test_getHost.js @@ -1,6 +1,6 @@ // Test getLocalHost/getLocalPort and getRemoteHost/getRemotePort. -const {HttpServer} = ChromeUtils.import("resource://testing-common/httpd.js"); +const { HttpServer } = ChromeUtils.import("resource://testing-common/httpd.js"); var httpserver = new HttpServer(); httpserver.start(-1); @@ -36,12 +36,12 @@ CheckGetHostListener.prototype = { }, QueryInterface: ChromeUtils.generateQI(["nsIRequestObserver"]), -} +}; function make_channel(url) { return NetUtil.newChannel({ uri: url, - loadUsingSystemPrincipal: true + loadUsingSystemPrincipal: true, }).QueryInterface(Ci.nsIHttpChannel); } diff --git a/netwerk/test/unit/test_gre_resources.js b/netwerk/test/unit/test_gre_resources.js index 1912b70e5db4..ba864da97ad8 100644 --- a/netwerk/test/unit/test_gre_resources.js +++ b/netwerk/test/unit/test_gre_resources.js @@ -1,9 +1,8 @@ // test that things that are expected to be in gre-resources are still there -var ios = Cc["@mozilla.org/network/io-service;1"]. getService(Ci.nsIIOService); +var ios = Cc["@mozilla.org/network/io-service;1"].getService(Ci.nsIIOService); -function wrapInputStream(input) -{ +function wrapInputStream(input) { var nsIScriptableInputStream = Ci.nsIScriptableInputStream; var factory = Cc["@mozilla.org/scriptableinputstream;1"]; var wrapper = factory.createInstance(nsIScriptableInputStream); @@ -13,18 +12,19 @@ function wrapInputStream(input) function check_file(file) { var channel = NetUtil.newChannel({ - uri: "resource://gre-resources/"+file, - loadUsingSystemPrincipal: true + uri: "resource://gre-resources/" + file, + loadUsingSystemPrincipal: true, }); try { let instr = wrapInputStream(channel.open()); - Assert.ok(instr.read(1024).length > 0) + Assert.ok(instr.read(1024).length > 0); } catch (e) { - do_throw("Failed to read " + file + " from gre-resources:"+e) + do_throw("Failed to read " + file + " from gre-resources:" + e); } } function run_test() { - for (let file of ["ua.css"]) - check_file(file) + for (let file of ["ua.css"]) { + check_file(file); + } } diff --git a/netwerk/test/unit/test_gzipped_206.js b/netwerk/test/unit/test_gzipped_206.js index 3361c25561ed..a0f56a36e87c 100644 --- a/netwerk/test/unit/test_gzipped_206.js +++ b/netwerk/test/unit/test_gzipped_206.js @@ -1,16 +1,76 @@ -const {HttpServer} = ChromeUtils.import("resource://testing-common/httpd.js"); - +const { HttpServer } = ChromeUtils.import("resource://testing-common/httpd.js"); var httpserver = null; // testString = "This is a slightly longer test\n"; -const responseBody = [0x1f, 0x8b, 0x08, 0x08, 0xef, 0x70, 0xe6, 0x4c, 0x00, 0x03, 0x74, 0x65, 0x78, 0x74, 0x66, 0x69, - 0x6c, 0x65, 0x2e, 0x74, 0x78, 0x74, 0x00, 0x0b, 0xc9, 0xc8, 0x2c, 0x56, 0x00, 0xa2, 0x44, 0x85, - 0xe2, 0x9c, 0xcc, 0xf4, 0x8c, 0x92, 0x9c, 0x4a, 0x85, 0x9c, 0xfc, 0xbc, 0xf4, 0xd4, 0x22, 0x85, - 0x92, 0xd4, 0xe2, 0x12, 0x2e, 0x2e, 0x00, 0x00, 0xe5, 0xe6, 0xf0, 0x20, 0x00, 0x00, 0x00]; +const responseBody = [ + 0x1f, + 0x8b, + 0x08, + 0x08, + 0xef, + 0x70, + 0xe6, + 0x4c, + 0x00, + 0x03, + 0x74, + 0x65, + 0x78, + 0x74, + 0x66, + 0x69, + 0x6c, + 0x65, + 0x2e, + 0x74, + 0x78, + 0x74, + 0x00, + 0x0b, + 0xc9, + 0xc8, + 0x2c, + 0x56, + 0x00, + 0xa2, + 0x44, + 0x85, + 0xe2, + 0x9c, + 0xcc, + 0xf4, + 0x8c, + 0x92, + 0x9c, + 0x4a, + 0x85, + 0x9c, + 0xfc, + 0xbc, + 0xf4, + 0xd4, + 0x22, + 0x85, + 0x92, + 0xd4, + 0xe2, + 0x12, + 0x2e, + 0x2e, + 0x00, + 0x00, + 0xe5, + 0xe6, + 0xf0, + 0x20, + 0x00, + 0x00, + 0x00, +]; function make_channel(url, callback, ctx) { - return NetUtil.newChannel({uri: url, loadUsingSystemPrincipal: true}); + return NetUtil.newChannel({ uri: url, loadUsingSystemPrincipal: true }); } var doRangeResponse = false; @@ -25,9 +85,11 @@ function cachedHandler(metadata, response) { if (doRangeResponse) { Assert.ok(metadata.hasHeader("Range")); - var matches = metadata.getHeader("Range").match(/^\s*bytes=(\d+)?-(\d+)?\s*$/); - var from = (matches[1] === undefined) ? 0 : matches[1]; - var to = (matches[2] === undefined) ? responseBody.length - 1 : matches[2]; + var matches = metadata + .getHeader("Range") + .match(/^\s*bytes=(\d+)?-(\d+)?\s*$/); + var from = matches[1] === undefined ? 0 : matches[1]; + var to = matches[2] === undefined ? responseBody.length - 1 : matches[2]; if (from >= responseBody.length) { response.setStatusLine(metadata.httpVersion, 416, "Start pos too high"); response.setHeader("Content-Range", "*/" + responseBody.length, false); @@ -37,7 +99,11 @@ function cachedHandler(metadata, response) { response.setHeader("Content-Length", "" + (to + 1 - from)); // always respond to successful range requests with 206 response.setStatusLine(metadata.httpVersion, 206, "Partial Content"); - response.setHeader("Content-Range", from + "-" + to + "/" + responseBody.length, false); + response.setHeader( + "Content-Range", + from + "-" + to + "/" + responseBody.length, + false + ); } else { // This response will get cut off prematurely response.setHeader("Content-Length", "" + responseBody.length); @@ -46,8 +112,9 @@ function cachedHandler(metadata, response) { doRangeResponse = true; } - var bos = Cc["@mozilla.org/binaryoutputstream;1"] - .createInstance(Ci.nsIBinaryOutputStream); + var bos = Cc["@mozilla.org/binaryoutputstream;1"].createInstance( + Ci.nsIBinaryOutputStream + ); bos.setOutputStream(response.bodyOutputStream); response.processAsync(); @@ -57,8 +124,9 @@ function cachedHandler(metadata, response) { function continue_test(request, data) { Assert.equal(17, data.length); - var chan = make_channel("http://localhost:" + - httpserver.identity.primaryPort + "/cached/test.gz"); + var chan = make_channel( + "http://localhost:" + httpserver.identity.primaryPort + "/cached/test.gz" + ); chan.asyncOpen(new ChannelListener(finish_test, null, CL_EXPECT_GZIP)); } @@ -75,7 +143,9 @@ function finish_test(request, data, ctx) { } function run_test() { - enforcePref = Services.prefs.getBoolPref("network.http.enforce-framing.http1"); + enforcePref = Services.prefs.getBoolPref( + "network.http.enforce-framing.http1" + ); Services.prefs.setBoolPref("network.http.enforce-framing.http1", false); httpserver = new HttpServer(); @@ -85,8 +155,11 @@ function run_test() { // wipe out cached content evict_cache_entries(); - var chan = make_channel("http://localhost:" + - httpserver.identity.primaryPort + "/cached/test.gz"); - chan.asyncOpen(new ChannelListener(continue_test, null, CL_EXPECT_GZIP | CL_IGNORE_CL)); + var chan = make_channel( + "http://localhost:" + httpserver.identity.primaryPort + "/cached/test.gz" + ); + chan.asyncOpen( + new ChannelListener(continue_test, null, CL_EXPECT_GZIP | CL_IGNORE_CL) + ); do_test_pending(); } diff --git a/netwerk/test/unit/test_head.js b/netwerk/test/unit/test_head.js index dde3399f2543..69057fedd5c0 100644 --- a/netwerk/test/unit/test_head.js +++ b/netwerk/test/unit/test_head.js @@ -4,10 +4,12 @@ // Note: sets Cc and Ci variables -const {HttpServer} = ChromeUtils.import("resource://testing-common/httpd.js"); -const ReferrerInfo = Components.Constructor("@mozilla.org/referrer-info;1", - "nsIReferrerInfo", - "init"); +const { HttpServer } = ChromeUtils.import("resource://testing-common/httpd.js"); +const ReferrerInfo = Components.Constructor( + "@mozilla.org/referrer-info;1", + "nsIReferrerInfo", + "init" +); XPCOMUtils.defineLazyGetter(this, "URL", function() { return "http://localhost:" + httpserver.identity.primaryPort; @@ -20,7 +22,9 @@ var channel; var ios; var dbg = 0; -if (dbg) { print("============== START =========="); } +if (dbg) { + print("============== START =========="); +} function run_test() { setup_test(); @@ -28,7 +32,9 @@ function run_test() { } function setup_test() { - if (dbg) { print("============== setup_test: in"); } + if (dbg) { + print("============== setup_test: in"); + } httpserver.registerPathHandler(testpath, serverHandler); httpserver.start(-1); @@ -67,19 +73,29 @@ function setup_test() { Assert.equal(setOK, "foo"); var uri = NetUtil.newURI("http://foo1.invalid:80"); - channel.referrerInfo = new ReferrerInfo(Ci.nsIHttpChannel.REFERRER_POLICY_UNSET, true, uri); + channel.referrerInfo = new ReferrerInfo( + Ci.nsIHttpChannel.REFERRER_POLICY_UNSET, + true, + uri + ); setOK = channel.getRequestHeader("Referer"); Assert.equal(setOK, "http://foo1.invalid/"); uri = NetUtil.newURI("http://foo2.invalid:90/bar"); - channel.referrerInfo = new ReferrerInfo(Ci.nsIHttpChannel.REFERRER_POLICY_UNSET, true, uri); + channel.referrerInfo = new ReferrerInfo( + Ci.nsIHttpChannel.REFERRER_POLICY_UNSET, + true, + uri + ); setOK = channel.getRequestHeader("Referer"); Assert.equal(setOK, "http://foo2.invalid:90/bar"); // ChannelListener defined in head_channels.js channel.asyncOpen(new ChannelListener(checkRequestResponse, channel)); - if (dbg) { print("============== setup_test: out"); } + if (dbg) { + print("============== setup_test: out"); + } } function setupChannel(path) { @@ -93,7 +109,9 @@ function setupChannel(path) { } function serverHandler(metadata, response) { - if (dbg) { print("============== serverHandler: in"); } + if (dbg) { + print("============== serverHandler: in"); + } var setOK = metadata.getHeader("ReplaceMe"); Assert.equal(setOK, "replaced"); @@ -122,11 +140,15 @@ function serverHandler(metadata, response) { response.bodyOutputStream.write(httpbody, httpbody.length); - if (dbg) { print("============== serverHandler: out"); } + if (dbg) { + print("============== serverHandler: out"); + } } function checkRequestResponse(request, data, context) { - if (dbg) { print("============== checkRequestResponse: in"); } + if (dbg) { + print("============== checkRequestResponse: in"); + } Assert.equal(channel.responseStatus, 200); Assert.equal(channel.responseStatusText, "OK"); @@ -147,5 +169,7 @@ function checkRequestResponse(request, data, context) { Assert.equal(data, httpbody); httpserver.stop(do_test_finished); - if (dbg) { print("============== checkRequestResponse: out"); } + if (dbg) { + print("============== checkRequestResponse: out"); + } } diff --git a/netwerk/test/unit/test_head_request_no_response_body.js b/netwerk/test/unit/test_head_request_no_response_body.js index 2ff7bfbb50aa..df319cbaee07 100644 --- a/netwerk/test/unit/test_head_request_no_response_body.js +++ b/netwerk/test/unit/test_head_request_no_response_body.js @@ -15,7 +15,7 @@ Test that a response to HEAD method should not have a body. "use strict"; -const {HttpServer} = ChromeUtils.import("resource://testing-common/httpd.js"); +const { HttpServer } = ChromeUtils.import("resource://testing-common/httpd.js"); const responseContent = "response body"; @@ -29,18 +29,22 @@ function test_handler(metadata, response) { } function make_channel(url, method) { - let channel = NetUtil.newChannel({uri: url, loadUsingSystemPrincipal: true}) - .QueryInterface(Ci.nsIHttpChannel); + let channel = NetUtil.newChannel({ + uri: url, + loadUsingSystemPrincipal: true, + }).QueryInterface(Ci.nsIHttpChannel); channel.requestMethod = method; return channel; } async function get_response(channel, fromCache) { return new Promise(resolve => { - channel.asyncOpen(new ChannelListener((request, buffer, ctx, isFromCache) => { - ok(fromCache == isFromCache, `got response from cache = ${fromCache}`); - resolve(buffer); - })); + channel.asyncOpen( + new ChannelListener((request, buffer, ctx, isFromCache) => { + ok(fromCache == isFromCache, `got response from cache = ${fromCache}`); + resolve(buffer); + }) + ); }); } diff --git a/netwerk/test/unit/test_header_Accept-Language.js b/netwerk/test/unit/test_header_Accept-Language.js index f1e5ca77059a..ef47c6b27b0e 100644 --- a/netwerk/test/unit/test_header_Accept-Language.js +++ b/netwerk/test/unit/test_header_Accept-Language.js @@ -11,7 +11,9 @@ var testpath = "/bug672448"; function run_test() { - let intlPrefs = Cc["@mozilla.org/preferences-service;1"].getService(Ci.nsIPrefService).getBranch("intl."); + let intlPrefs = Cc["@mozilla.org/preferences-service;1"] + .getService(Ci.nsIPrefService) + .getBranch("intl."); // Save old value of preference for later. let oldPref = intlPrefs.getCharPref("accept_languages"); @@ -53,8 +55,10 @@ function test_accepted_languages() { try { // The q-value must conform to the definition in HTTP/1.1 Section 3.9. - [unused, acceptedLanguage, qualityValue] = acceptedLanguages[i].trim().match(/^([a-z0-9_-]*?)(?:;q=(1(?:\.0{0,3})?|0(?:\.[0-9]{0,3})))?$/i); - } catch(e) { + [unused, acceptedLanguage, qualityValue] = acceptedLanguages[i] + .trim() + .match(/^([a-z0-9_-]*?)(?:;q=(1(?:\.0{0,3})?|0(?:\.[0-9]{0,3})))?$/i); + } catch (e) { do_throw("Invalid language tag or quality value: " + e); } @@ -78,16 +82,18 @@ function test_accepted_languages() { } // All the other languages should have an evenly-spaced quality value. - Assert.equal(parseFloat(qualityValue).toFixed(decimalPlaces), (1.0 - ((1 / acceptedLanguagesLength) * i)).toFixed(decimalPlaces)); + Assert.equal( + parseFloat(qualityValue).toFixed(decimalPlaces), + (1.0 - (1 / acceptedLanguagesLength) * i).toFixed(decimalPlaces) + ); } } } function setupChannel(path) { - - let chan = NetUtil.newChannel ({ + let chan = NetUtil.newChannel({ uri: "http://localhost:4444" + path, - loadUsingSystemPrincipal: true + loadUsingSystemPrincipal: true, }); chan.QueryInterface(Ci.nsIHttpChannel); diff --git a/netwerk/test/unit/test_header_Accept-Language_case.js b/netwerk/test/unit/test_header_Accept-Language_case.js index 26be935f7a1f..c656be23dd1b 100644 --- a/netwerk/test/unit/test_header_Accept-Language_case.js +++ b/netwerk/test/unit/test_header_Accept-Language_case.js @@ -1,28 +1,29 @@ - var testpath = "/bug1054739"; function run_test() { - let intlPrefs = Cc["@mozilla.org/preferences-service;1"].getService(Ci.nsIPrefService).getBranch("intl."); + let intlPrefs = Cc["@mozilla.org/preferences-service;1"] + .getService(Ci.nsIPrefService) + .getBranch("intl."); let oldAcceptLangPref = intlPrefs.getCharPref("accept_languages"); let testData = [ - ["en", "en"], - ["ast", "ast"], - ["fr-ca", "fr-CA"], - ["zh-yue", "zh-yue"], - ["az-latn", "az-Latn"], - ["sl-nedis", "sl-nedis"], - ["zh-hant-hk", "zh-Hant-HK"], - ["ZH-HANT-HK", "zh-Hant-HK"], - ["en-us-x-priv", "en-US-x-priv"], - ["en-us-x-twain", "en-US-x-twain"], - ["de, en-US, en", "de,en-US;q=0.7,en;q=0.3"], - ["de,en-us,en", "de,en-US;q=0.7,en;q=0.3"], - ["en-US, en", "en-US,en;q=0.5"], + ["en", "en"], + ["ast", "ast"], + ["fr-ca", "fr-CA"], + ["zh-yue", "zh-yue"], + ["az-latn", "az-Latn"], + ["sl-nedis", "sl-nedis"], + ["zh-hant-hk", "zh-Hant-HK"], + ["ZH-HANT-HK", "zh-Hant-HK"], + ["en-us-x-priv", "en-US-x-priv"], + ["en-us-x-twain", "en-US-x-twain"], + ["de, en-US, en", "de,en-US;q=0.7,en;q=0.3"], + ["de,en-us,en", "de,en-US;q=0.7,en;q=0.3"], + ["en-US, en", "en-US,en;q=0.5"], ["EN-US;q=0.2, EN", "en-US,en;q=0.5"], ["en ;q=0.8, de ", "en,de;q=0.5"], - [",en,", "en"], + [",en,", "en"], ]; for (let i = 0; i < testData.length; i++) { @@ -30,7 +31,9 @@ function run_test() { let expectedHeader = testData[i][1]; intlPrefs.setCharPref("accept_languages", acceptLangPref); - let acceptLangHeader = setupChannel(testpath).getRequestHeader("Accept-Language"); + let acceptLangHeader = setupChannel(testpath).getRequestHeader( + "Accept-Language" + ); equal(acceptLangHeader, expectedHeader); } @@ -41,7 +44,7 @@ function setupChannel(path) { let uri = NetUtil.newURI("http://localhost:4444" + path); let chan = NetUtil.newChannel({ uri, - loadUsingSystemPrincipal: true + loadUsingSystemPrincipal: true, }); chan.QueryInterface(Ci.nsIHttpChannel); return chan; diff --git a/netwerk/test/unit/test_header_Server_Timing.js b/netwerk/test/unit/test_header_Server_Timing.js index 0397fad9f100..d90a2d0a418a 100644 --- a/netwerk/test/unit/test_header_Server_Timing.js +++ b/netwerk/test/unit/test_header_Server_Timing.js @@ -6,25 +6,28 @@ // HTTP Server-Timing header test // - function make_and_open_channel(url, callback) { - let chan = NetUtil.newChannel({uri: url, loadUsingSystemPrincipal: true}); + let chan = NetUtil.newChannel({ uri: url, loadUsingSystemPrincipal: true }); chan.asyncOpen(new ChannelListener(callback, null, CL_ALLOW_UNKNOWN_CL)); } -var responseServerTiming = [{metric:"metric", duration:"123.4", description:"description"}, - {metric:"metric2", duration:"456.78", description:"description1"}]; -var trailerServerTiming = [{metric:"metric3", duration:"789.11", description:"description2"}, - {metric:"metric4", duration:"1112.13", description:"description3"}]; +var responseServerTiming = [ + { metric: "metric", duration: "123.4", description: "description" }, + { metric: "metric2", duration: "456.78", description: "description1" }, +]; +var trailerServerTiming = [ + { metric: "metric3", duration: "789.11", description: "description2" }, + { metric: "metric4", duration: "1112.13", description: "description3" }, +]; -function run_test() -{ +function run_test() { do_test_pending(); // Set up to allow the cert presented by the server do_get_profile(); - let certdb = Cc["@mozilla.org/security/x509certdb;1"] - .getService(Ci.nsIX509CertDB); + let certdb = Cc["@mozilla.org/security/x509certdb;1"].getService( + Ci.nsIX509CertDB + ); addCertFromFile(certdb, "http2-ca.pem", "CTu,u,u"); Services.prefs.setCharPref("network.dns.localDomains", "foo.example.com"); @@ -32,9 +35,14 @@ function run_test() Services.prefs.clearUserPref("network.dns.localDomains"); }); - var env = Cc["@mozilla.org/process/environment;1"].getService(Ci.nsIEnvironment); + var env = Cc["@mozilla.org/process/environment;1"].getService( + Ci.nsIEnvironment + ); var serverPort = env.get("MOZHTTP2_PORT"); - make_and_open_channel("https://foo.example.com:" + serverPort + "/server-timing", readServerContent); + make_and_open_channel( + "https://foo.example.com:" + serverPort + "/server-timing", + readServerContent + ); } function checkServerTimingContent(headers) { @@ -49,8 +57,7 @@ function checkServerTimingContent(headers) { } } -function readServerContent(request, buffer) -{ +function readServerContent(request, buffer) { let channel = request.QueryInterface(Ci.nsITimedChannel); let headers = channel.serverTiming.QueryInterface(Ci.nsIArray); checkServerTimingContent(headers); diff --git a/netwerk/test/unit/test_headers.js b/netwerk/test/unit/test_headers.js index 61842d0bd77e..ab61aea1f89b 100644 --- a/netwerk/test/unit/test_headers.js +++ b/netwerk/test/unit/test_headers.js @@ -6,8 +6,8 @@ // TO ADD NEW TESTS: // 1) Increment up 'lastTest' to new number (say, "99") // 2) Add new test 'handler99' and 'completeTest99' functions. -// 3) If your test should fail the necko channel, set -// test_flags[99] = CL_EXPECT_FAILURE. +// 3) If your test should fail the necko channel, set +// test_flags[99] = CL_EXPECT_FAILURE. // // TO DEBUG JUST ONE TEST: temporarily change firstTest and lastTest to equal // the test # you're interested in. @@ -15,13 +15,13 @@ // For tests that need duplicate copies of headers to be sent, see // test_duplicate_headers.js -var firstTest = 1; // set to test of interest when debugging -var lastTest = 4; // set to test of interest when debugging +var firstTest = 1; // set to test of interest when debugging +var lastTest = 4; // set to test of interest when debugging //////////////////////////////////////////////////////////////////////////////// // Note: sets Cc and Ci variables -const {HttpServer} = ChromeUtils.import("resource://testing-common/httpd.js"); +const { HttpServer } = ChromeUtils.import("resource://testing-common/httpd.js"); XPCOMUtils.defineLazyGetter(this, "URL", function() { return "http://localhost:" + httpserver.identity.primaryPort; @@ -33,68 +33,64 @@ var nextTest = firstTest; var test_flags = new Array(); var testPathBase = "/test_headers"; -function run_test() -{ +function run_test() { httpserver.start(-1); do_test_pending(); run_test_number(nextTest); } -function runNextTest() -{ +function runNextTest() { if (nextTest == lastTest) { endTests(); return; } nextTest++; // Make sure test functions exist - if (this["handler" + nextTest] == undefined) + if (this["handler" + nextTest] == undefined) { do_throw("handler" + nextTest + " undefined!"); - if (this["completeTest" + nextTest] == undefined) + } + if (this["completeTest" + nextTest] == undefined) { do_throw("completeTest" + nextTest + " undefined!"); - + } + run_test_number(nextTest); } -function run_test_number(num) -{ +function run_test_number(num) { testPath = testPathBase + num; httpserver.registerPathHandler(testPath, this["handler" + num]); var channel = setupChannel(testPath); - flags = test_flags[num]; // OK if flags undefined for test - channel.asyncOpen(new ChannelListener(this["completeTest" + num], - channel, flags)); + flags = test_flags[num]; // OK if flags undefined for test + channel.asyncOpen( + new ChannelListener(this["completeTest" + num], channel, flags) + ); } -function setupChannel(url) -{ +function setupChannel(url) { var chan = NetUtil.newChannel({ uri: URL + url, - loadUsingSystemPrincipal: true + loadUsingSystemPrincipal: true, }); var httpChan = chan.QueryInterface(Ci.nsIHttpChannel); return httpChan; } -function endTests() -{ +function endTests() { httpserver.stop(do_test_finished); } //////////////////////////////////////////////////////////////////////////////// // Test 1: test Content-Disposition channel attributes -function handler1(metadata, response) -{ +function handler1(metadata, response) { response.setStatusLine(metadata.httpVersion, 200, "OK"); response.setHeader("Content-Disposition", "attachment; filename=foo"); response.setHeader("Content-Type", "text/plain", false); var body = "foo"; } -function completeTest1(request, data, ctx) -{ +function completeTest1(request, data, ctx) { try { var chan = request.QueryInterface(Ci.nsIChannel); Assert.equal(chan.contentDisposition, chan.DISPOSITION_ATTACHMENT); @@ -103,13 +99,12 @@ function completeTest1(request, data, ctx) } catch (ex) { do_throw("error parsing Content-Disposition: " + ex); } - runNextTest(); + runNextTest(); } //////////////////////////////////////////////////////////////////////////////// -// Test 2: no filename -function handler2(metadata, response) -{ +// Test 2: no filename +function handler2(metadata, response) { response.setStatusLine(metadata.httpVersion, 200, "OK"); response.setHeader("Content-Type", "text/plain", false); response.setHeader("Content-Disposition", "attachment"); @@ -117,25 +112,23 @@ function handler2(metadata, response) response.bodyOutputStream.write(body, body.length); } -function completeTest2(request, data, ctx) -{ +function completeTest2(request, data, ctx) { try { var chan = request.QueryInterface(Ci.nsIChannel); Assert.equal(chan.contentDisposition, chan.DISPOSITION_ATTACHMENT); Assert.equal(chan.contentDispositionHeader, "attachment"); - filename = chan.contentDispositionFilename; // should barf + filename = chan.contentDispositionFilename; // should barf do_throw("Should have failed getting Content-Disposition filename"); } catch (ex) { - info("correctly ate exception"); + info("correctly ate exception"); } - runNextTest(); + runNextTest(); } //////////////////////////////////////////////////////////////////////////////// // Test 3: filename missing -function handler3(metadata, response) -{ +function handler3(metadata, response) { response.setStatusLine(metadata.httpVersion, 200, "OK"); response.setHeader("Content-Type", "text/plain", false); response.setHeader("Content-Disposition", "attachment; filename="); @@ -143,25 +136,23 @@ function handler3(metadata, response) response.bodyOutputStream.write(body, body.length); } -function completeTest3(request, data, ctx) -{ +function completeTest3(request, data, ctx) { try { var chan = request.QueryInterface(Ci.nsIChannel); Assert.equal(chan.contentDisposition, chan.DISPOSITION_ATTACHMENT); Assert.equal(chan.contentDispositionHeader, "attachment; filename="); - filename = chan.contentDispositionFilename; // should barf + filename = chan.contentDispositionFilename; // should barf do_throw("Should have failed getting Content-Disposition filename"); } catch (ex) { - info("correctly ate exception"); + info("correctly ate exception"); } - runNextTest(); + runNextTest(); } //////////////////////////////////////////////////////////////////////////////// // Test 4: inline -function handler4(metadata, response) -{ +function handler4(metadata, response) { response.setStatusLine(metadata.httpVersion, 200, "OK"); response.setHeader("Content-Type", "text/plain", false); response.setHeader("Content-Disposition", "inline"); @@ -169,17 +160,16 @@ function handler4(metadata, response) response.bodyOutputStream.write(body, body.length); } -function completeTest4(request, data, ctx) -{ +function completeTest4(request, data, ctx) { try { var chan = request.QueryInterface(Ci.nsIChannel); Assert.equal(chan.contentDisposition, chan.DISPOSITION_INLINE); Assert.equal(chan.contentDispositionHeader, "inline"); - filename = chan.contentDispositionFilename; // should barf + filename = chan.contentDispositionFilename; // should barf do_throw("Should have failed getting Content-Disposition filename"); } catch (ex) { - info("correctly ate exception"); + info("correctly ate exception"); } runNextTest(); } diff --git a/netwerk/test/unit/test_hostnameIsLocalIPAddress.js b/netwerk/test/unit/test_hostnameIsLocalIPAddress.js index 7c5af0ae73c7..1a8603836453 100644 --- a/netwerk/test/unit/test_hostnameIsLocalIPAddress.js +++ b/netwerk/test/unit/test_hostnameIsLocalIPAddress.js @@ -1,4 +1,6 @@ -var ioService = Cc["@mozilla.org/network/io-service;1"].getService(Ci.nsIIOService); +var ioService = Cc["@mozilla.org/network/io-service;1"].getService( + Ci.nsIIOService +); function run_test() { let testURIs = [ @@ -26,4 +28,3 @@ function run_test() { equal(isLocal, ioService.hostnameIsLocalIPAddress(nsuri)); } } - diff --git a/netwerk/test/unit/test_http1-proxy.js b/netwerk/test/unit/test_http1-proxy.js index ae5b2e6a598d..ccf1a05d1173 100644 --- a/netwerk/test/unit/test_http1-proxy.js +++ b/netwerk/test/unit/test_http1-proxy.js @@ -35,11 +35,20 @@ class ProxyFilter { cb.onProxyFilterResult(pi); return; } - cb.onProxyFilterResult(pps.newProxyInfo( - this._type, this._host, this._port, - "", "", this._flags, 1000, null)); + cb.onProxyFilterResult( + pps.newProxyInfo( + this._type, + this._host, + this._port, + "", + "", + this._flags, + 1000, + null + ) + ); } -}; +} class UnxpectedAuthPrompt2 { constructor(signal) { @@ -50,7 +59,7 @@ class UnxpectedAuthPrompt2 { this.signal.triggered = true; throw Cr.ERROR_UNEXPECTED; } -}; +} class AuthRequestor { constructor(prompt) { @@ -63,7 +72,7 @@ class AuthRequestor { } throw Cr.NS_ERROR_NO_INTERFACE; } -}; +} function make_channel(url) { return NetUtil.newChannel({ @@ -76,13 +85,19 @@ function make_channel(url) { function get_response(channel, flags = CL_ALLOW_UNKNOWN_CL) { return new Promise(resolve => { - channel.asyncOpen(new ChannelListener((request, data) => { - request.QueryInterface(Ci.nsIHttpChannel); - const status = request.status; - const http_code = status ? undefined : request.responseStatus; + channel.asyncOpen( + new ChannelListener( + (request, data) => { + request.QueryInterface(Ci.nsIHttpChannel); + const status = request.status; + const http_code = status ? undefined : request.responseStatus; - resolve({ status, http_code, data }); - }, null, flags)); + resolve({ status, http_code, data }); + }, + null, + flags + ) + ); }); } @@ -137,7 +152,9 @@ registerCleanupFunction(() => { add_task(async function proxy_auth_failure() { const chan = make_channel(`https://407.example.com/`); const auth_prompt = { triggered: false }; - chan.notificationCallbacks = new AuthRequestor(() => new UnxpectedAuthPrompt2(auth_prompt)); + chan.notificationCallbacks = new AuthRequestor( + () => new UnxpectedAuthPrompt2(auth_prompt) + ); const { status, http_code } = await get_response(chan, CL_EXPECT_FAILURE); Assert.equal(status, Cr.NS_ERROR_PROXY_AUTHENTICATION_FAILED); @@ -147,7 +164,10 @@ add_task(async function proxy_auth_failure() { // 502 Bad gateway code returned by the proxy. add_task(async function proxy_bad_gateway_failure() { - const { status, http_code } = await get_response(make_channel(`https://502.example.com/`), CL_EXPECT_FAILURE); + const { status, http_code } = await get_response( + make_channel(`https://502.example.com/`), + CL_EXPECT_FAILURE + ); Assert.equal(status, Cr.NS_ERROR_PROXY_BAD_GATEWAY); Assert.equal(http_code, undefined); @@ -155,7 +175,10 @@ add_task(async function proxy_bad_gateway_failure() { // 504 Gateway timeout code returned by the proxy. add_task(async function proxy_gateway_timeout_failure() { - const { status, http_code } = await get_response(make_channel(`https://504.example.com/`), CL_EXPECT_FAILURE); + const { status, http_code } = await get_response( + make_channel(`https://504.example.com/`), + CL_EXPECT_FAILURE + ); Assert.equal(status, Cr.NS_ERROR_PROXY_GATEWAY_TIMEOUT); Assert.equal(http_code, undefined); @@ -163,7 +186,10 @@ add_task(async function proxy_gateway_timeout_failure() { // 404 Not Found means the proxy could not resolve the host. add_task(async function proxy_host_not_found_failure() { - const { status, http_code } = await get_response(make_channel(`https://404.example.com/`), CL_EXPECT_FAILURE); + const { status, http_code } = await get_response( + make_channel(`https://404.example.com/`), + CL_EXPECT_FAILURE + ); Assert.equal(status, Cr.NS_ERROR_UNKNOWN_HOST); Assert.equal(http_code, undefined); diff --git a/netwerk/test/unit/test_http2-proxy.js b/netwerk/test/unit/test_http2-proxy.js index 30e2e98dd7ec..493efb1a10c6 100644 --- a/netwerk/test/unit/test_http2-proxy.js +++ b/netwerk/test/unit/test_http2-proxy.js @@ -27,7 +27,7 @@ let proxy_port; let server_port; // See moz-http2 -const proxy_auth = 'authorization-token'; +const proxy_auth = "authorization-token"; let proxy_isolation; class ProxyFilter { @@ -43,11 +43,20 @@ class ProxyFilter { cb.onProxyFilterResult(pi); return; } - cb.onProxyFilterResult(pps.newProxyInfo( - this._type, this._host, this._port, - proxy_auth, proxy_isolation, this._flags, 1000, null)); + cb.onProxyFilterResult( + pps.newProxyInfo( + this._type, + this._host, + this._port, + proxy_auth, + proxy_isolation, + this._flags, + 1000, + null + ) + ); } -}; +} class UnxpectedAuthPrompt2 { constructor(signal) { @@ -58,7 +67,7 @@ class UnxpectedAuthPrompt2 { this.signal.triggered = true; throw Cr.ERROR_UNEXPECTED; } -}; +} class AuthRequestor { constructor(prompt) { @@ -71,7 +80,7 @@ class AuthRequestor { } throw Cr.NS_ERROR_NO_INTERFACE; } -}; +} function make_channel(url) { return NetUtil.newChannel({ @@ -84,13 +93,19 @@ function make_channel(url) { function get_response(channel, flags = CL_ALLOW_UNKNOWN_CL) { return new Promise(resolve => { - channel.asyncOpen(new ChannelListener((request, data) => { - request.QueryInterface(Ci.nsIHttpChannel); - const status = request.status; - const http_code = status ? undefined : request.responseStatus; + channel.asyncOpen( + new ChannelListener( + (request, data) => { + request.QueryInterface(Ci.nsIHttpChannel); + const status = request.status; + const http_code = status ? undefined : request.responseStatus; - resolve({ status, http_code, data }); - }, null, flags)); + resolve({ status, http_code, data }); + }, + null, + flags + ) + ); }); } @@ -98,14 +113,18 @@ let initial_session_count = 0; function proxy_session_counter() { return new Promise(async resolve => { - const channel = make_channel(`https://localhost:${server_port}/proxy-session-counter`); + const channel = make_channel( + `https://localhost:${server_port}/proxy-session-counter` + ); const { data } = await get_response(channel); resolve(parseInt(data) - initial_session_count); }); } add_task(async function setup() { - const env = Cc["@mozilla.org/process/environment;1"].getService(Ci.nsIEnvironment); + const env = Cc["@mozilla.org/process/environment;1"].getService( + Ci.nsIEnvironment + ); server_port = env.get("MOZHTTP2_PORT"); Assert.notEqual(server_port, null); proxy_port = env.get("MOZHTTP2_PROXY_PORT"); @@ -122,8 +141,9 @@ add_task(async function setup() { // The moz-http2 cert is for foo.example.com and is signed by http2-ca.pem // so add that cert to the trust list as a signing cert. - let certdb = Cc["@mozilla.org/security/x509certdb;1"] - .getService(Ci.nsIX509CertDB); + let certdb = Cc["@mozilla.org/security/x509certdb;1"].getService( + Ci.nsIX509CertDB + ); addCertFromFile(certdb, "http2-ca.pem", "CTu,u,u"); pps.registerFilter(new ProxyFilter("https", "localhost", proxy_port, 0), 10); @@ -147,8 +167,12 @@ registerCleanupFunction(() => { add_task(async function proxy_success_one_session() { proxy_isolation = "TOKEN1"; - const foo = await get_response(make_channel(`https://foo.example.com/random-request-1`)); - const alt1 = await get_response(make_channel(`https://alt1.example.com/random-request-2`)); + const foo = await get_response( + make_channel(`https://foo.example.com/random-request-1`) + ); + const alt1 = await get_response( + make_channel(`https://alt1.example.com/random-request-2`) + ); Assert.equal(foo.status, Cr.NS_OK); Assert.equal(foo.http_code, 200); @@ -158,7 +182,11 @@ add_task(async function proxy_success_one_session() { Assert.equal(alt1.http_code, 200); Assert.ok(alt1.data.match("random-request-2")); Assert.ok(alt1.data.match("You Win!")); - Assert.equal(await proxy_session_counter(), 1, "Created just one session with the proxy"); + Assert.equal( + await proxy_session_counter(), + 1, + "Created just one session with the proxy" + ); }); // The proxy responses with 407 instead of 200 Connected, make sure we get a proper error @@ -166,58 +194,96 @@ add_task(async function proxy_success_one_session() { add_task(async function proxy_auth_failure() { const chan = make_channel(`https://407.example.com/`); const auth_prompt = { triggered: false }; - chan.notificationCallbacks = new AuthRequestor(() => new UnxpectedAuthPrompt2(auth_prompt)); + chan.notificationCallbacks = new AuthRequestor( + () => new UnxpectedAuthPrompt2(auth_prompt) + ); const { status, http_code } = await get_response(chan, CL_EXPECT_FAILURE); Assert.equal(status, Cr.NS_ERROR_PROXY_AUTHENTICATION_FAILED); Assert.equal(http_code, undefined); Assert.equal(auth_prompt.triggered, false, "Auth prompt didn't trigger"); - Assert.equal(await proxy_session_counter(), 1, "No new session created by 407"); + Assert.equal( + await proxy_session_counter(), + 1, + "No new session created by 407" + ); }); // 502 Bad gateway code returned by the proxy, still one session only, proper different code // from the channel. add_task(async function proxy_bad_gateway_failure() { - const { status, http_code } = await get_response(make_channel(`https://502.example.com/`), CL_EXPECT_FAILURE); + const { status, http_code } = await get_response( + make_channel(`https://502.example.com/`), + CL_EXPECT_FAILURE + ); Assert.equal(status, Cr.NS_ERROR_PROXY_BAD_GATEWAY); Assert.equal(http_code, undefined); - Assert.equal(await proxy_session_counter(), 1, "No new session created by 502 after 407"); + Assert.equal( + await proxy_session_counter(), + 1, + "No new session created by 502 after 407" + ); }); // Second 502 Bad gateway code returned by the proxy, still one session only with the proxy. add_task(async function proxy_bad_gateway_failure_two() { - const { status, http_code } = await get_response(make_channel(`https://502.example.com/`), CL_EXPECT_FAILURE); + const { status, http_code } = await get_response( + make_channel(`https://502.example.com/`), + CL_EXPECT_FAILURE + ); Assert.equal(status, Cr.NS_ERROR_PROXY_BAD_GATEWAY); Assert.equal(http_code, undefined); - Assert.equal(await proxy_session_counter(), 1, "No new session created by second 502"); + Assert.equal( + await proxy_session_counter(), + 1, + "No new session created by second 502" + ); }); // 504 Gateway timeout code returned by the proxy, still one session only, proper different code // from the channel. add_task(async function proxy_gateway_timeout_failure() { - const { status, http_code } = await get_response(make_channel(`https://504.example.com/`), CL_EXPECT_FAILURE); + const { status, http_code } = await get_response( + make_channel(`https://504.example.com/`), + CL_EXPECT_FAILURE + ); Assert.equal(status, Cr.NS_ERROR_PROXY_GATEWAY_TIMEOUT); Assert.equal(http_code, undefined); - Assert.equal(await proxy_session_counter(), 1, "No new session created by 504 after 502"); + Assert.equal( + await proxy_session_counter(), + 1, + "No new session created by 504 after 502" + ); }); // 404 Not Found means the proxy could not resolve the host. As for other error responses // we still expect this not to close the existing session. add_task(async function proxy_host_not_found_failure() { - const { status, http_code } = await get_response(make_channel(`https://404.example.com/`), CL_EXPECT_FAILURE); + const { status, http_code } = await get_response( + make_channel(`https://404.example.com/`), + CL_EXPECT_FAILURE + ); Assert.equal(status, Cr.NS_ERROR_UNKNOWN_HOST); Assert.equal(http_code, undefined); - Assert.equal(await proxy_session_counter(), 1, "No new session created by 404 after 504"); + Assert.equal( + await proxy_session_counter(), + 1, + "No new session created by 404 after 504" + ); }); // Make sure that the above error codes don't kill the session and we still reach the end server add_task(async function proxy_success_still_one_session() { - const foo = await get_response(make_channel(`https://foo.example.com/random-request-1`)); - const alt1 = await get_response(make_channel(`https://alt1.example.com/random-request-2`)); + const foo = await get_response( + make_channel(`https://foo.example.com/random-request-1`) + ); + const alt1 = await get_response( + make_channel(`https://alt1.example.com/random-request-2`) + ); Assert.equal(foo.status, Cr.NS_OK); Assert.equal(foo.http_code, 200); @@ -225,7 +291,11 @@ add_task(async function proxy_success_still_one_session() { Assert.equal(alt1.status, Cr.NS_OK); Assert.equal(alt1.http_code, 200); Assert.ok(alt1.data.match("random-request-2")); - Assert.equal(await proxy_session_counter(), 1, "No new session created after proxy error codes"); + Assert.equal( + await proxy_session_counter(), + 1, + "No new session created after proxy error codes" + ); }); // Have a new isolation key, this means we are expected to create a new, and again one only, @@ -234,9 +304,15 @@ add_task(async function proxy_success_isolated_session() { Assert.notEqual(proxy_isolation, "TOKEN2"); proxy_isolation = "TOKEN2"; - const foo = await get_response(make_channel(`https://foo.example.com/random-request-1`)); - const alt1 = await get_response(make_channel(`https://alt1.example.com/random-request-2`)); - const lh = await get_response(make_channel(`https://localhost/random-request-3`)); + const foo = await get_response( + make_channel(`https://foo.example.com/random-request-1`) + ); + const alt1 = await get_response( + make_channel(`https://alt1.example.com/random-request-2`) + ); + const lh = await get_response( + make_channel(`https://localhost/random-request-3`) + ); Assert.equal(foo.status, Cr.NS_OK); Assert.equal(foo.http_code, 200); @@ -250,17 +326,31 @@ add_task(async function proxy_success_isolated_session() { Assert.equal(lh.http_code, 200); Assert.ok(lh.data.match("random-request-3")); Assert.ok(lh.data.match("You Win!")); - Assert.equal(await proxy_session_counter(), 2, "Just one new session seen after changing the isolation key"); + Assert.equal( + await proxy_session_counter(), + 2, + "Just one new session seen after changing the isolation key" + ); }); // Check that error codes are still handled the same way with new isolation, just in case. add_task(async function proxy_bad_gateway_failure_isolated() { - const failure1 = await get_response(make_channel(`https://502.example.com/`), CL_EXPECT_FAILURE); - const failure2 = await get_response(make_channel(`https://502.example.com/`), CL_EXPECT_FAILURE); + const failure1 = await get_response( + make_channel(`https://502.example.com/`), + CL_EXPECT_FAILURE + ); + const failure2 = await get_response( + make_channel(`https://502.example.com/`), + CL_EXPECT_FAILURE + ); Assert.equal(failure1.status, Cr.NS_ERROR_PROXY_BAD_GATEWAY); Assert.equal(failure1.http_code, undefined); Assert.equal(failure2.status, Cr.NS_ERROR_PROXY_BAD_GATEWAY); Assert.equal(failure2.http_code, undefined); - Assert.equal(await proxy_session_counter(), 2, "No new session created by 502"); + Assert.equal( + await proxy_session_counter(), + 2, + "No new session created by 502" + ); }); diff --git a/netwerk/test/unit/test_http2.js b/netwerk/test/unit/test_http2.js index 9fbee2567f9f..990a708bee2f 100644 --- a/netwerk/test/unit/test_http2.js +++ b/netwerk/test/unit/test_http2.js @@ -17,11 +17,13 @@ posts.push(generateContent(250000)); posts.push(generateContent(128000)); // pre-calculated md5sums (in hex) of the above posts -var md5s = ['f1b708bba17f1ce948dc979f4d7092bc', - '2ef8d3b6c8f329318eb1a119b12622b6']; +var md5s = [ + "f1b708bba17f1ce948dc979f4d7092bc", + "2ef8d3b6c8f329318eb1a119b12622b6", +]; var bigListenerData = generateContent(128 * 1024); -var bigListenerMD5 = '8f607cfdd2c87d6a7eedb657dafbd836'; +var bigListenerMD5 = "8f607cfdd2c87d6a7eedb657dafbd836"; function checkIsHttp2(request) { try { @@ -43,8 +45,8 @@ Http2CheckListener.prototype = { onStartRequestFired: false, onDataAvailableFired: false, isHttp2Connection: false, - shouldBeHttp2 : true, - accum : 0, + shouldBeHttp2: true, + accum: 0, expected: -1, shouldSucceed: true, @@ -52,7 +54,10 @@ Http2CheckListener.prototype = { this.onStartRequestFired = true; if (this.shouldSucceed && !Components.isSuccessCode(request.status)) { do_throw("Channel should have a success code! (" + request.status + ")"); - } else if (!this.shouldSucceed && Components.isSuccessCode(request.status)) { + } else if ( + !this.shouldSucceed && + Components.isSuccessCode(request.status) + ) { do_throw("Channel succeeded unexpectedly!"); } @@ -85,19 +90,22 @@ Http2CheckListener.prototype = { run_next_test(); do_test_finished(); - } + }, }; /* * Support for testing valid multiplexing of streams */ -var multiplexContent = generateContent(30*1024); +var multiplexContent = generateContent(30 * 1024); var completed_channels = []; function register_completed_channel(listener) { completed_channels.push(listener); if (completed_channels.length == 2) { - Assert.notEqual(completed_channels[0].streamID, completed_channels[1].streamID); + Assert.notEqual( + completed_channels[0].streamID, + completed_channels[1].streamID + ); run_next_test(); do_test_finished(); } @@ -111,7 +119,12 @@ Http2MultiplexListener.prototype = new Http2CheckListener(); Http2MultiplexListener.prototype.streamID = 0; Http2MultiplexListener.prototype.buffer = ""; -Http2MultiplexListener.prototype.onDataAvailable = function(request, stream, off, cnt) { +Http2MultiplexListener.prototype.onDataAvailable = function( + request, + stream, + off, + cnt +) { this.onDataAvailableFired = true; this.isHttp2Connection = checkIsHttp2(request); this.streamID = parseInt(request.getResponseHeader("X-Http2-StreamID")); @@ -138,7 +151,12 @@ var Http2HeaderListener = function(name, callback) { Http2HeaderListener.prototype = new Http2CheckListener(); Http2HeaderListener.prototype.value = ""; -Http2HeaderListener.prototype.onDataAvailable = function(request, stream, off, cnt) { +Http2HeaderListener.prototype.onDataAvailable = function( + request, + stream, + off, + cnt +) { this.onDataAvailableFired = true; this.isHttp2Connection = checkIsHttp2(request); var hvalue = request.getResponseHeader(this.name); @@ -153,19 +171,35 @@ var Http2PushListener = function(shouldBePushed) { Http2PushListener.prototype = new Http2CheckListener(); -Http2PushListener.prototype.onDataAvailable = function(request, stream, off, cnt) { +Http2PushListener.prototype.onDataAvailable = function( + request, + stream, + off, + cnt +) { this.onDataAvailableFired = true; this.isHttp2Connection = checkIsHttp2(request); - if (request.originalURI.spec == "https://localhost:" + serverPort + "/push.js" || - request.originalURI.spec == "https://localhost:" + serverPort + "/push2.js" || - request.originalURI.spec == "https://localhost:" + serverPort + "/push5.js") { - Assert.equal(request.getResponseHeader("pushed"), this.shouldBePushed ? "yes" : "no"); + if ( + request.originalURI.spec == + "https://localhost:" + serverPort + "/push.js" || + request.originalURI.spec == + "https://localhost:" + serverPort + "/push2.js" || + request.originalURI.spec == "https://localhost:" + serverPort + "/push5.js" + ) { + Assert.equal( + request.getResponseHeader("pushed"), + this.shouldBePushed ? "yes" : "no" + ); } read_stream(stream, cnt); }; -const pushHdrTxt = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"; -const pullHdrTxt = pushHdrTxt.split('').reverse().join(''); +const pushHdrTxt = + "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"; +const pullHdrTxt = pushHdrTxt + .split("") + .reverse() + .join(""); function checkContinuedHeaders(getHeader, headerPrefix, headerText) { for (var i = 0; i < 265; i++) { @@ -179,23 +213,41 @@ Http2ContinuedHeaderListener.prototype = new Http2CheckListener(); Http2ContinuedHeaderListener.prototype.onStopsLeft = 2; -Http2ContinuedHeaderListener.prototype.QueryInterface = ChromeUtils.generateQI(["nsIHttpPushListener", "nsIStreamListener"]); +Http2ContinuedHeaderListener.prototype.QueryInterface = ChromeUtils.generateQI([ + "nsIHttpPushListener", + "nsIStreamListener", +]); Http2ContinuedHeaderListener.prototype.getInterface = function(aIID) { return this.QueryInterface(aIID); }; -Http2ContinuedHeaderListener.prototype.onDataAvailable = function (request, stream, off, cnt) { +Http2ContinuedHeaderListener.prototype.onDataAvailable = function( + request, + stream, + off, + cnt +) { this.onDataAvailableFired = true; this.isHttp2Connection = checkIsHttp2(request); - if (request.originalURI.spec == "https://localhost:" + serverPort + "/continuedheaders") { + if ( + request.originalURI.spec == + "https://localhost:" + serverPort + "/continuedheaders" + ) { // This is the original request, so the only one where we'll have continued response headers - checkContinuedHeaders(request.getResponseHeader, "X-Pull-Test-Header-", pullHdrTxt); + checkContinuedHeaders( + request.getResponseHeader, + "X-Pull-Test-Header-", + pullHdrTxt + ); } read_stream(stream, cnt); }; -Http2ContinuedHeaderListener.prototype.onStopRequest = function (request, status) { +Http2ContinuedHeaderListener.prototype.onStopRequest = function( + request, + status +) { Assert.ok(this.onStartRequestFired); Assert.ok(Components.isSuccessCode(status)); Assert.ok(this.onDataAvailableFired); @@ -208,10 +260,20 @@ Http2ContinuedHeaderListener.prototype.onStopRequest = function (request, status } }; -Http2ContinuedHeaderListener.prototype.onPush = function(associatedChannel, pushChannel) { - Assert.equal(associatedChannel.originalURI.spec, "https://localhost:" + serverPort + "/continuedheaders"); +Http2ContinuedHeaderListener.prototype.onPush = function( + associatedChannel, + pushChannel +) { + Assert.equal( + associatedChannel.originalURI.spec, + "https://localhost:" + serverPort + "/continuedheaders" + ); Assert.equal(pushChannel.getRequestHeader("x-pushed-request"), "true"); - checkContinuedHeaders(pushChannel.getRequestHeader, "X-Push-Test-Header-", pushHdrTxt); + checkContinuedHeaders( + pushChannel.getRequestHeader, + "X-Push-Test-Header-", + pushHdrTxt + ); pushChannel.asyncOpen(this); }; @@ -222,7 +284,12 @@ var Http2BigListener = function() {}; Http2BigListener.prototype = new Http2CheckListener(); Http2BigListener.prototype.buffer = ""; -Http2BigListener.prototype.onDataAvailable = function(request, stream, off, cnt) { +Http2BigListener.prototype.onDataAvailable = function( + request, + stream, + off, + cnt +) { this.onDataAvailableFired = true; this.isHttp2Connection = checkIsHttp2(request); this.buffer = this.buffer.concat(read_stream(stream, cnt)); @@ -248,7 +315,12 @@ var Http2HugeSuspendedListener = function() {}; Http2HugeSuspendedListener.prototype = new Http2CheckListener(); Http2HugeSuspendedListener.prototype.count = 0; -Http2HugeSuspendedListener.prototype.onDataAvailable = function(request, stream, off, cnt) { +Http2HugeSuspendedListener.prototype.onDataAvailable = function( + request, + stream, + off, + cnt +) { this.onDataAvailableFired = true; this.isHttp2Connection = checkIsHttp2(request); this.count += cnt; @@ -272,16 +344,26 @@ var Http2PostListener = function(expected_md5) { Http2PostListener.prototype = new Http2CheckListener(); Http2PostListener.prototype.expected_md5 = ""; -Http2PostListener.prototype.onDataAvailable = function(request, stream, off, cnt) { +Http2PostListener.prototype.onDataAvailable = function( + request, + stream, + off, + cnt +) { this.onDataAvailableFired = true; this.isHttp2Connection = checkIsHttp2(request); read_stream(stream, cnt); - Assert.equal(this.expected_md5, request.getResponseHeader("X-Calculated-MD5")); + Assert.equal( + this.expected_md5, + request.getResponseHeader("X-Calculated-MD5") + ); }; function makeChan(url) { - return NetUtil.newChannel({uri: url, loadUsingSystemPrincipal: true}) - .QueryInterface(Ci.nsIHttpChannel); + return NetUtil.newChannel({ + uri: url, + loadUsingSystemPrincipal: true, + }).QueryInterface(Ci.nsIHttpChannel); } var ResumeStalledChannelListener = function() {}; @@ -290,13 +372,14 @@ ResumeStalledChannelListener.prototype = { onStartRequestFired: false, onDataAvailableFired: false, isHttp2Connection: false, - shouldBeHttp2 : true, - resumable : null, + shouldBeHttp2: true, + resumable: null, onStartRequest: function testOnStartRequest(request) { this.onStartRequestFired = true; - if (!Components.isSuccessCode(request.status)) + if (!Components.isSuccessCode(request.status)) { do_throw("Channel should have a success code! (" + request.status + ")"); + } Assert.ok(request instanceof Ci.nsIHttpChannel); Assert.equal(request.responseStatus, 200); @@ -315,7 +398,7 @@ ResumeStalledChannelListener.prototype = { Assert.ok(this.onDataAvailableFired); Assert.ok(this.isHttp2Connection == this.shouldBeHttp2); this.resumable.resume(); - } + }, }; // test a large download that creates stream flow control and @@ -333,10 +416,10 @@ function test_http2_blocking_download() { // can do a basic transaction (i.e. session not blocked). afterwards resume // channel do_timeout(5000, function() { - var simpleChannel = makeChan("https://localhost:" + serverPort + "/"); - var sl = new ResumeStalledChannelListener(); - sl.resumable = chan; - simpleChannel.asyncOpen(sl); + var simpleChannel = makeChan("https://localhost:" + serverPort + "/"); + var sl = new ResumeStalledChannelListener(); + sl.resumable = chan; + simpleChannel.asyncOpen(sl); }); } @@ -348,7 +431,9 @@ function test_http2_basic() { } function test_http2_basic_unblocked_dep() { - var chan = makeChan("https://localhost:" + serverPort + "/basic_unblocked_dep"); + var chan = makeChan( + "https://localhost:" + serverPort + "/basic_unblocked_dep" + ); var cos = chan.QueryInterface(Ci.nsIClassOfService); cos.addClassFlags(Ci.nsIClassOfService.Unblocked); var listener = new Http2CheckListener(); @@ -381,7 +466,9 @@ function checkXhr(xhr) { function test_http2_xhr() { var req = new XMLHttpRequest(); req.open("GET", "https://localhost:" + serverPort + "/", true); - req.addEventListener("readystatechange", function (evt) { checkXhr(req); }); + req.addEventListener("readystatechange", function(evt) { + checkXhr(req); + }); req.send(null); } @@ -414,11 +501,15 @@ Http2ConcurrentListener.prototype.onStopRequest = function(request, status) { function test_http2_concurrent() { var concurrent_listener = new Http2ConcurrentListener(); concurrent_listener.target = 201; - concurrent_listener.reset = prefs.getIntPref("network.http.spdy.default-concurrent"); + concurrent_listener.reset = prefs.getIntPref( + "network.http.spdy.default-concurrent" + ); prefs.setIntPref("network.http.spdy.default-concurrent", 100); for (var i = 0; i < concurrent_listener.target; i++) { - concurrent_channels[i] = makeChan("https://localhost:" + serverPort + "/750ms"); + concurrent_channels[i] = makeChan( + "https://localhost:" + serverPort + "/750ms" + ); concurrent_channels[i].loadFlags = Ci.nsIRequest.LOAD_BYPASS_CACHE; concurrent_channels[i].asyncOpen(concurrent_listener); } @@ -428,14 +519,19 @@ function test_http2_concurrent_post() { var concurrent_listener = new Http2ConcurrentListener(); concurrent_listener.target = 8; concurrent_listener.recvdHdr = posts[2].length; - concurrent_listener.reset = prefs.getIntPref("network.http.spdy.default-concurrent"); + concurrent_listener.reset = prefs.getIntPref( + "network.http.spdy.default-concurrent" + ); prefs.setIntPref("network.http.spdy.default-concurrent", 3); for (var i = 0; i < concurrent_listener.target; i++) { - concurrent_channels[i] = makeChan("https://localhost:" + serverPort + "/750msPost"); + concurrent_channels[i] = makeChan( + "https://localhost:" + serverPort + "/750msPost" + ); concurrent_channels[i].loadFlags = Ci.nsIRequest.LOAD_BYPASS_CACHE; - var stream = Cc["@mozilla.org/io/string-input-stream;1"] - .createInstance(Ci.nsIStringInputStream); + var stream = Cc["@mozilla.org/io/string-input-stream;1"].createInstance( + Ci.nsIStringInputStream + ); stream.data = posts[2]; var uchan = concurrent_channels[i].QueryInterface(Ci.nsIUploadChannel); uchan.setUploadStream(stream, "text/plain", stream.available()); @@ -459,7 +555,9 @@ function test_http2_header() { var chan = makeChan("https://localhost:" + serverPort + "/header"); var hvalue = "Headers are fun"; chan.setRequestHeader("X-Test-Header", hvalue, false); - var listener = new Http2HeaderListener("X-Received-Test-Header", function(received_hvalue) { + var listener = new Http2HeaderListener("X-Received-Test-Header", function( + received_hvalue + ) { Assert.equal(received_hvalue, hvalue); }); chan.asyncOpen(listener); @@ -468,17 +566,22 @@ function test_http2_header() { // Test to make sure cookies are split into separate fields before compression function test_http2_cookie_crumbling() { var chan = makeChan("https://localhost:" + serverPort + "/cookie_crumbling"); - var cookiesSent = ['a=b', 'c=d01234567890123456789', 'e=f'].sort(); - chan.setRequestHeader("Cookie", cookiesSent.join('; '), false); - var listener = new Http2HeaderListener("X-Received-Header-Pairs", function(pairsReceived) { - var cookiesReceived = JSON.parse(pairsReceived).filter(function(pair) { - return pair[0] == 'cookie'; - }).map(function(pair) { - return pair[1]; - }).sort(); + var cookiesSent = ["a=b", "c=d01234567890123456789", "e=f"].sort(); + chan.setRequestHeader("Cookie", cookiesSent.join("; "), false); + var listener = new Http2HeaderListener("X-Received-Header-Pairs", function( + pairsReceived + ) { + var cookiesReceived = JSON.parse(pairsReceived) + .filter(function(pair) { + return pair[0] == "cookie"; + }) + .map(function(pair) { + return pair[1]; + }) + .sort(); Assert.equal(cookiesReceived.length, cookiesSent.length); cookiesReceived.forEach(function(cookieReceived, index) { - Assert.equal(cookiesSent[index], cookieReceived) + Assert.equal(cookiesSent[index], cookieReceived); }); }); chan.asyncOpen(listener); @@ -551,8 +654,9 @@ function test_http2_huge_suspended() { // Support for doing a POST function do_post(content, chan, listener, method) { - var stream = Cc["@mozilla.org/io/string-input-stream;1"] - .createInstance(Ci.nsIStringInputStream); + var stream = Cc["@mozilla.org/io/string-input-stream;1"].createInstance( + Ci.nsIStringInputStream + ); stream.data = content; var uchan = chan.QueryInterface(Ci.nsIUploadChannel); @@ -584,12 +688,11 @@ function test_http2_post_big() { do_post(posts[1], chan, listener, "POST"); } -const {HttpServer} = ChromeUtils.import("resource://testing-common/httpd.js"); +const { HttpServer } = ChromeUtils.import("resource://testing-common/httpd.js"); var httpserv = null; var httpserv2 = null; -var ios = Cc["@mozilla.org/network/io-service;1"] - .getService(Ci.nsIIOService); +var ios = Cc["@mozilla.org/network/io-service;1"].getService(Ci.nsIIOService); var altsvcClientListener = { onStartRequest: function test_onStartR(request) { @@ -597,29 +700,36 @@ var altsvcClientListener = { }, onDataAvailable: function test_ODA(request, stream, offset, cnt) { - read_stream(stream, cnt); + read_stream(stream, cnt); }, onStopRequest: function test_onStopR(request, status) { - var isHttp2Connection = checkIsHttp2(request.QueryInterface(Ci.nsIHttpChannel)); + var isHttp2Connection = checkIsHttp2( + request.QueryInterface(Ci.nsIHttpChannel) + ); if (!isHttp2Connection) { dump("/altsvc1 not over h2 yet - retry\n"); - var chan = makeChan("http://foo.example.com:" + httpserv.identity.primaryPort + "/altsvc1") - .QueryInterface(Ci.nsIHttpChannel); + var chan = makeChan( + "http://foo.example.com:" + httpserv.identity.primaryPort + "/altsvc1" + ).QueryInterface(Ci.nsIHttpChannel); // we use this header to tell the server to issue a altsvc frame for the // speficied origin we will use in the next part of the test - chan.setRequestHeader("x-redirect-origin", - "http://foo.example.com:" + httpserv2.identity.primaryPort, false); + chan.setRequestHeader( + "x-redirect-origin", + "http://foo.example.com:" + httpserv2.identity.primaryPort, + false + ); chan.loadFlags = Ci.nsIRequest.LOAD_BYPASS_CACHE; chan.asyncOpen(altsvcClientListener); } else { Assert.ok(isHttp2Connection); - var chan = makeChan("http://foo.example.com:" + httpserv2.identity.primaryPort + "/altsvc2") - .QueryInterface(Ci.nsIHttpChannel); + var chan = makeChan( + "http://foo.example.com:" + httpserv2.identity.primaryPort + "/altsvc2" + ).QueryInterface(Ci.nsIHttpChannel); chan.loadFlags = Ci.nsIRequest.LOAD_BYPASS_CACHE; chan.asyncOpen(altsvcClientListener2); } - } + }, }; var altsvcClientListener2 = { @@ -628,15 +738,18 @@ var altsvcClientListener2 = { }, onDataAvailable: function test_ODA(request, stream, offset, cnt) { - read_stream(stream, cnt); + read_stream(stream, cnt); }, onStopRequest: function test_onStopR(request, status) { - var isHttp2Connection = checkIsHttp2(request.QueryInterface(Ci.nsIHttpChannel)); + var isHttp2Connection = checkIsHttp2( + request.QueryInterface(Ci.nsIHttpChannel) + ); if (!isHttp2Connection) { dump("/altsvc2 not over h2 yet - retry\n"); - var chan = makeChan("http://foo.example.com:" + httpserv2.identity.primaryPort + "/altsvc2") - .QueryInterface(Ci.nsIHttpChannel); + var chan = makeChan( + "http://foo.example.com:" + httpserv2.identity.primaryPort + "/altsvc2" + ).QueryInterface(Ci.nsIHttpChannel); chan.loadFlags = Ci.nsIRequest.LOAD_BYPASS_CACHE; chan.asyncOpen(altsvcClientListener2); } else { @@ -644,7 +757,7 @@ var altsvcClientListener2 = { run_next_test(); do_test_finished(); } - } + }, }; function altsvcHttp1Server(metadata, response) { @@ -669,9 +782,9 @@ function h1ServerWK(metadata, response) { } function altsvcHttp1Server2(metadata, response) { -// this server should never be used thanks to an alt svc frame from the -// h2 server.. but in case of some async lag in setting the alt svc route -// up we have it. + // this server should never be used thanks to an alt svc frame from the + // h2 server.. but in case of some async lag in setting the alt svc route + // up we have it. response.setStatusLine(metadata.httpVersion, 200, "OK"); response.setHeader("Content-Type", "text/plain", false); response.setHeader("Connection", "close", false); @@ -687,12 +800,14 @@ function h1ServerWK2(metadata, response) { response.setHeader("Access-Control-Allow-Origin", "*", false); response.setHeader("Access-Control-Allow-Method", "GET", false); - var body = '["http://foo.example.com:' + httpserv2.identity.primaryPort + '"]'; + var body = + '["http://foo.example.com:' + httpserv2.identity.primaryPort + '"]'; response.bodyOutputStream.write(body, body.length); } function test_http2_altsvc() { - var chan = makeChan("http://foo.example.com:" + httpserv.identity.primaryPort + "/altsvc1") - .QueryInterface(Ci.nsIHttpChannel); + var chan = makeChan( + "http://foo.example.com:" + httpserv.identity.primaryPort + "/altsvc1" + ).QueryInterface(Ci.nsIHttpChannel); chan.asyncOpen(altsvcClientListener); } @@ -705,38 +820,66 @@ Http2PushApiListener.prototype = { return this.QueryInterface(aIID); }, - QueryInterface: ChromeUtils.generateQI(["nsIHttpPushListener", "nsIStreamListener"]), + QueryInterface: ChromeUtils.generateQI([ + "nsIHttpPushListener", + "nsIStreamListener", + ]), // nsIHttpPushListener onPush: function onPush(associatedChannel, pushChannel) { - Assert.equal(associatedChannel.originalURI.spec, "https://localhost:" + serverPort + "/pushapi1"); - Assert.equal (pushChannel.getRequestHeader("x-pushed-request"), "true"); + Assert.equal( + associatedChannel.originalURI.spec, + "https://localhost:" + serverPort + "/pushapi1" + ); + Assert.equal(pushChannel.getRequestHeader("x-pushed-request"), "true"); pushChannel.asyncOpen(this); - if (pushChannel.originalURI.spec == "https://localhost:" + serverPort + "/pushapi1/2") { + if ( + pushChannel.originalURI.spec == + "https://localhost:" + serverPort + "/pushapi1/2" + ) { pushChannel.cancel(Cr.NS_ERROR_ABORT); - } else if (pushChannel.originalURI.spec == "https://localhost:" + serverPort + "/pushapi1/3") { + } else if ( + pushChannel.originalURI.spec == + "https://localhost:" + serverPort + "/pushapi1/3" + ) { Assert.ok(pushChannel.getRequestHeader("Accept-Encoding").includes("br")); } }, - // normal Channel listeners - onStartRequest: function pushAPIOnStart(request) { - }, + // normal Channel listeners + onStartRequest: function pushAPIOnStart(request) {}, - onDataAvailable: function pushAPIOnDataAvailable(request, stream, offset, cnt) { - Assert.notEqual(request.originalURI.spec, "https://localhost:" + serverPort + "/pushapi1/2"); + onDataAvailable: function pushAPIOnDataAvailable( + request, + stream, + offset, + cnt + ) { + Assert.notEqual( + request.originalURI.spec, + "https://localhost:" + serverPort + "/pushapi1/2" + ); var data = read_stream(stream, cnt); - if (request.originalURI.spec == "https://localhost:" + serverPort + "/pushapi1") { - Assert.equal(data[0], '0'); + if ( + request.originalURI.spec == + "https://localhost:" + serverPort + "/pushapi1" + ) { + Assert.equal(data[0], "0"); --this.checksPending; - } else if (request.originalURI.spec == "https://localhost:" + serverPort + "/pushapi1/1") { - Assert.equal(data[0], '1'); + } else if ( + request.originalURI.spec == + "https://localhost:" + serverPort + "/pushapi1/1" + ) { + Assert.equal(data[0], "1"); --this.checksPending; // twice - } else if (request.originalURI.spec == "https://localhost:" + serverPort + "/pushapi1/3") { - Assert.equal(data[0], '3'); + } else if ( + request.originalURI.spec == + "https://localhost:" + serverPort + "/pushapi1/3" + ) { + Assert.equal(data[0], "3"); --this.checksPending; } else { Assert.equal(true, false); @@ -744,7 +887,10 @@ Http2PushApiListener.prototype = { }, onStopRequest: function test_onStopR(request, status) { - if (request.originalURI.spec == "https://localhost:" + serverPort + "/pushapi1/2") { + if ( + request.originalURI.spec == + "https://localhost:" + serverPort + "/pushapi1/2" + ) { Assert.equal(request.status, Cr.NS_ERROR_ABORT); } else { Assert.equal(request.status, Cr.NS_OK); @@ -755,7 +901,7 @@ Http2PushApiListener.prototype = { run_next_test(); do_test_finished(); } - } + }, }; // pushAPI testcase 1 expects @@ -788,7 +934,9 @@ function test_http2_wrongsuite_tls12() { prefs.setBoolPref("security.ssl3.ecdhe_rsa_aes_128_gcm_sha256", false); prefs.setIntPref("security.tls.version.max", 3); var chan = makeChan("https://localhost:" + serverPort + "/wrongsuite"); - chan.loadFlags = Ci.nsIRequest.LOAD_FRESH_CONNECTION | Ci.nsIChannel.LOAD_INITIAL_DOCUMENT_URI; + chan.loadFlags = + Ci.nsIRequest.LOAD_FRESH_CONNECTION | + Ci.nsIChannel.LOAD_INITIAL_DOCUMENT_URI; var listener = new WrongSuiteListener(); chan.asyncOpen(listener); } @@ -798,23 +946,27 @@ function test_http2_wrongsuite_tls12() { function test_http2_wrongsuite_tls13() { prefs.setBoolPref("security.ssl3.ecdhe_rsa_aes_128_gcm_sha256", false); var chan = makeChan("https://localhost:" + serverPort + "/wrongsuite"); - chan.loadFlags = Ci.nsIRequest.LOAD_FRESH_CONNECTION | Ci.nsIChannel.LOAD_INITIAL_DOCUMENT_URI; + chan.loadFlags = + Ci.nsIRequest.LOAD_FRESH_CONNECTION | + Ci.nsIChannel.LOAD_INITIAL_DOCUMENT_URI; var listener = new WrongSuiteListener(); listener.shouldBeHttp2 = true; chan.asyncOpen(listener); } function test_http2_h11required_stream() { - var chan = makeChan("https://localhost:" + serverPort + "/h11required_stream"); + var chan = makeChan( + "https://localhost:" + serverPort + "/h11required_stream" + ); var listener = new Http2CheckListener(); listener.shouldBeHttp2 = false; chan.asyncOpen(listener); } -function H11RequiredSessionListener () { } +function H11RequiredSessionListener() {} H11RequiredSessionListener.prototype = new Http2CheckListener(); -H11RequiredSessionListener.prototype.onStopRequest = function (request, status) { +H11RequiredSessionListener.prototype.onStopRequest = function(request, status) { var streamReused = request.getResponseHeader("X-H11Required-Stream-Ok"); Assert.equal(streamReused, "yes"); @@ -827,7 +979,9 @@ H11RequiredSessionListener.prototype.onStopRequest = function (request, status) }; function test_http2_h11required_session() { - var chan = makeChan("https://localhost:" + serverPort + "/h11required_session"); + var chan = makeChan( + "https://localhost:" + serverPort + "/h11required_session" + ); var listener = new H11RequiredSessionListener(); listener.shouldBeHttp2 = false; chan.asyncOpen(listener); @@ -847,12 +1001,15 @@ function test_http2_continuations() { chan.asyncOpen(listener); } -function Http2IllegalHpackValidationListener() { } +function Http2IllegalHpackValidationListener() {} Http2IllegalHpackValidationListener.prototype = new Http2CheckListener(); Http2IllegalHpackValidationListener.prototype.shouldGoAway = false; -Http2IllegalHpackValidationListener.prototype.onStopRequest = function (request, status) { - var wentAway = (request.getResponseHeader('X-Did-Goaway') === 'yes'); +Http2IllegalHpackValidationListener.prototype.onStopRequest = function( + request, + status +) { + var wentAway = request.getResponseHeader("X-Did-Goaway") === "yes"; Assert.equal(wentAway, this.shouldGoAway); Assert.ok(this.onStartRequestFired); @@ -863,12 +1020,14 @@ Http2IllegalHpackValidationListener.prototype.onStopRequest = function (request, do_test_finished(); }; -function Http2IllegalHpackListener() { } +function Http2IllegalHpackListener() {} Http2IllegalHpackListener.prototype = new Http2CheckListener(); Http2IllegalHpackListener.prototype.shouldGoAway = false; -Http2IllegalHpackListener.prototype.onStopRequest = function (request, status) { - var chan = makeChan("https://localhost:" + serverPort + "/illegalhpack_validate"); +Http2IllegalHpackListener.prototype.onStopRequest = function(request, status) { + var chan = makeChan( + "https://localhost:" + serverPort + "/illegalhpack_validate" + ); var listener = new Http2IllegalHpackValidationListener(); listener.shouldGoAway = this.shouldGoAway; chan.asyncOpen(listener); @@ -963,13 +1122,21 @@ var PulledDiskCacheListener = function() {}; PulledDiskCacheListener.prototype = new Http2CheckListener(); PulledDiskCacheListener.prototype.EXPECTED_DATA = "this was pulled via h2"; PulledDiskCacheListener.prototype.readData = ""; -PulledDiskCacheListener.prototype.onDataAvailable = function testOnDataAvailable(request, stream, off, cnt) { +PulledDiskCacheListener.prototype.onDataAvailable = function testOnDataAvailable( + request, + stream, + off, + cnt +) { this.onDataAvailableFired = true; this.isHttp2Connection = checkIsHttp2(request); this.accum += cnt; this.readData += read_stream(stream, cnt); }; -PulledDiskCacheListener.prototype.onStopRequest = function testOnStopRequest(request, status) { +PulledDiskCacheListener.prototype.onStopRequest = function testOnStopRequest( + request, + status +) { Assert.equal(this.EXPECTED_DATA, this.readData); Http2CheckListener.prorotype.onStopRequest.call(this, request, status); }; @@ -1014,7 +1181,7 @@ FromDiskCacheListener.prototype = { chan.loadGroup = loadGroup; chan.asyncOpen(listener); }); - } + }, }; var Http2DiskCachePushListener = function() {}; @@ -1022,17 +1189,17 @@ var Http2DiskCachePushListener = function() {}; Http2DiskCachePushListener.prototype = new Http2CheckListener(); Http2DiskCachePushListener.onStopRequest = function(request, status) { - Assert.ok(this.onStartRequestFired); - Assert.ok(Components.isSuccessCode(status)); - Assert.ok(this.onDataAvailableFired); - Assert.ok(this.isHttp2Connection == this.shouldBeHttp2); + Assert.ok(this.onStartRequestFired); + Assert.ok(Components.isSuccessCode(status)); + Assert.ok(this.onDataAvailableFired); + Assert.ok(this.isHttp2Connection == this.shouldBeHttp2); - // Now we need to open a channel to ensure we get data from the disk cache - // for the pushed item, instead of from the push cache. - var chan = makeChan("https://localhost:" + serverPort + "/diskcache"); - chan.listener = new FromDiskCacheListener(); - chan.loadGroup = loadGroup; - chan.asyncOpen(listener); + // Now we need to open a channel to ensure we get data from the disk cache + // for the pushed item, instead of from the push cache. + var chan = makeChan("https://localhost:" + serverPort + "/diskcache"); + chan.listener = new FromDiskCacheListener(); + chan.loadGroup = loadGroup; + chan.asyncOpen(listener); }; function continue_test_http2_disk_cache_push(status, entry, appCache) { @@ -1050,9 +1217,14 @@ function continue_test_http2_disk_cache_push(status, entry, appCache) { } function test_http2_disk_cache_push() { - asyncOpenCacheEntry("https://localhost:" + serverPort + "/diskcache", - "disk", Ci.nsICacheStorage.OPEN_NORMALLY, null, - continue_test_http2_disk_cache_push, false); + asyncOpenCacheEntry( + "https://localhost:" + serverPort + "/diskcache", + "disk", + Ci.nsICacheStorage.OPEN_NORMALLY, + null, + continue_test_http2_disk_cache_push, + false + ); } function test_complete() { @@ -1063,12 +1235,12 @@ function test_complete() { httpserv2.stop(do_test_finished); do_test_finished(); - do_timeout(0,run_next_test); + do_timeout(0, run_next_test); } -var Http2DoublepushListener = function () {}; +var Http2DoublepushListener = function() {}; Http2DoublepushListener.prototype = new Http2CheckListener(); -Http2DoublepushListener.prototype.onStopRequest = function (request, status) { +Http2DoublepushListener.prototype.onStopRequest = function(request, status) { Assert.ok(this.onStartRequestFired); Assert.ok(Components.isSuccessCode(status)); Assert.ok(this.onDataAvailableFired); @@ -1080,15 +1252,20 @@ Http2DoublepushListener.prototype.onStopRequest = function (request, status) { chan.asyncOpen(listener); }; -var Http2DoublypushedListener = function () {}; +var Http2DoublypushedListener = function() {}; Http2DoublypushedListener.prototype = new Http2CheckListener(); Http2DoublypushedListener.prototype.readData = ""; -Http2DoublypushedListener.prototype.onDataAvailable = function (request, stream, off, cnt) { +Http2DoublypushedListener.prototype.onDataAvailable = function( + request, + stream, + off, + cnt +) { this.onDataAvailableFired = true; this.accum += cnt; this.readData += read_stream(stream, cnt); }; -Http2DoublypushedListener.prototype.onStopRequest = function (request, status) { +Http2DoublypushedListener.prototype.onStopRequest = function(request, status) { Assert.ok(this.onStartRequestFired); Assert.ok(Components.isSuccessCode(status)); Assert.ok(this.onDataAvailableFired); @@ -1110,56 +1287,57 @@ function test_http2_doublepush() { // // make sure post_big runs first to test race condition in restarting // a stalled stream when a SETTINGS frame arrives -var tests = [ test_http2_post_big - , test_http2_basic - , test_http2_concurrent - , test_http2_concurrent_post - , test_http2_basic_unblocked_dep - , test_http2_nospdy - , test_http2_push1 - , test_http2_push2 - , test_http2_push3 - , test_http2_push4 - , test_http2_push5 - , test_http2_push6 - , test_http2_altsvc - , test_http2_doubleheader - , test_http2_xhr - , test_http2_header - , test_http2_cookie_crumbling - , test_http2_multiplex - , test_http2_big - , test_http2_huge_suspended - , test_http2_post - , test_http2_patch - , test_http2_pushapi_1 - , test_http2_continuations - , test_http2_blocking_download - , test_http2_illegalhpacksoft - , test_http2_illegalhpackhard - , test_http2_folded_header - , test_http2_empty_data - , test_http2_status_phrase - , test_http2_doublepush - , test_http2_disk_cache_push - // Add new tests above here - best to add new tests before h1 - // streams get too involved - // These next two must always come in this order - , test_http2_h11required_stream - , test_http2_h11required_session - , test_http2_retry_rst - , test_http2_wrongsuite_tls12 - , test_http2_wrongsuite_tls13 - , test_http2_push_firstparty1 - , test_http2_push_firstparty2 - , test_http2_push_firstparty3 - , test_http2_push_userContext1 - , test_http2_push_userContext2 - , test_http2_push_userContext3 +var tests = [ + test_http2_post_big, + test_http2_basic, + test_http2_concurrent, + test_http2_concurrent_post, + test_http2_basic_unblocked_dep, + test_http2_nospdy, + test_http2_push1, + test_http2_push2, + test_http2_push3, + test_http2_push4, + test_http2_push5, + test_http2_push6, + test_http2_altsvc, + test_http2_doubleheader, + test_http2_xhr, + test_http2_header, + test_http2_cookie_crumbling, + test_http2_multiplex, + test_http2_big, + test_http2_huge_suspended, + test_http2_post, + test_http2_patch, + test_http2_pushapi_1, + test_http2_continuations, + test_http2_blocking_download, + test_http2_illegalhpacksoft, + test_http2_illegalhpackhard, + test_http2_folded_header, + test_http2_empty_data, + test_http2_status_phrase, + test_http2_doublepush, + test_http2_disk_cache_push, + // Add new tests above here - best to add new tests before h1 + // streams get too involved + // These next two must always come in this order + test_http2_h11required_stream, + test_http2_h11required_session, + test_http2_retry_rst, + test_http2_wrongsuite_tls12, + test_http2_wrongsuite_tls13, + test_http2_push_firstparty1, + test_http2_push_firstparty2, + test_http2_push_firstparty3, + test_http2_push_userContext1, + test_http2_push_userContext2, + test_http2_push_userContext3, - // cleanup - , test_complete - ]; + // cleanup + test_complete, +]; var current_test = 0; function run_next_test() { @@ -1193,7 +1371,9 @@ function resetPrefs() { } function run_test() { - var env = Cc["@mozilla.org/process/environment;1"].getService(Ci.nsIEnvironment); + var env = Cc["@mozilla.org/process/environment;1"].getService( + Ci.nsIEnvironment + ); serverPort = env.get("MOZHTTP2_PORT"); Assert.notEqual(serverPort, null); dump("using port " + serverPort + "\n"); @@ -1201,15 +1381,18 @@ function run_test() { // Set to allow the cert presented by our H2 server do_get_profile(); prefs = Cc["@mozilla.org/preferences-service;1"].getService(Ci.nsIPrefBranch); - speculativeLimit = prefs.getIntPref("network.http.speculative-parallel-limit"); + speculativeLimit = prefs.getIntPref( + "network.http.speculative-parallel-limit" + ); prefs.setIntPref("network.http.speculative-parallel-limit", 0); // The moz-http2 cert is for foo.example.com and is signed by http2-ca.pem // so add that cert to the trust list as a signing cert. Some older tests in // this suite use localhost with a TOFU exception, but new ones should use // foo.example.com - let certdb = Cc["@mozilla.org/security/x509certdb;1"] - .getService(Ci.nsIX509CertDB); + let certdb = Cc["@mozilla.org/security/x509certdb;1"].getService( + Ci.nsIX509CertDB + ); addCertFromFile(certdb, "http2-ca.pem", "CTu,u,u"); // Enable all versions of spdy to see that we auto negotiate http/2 @@ -1224,22 +1407,35 @@ function run_test() { prefs.setBoolPref("network.http.spdy.enabled.http2", true); prefs.setBoolPref("network.http.altsvc.enabled", true); prefs.setBoolPref("network.http.altsvc.oe", true); - prefs.setCharPref("network.dns.localDomains", "foo.example.com, bar.example.com"); + prefs.setCharPref( + "network.dns.localDomains", + "foo.example.com, bar.example.com" + ); prefs.setBoolPref("network.cookieSettings.unblocked_for_testing", true); - loadGroup = Cc["@mozilla.org/network/load-group;1"].createInstance(Ci.nsILoadGroup); + loadGroup = Cc["@mozilla.org/network/load-group;1"].createInstance( + Ci.nsILoadGroup + ); httpserv = new HttpServer(); httpserv.registerPathHandler("/altsvc1", altsvcHttp1Server); httpserv.registerPathHandler("/.well-known/http-opportunistic", h1ServerWK); httpserv.start(-1); - httpserv.identity.setPrimary("http", "foo.example.com", httpserv.identity.primaryPort); + httpserv.identity.setPrimary( + "http", + "foo.example.com", + httpserv.identity.primaryPort + ); httpserv2 = new HttpServer(); httpserv2.registerPathHandler("/altsvc2", altsvcHttp1Server2); httpserv2.registerPathHandler("/.well-known/http-opportunistic", h1ServerWK2); httpserv2.start(-1); - httpserv2.identity.setPrimary("http", "foo.example.com", httpserv2.identity.primaryPort); + httpserv2.identity.setPrimary( + "http", + "foo.example.com", + httpserv2.identity.primaryPort + ); // And make go! run_next_test(); diff --git a/netwerk/test/unit/test_httpResponseTimeout.js b/netwerk/test/unit/test_httpResponseTimeout.js index df78b476e928..6c827581562d 100644 --- a/netwerk/test/unit/test_httpResponseTimeout.js +++ b/netwerk/test/unit/test_httpResponseTimeout.js @@ -6,7 +6,7 @@ "use strict"; -const {HttpServer} = ChromeUtils.import("resource://testing-common/httpd.js"); +const { HttpServer } = ChromeUtils.import("resource://testing-common/httpd.js"); var baseURL; const kResponseTimeoutPref = "network.http.response.timeout"; @@ -16,8 +16,9 @@ const kShortLivedKeepalivePref = const kLongLivedKeepalivePref = "network.http.tcp_keepalive.long_lived_connections"; -const prefService = Cc["@mozilla.org/preferences-service;1"] - .getService(Ci.nsIPrefBranch); +const prefService = Cc["@mozilla.org/preferences-service;1"].getService( + Ci.nsIPrefBranch +); var server = new HttpServer(); @@ -26,13 +27,11 @@ function TimeoutListener(expectResponse) { } TimeoutListener.prototype = { - onStartRequest (request) { - }, + onStartRequest(request) {}, - onDataAvailable (request, stream) { - }, + onDataAvailable(request, stream) {}, - onStopRequest (request, status) { + onStopRequest(request, status) { if (this.expectResponse) { Assert.equal(status, Cr.NS_OK); } else { @@ -55,8 +54,10 @@ function testTimeout(timeoutEnabled, expectResponse) { prefService.setIntPref(kResponseTimeoutPref, 0); } - var chan = NetUtil.newChannel({uri: baseURL, loadUsingSystemPrincipal: true}) - .QueryInterface(Ci.nsIHttpChannel); + var chan = NetUtil.newChannel({ + uri: baseURL, + loadUsingSystemPrincipal: true, + }).QueryInterface(Ci.nsIHttpChannel); var listener = new TimeoutListener(expectResponse); chan.asyncOpen(listener); } @@ -124,10 +125,10 @@ function setup_tests() { // Disable by enabling TCP keepalive for long-lived HTTP connections. testTimeoutDisabledByLongLivedKeepalives, // Disable by enabling TCP keepalive for both HTTP connection types. - testTimeoutDisabledByBothKeepalives + testTimeoutDisabledByBothKeepalives, ]; - for (var i=0; i < tests.length; i++) { + for (var i = 0; i < tests.length; i++) { add_test(tests[i]); } } @@ -137,11 +138,11 @@ function setup_http_server() { server.start(-1); baseURL = "http://localhost:" + server.identity.primaryPort + "/"; info("Using baseURL: " + baseURL); - server.registerPathHandler('/', function(metadata, response) { + server.registerPathHandler("/", function(metadata, response) { // Wait until the timeout should have passed, then respond. response.processAsync(); - do_timeout((kResponseTimeout+1)*1000 /* ms */, function() { + do_timeout((kResponseTimeout + 1) * 1000 /* ms */, function() { response.setStatusLine(metadata.httpVersion, 200, "OK"); response.write("Hello world"); response.finish(); diff --git a/netwerk/test/unit/test_http_headers.js b/netwerk/test/unit/test_http_headers.js index 89f71cdd890e..29adfeff1c34 100644 --- a/netwerk/test/unit/test_http_headers.js +++ b/netwerk/test/unit/test_http_headers.js @@ -1,4 +1,3 @@ - function check_request_header(chan, name, value) { var chanValue; try { @@ -10,10 +9,9 @@ function check_request_header(chan, name, value) { } function run_test() { - - var chan = NetUtil.newChannel ({ + var chan = NetUtil.newChannel({ uri: "http://www.mozilla.org/", - loadUsingSystemPrincipal: true + loadUsingSystemPrincipal: true, }).QueryInterface(Ci.nsIHttpChannel); check_request_header(chan, "host", "www.mozilla.org"); @@ -25,11 +23,13 @@ function run_test() { chan.setRequestHeader("foopy", "baz", true); check_request_header(chan, "foopy", "bar, baz"); - for (var i = 0; i < 100; ++i) + for (var i = 0; i < 100; ++i) { chan.setRequestHeader("foopy" + i, i, false); + } - for (var i = 0; i < 100; ++i) + for (var i = 0; i < 100; ++i) { check_request_header(chan, "foopy" + i, i); + } var x = false; try { @@ -37,8 +37,9 @@ function run_test() { } catch (e) { x = true; } - if (!x) + if (!x) { do_throw("header with colon not rejected"); + } x = false; try { @@ -46,8 +47,9 @@ function run_test() { } catch (e) { x = true; } - if (!x) + if (!x) { do_throw("header value with newline not rejected"); + } x = false; try { @@ -55,8 +57,9 @@ function run_test() { } catch (e) { x = true; } - if (!x) + if (!x) { do_throw("header name with non-ASCII not rejected"); + } x = false; try { @@ -64,6 +67,7 @@ function run_test() { } catch (e) { x = true; } - if (!x) + if (!x) { do_throw("header value with null-byte not rejected"); + } } diff --git a/netwerk/test/unit/test_httpauth.js b/netwerk/test/unit/test_httpauth.js index 1f8ee231f487..516c414eedfd 100644 --- a/netwerk/test/unit/test_httpauth.js +++ b/netwerk/test/unit/test_httpauth.js @@ -6,8 +6,9 @@ // when entering and leaving the private browsing mode. function run_test() { - var am = Cc["@mozilla.org/network/http-auth-manager;1"]. - getService(Ci.nsIHttpAuthManager); + var am = Cc["@mozilla.org/network/http-auth-manager;1"].getService( + Ci.nsIHttpAuthManager + ); const kHost1 = "pbtest3.example.com"; const kHost2 = "pbtest4.example.com"; @@ -21,26 +22,64 @@ function run_test() { const kPassword = "pass"; const kPassword2 = "pass2"; const kEmpty = ""; - + const PRIVATE = true; const NOT_PRIVATE = false; - + try { - var domain = {value: kEmpty}, user = {value: kEmpty}, pass = {value: kEmpty}; + var domain = { value: kEmpty }, + user = { value: kEmpty }, + pass = { value: kEmpty }; // simulate a login via HTTP auth outside of the private mode - am.setAuthIdentity(kHTTP, kHost1, kPort, kBasic, kRealm, kEmpty, kDomain, kUser, kPassword); + am.setAuthIdentity( + kHTTP, + kHost1, + kPort, + kBasic, + kRealm, + kEmpty, + kDomain, + kUser, + kPassword + ); // make sure the recently added auth entry is available outside the private browsing mode - am.getAuthIdentity(kHTTP, kHost1, kPort, kBasic, kRealm, kEmpty, domain, user, pass, NOT_PRIVATE); + am.getAuthIdentity( + kHTTP, + kHost1, + kPort, + kBasic, + kRealm, + kEmpty, + domain, + user, + pass, + NOT_PRIVATE + ); Assert.equal(domain.value, kDomain); Assert.equal(user.value, kUser); Assert.equal(pass.value, kPassword); // make sure the added auth entry is no longer accessible in private - domain = {value: kEmpty}, user = {value: kEmpty}, pass = {value: kEmpty}; + (domain = { value: kEmpty }), + (user = { value: kEmpty }), + (pass = { value: kEmpty }); try { // should throw - am.getAuthIdentity(kHTTP, kHost1, kPort, kBasic, kRealm, kEmpty, domain, user, pass, PRIVATE); - do_throw("Auth entry should not be retrievable after entering the private browsing mode"); + am.getAuthIdentity( + kHTTP, + kHost1, + kPort, + kBasic, + kRealm, + kEmpty, + domain, + user, + pass, + PRIVATE + ); + do_throw( + "Auth entry should not be retrievable after entering the private browsing mode" + ); } catch (e) { Assert.equal(domain.value, kEmpty); Assert.equal(user.value, kEmpty); @@ -48,19 +87,58 @@ function run_test() { } // simulate a login via HTTP auth inside of the private mode - am.setAuthIdentity(kHTTP, kHost2, kPort, kBasic, kRealm, kEmpty, kDomain, kUser2, kPassword2, PRIVATE); + am.setAuthIdentity( + kHTTP, + kHost2, + kPort, + kBasic, + kRealm, + kEmpty, + kDomain, + kUser2, + kPassword2, + PRIVATE + ); // make sure the recently added auth entry is available inside the private browsing mode - domain = {value: kEmpty}, user = {value: kEmpty}, pass = {value: kEmpty}; - am.getAuthIdentity(kHTTP, kHost2, kPort, kBasic, kRealm, kEmpty, domain, user, pass, PRIVATE); + (domain = { value: kEmpty }), + (user = { value: kEmpty }), + (pass = { value: kEmpty }); + am.getAuthIdentity( + kHTTP, + kHost2, + kPort, + kBasic, + kRealm, + kEmpty, + domain, + user, + pass, + PRIVATE + ); Assert.equal(domain.value, kDomain); Assert.equal(user.value, kUser2); Assert.equal(pass.value, kPassword2); try { // make sure the recently added auth entry is not available outside the private browsing mode - domain = {value: kEmpty}, user = {value: kEmpty}, pass = {value: kEmpty}; - am.getAuthIdentity(kHTTP, kHost2, kPort, kBasic, kRealm, kEmpty, domain, user, pass, NOT_PRIVATE); - do_throw("Auth entry should not be retrievable outside of private browsing mode"); + (domain = { value: kEmpty }), + (user = { value: kEmpty }), + (pass = { value: kEmpty }); + am.getAuthIdentity( + kHTTP, + kHost2, + kPort, + kBasic, + kRealm, + kEmpty, + domain, + user, + pass, + NOT_PRIVATE + ); + do_throw( + "Auth entry should not be retrievable outside of private browsing mode" + ); } catch (x) { Assert.equal(domain.value, kEmpty); Assert.equal(user.value, kEmpty); @@ -71,11 +149,26 @@ function run_test() { Services.obs.notifyObservers(null, "last-pb-context-exited"); // make sure the added auth entry is no longer accessible in any privacy state - domain = {value: kEmpty}, user = {value: kEmpty}, pass = {value: kEmpty}; + (domain = { value: kEmpty }), + (user = { value: kEmpty }), + (pass = { value: kEmpty }); try { // should throw (not available in public mode) - am.getAuthIdentity(kHTTP, kHost2, kPort, kBasic, kRealm, kEmpty, domain, user, pass, NOT_PRIVATE); - do_throw("Auth entry should not be retrievable after exiting the private browsing mode"); + am.getAuthIdentity( + kHTTP, + kHost2, + kPort, + kBasic, + kRealm, + kEmpty, + domain, + user, + pass, + NOT_PRIVATE + ); + do_throw( + "Auth entry should not be retrievable after exiting the private browsing mode" + ); } catch (e) { Assert.equal(domain.value, kEmpty); Assert.equal(user.value, kEmpty); @@ -83,8 +176,21 @@ function run_test() { } try { // should throw (no longer available in private mode) - am.getAuthIdentity(kHTTP, kHost2, kPort, kBasic, kRealm, kEmpty, domain, user, pass, PRIVATE); - do_throw("Auth entry should not be retrievable in private mode after exiting the private browsing mode"); + am.getAuthIdentity( + kHTTP, + kHost2, + kPort, + kBasic, + kRealm, + kEmpty, + domain, + user, + pass, + PRIVATE + ); + do_throw( + "Auth entry should not be retrievable in private mode after exiting the private browsing mode" + ); } catch (x) { Assert.equal(domain.value, kEmpty); Assert.equal(user.value, kEmpty); @@ -94,4 +200,3 @@ function run_test() { do_throw("Unexpected exception while testing HTTP auth manager: " + e); } } - diff --git a/netwerk/test/unit/test_httpcancel.js b/netwerk/test/unit/test_httpcancel.js index 328480127dbf..8f1f4fb9be96 100644 --- a/netwerk/test/unit/test_httpcancel.js +++ b/netwerk/test/unit/test_httpcancel.js @@ -9,19 +9,21 @@ "use strict"; -const {HttpServer} = ChromeUtils.import("resource://testing-common/httpd.js"); +const { HttpServer } = ChromeUtils.import("resource://testing-common/httpd.js"); function inChildProcess() { - return Cc["@mozilla.org/xre/app-info;1"] - .getService(Ci.nsIXULRuntime) - .processType != Ci.nsIXULRuntime.PROCESS_TYPE_DEFAULT; + return ( + Cc["@mozilla.org/xre/app-info;1"].getService(Ci.nsIXULRuntime) + .processType != Ci.nsIXULRuntime.PROCESS_TYPE_DEFAULT + ); } -var ios = Cc["@mozilla.org/network/io-service;1"] - .getService(Ci.nsIIOService); -var ReferrerInfo = Components.Constructor("@mozilla.org/referrer-info;1", - "nsIReferrerInfo", - "init"); +var ios = Cc["@mozilla.org/network/io-service;1"].getService(Ci.nsIIOService); +var ReferrerInfo = Components.Constructor( + "@mozilla.org/referrer-info;1", + "nsIReferrerInfo", + "init" +); var observer = { QueryInterface: ChromeUtils.generateQI(["nsIObserver"]), @@ -35,7 +37,11 @@ var observer = { let currentReferrer = subject.getRequestHeader("Referer"); Assert.equal(currentReferrer, "http://site1.com/"); var uri = ios.newURI("http://site2.com"); - subject.referrerInfo = new ReferrerInfo(Ci.nsIHttpChannel.REFERRER_POLICY_UNSET, true, uri); + subject.referrerInfo = new ReferrerInfo( + Ci.nsIHttpChannel.REFERRER_POLICY_UNSET, + true, + uri + ); } catch (ex) { do_throw("Exception: " + ex); } @@ -54,14 +60,19 @@ let cancelDuringOnStartListener = { var uri = ios.newURI("http://site3.com/"); // Need to set NECKO_ERRORS_ARE_FATAL=0 else we'll abort process - var env = Cc["@mozilla.org/process/environment;1"]. - getService(Ci.nsIEnvironment); + var env = Cc["@mozilla.org/process/environment;1"].getService( + Ci.nsIEnvironment + ); env.set("NECKO_ERRORS_ARE_FATAL", "0"); // we expect setting referrer to fail try { - request.referrerInfo = new ReferrerInfo(Ci.nsIHttpChannel.REFERRER_POLICY_UNSET, true, uri); + request.referrerInfo = new ReferrerInfo( + Ci.nsIHttpChannel.REFERRER_POLICY_UNSET, + true, + uri + ); do_throw("Error should have been thrown before getting here"); - } catch (ex) { } + } catch (ex) {} } catch (ex) { do_throw("Exception: " + ex); } @@ -73,7 +84,7 @@ let cancelDuringOnStartListener = { onStopRequest: function test_onStopR(request, status) { this.resolved(); - } + }, }; var cancelDuringOnDataListener = { @@ -102,12 +113,18 @@ var cancelDuringOnDataListener = { }; function makeChan(url) { - var chan = NetUtil.newChannel({uri: url, loadUsingSystemPrincipal: true}) - .QueryInterface(Ci.nsIHttpChannel); + var chan = NetUtil.newChannel({ + uri: url, + loadUsingSystemPrincipal: true, + }).QueryInterface(Ci.nsIHttpChannel); // ENSURE_CALLED_BEFORE_CONNECT: set original value var uri = ios.newURI("http://site1.com"); - chan.referrerInfo = new ReferrerInfo(Ci.nsIHttpChannel.REFERRER_POLICY_UNSET, true, uri); + chan.referrerInfo = new ReferrerInfo( + Ci.nsIHttpChannel.REFERRER_POLICY_UNSET, + true, + uri + ); return chan; } @@ -126,8 +143,9 @@ add_task(async function setup() { }); add_task(async function test_cancel_during_onModifyRequest() { - var chan = makeChan("http://localhost:" + - httpserv.identity.primaryPort + "/failtest"); + var chan = makeChan( + "http://localhost:" + httpserv.identity.primaryPort + "/failtest" + ); if (!inChildProcess()) { Services.obs.addObserver(observer, "http-on-modify-request"); @@ -139,7 +157,7 @@ add_task(async function test_cancel_during_onModifyRequest() { await new Promise(resolve => { cancelDuringOnStartListener.resolved = resolve; chan.asyncOpen(cancelDuringOnStartListener); - }) + }); if (!inChildProcess()) { Services.obs.removeObserver(observer, "http-on-modify-request"); @@ -150,18 +168,25 @@ add_task(async function test_cancel_during_onModifyRequest() { }); add_task(async function test_cancel_before_asyncOpen() { - var chan = makeChan("http://localhost:" + - httpserv.identity.primaryPort + "/failtest"); + var chan = makeChan( + "http://localhost:" + httpserv.identity.primaryPort + "/failtest" + ); chan.cancel(Cr.NS_BINDING_ABORTED); - Assert.throws(() => { chan.asyncOpen(cancelDuringOnStartListener); }, - /NS_BINDING_ABORTED/, "cannot open if already cancelled"); + Assert.throws( + () => { + chan.asyncOpen(cancelDuringOnStartListener); + }, + /NS_BINDING_ABORTED/, + "cannot open if already cancelled" + ); }); add_task(async function test_cancel_during_onData() { - var chan = makeChan("http://localhost:" + - httpserv.identity.primaryPort + "/cancel_middle"); + var chan = makeChan( + "http://localhost:" + httpserv.identity.primaryPort + "/cancel_middle" + ); await new Promise(resolve => { cancelDuringOnDataListener.resolved = resolve; @@ -170,7 +195,6 @@ add_task(async function test_cancel_during_onData() { }); }); - var cancelAfterOnStopListener = { data: "", channel: null, @@ -187,12 +211,13 @@ var cancelAfterOnStopListener = { info("onStopRequest"); Assert.equal(request.status, Cr.NS_OK); this.resolved(); - } + }, }; add_task(async function test_cancel_after_onStop() { - var chan = makeChan("http://localhost:" + - httpserv.identity.primaryPort + "/normal_response"); + var chan = makeChan( + "http://localhost:" + httpserv.identity.primaryPort + "/normal_response" + ); await new Promise(resolve => { cancelAfterOnStopListener.resolved = resolve; @@ -208,7 +233,6 @@ add_task(async function test_cancel_after_onStop() { Assert.equal(chan.status, Cr.NS_BINDING_ABORTED); }); - // PATHS // /failtest @@ -219,7 +243,7 @@ function failtest(metadata, response) { function cancel_middle(metadata, response) { response.processAsync(); response.setStatusLine(metadata.httpVersion, 200, "OK"); - let str1 = "a".repeat(128*1024); + let str1 = "a".repeat(128 * 1024); response.write(str1, str1.length); response.bodyOutputStream.flush(); @@ -227,7 +251,7 @@ function cancel_middle(metadata, response) { cancelDuringOnDataListener.receivedSomeData = resolve; }); p.then(() => { - let str1 = "b".repeat(128*1024); + let str1 = "b".repeat(128 * 1024); response.write(str2, str2.length); response.finish(); }); diff --git a/netwerk/test/unit/test_httpsuspend.js b/netwerk/test/unit/test_httpsuspend.js index 37cb07da7221..c3b8a5d99aa0 100644 --- a/netwerk/test/unit/test_httpsuspend.js +++ b/netwerk/test/unit/test_httpsuspend.js @@ -1,7 +1,7 @@ // This file ensures that suspending a channel directly after opening it // suspends future notifications correctly. -const {HttpServer} = ChromeUtils.import("resource://testing-common/httpd.js"); +const { HttpServer } = ChromeUtils.import("resource://testing-common/httpd.js"); XPCOMUtils.defineLazyGetter(this, "URL", function() { return "http://localhost:" + httpserv.identity.primaryPort; @@ -14,7 +14,10 @@ var listener = { _lastEvent: 0, _gotData: false, - QueryInterface: ChromeUtils.generateQI(["nsIStreamListener", "nsIRequestObserver"]), + QueryInterface: ChromeUtils.generateQI([ + "nsIStreamListener", + "nsIRequestObserver", + ]), onStartRequest(request) { this._lastEvent = Date.now(); @@ -24,8 +27,12 @@ var listener = { // works correctly request.suspend(); request.suspend(); - do_timeout(RESUME_DELAY, function() { request.resume(); }); - do_timeout(RESUME_DELAY + 1000, function() { request.resume(); }); + do_timeout(RESUME_DELAY, function() { + request.resume(); + }); + do_timeout(RESUME_DELAY + 1000, function() { + request.resume(); + }); }, onDataAvailable(request, stream, offset, count) { @@ -44,12 +51,14 @@ var listener = { onStopRequest(request, status) { Assert.ok(this._gotData); httpserv.stop(do_test_finished); - } + }, }; function makeChan(url) { - return NetUtil.newChannel({uri: url, loadUsingSystemPrincipal: true}) - .QueryInterface(Ci.nsIHttpChannel); + return NetUtil.newChannel({ + uri: url, + loadUsingSystemPrincipal: true, + }).QueryInterface(Ci.nsIHttpChannel); } var httpserv = null; diff --git a/netwerk/test/unit/test_idn_blacklist.js b/netwerk/test/unit/test_idn_blacklist.js index aea45d706053..8d2bd17b9249 100644 --- a/netwerk/test/unit/test_idn_blacklist.js +++ b/netwerk/test/unit/test_idn_blacklist.js @@ -1,165 +1,170 @@ // Test that URLs containing characters in the IDN blacklist are // always displayed as punycode const testcases = [ - // Original Punycode or - // normalized form - // - ["\u00BC", "xn--14-c6t"], - ["\u00BD", "xn--12-c6t"], - ["\u00BE", "xn--34-c6t"], - ["\u01C3", "xn--ija"], - ["\u02D0", "xn--6qa"], - ["\u0337", "xn--4ta"], - ["\u0338", "xn--5ta"], - ["\u0589", "xn--3bb"], - ["\u05C3", "xn--rdb"], - ["\u05F4", "xn--5eb"], - ["\u0609", "xn--rfb"], - ["\u060A", "xn--sfb"], - ["\u066A", "xn--jib"], - ["\u06D4", "xn--klb"], - ["\u0701", "xn--umb"], - ["\u0702", "xn--vmb"], - ["\u0703", "xn--wmb"], - ["\u0704", "xn--xmb"], - ["\u115F", "xn--osd"], - ["\u1160", "xn--psd"], - ["\u1735", "xn--d0e"], - ["\u2027", "xn--svg"], - ["\u2028", "xn--tvg"], - ["\u2029", "xn--uvg"], - ["\u2039", "xn--bwg"], - ["\u203A", "xn--cwg"], - ["\u2041", "xn--jwg"], - ["\u2044", "xn--mwg"], - ["\u2052", "xn--0wg"], - ["\u2153", "xn--13-c6t"], - ["\u2154", "xn--23-c6t"], - ["\u2155", "xn--15-c6t"], - ["\u2156", "xn--25-c6t"], - ["\u2157", "xn--35-c6t"], - ["\u2158", "xn--45-c6t"], - ["\u2159", "xn--16-c6t"], - ["\u215A", "xn--56-c6t"], - ["\u215B", "xn--18-c6t"], - ["\u215C", "xn--38-c6t"], - ["\u215D", "xn--58-c6t"], - ["\u215E", "xn--78-c6t"], - ["\u215F", "xn--1-zjn"], - ["\u2215", "xn--w9g"], - ["\u2236", "xn--ubh"], - ["\u23AE", "xn--lmh"], - ["\u2571", "xn--hzh"], - ["\u29F6", "xn--jxi"], - ["\u29F8", "xn--lxi"], - ["\u2AFB", "xn--z4i"], - ["\u2AFD", "xn--14i"], - ["\u2FF0", "xn--85j"], - ["\u2FF1", "xn--95j"], - ["\u2FF2", "xn--b6j"], - ["\u2FF3", "xn--c6j"], - ["\u2FF4", "xn--d6j"], - ["\u2FF5", "xn--e6j"], - ["\u2FF6", "xn--f6j"], - ["\u2FF7", "xn--g6j"], - ["\u2FF8", "xn--h6j"], - ["\u2FF9", "xn--i6j"], - ["\u2FFA", "xn--j6j"], - ["\u2FFB", "xn--k6j"], - ["\u3014", "xn--96j"], - ["\u3015", "xn--b7j"], - ["\u3033", "xn--57j"], - ["\u3164", "xn--psd"], - ["\u321D", "xn--()-357j35d"], - ["\u321E", "xn--()-357jf36c"], - ["\u33AE", "xn--rads-id9a"], - ["\u33AF", "xn--rads2-4d6b"], - ["\u33C6", "xn--ckg-tc2a"], - ["\u33DF", "xn--am-6bv"], - ["\uA789", "xn--058a"], - ["\uFE3F", "xn--x6j"], - ["\uFE5D", "xn--96j"], - ["\uFE5E", "xn--b7j"], - ["\uFFA0", "xn--psd"], - ["\uFFF9", "xn--vn7c"], - ["\uFFFA", "xn--wn7c"], - ["\uFFFB", "xn--xn7c"], - ["\uFFFC", "xn--yn7c"], - ["\uFFFD", "xn--zn7c"], + // Original Punycode or + // normalized form + // + ["\u00BC", "xn--14-c6t"], + ["\u00BD", "xn--12-c6t"], + ["\u00BE", "xn--34-c6t"], + ["\u01C3", "xn--ija"], + ["\u02D0", "xn--6qa"], + ["\u0337", "xn--4ta"], + ["\u0338", "xn--5ta"], + ["\u0589", "xn--3bb"], + ["\u05C3", "xn--rdb"], + ["\u05F4", "xn--5eb"], + ["\u0609", "xn--rfb"], + ["\u060A", "xn--sfb"], + ["\u066A", "xn--jib"], + ["\u06D4", "xn--klb"], + ["\u0701", "xn--umb"], + ["\u0702", "xn--vmb"], + ["\u0703", "xn--wmb"], + ["\u0704", "xn--xmb"], + ["\u115F", "xn--osd"], + ["\u1160", "xn--psd"], + ["\u1735", "xn--d0e"], + ["\u2027", "xn--svg"], + ["\u2028", "xn--tvg"], + ["\u2029", "xn--uvg"], + ["\u2039", "xn--bwg"], + ["\u203A", "xn--cwg"], + ["\u2041", "xn--jwg"], + ["\u2044", "xn--mwg"], + ["\u2052", "xn--0wg"], + ["\u2153", "xn--13-c6t"], + ["\u2154", "xn--23-c6t"], + ["\u2155", "xn--15-c6t"], + ["\u2156", "xn--25-c6t"], + ["\u2157", "xn--35-c6t"], + ["\u2158", "xn--45-c6t"], + ["\u2159", "xn--16-c6t"], + ["\u215A", "xn--56-c6t"], + ["\u215B", "xn--18-c6t"], + ["\u215C", "xn--38-c6t"], + ["\u215D", "xn--58-c6t"], + ["\u215E", "xn--78-c6t"], + ["\u215F", "xn--1-zjn"], + ["\u2215", "xn--w9g"], + ["\u2236", "xn--ubh"], + ["\u23AE", "xn--lmh"], + ["\u2571", "xn--hzh"], + ["\u29F6", "xn--jxi"], + ["\u29F8", "xn--lxi"], + ["\u2AFB", "xn--z4i"], + ["\u2AFD", "xn--14i"], + ["\u2FF0", "xn--85j"], + ["\u2FF1", "xn--95j"], + ["\u2FF2", "xn--b6j"], + ["\u2FF3", "xn--c6j"], + ["\u2FF4", "xn--d6j"], + ["\u2FF5", "xn--e6j"], + ["\u2FF6", "xn--f6j"], + ["\u2FF7", "xn--g6j"], + ["\u2FF8", "xn--h6j"], + ["\u2FF9", "xn--i6j"], + ["\u2FFA", "xn--j6j"], + ["\u2FFB", "xn--k6j"], + ["\u3014", "xn--96j"], + ["\u3015", "xn--b7j"], + ["\u3033", "xn--57j"], + ["\u3164", "xn--psd"], + ["\u321D", "xn--()-357j35d"], + ["\u321E", "xn--()-357jf36c"], + ["\u33AE", "xn--rads-id9a"], + ["\u33AF", "xn--rads2-4d6b"], + ["\u33C6", "xn--ckg-tc2a"], + ["\u33DF", "xn--am-6bv"], + ["\uA789", "xn--058a"], + ["\uFE3F", "xn--x6j"], + ["\uFE5D", "xn--96j"], + ["\uFE5E", "xn--b7j"], + ["\uFFA0", "xn--psd"], + ["\uFFF9", "xn--vn7c"], + ["\uFFFA", "xn--wn7c"], + ["\uFFFB", "xn--xn7c"], + ["\uFFFC", "xn--yn7c"], + ["\uFFFD", "xn--zn7c"], - // Characters from the IDN blacklist that normalize to ASCII - // If we start using STD3ASCIIRules these will be blocked (bug 316444) - ["\u00A0", " "], - ["\u2000", " "], - ["\u2001", " "], - ["\u2002", " "], - ["\u2003", " "], - ["\u2004", " "], - ["\u2005", " "], - ["\u2006", " "], - ["\u2007", " "], - ["\u2008", " "], - ["\u2009", " "], - ["\u200A", " "], - ["\u2024", "."], - ["\u202F", " "], - ["\u205F", " "], - ["\u3000", " "], - ["\u3002", "."], - ["\uFE14", ";"], - ["\uFE15", "!"], - ["\uFF0E", "."], - ["\uFF0F", "/"], - ["\uFF61", "."], + // Characters from the IDN blacklist that normalize to ASCII + // If we start using STD3ASCIIRules these will be blocked (bug 316444) + ["\u00A0", " "], + ["\u2000", " "], + ["\u2001", " "], + ["\u2002", " "], + ["\u2003", " "], + ["\u2004", " "], + ["\u2005", " "], + ["\u2006", " "], + ["\u2007", " "], + ["\u2008", " "], + ["\u2009", " "], + ["\u200A", " "], + ["\u2024", "."], + ["\u202F", " "], + ["\u205F", " "], + ["\u3000", " "], + ["\u3002", "."], + ["\uFE14", ";"], + ["\uFE15", "!"], + ["\uFF0E", "."], + ["\uFF0F", "/"], + ["\uFF61", "."], - // Characters from the IDN blacklist that are stripped by Nameprep - ["\u200B", ""], - ["\uFEFF", ""], + // Characters from the IDN blacklist that are stripped by Nameprep + ["\u200B", ""], + ["\uFEFF", ""], ]; - function run_test() { - var pbi = Cc["@mozilla.org/preferences-service;1"].getService(Ci.nsIPrefBranch); - var oldProfile = pbi.getCharPref("network.IDN.restriction_profile", "moderate"); - var oldWhitelistCom = pbi.getBoolPref("network.IDN.whitelist.com", false); - var idnService = Cc["@mozilla.org/network/idn-service;1"].getService(Ci.nsIIDNService); + var pbi = Cc["@mozilla.org/preferences-service;1"].getService( + Ci.nsIPrefBranch + ); + var oldProfile = pbi.getCharPref( + "network.IDN.restriction_profile", + "moderate" + ); + var oldWhitelistCom = pbi.getBoolPref("network.IDN.whitelist.com", false); + var idnService = Cc["@mozilla.org/network/idn-service;1"].getService( + Ci.nsIIDNService + ); - pbi.setCharPref("network.IDN.restriction_profile", "moderate"); - pbi.setBoolPref("network.IDN.whitelist.com", false); + pbi.setCharPref("network.IDN.restriction_profile", "moderate"); + pbi.setBoolPref("network.IDN.whitelist.com", false); - for (var j = 0; j < testcases.length; ++j) { - var test = testcases[j]; - var URL = test[0] + ".com"; - var punycodeURL = test[1] + ".com"; - var isASCII = {}; + for (var j = 0; j < testcases.length; ++j) { + var test = testcases[j]; + var URL = test[0] + ".com"; + var punycodeURL = test[1] + ".com"; + var isASCII = {}; - var result; - try { - result = idnService.convertToDisplayIDN(URL, isASCII); - } catch(e) { - result = ".com"; - } - // If the punycode URL is equivalent to \ufffd.com (i.e. the - // blacklisted character has been replaced by a unicode - // REPLACEMENT CHARACTER, skip the test - if (result != "xn--zn7c.com") { - - if (punycodeURL.substr(0, 4) == "xn--") { - // test convertToDisplayIDN with a Unicode URL and with a - // Punycode URL if we have one - equal(escape(result), escape(punycodeURL)); - - result = idnService.convertToDisplayIDN(punycodeURL, isASCII); - equal(escape(result), escape(punycodeURL)); - } else { - // The "punycode" URL isn't punycode. This happens in testcases - // where the Unicode URL has become normalized to an ASCII URL, - // so, even though expectedUnicode is true, the expected result - // is equal to punycodeURL - equal(escape(result), escape(punycodeURL)); - } - } + var result; + try { + result = idnService.convertToDisplayIDN(URL, isASCII); + } catch (e) { + result = ".com"; } - pbi.setBoolPref("network.IDN.whitelist.com", oldWhitelistCom); - pbi.setCharPref("network.IDN.restriction_profile", oldProfile); + // If the punycode URL is equivalent to \ufffd.com (i.e. the + // blacklisted character has been replaced by a unicode + // REPLACEMENT CHARACTER, skip the test + if (result != "xn--zn7c.com") { + if (punycodeURL.substr(0, 4) == "xn--") { + // test convertToDisplayIDN with a Unicode URL and with a + // Punycode URL if we have one + equal(escape(result), escape(punycodeURL)); + + result = idnService.convertToDisplayIDN(punycodeURL, isASCII); + equal(escape(result), escape(punycodeURL)); + } else { + // The "punycode" URL isn't punycode. This happens in testcases + // where the Unicode URL has become normalized to an ASCII URL, + // so, even though expectedUnicode is true, the expected result + // is equal to punycodeURL + equal(escape(result), escape(punycodeURL)); + } + } + } + pbi.setBoolPref("network.IDN.whitelist.com", oldWhitelistCom); + pbi.setCharPref("network.IDN.restriction_profile", oldProfile); } diff --git a/netwerk/test/unit/test_idn_urls.js b/netwerk/test/unit/test_idn_urls.js index 7478e4e9b12d..e7b6aaf13738 100644 --- a/netwerk/test/unit/test_idn_urls.js +++ b/netwerk/test/unit/test_idn_urls.js @@ -1,18 +1,18 @@ // Test algorithm for unicode display of IDNA URL (bug 722299) const testcases = [ - // Original Punycode or Expected UTF-8 by profile - // URL normalized form ASCII-Only, High, Moderate - // - // Latin script - ["cuillère", "xn--cuillre-6xa", false, true, true], + // Original Punycode or Expected UTF-8 by profile + // URL normalized form ASCII-Only, High, Moderate + // + // Latin script + ["cuillère", "xn--cuillre-6xa", false, true, true], - // repeated non-spacing marks - ["gruz̀̀ere", "xn--gruzere-ogea", false, false, false], + // repeated non-spacing marks + ["gruz̀̀ere", "xn--gruzere-ogea", false, false, false], - // non-XID character - ["I♥NY", "xn--iny-zx5a", false, false, false], + // non-XID character + ["I♥NY", "xn--iny-zx5a", false, false, false], -/* + /* Behaviour of this test changed in IDNA2008, replacing the non-XID character with U+FFFD replacement character - when all platforms use IDNA2008 it can be uncommented and the punycode URL changed to @@ -22,341 +22,417 @@ const testcases = [ ["حلا\u061cل", "xn--bgbvr6gc", false, false, false], */ - // U+30FB KATAKANA MIDDLE DOT is excluded from non-XID characters (bug 857490) - ["乾燥肌・石けん", "xn--08j4gylj12hz80b0uhfup", false, true, true], + // U+30FB KATAKANA MIDDLE DOT is excluded from non-XID characters (bug 857490) + ["乾燥肌・石けん", "xn--08j4gylj12hz80b0uhfup", false, true, true], - // Cyrillic alone - ["толсто́й", "xn--lsa83dealbred", false, true, true], + // Cyrillic alone + ["толсто́й", "xn--lsa83dealbred", false, true, true], - // Mixed script Cyrillic/Latin - ["толсто́й-in-Russian", - "xn---in-russian-1jg071b0a8bb4cpd", false, false, false], + // Mixed script Cyrillic/Latin + [ + "толсто́й-in-Russian", + "xn---in-russian-1jg071b0a8bb4cpd", + false, + false, + false, + ], - // Mixed script Latin/Cyrillic - ["war-and-миръ", "xn--war-and--b9g3b7b3h", false, false, false], + // Mixed script Latin/Cyrillic + ["war-and-миръ", "xn--war-and--b9g3b7b3h", false, false, false], - // Cherokee (Restricted script) - ["ᏣᎳᎩ", "xn--f9dt7l", false, false, false], + // Cherokee (Restricted script) + ["ᏣᎳᎩ", "xn--f9dt7l", false, false, false], - // Yi (former Aspirational script, now Restricted per Unicode 10.0 update to UAX 31) - ["ꆈꌠꁱꂷ", "xn--4o7a6e1x64c", false, false, false], + // Yi (former Aspirational script, now Restricted per Unicode 10.0 update to UAX 31) + ["ꆈꌠꁱꂷ", "xn--4o7a6e1x64c", false, false, false], - // Greek alone - ["πλάτων", "xn--hxa3ahjw4a", false, true, true], + // Greek alone + ["πλάτων", "xn--hxa3ahjw4a", false, true, true], - // Mixed script Greek/Latin - ["πλάτωνicrelationship", - "xn--icrelationship-96j4t9a3cwe2e", false, false, false], + // Mixed script Greek/Latin + [ + "πλάτωνicrelationship", + "xn--icrelationship-96j4t9a3cwe2e", + false, + false, + false, + ], - // Mixed script Latin/Greek - ["spaceὈδύσσεια", "xn--space-h9dui0b0ga2j1562b", false, false, false], + // Mixed script Latin/Greek + ["spaceὈδύσσεια", "xn--space-h9dui0b0ga2j1562b", false, false, false], - // Devanagari alone - ["मराठी", "xn--d2b1ag0dl", false, true, true], + // Devanagari alone + ["मराठी", "xn--d2b1ag0dl", false, true, true], - // Devanagari with Armenian - ["मराठीՀայաստան", - "xn--y9aaa1d0ai1cq964f8dwa2o1a", false, false, false], + // Devanagari with Armenian + ["मराठीՀայաստան", "xn--y9aaa1d0ai1cq964f8dwa2o1a", false, false, false], - // Devanagari with common - ["मराठी123", "xn--123-mhh3em2hra", false, true, true], + // Devanagari with common + ["मराठी123", "xn--123-mhh3em2hra", false, true, true], - // Common with Devanagari - ["123मराठी", "xn--123-phh3em2hra", false, true, true], + // Common with Devanagari + ["123मराठी", "xn--123-phh3em2hra", false, true, true], - // Latin with Han - ["chairman毛", - "xn--chairman-k65r", false, true, true], + // Latin with Han + ["chairman毛", "xn--chairman-k65r", false, true, true], - // Han with Latin - ["山葵sauce", "xn--sauce-6j9ii40v", false, true, true], + // Han with Latin + ["山葵sauce", "xn--sauce-6j9ii40v", false, true, true], - // Latin with Han, Hiragana and Katakana - ["van語ではドイ", "xn--van-ub4bpb6w0in486d", false, true, true], + // Latin with Han, Hiragana and Katakana + ["van語ではドイ", "xn--van-ub4bpb6w0in486d", false, true, true], - // Latin with Han, Katakana and Hiragana - ["van語ドイでは", "xn--van-ub4bpb4w0ip486d", false, true, true], + // Latin with Han, Katakana and Hiragana + ["van語ドイでは", "xn--van-ub4bpb4w0ip486d", false, true, true], - // Latin with Hiragana, Han and Katakana - ["vanでは語ドイ", "xn--van-ub4bpb6w0ip486d", false, true, true], + // Latin with Hiragana, Han and Katakana + ["vanでは語ドイ", "xn--van-ub4bpb6w0ip486d", false, true, true], - // Latin with Hiragana, Katakana and Han - ["vanではドイ語", "xn--van-ub4bpb6w0ir486d", false, true, true], + // Latin with Hiragana, Katakana and Han + ["vanではドイ語", "xn--van-ub4bpb6w0ir486d", false, true, true], - // Latin with Katakana, Han and Hiragana - ["vanドイ語では", "xn--van-ub4bpb4w0ir486d", false, true, true], + // Latin with Katakana, Han and Hiragana + ["vanドイ語では", "xn--van-ub4bpb4w0ir486d", false, true, true], - // Latin with Katakana, Hiragana and Han - ["vanドイでは語", "xn--van-ub4bpb4w0it486d", false, true, true], + // Latin with Katakana, Hiragana and Han + ["vanドイでは語", "xn--van-ub4bpb4w0it486d", false, true, true], - // Han with Latin, Hiragana and Katakana - ["語vanではドイ", "xn--van-ub4bpb6w0ik486d", false, true, true], + // Han with Latin, Hiragana and Katakana + ["語vanではドイ", "xn--van-ub4bpb6w0ik486d", false, true, true], - // Han with Latin, Katakana and Hiragana - ["語vanドイでは", "xn--van-ub4bpb4w0im486d", false, true, true], + // Han with Latin, Katakana and Hiragana + ["語vanドイでは", "xn--van-ub4bpb4w0im486d", false, true, true], - // Han with Hiragana, Latin and Katakana - ["語ではvanドイ", "xn--van-rb4bpb9w0ik486d", false, true, true], + // Han with Hiragana, Latin and Katakana + ["語ではvanドイ", "xn--van-rb4bpb9w0ik486d", false, true, true], - // Han with Hiragana, Katakana and Latin - ["語ではドイvan", "xn--van-rb4bpb6w0in486d", false, true, true], + // Han with Hiragana, Katakana and Latin + ["語ではドイvan", "xn--van-rb4bpb6w0in486d", false, true, true], - // Han with Katakana, Latin and Hiragana - ["語ドイvanでは", "xn--van-ub4bpb1w0ip486d", false, true, true], + // Han with Katakana, Latin and Hiragana + ["語ドイvanでは", "xn--van-ub4bpb1w0ip486d", false, true, true], - // Han with Katakana, Hiragana and Latin - ["語ドイではvan", "xn--van-rb4bpb4w0ip486d", false, true, true], + // Han with Katakana, Hiragana and Latin + ["語ドイではvan", "xn--van-rb4bpb4w0ip486d", false, true, true], - // Hiragana with Latin, Han and Katakana - ["イツvan語ではド", "xn--van-ub4bpb1wvhsbx330n", false, true, true], + // Hiragana with Latin, Han and Katakana + ["イツvan語ではド", "xn--van-ub4bpb1wvhsbx330n", false, true, true], - // Hiragana with Latin, Katakana and Han - ["ではvanドイ語", "xn--van-rb4bpb9w0ir486d", false, true, true], + // Hiragana with Latin, Katakana and Han + ["ではvanドイ語", "xn--van-rb4bpb9w0ir486d", false, true, true], - // Hiragana with Han, Latin and Katakana - ["では語vanドイ", "xn--van-rb4bpb9w0im486d", false, true, true], + // Hiragana with Han, Latin and Katakana + ["では語vanドイ", "xn--van-rb4bpb9w0im486d", false, true, true], - // Hiragana with Han, Katakana and Latin - ["では語ドイvan", "xn--van-rb4bpb6w0ip486d", false, true, true], + // Hiragana with Han, Katakana and Latin + ["では語ドイvan", "xn--van-rb4bpb6w0ip486d", false, true, true], - // Hiragana with Katakana, Latin and Han - ["ではドイvan語", "xn--van-rb4bpb6w0iu486d", false, true, true], + // Hiragana with Katakana, Latin and Han + ["ではドイvan語", "xn--van-rb4bpb6w0iu486d", false, true, true], - // Hiragana with Katakana, Han and Latin - ["ではドイ語van", "xn--van-rb4bpb6w0ir486d", false, true, true], + // Hiragana with Katakana, Han and Latin + ["ではドイ語van", "xn--van-rb4bpb6w0ir486d", false, true, true], - // Katakana with Latin, Han and Hiragana - ["ドイvan語では", "xn--van-ub4bpb1w0iu486d", false, true, true], + // Katakana with Latin, Han and Hiragana + ["ドイvan語では", "xn--van-ub4bpb1w0iu486d", false, true, true], - // Katakana with Latin, Hiragana and Han - ["ドイvanでは語", "xn--van-ub4bpb1w0iw486d", false, true, true], + // Katakana with Latin, Hiragana and Han + ["ドイvanでは語", "xn--van-ub4bpb1w0iw486d", false, true, true], - // Katakana with Han, Latin and Hiragana - ["ドイ語vanでは", "xn--van-ub4bpb1w0ir486d", false, true, true], + // Katakana with Han, Latin and Hiragana + ["ドイ語vanでは", "xn--van-ub4bpb1w0ir486d", false, true, true], - // Katakana with Han, Hiragana and Latin - ["ドイ語ではvan", "xn--van-rb4bpb4w0ir486d", false, true, true], + // Katakana with Han, Hiragana and Latin + ["ドイ語ではvan", "xn--van-rb4bpb4w0ir486d", false, true, true], - // Katakana with Hiragana, Latin and Han - ["ドイではvan語", "xn--van-rb4bpb4w0iw486d", false, true, true], + // Katakana with Hiragana, Latin and Han + ["ドイではvan語", "xn--van-rb4bpb4w0iw486d", false, true, true], - // Katakana with Hiragana, Han and Latin - ["ドイでは語van", "xn--van-rb4bpb4w0it486d", false, true, true], + // Katakana with Hiragana, Han and Latin + ["ドイでは語van", "xn--van-rb4bpb4w0it486d", false, true, true], - // Han with common - ["中国123", "xn--123-u68dy61b", false, true, true], + // Han with common + ["中国123", "xn--123-u68dy61b", false, true, true], - // common with Han - ["123中国", "xn--123-x68dy61b", false, true, true], + // common with Han + ["123中国", "xn--123-x68dy61b", false, true, true], - // Characters that normalize to permitted characters - // (also tests Plane 1 supplementary characters) - ["super𝟖", "super8", true, true, true], + // Characters that normalize to permitted characters + // (also tests Plane 1 supplementary characters) + ["super𝟖", "super8", true, true, true], - // Han from Plane 2 - ["𠀀𠀁𠀂", "xn--j50icd", false, true, true], + // Han from Plane 2 + ["𠀀𠀁𠀂", "xn--j50icd", false, true, true], - // Han from Plane 2 with js (UTF-16) escapes - ["\uD840\uDC00\uD840\uDC01\uD840\uDC02", - "xn--j50icd", false, true, true], + // Han from Plane 2 with js (UTF-16) escapes + ["\uD840\uDC00\uD840\uDC01\uD840\uDC02", "xn--j50icd", false, true, true], - // Same with a lone high surrogate at the end - ["\uD840\uDC00\uD840\uDC01\uD840", - "xn--zn7c0336bda", false, false, false], + // Same with a lone high surrogate at the end + ["\uD840\uDC00\uD840\uDC01\uD840", "xn--zn7c0336bda", false, false, false], - // Latin text and Bengali digits - ["super৪", "xn--super-k2l", false, false, true], + // Latin text and Bengali digits + ["super৪", "xn--super-k2l", false, false, true], - // Bengali digits and Latin text - ["৫ab", "xn--ab-x5f", false, false, true], - - // Bengali text and Latin digits - ["অঙ্কুর8", "xn--8-70d2cp0j6dtd", false, true, true], - - // Latin digits and Bengali text - ["5াব", "xn--5-h3d7c", false, true, true], - - // Mixed numbering systems - ["٢٠۰٠", "xn--8hbae38c", false, false, false], - - // Traditional Chinese - ["萬城", "xn--uis754h", false, true, true], - - // Simplified Chinese - ["万城", "xn--chq31v", false, true, true], - - // Simplified-only and Traditional-only Chinese in the same label - ["万萬城", "xn--chq31vsl1b", false, true, true], - - // Traditional-only and Simplified-only Chinese in the same label - ["萬万城", "xn--chq31vrl1b", false, true, true], - - // Han and Latin and Bopomofo - ["注音符号bopomofoㄅㄆㄇㄈ", - "xn--bopomofo-hj5gkalm1637i876cuw0brk5f", - false, true, true], - - // Han, bopomofo, Latin - ["注音符号ㄅㄆㄇㄈbopomofo", - "xn--bopomofo-8i5gkalm9637i876cuw0brk5f", - false, true, true], - - // Latin, Han, Bopomofo - ["bopomofo注音符号ㄅㄆㄇㄈ", - "xn--bopomofo-hj5gkalm9637i876cuw0brk5f", - false, true, true], - - // Latin, Bopomofo, Han - ["bopomofoㄅㄆㄇㄈ注音符号", - "xn--bopomofo-hj5gkalm3737i876cuw0brk5f", - false, true, true], - - // Bopomofo, Han, Latin - ["ㄅㄆㄇㄈ注音符号bopomofo", - "xn--bopomofo-8i5gkalm3737i876cuw0brk5f", - false, true, true], - - // Bopomofo, Latin, Han - ["ㄅㄆㄇㄈbopomofo注音符号", - "xn--bopomofo-8i5gkalm1837i876cuw0brk5f", - false, true, true], - - // Han, bopomofo and katakana - ["注音符号ㄅㄆㄇㄈボポモフォ", - "xn--jckteuaez1shij0450gylvccz9asi4e", - false, false, false], - - // Han, katakana, bopomofo - ["注音符号ボポモフォㄅㄆㄇㄈ", - "xn--jckteuaez6shij5350gylvccz9asi4e", - false, false, false], - - // bopomofo, han, katakana - ["ㄅㄆㄇㄈ注音符号ボポモフォ", - "xn--jckteuaez1shij4450gylvccz9asi4e", - false, false, false], - - // bopomofo, katakana, han - ["ㄅㄆㄇㄈボポモフォ注音符号", - "xn--jckteuaez1shij9450gylvccz9asi4e", - false, false, false], - - // katakana, Han, bopomofo - ["ボポモフォ注音符号ㄅㄆㄇㄈ", - "xn--jckteuaez6shij0450gylvccz9asi4e", - false, false, false], - - // katakana, bopomofo, Han - ["ボポモフォㄅㄆㄇㄈ注音符号", - "xn--jckteuaez6shij4450gylvccz9asi4e", - false, false, false], - - // Han, Hangul and Latin - ["韓한글hangul", - "xn--hangul-2m5ti09k79ze", false, true, true], - - // Han, Latin and Hangul - ["韓hangul한글", - "xn--hangul-2m5to09k79ze", false, true, true], - - // Hangul, Han and Latin - ["한글韓hangul", - "xn--hangul-2m5th09k79ze", false, true, true], - - // Hangul, Latin and Han - ["한글hangul韓", - "xn--hangul-8m5t898k79ze", false, true, true], - - // Latin, Han and Hangul - ["hangul韓한글", - "xn--hangul-8m5ti09k79ze", false, true, true], - - // Latin, Hangul and Han - ["hangul한글韓", - "xn--hangul-8m5th09k79ze", false, true, true], - - // Hangul and katakana - ["한글ハングル", - "xn--qck1c2d4a9266lkmzb", false, false, false], - - // Katakana and Hangul - ["ハングル한글", - "xn--qck1c2d4a2366lkmzb", false, false, false], - - // Thai (also tests that node with over 63 UTF-8 octets doesn't fail) - ["เครื่องทําน้ําทําน้ําแข็ง", - "xn--22cdjb2fanb9fyepcbbb9dwh4a3igze4fdcd", - false, true, true], - - // Effect of adding valid or invalid subdomains (bug 1399540) - ["䕮䕵䕶䕱.ascii", "xn--google.ascii", false, true, true], - ["ascii.䕮䕵䕶䕱", "ascii.xn--google", false, true, true], - ["中国123.䕮䕵䕶䕱", "xn--123-u68dy61b.xn--google", false, true, true], - ["䕮䕵䕶䕱.中国123", "xn--google.xn--123-u68dy61b", false, true, true], - ["xn--accountlogin.䕮䕵䕶䕱", "xn--accountlogin.xn--google", false, true, true], - ["䕮䕵䕶䕱.xn--accountlogin", "xn--google.xn--accountlogin", false, true, true], - - // Arabic diacritic not allowed in Latin text (bug 1370497) - ["goo\u0650gle", "xn--google-yri", false, false, false], - // ...but Arabic diacritics are allowed on Arabic text - ["العَرَبِي", "xn--mgbc0a5a6cxbzabt", false, true, true], - - // Hebrew diacritic also not allowed in Latin text (bug 1404349) - ["goo\u05b4gle", "xn--google-rvh", false, false, false], - - // Accents above dotless-i are not allowed - ["na\u0131\u0308ve", "xn--nave-mza04z", false, false, false], - ["d\u0131\u0302ner", "xn--dner-lza40z", false, false, false], - // but the corresponding accented-i (based on dotted i) is OK - ["na\u00efve.com", "xn--nave-6pa.com", false, true, true], - ["d\u00eener.com", "xn--dner-0pa.com", false, true, true], + // Bengali digits and Latin text + ["৫ab", "xn--ab-x5f", false, false, true], + + // Bengali text and Latin digits + ["অঙ্কুর8", "xn--8-70d2cp0j6dtd", false, true, true], + + // Latin digits and Bengali text + ["5াব", "xn--5-h3d7c", false, true, true], + + // Mixed numbering systems + ["٢٠۰٠", "xn--8hbae38c", false, false, false], + + // Traditional Chinese + ["萬城", "xn--uis754h", false, true, true], + + // Simplified Chinese + ["万城", "xn--chq31v", false, true, true], + + // Simplified-only and Traditional-only Chinese in the same label + ["万萬城", "xn--chq31vsl1b", false, true, true], + + // Traditional-only and Simplified-only Chinese in the same label + ["萬万城", "xn--chq31vrl1b", false, true, true], + + // Han and Latin and Bopomofo + [ + "注音符号bopomofoㄅㄆㄇㄈ", + "xn--bopomofo-hj5gkalm1637i876cuw0brk5f", + false, + true, + true, + ], + + // Han, bopomofo, Latin + [ + "注音符号ㄅㄆㄇㄈbopomofo", + "xn--bopomofo-8i5gkalm9637i876cuw0brk5f", + false, + true, + true, + ], + + // Latin, Han, Bopomofo + [ + "bopomofo注音符号ㄅㄆㄇㄈ", + "xn--bopomofo-hj5gkalm9637i876cuw0brk5f", + false, + true, + true, + ], + + // Latin, Bopomofo, Han + [ + "bopomofoㄅㄆㄇㄈ注音符号", + "xn--bopomofo-hj5gkalm3737i876cuw0brk5f", + false, + true, + true, + ], + + // Bopomofo, Han, Latin + [ + "ㄅㄆㄇㄈ注音符号bopomofo", + "xn--bopomofo-8i5gkalm3737i876cuw0brk5f", + false, + true, + true, + ], + + // Bopomofo, Latin, Han + [ + "ㄅㄆㄇㄈbopomofo注音符号", + "xn--bopomofo-8i5gkalm1837i876cuw0brk5f", + false, + true, + true, + ], + + // Han, bopomofo and katakana + [ + "注音符号ㄅㄆㄇㄈボポモフォ", + "xn--jckteuaez1shij0450gylvccz9asi4e", + false, + false, + false, + ], + + // Han, katakana, bopomofo + [ + "注音符号ボポモフォㄅㄆㄇㄈ", + "xn--jckteuaez6shij5350gylvccz9asi4e", + false, + false, + false, + ], + + // bopomofo, han, katakana + [ + "ㄅㄆㄇㄈ注音符号ボポモフォ", + "xn--jckteuaez1shij4450gylvccz9asi4e", + false, + false, + false, + ], + + // bopomofo, katakana, han + [ + "ㄅㄆㄇㄈボポモフォ注音符号", + "xn--jckteuaez1shij9450gylvccz9asi4e", + false, + false, + false, + ], + + // katakana, Han, bopomofo + [ + "ボポモフォ注音符号ㄅㄆㄇㄈ", + "xn--jckteuaez6shij0450gylvccz9asi4e", + false, + false, + false, + ], + + // katakana, bopomofo, Han + [ + "ボポモフォㄅㄆㄇㄈ注音符号", + "xn--jckteuaez6shij4450gylvccz9asi4e", + false, + false, + false, + ], + + // Han, Hangul and Latin + ["韓한글hangul", "xn--hangul-2m5ti09k79ze", false, true, true], + + // Han, Latin and Hangul + ["韓hangul한글", "xn--hangul-2m5to09k79ze", false, true, true], + + // Hangul, Han and Latin + ["한글韓hangul", "xn--hangul-2m5th09k79ze", false, true, true], + + // Hangul, Latin and Han + ["한글hangul韓", "xn--hangul-8m5t898k79ze", false, true, true], + + // Latin, Han and Hangul + ["hangul韓한글", "xn--hangul-8m5ti09k79ze", false, true, true], + + // Latin, Hangul and Han + ["hangul한글韓", "xn--hangul-8m5th09k79ze", false, true, true], + + // Hangul and katakana + ["한글ハングル", "xn--qck1c2d4a9266lkmzb", false, false, false], + + // Katakana and Hangul + ["ハングル한글", "xn--qck1c2d4a2366lkmzb", false, false, false], + + // Thai (also tests that node with over 63 UTF-8 octets doesn't fail) + [ + "เครื่องทําน้ําทําน้ําแข็ง", + "xn--22cdjb2fanb9fyepcbbb9dwh4a3igze4fdcd", + false, + true, + true, + ], + + // Effect of adding valid or invalid subdomains (bug 1399540) + ["䕮䕵䕶䕱.ascii", "xn--google.ascii", false, true, true], + ["ascii.䕮䕵䕶䕱", "ascii.xn--google", false, true, true], + ["中国123.䕮䕵䕶䕱", "xn--123-u68dy61b.xn--google", false, true, true], + ["䕮䕵䕶䕱.中国123", "xn--google.xn--123-u68dy61b", false, true, true], + [ + "xn--accountlogin.䕮䕵䕶䕱", + "xn--accountlogin.xn--google", + false, + true, + true, + ], + [ + "䕮䕵䕶䕱.xn--accountlogin", + "xn--google.xn--accountlogin", + false, + true, + true, + ], + + // Arabic diacritic not allowed in Latin text (bug 1370497) + ["goo\u0650gle", "xn--google-yri", false, false, false], + // ...but Arabic diacritics are allowed on Arabic text + ["العَرَبِي", "xn--mgbc0a5a6cxbzabt", false, true, true], + + // Hebrew diacritic also not allowed in Latin text (bug 1404349) + ["goo\u05b4gle", "xn--google-rvh", false, false, false], + + // Accents above dotless-i are not allowed + ["na\u0131\u0308ve", "xn--nave-mza04z", false, false, false], + ["d\u0131\u0302ner", "xn--dner-lza40z", false, false, false], + // but the corresponding accented-i (based on dotted i) is OK + ["na\u00efve.com", "xn--nave-6pa.com", false, true, true], + ["d\u00eener.com", "xn--dner-0pa.com", false, true, true], ]; const profiles = ["ASCII", "high", "moderate"]; function run_test() { - var pbi = Cc["@mozilla.org/preferences-service;1"].getService(Ci.nsIPrefBranch); - var oldProfile = pbi.getCharPref("network.IDN.restriction_profile", "moderate"); - var oldWhitelistCom = pbi.getBoolPref("network.IDN.whitelist.com", false); - var idnService = Cc["@mozilla.org/network/idn-service;1"].getService(Ci.nsIIDNService); + var pbi = Cc["@mozilla.org/preferences-service;1"].getService( + Ci.nsIPrefBranch + ); + var oldProfile = pbi.getCharPref( + "network.IDN.restriction_profile", + "moderate" + ); + var oldWhitelistCom = pbi.getBoolPref("network.IDN.whitelist.com", false); + var idnService = Cc["@mozilla.org/network/idn-service;1"].getService( + Ci.nsIIDNService + ); - for (var i = 0; i < profiles.length; ++i) { - pbi.setCharPref("network.IDN.restriction_profile", profiles[i]); - pbi.setBoolPref("network.IDN.whitelist.com", false); + for (var i = 0; i < profiles.length; ++i) { + pbi.setCharPref("network.IDN.restriction_profile", profiles[i]); + pbi.setBoolPref("network.IDN.whitelist.com", false); - dump("testing " + profiles[i] + " profile"); + dump("testing " + profiles[i] + " profile"); - for (var j = 0; j < testcases.length; ++j) { - var test = testcases[j]; - var URL = test[0] + ".com"; - var punycodeURL = test[1] + ".com"; - var expectedUnicode = test[2 + i]; - var isASCII = {}; + for (var j = 0; j < testcases.length; ++j) { + var test = testcases[j]; + var URL = test[0] + ".com"; + var punycodeURL = test[1] + ".com"; + var expectedUnicode = test[2 + i]; + var isASCII = {}; - var result; - try { - result = idnService.convertToDisplayIDN(URL, isASCII); - } catch(e) { - result = ".com"; - } - if (punycodeURL.substr(0, 4) == "xn--" || punycodeURL.indexOf(".xn--") > 0) { - // test convertToDisplayIDN with a Unicode URL and with a - // Punycode URL if we have one - Assert.equal(escape(result), - expectedUnicode ? escape(URL) : escape(punycodeURL)); + var result; + try { + result = idnService.convertToDisplayIDN(URL, isASCII); + } catch (e) { + result = ".com"; + } + if ( + punycodeURL.substr(0, 4) == "xn--" || + punycodeURL.indexOf(".xn--") > 0 + ) { + // test convertToDisplayIDN with a Unicode URL and with a + // Punycode URL if we have one + Assert.equal( + escape(result), + expectedUnicode ? escape(URL) : escape(punycodeURL) + ); - result = idnService.convertToDisplayIDN(punycodeURL, isASCII); - Assert.equal(escape(result), - expectedUnicode ? escape(URL) : escape(punycodeURL)); - } else { - // The "punycode" URL isn't punycode. This happens in testcases - // where the Unicode URL has become normalized to an ASCII URL, - // so, even though expectedUnicode is true, the expected result - // is equal to punycodeURL - Assert.equal(escape(result), escape(punycodeURL)); - } - } + result = idnService.convertToDisplayIDN(punycodeURL, isASCII); + Assert.equal( + escape(result), + expectedUnicode ? escape(URL) : escape(punycodeURL) + ); + } else { + // The "punycode" URL isn't punycode. This happens in testcases + // where the Unicode URL has become normalized to an ASCII URL, + // so, even though expectedUnicode is true, the expected result + // is equal to punycodeURL + Assert.equal(escape(result), escape(punycodeURL)); + } } - pbi.setBoolPref("network.IDN.whitelist.com", oldWhitelistCom); - pbi.setCharPref("network.IDN.restriction_profile", oldProfile); + } + pbi.setBoolPref("network.IDN.whitelist.com", oldWhitelistCom); + pbi.setCharPref("network.IDN.restriction_profile", oldProfile); } diff --git a/netwerk/test/unit/test_idna2008.js b/netwerk/test/unit/test_idna2008.js index 4f115d5903b1..0e0290ce7952 100644 --- a/netwerk/test/unit/test_idna2008.js +++ b/netwerk/test/unit/test_idna2008.js @@ -30,7 +30,7 @@ const transitionalExpected = [ "xn--mgba3gch31f", "xn--10cl1a0b", "", - "" + "", ]; const nonTransitionalExpected = [ @@ -39,22 +39,21 @@ const nonTransitionalExpected = [ "xn--mgba3gch31f060k", "xn--10cl1a0b660p", "", - "" + "", ]; // Test options for converting IDN URLs under IDNA2008 -function run_test() -{ - var idnService = Cc["@mozilla.org/network/idn-service;1"] - .getService(Ci.nsIIDNService); - +function run_test() { + var idnService = Cc["@mozilla.org/network/idn-service;1"].getService( + Ci.nsIIDNService + ); for (var i = 0; i < labels.length; ++i) { var result; try { - result = idnService.convertUTF8toACE(labels[i]); - } catch(e) { - result = ""; + result = idnService.convertUTF8toACE(labels[i]); + } catch (e) { + result = ""; } if (kTransitionalProcessing) { diff --git a/netwerk/test/unit/test_idnservice.js b/netwerk/test/unit/test_idnservice.js index 12255299c9eb..0c52f300e370 100644 --- a/netwerk/test/unit/test_idnservice.js +++ b/netwerk/test/unit/test_idnservice.js @@ -2,35 +2,38 @@ "use strict"; -const idnService = Cc["@mozilla.org/network/idn-service;1"] - .getService(Ci.nsIIDNService); +const idnService = Cc["@mozilla.org/network/idn-service;1"].getService( + Ci.nsIIDNService +); add_task(async function test_simple() { let reference = [ - // The 3rd element indicates whether the second element - // is ACE-encoded - ["asciihost", "asciihost", false], - ["b\u00FCcher", "xn--bcher-kva", true] - ]; - + // The 3rd element indicates whether the second element + // is ACE-encoded + ["asciihost", "asciihost", false], + ["b\u00FCcher", "xn--bcher-kva", true], + ]; for (var i = 0; i < reference.length; ++i) { - dump("Testing " + reference[i] + "\n"); - // We test the following: - // - Converting UTF-8 to ACE and back gives us the expected answer - // - Converting the ASCII string UTF-8 -> ACE leaves the string unchanged - // - isACE returns true when we expect it to (third array elem true) - Assert.equal(idnService.convertUTF8toACE(reference[i][0]), reference[i][1]); - Assert.equal(idnService.convertUTF8toACE(reference[i][1]), reference[i][1]); - Assert.equal(idnService.convertACEtoUTF8(reference[i][1]), reference[i][0]); - Assert.equal(idnService.isACE(reference[i][1]), reference[i][2]); + dump("Testing " + reference[i] + "\n"); + // We test the following: + // - Converting UTF-8 to ACE and back gives us the expected answer + // - Converting the ASCII string UTF-8 -> ACE leaves the string unchanged + // - isACE returns true when we expect it to (third array elem true) + Assert.equal(idnService.convertUTF8toACE(reference[i][0]), reference[i][1]); + Assert.equal(idnService.convertUTF8toACE(reference[i][1]), reference[i][1]); + Assert.equal(idnService.convertACEtoUTF8(reference[i][1]), reference[i][0]); + Assert.equal(idnService.isACE(reference[i][1]), reference[i][2]); } }); add_task(async function test_extra_blocked() { - let isAscii = {}; - equal(idnService.convertToDisplayIDN("xn--gou-2lb.ro", isAscii), "goșu.ro"); - Services.prefs.setStringPref("network.IDN.extra_blocked_chars", "ș"); - equal(idnService.convertToDisplayIDN("xn--gou-2lb.ro", isAscii), "xn--gou-2lb.ro"); - Services.prefs.clearUserPref("network.IDN.extra_blocked_chars"); + let isAscii = {}; + equal(idnService.convertToDisplayIDN("xn--gou-2lb.ro", isAscii), "goșu.ro"); + Services.prefs.setStringPref("network.IDN.extra_blocked_chars", "ș"); + equal( + idnService.convertToDisplayIDN("xn--gou-2lb.ro", isAscii), + "xn--gou-2lb.ro" + ); + Services.prefs.clearUserPref("network.IDN.extra_blocked_chars"); }); diff --git a/netwerk/test/unit/test_immutable.js b/netwerk/test/unit/test_immutable.js index c1242169a202..fe30c1ae4c7e 100644 --- a/netwerk/test/unit/test_immutable.js +++ b/netwerk/test/unit/test_immutable.js @@ -1,4 +1,3 @@ - var prefs; var spdypref; var http2pref; @@ -6,7 +5,9 @@ var origin; var rcwnpref; function run_test() { - var env = Cc["@mozilla.org/process/environment;1"].getService(Ci.nsIEnvironment); + var env = Cc["@mozilla.org/process/environment;1"].getService( + Ci.nsIEnvironment + ); var h2Port = env.get("MOZHTTP2_PORT"); Assert.notEqual(h2Port, null); Assert.notEqual(h2Port, ""); @@ -21,18 +22,22 @@ function run_test() { prefs.setBoolPref("network.http.spdy.enabled", true); prefs.setBoolPref("network.http.spdy.enabled.http2", true); - prefs.setCharPref("network.dns.localDomains", "foo.example.com, bar.example.com"); + prefs.setCharPref( + "network.dns.localDomains", + "foo.example.com, bar.example.com" + ); // Disable rcwn to make cache behavior deterministic. prefs.setBoolPref("network.http.rcwn.enabled", false); // The moz-http2 cert is for foo.example.com and is signed by http2-ca.pem // so add that cert to the trust list as a signing cert. // the foo.example.com domain name. - let certdb = Cc["@mozilla.org/security/x509certdb;1"] - .getService(Ci.nsIX509CertDB); + let certdb = Cc["@mozilla.org/security/x509certdb;1"].getService( + Ci.nsIX509CertDB + ); addCertFromFile(certdb, "http2-ca.pem", "CTu,u,u"); origin = "https://foo.example.com:" + h2Port; - dump ("origin - " + origin + "\n"); + dump("origin - " + origin + "\n"); doTest1(); } @@ -46,7 +51,7 @@ function resetPrefs() { function makeChan(origin, path) { return NetUtil.newChannel({ uri: origin + path, - loadUsingSystemPrincipal: true + loadUsingSystemPrincipal: true, }).QueryInterface(Ci.nsIHttpChannel); } @@ -61,7 +66,9 @@ Listener.prototype = { if (expectPass) { if (!Components.isSuccessCode(request.status)) { - do_throw("Channel should have a success code! (" + request.status + ")"); + do_throw( + "Channel should have a success code! (" + request.status + ")" + ); } Assert.equal(request.responseStatus, 200); } else { @@ -74,25 +81,26 @@ Listener.prototype = { }, onStopRequest: function testOnStopRequest(request, status) { - if (expectConditional) { - Assert.equal(request.getResponseHeader("x-conditional"), "true"); - } else { - try { Assert.notEqual(request.getResponseHeader("x-conditional"), "true"); } - catch (e) { Assert.ok(true); } + if (expectConditional) { + Assert.equal(request.getResponseHeader("x-conditional"), "true"); + } else { + try { + Assert.notEqual(request.getResponseHeader("x-conditional"), "true"); + } catch (e) { + Assert.ok(true); + } } nextTest(); do_test_finished(); - } + }, }; -function testsDone() -{ +function testsDone() { dump("testDone\n"); resetPrefs(); } -function doTest1() -{ +function doTest1() { dump("execute doTest1 - resource without immutable. initial request\n"); do_test_pending(); expectConditional = false; @@ -102,8 +110,7 @@ function doTest1() chan.asyncOpen(listener); } -function doTest2() -{ +function doTest2() { dump("execute doTest2 - resource without immutable. reload\n"); do_test_pending(); expectConditional = true; @@ -114,8 +121,7 @@ function doTest2() chan.asyncOpen(listener); } -function doTest3() -{ +function doTest3() { dump("execute doTest3 - resource without immutable. shift reload\n"); do_test_pending(); expectConditional = false; @@ -126,8 +132,7 @@ function doTest3() chan.asyncOpen(listener); } -function doTest4() -{ +function doTest4() { dump("execute doTest1 - resource with immutable. initial request\n"); do_test_pending(); expectConditional = false; @@ -137,8 +142,7 @@ function doTest4() chan.asyncOpen(listener); } -function doTest5() -{ +function doTest5() { dump("execute doTest5 - resource with immutable. reload\n"); do_test_pending(); expectConditional = false; @@ -149,8 +153,7 @@ function doTest5() chan.asyncOpen(listener); } -function doTest6() -{ +function doTest6() { dump("execute doTest3 - resource with immutable. shift reload\n"); do_test_pending(); expectConditional = false; @@ -160,5 +163,3 @@ function doTest6() chan.loadFlags = Ci.nsIRequest.LOAD_BYPASS_CACHE; chan.asyncOpen(listener); } - - diff --git a/netwerk/test/unit/test_inhibit_caching.js b/netwerk/test/unit/test_inhibit_caching.js index 653f8be1eb6e..6b1e6531862a 100644 --- a/netwerk/test/unit/test_inhibit_caching.js +++ b/netwerk/test/unit/test_inhibit_caching.js @@ -1,9 +1,8 @@ -const {HttpServer} = ChromeUtils.import("resource://testing-common/httpd.js"); +const { HttpServer } = ChromeUtils.import("resource://testing-common/httpd.js"); var first = true; -function contentHandler(metadata, response) -{ - response.setHeader("Content-Type", 'text/plain'); +function contentHandler(metadata, response) { + response.setHeader("Content-Type", "text/plain"); var body = "first"; if (!first) { body = "second"; @@ -18,8 +17,7 @@ XPCOMUtils.defineLazyGetter(this, "uri", function() { var httpserver = null; -function run_test() -{ +function run_test() { // setup test httpserver = new HttpServer(); httpserver.registerPathHandler("/test", contentHandler); @@ -33,7 +31,10 @@ function run_test() // Makes a regular request function test_first_response() { - var chan = NetUtil.newChannel({uri: uri+"/test", loadUsingSystemPrincipal: true}); + var chan = NetUtil.newChannel({ + uri: uri + "/test", + loadUsingSystemPrincipal: true, + }); chan.asyncOpen(new ChannelListener(check_first_response, null)); } @@ -43,7 +44,13 @@ function check_first_response(request, buffer) { Assert.equal(request.responseStatus, 200); Assert.equal(buffer, "first"); // Open the cache entry to check its contents - asyncOpenCacheEntry(uri+"/test","disk", Ci.nsICacheStorage.OPEN_READONLY, null, cache_entry_callback); + asyncOpenCacheEntry( + uri + "/test", + "disk", + Ci.nsICacheStorage.OPEN_READONLY, + null, + cache_entry_callback + ); } // Checks that the cache entry has the correct contents @@ -51,15 +58,18 @@ function cache_entry_callback(status, entry) { equal(status, Cr.NS_OK); var inputStream = entry.openInputStream(0); pumpReadStream(inputStream, function(read) { - inputStream.close(); - equal(read,"first"); - run_next_test(); + inputStream.close(); + equal(read, "first"); + run_next_test(); }); } // Makes a request with the INHIBIT_CACHING load flag function test_inhibit_caching() { - var chan = NetUtil.newChannel({uri: uri+"/test", loadUsingSystemPrincipal: true}); + var chan = NetUtil.newChannel({ + uri: uri + "/test", + loadUsingSystemPrincipal: true, + }); chan.QueryInterface(Ci.nsIRequest).loadFlags |= Ci.nsIRequest.INHIBIT_CACHING; chan.asyncOpen(new ChannelListener(check_second_response, null)); } @@ -70,5 +80,11 @@ function check_second_response(request, buffer) { Assert.equal(request.responseStatus, 200); Assert.equal(buffer, "second"); // Checks that the cache entry still contains the content from the first request - asyncOpenCacheEntry(uri+"/test","disk", Ci.nsICacheStorage.OPEN_READONLY, null, cache_entry_callback); + asyncOpenCacheEntry( + uri + "/test", + "disk", + Ci.nsICacheStorage.OPEN_READONLY, + null, + cache_entry_callback + ); } diff --git a/netwerk/test/unit/test_ioservice.js b/netwerk/test/unit/test_ioservice.js index 0121d9997929..d218d77a7a94 100644 --- a/netwerk/test/unit/test_ioservice.js +++ b/netwerk/test/unit/test_ioservice.js @@ -1,9 +1,19 @@ "use strict"; -add_task(function test_extractScheme(){ +add_task(function test_extractScheme() { equal(Services.io.extractScheme("HtTp://example.com"), "http"); - Assert.throws(() => { Services.io.extractScheme("://example.com"); }, - /NS_ERROR_MALFORMED_URI/, "missing scheme"); - Assert.throws(() => { Services.io.extractScheme("ht%tp://example.com"); }, - /NS_ERROR_MALFORMED_URI/, "bad scheme"); + Assert.throws( + () => { + Services.io.extractScheme("://example.com"); + }, + /NS_ERROR_MALFORMED_URI/, + "missing scheme" + ); + Assert.throws( + () => { + Services.io.extractScheme("ht%tp://example.com"); + }, + /NS_ERROR_MALFORMED_URI/, + "bad scheme" + ); }); diff --git a/netwerk/test/unit/test_large_port.js b/netwerk/test/unit/test_large_port.js index f4a11c894f80..492a03047ff8 100644 --- a/netwerk/test/unit/test_large_port.js +++ b/netwerk/test/unit/test_large_port.js @@ -6,39 +6,63 @@ "use strict"; -function run_test() -{ - let mutator = Cc["@mozilla.org/network/standard-url-mutator;1"] - .createInstance(Ci.nsIURIMutator); - Assert.ok(mutator, "Mutator constructor works"); +function run_test() { + let mutator = Cc[ + "@mozilla.org/network/standard-url-mutator;1" + ].createInstance(Ci.nsIURIMutator); + Assert.ok(mutator, "Mutator constructor works"); - let url = Cc["@mozilla.org/network/standard-url-mutator;1"] - .createInstance(Ci.nsIStandardURLMutator) - .init(Ci.nsIStandardURL.URLTYPE_AUTHORITY, 65535, - "http://localhost", "UTF-8", null) - .finalize(); + let url = Cc["@mozilla.org/network/standard-url-mutator;1"] + .createInstance(Ci.nsIStandardURLMutator) + .init( + Ci.nsIStandardURL.URLTYPE_AUTHORITY, + 65535, + "http://localhost", + "UTF-8", + null + ) + .finalize(); - // Bug 1301621 makes invalid ports throw - Assert.throws(() => { - url = Cc["@mozilla.org/network/standard-url-mutator;1"] - .createInstance(Ci.nsIStandardURLMutator) - .init(Ci.nsIStandardURL.URLTYPE_AUTHORITY, 65536, - "http://localhost", "UTF-8", null) - .finalize(); - }, /NS_ERROR_MALFORMED_URI/, "invalid port during creation"); + // Bug 1301621 makes invalid ports throw + Assert.throws( + () => { + url = Cc["@mozilla.org/network/standard-url-mutator;1"] + .createInstance(Ci.nsIStandardURLMutator) + .init( + Ci.nsIStandardURL.URLTYPE_AUTHORITY, + 65536, + "http://localhost", + "UTF-8", + null + ) + .finalize(); + }, + /NS_ERROR_MALFORMED_URI/, + "invalid port during creation" + ); - Assert.throws(() => { - url = url.mutate() - .QueryInterface(Ci.nsIStandardURLMutator) - .setDefaultPort(65536) - .finalize(); - }, /NS_ERROR_MALFORMED_URI/, "invalid port in setDefaultPort"); - Assert.throws(() => { - url = url.mutate() - .setPort(65536) - .finalize(); - }, /NS_ERROR_MALFORMED_URI/, "invalid port in port setter"); + Assert.throws( + () => { + url = url + .mutate() + .QueryInterface(Ci.nsIStandardURLMutator) + .setDefaultPort(65536) + .finalize(); + }, + /NS_ERROR_MALFORMED_URI/, + "invalid port in setDefaultPort" + ); + Assert.throws( + () => { + url = url + .mutate() + .setPort(65536) + .finalize(); + }, + /NS_ERROR_MALFORMED_URI/, + "invalid port in port setter" + ); - Assert.equal(url.port, -1); - do_test_finished(); + Assert.equal(url.port, -1); + do_test_finished(); } diff --git a/netwerk/test/unit/test_localstreams.js b/netwerk/test/unit/test_localstreams.js index fad373b30ba4..d09b6a6ef613 100644 --- a/netwerk/test/unit/test_localstreams.js +++ b/netwerk/test/unit/test_localstreams.js @@ -1,6 +1,6 @@ // Tests bug 304414 -const PR_RDONLY = 0x1; // see prio.h +const PR_RDONLY = 0x1; // see prio.h // Does some sanity checks on the stream and returns the number of bytes read // when the checks passed. @@ -10,15 +10,18 @@ function test_stream(stream) { Assert.equal(stream.isNonBlocking(), false); // Check that the stream is not buffered - Assert.equal(Cc["@mozilla.org/io-util;1"] - .getService(Ci.nsIIOUtil) - .inputStreamIsBuffered(stream), - false); - + Assert.equal( + Cc["@mozilla.org/io-util;1"] + .getService(Ci.nsIIOUtil) + .inputStreamIsBuffered(stream), + false + ); + // Wrap it in a binary stream (to avoid wrong results that // scriptablestream would produce with binary content) - var binstream = Cc['@mozilla.org/binaryinputstream;1'] - .createInstance(Ci.nsIBinaryInputStream); + var binstream = Cc["@mozilla.org/binaryinputstream;1"].createInstance( + Ci.nsIBinaryInputStream + ); binstream.setInputStream(stream); var numread = 0; @@ -42,8 +45,9 @@ function test_stream(stream) { } catch (e) { // We expect the exception, so do nothing here } - if (could_read) + if (could_read) { do_throw("Data readable when available indicated EOF!"); + } return numread; } @@ -58,19 +62,19 @@ function test_stream(stream) { } function stream_for_file(file) { - var str = Cc["@mozilla.org/network/file-input-stream;1"] - .createInstance(Ci.nsIFileInputStream); + var str = Cc["@mozilla.org/network/file-input-stream;1"].createInstance( + Ci.nsIFileInputStream + ); str.init(file, PR_RDONLY, 0, 0); return str; } function stream_from_channel(file) { - var ios = Cc["@mozilla.org/network/io-service;1"] - .getService(Ci.nsIIOService); + var ios = Cc["@mozilla.org/network/io-service;1"].getService(Ci.nsIIOService); var uri = ios.newFileURI(file); return NetUtil.newChannel({ uri, - loadUsingSystemPrincipal: true + loadUsingSystemPrincipal: true, }).open(); } @@ -83,4 +87,3 @@ function run_test() { var dir = file.parent; test_stream(stream_from_channel(dir)); // Can't do size checking } - diff --git a/netwerk/test/unit/test_mismatch_last-modified.js b/netwerk/test/unit/test_mismatch_last-modified.js index b0eac15e981b..af4ab0e95a3d 100644 --- a/netwerk/test/unit/test_mismatch_last-modified.js +++ b/netwerk/test/unit/test_mismatch_last-modified.js @@ -1,4 +1,4 @@ -const {HttpServer} = ChromeUtils.import("resource://testing-common/httpd.js"); +const { HttpServer } = ChromeUtils.import("resource://testing-common/httpd.js"); var httpserver = new HttpServer(); var ios; @@ -16,120 +16,132 @@ var ios; // the third time the right data is returned. var listener_3 = { - // this listener is used to process the the request made after - // the cache invalidation. it expects to see the 'right data' + // this listener is used to process the the request made after + // the cache invalidation. it expects to see the 'right data' - QueryInterface: ChromeUtils.generateQI(["nsIStreamListener", "nsIRequestObserver"]), + QueryInterface: ChromeUtils.generateQI([ + "nsIStreamListener", + "nsIRequestObserver", + ]), - onStartRequest: function test_onStartR(request) {}, - - onDataAvailable: function test_ODA(request, inputStream, - offset, count) { - var data = new BinaryInputStream(inputStream).readByteArray(count); - - Assert.equal(data[0], "B".charCodeAt(0)); - }, + onStartRequest: function test_onStartR(request) {}, - onStopRequest: function test_onStopR(request, status) { - httpserver.stop(do_test_finished); - } + onDataAvailable: function test_ODA(request, inputStream, offset, count) { + var data = new BinaryInputStream(inputStream).readByteArray(count); + + Assert.equal(data[0], "B".charCodeAt(0)); + }, + + onStopRequest: function test_onStopR(request, status) { + httpserver.stop(do_test_finished); + }, }; XPCOMUtils.defineLazyGetter(this, "listener_2", function() { - return { + return { // this listener is used to process the revalidation of the // corrupted cache entry. its revalidation prompts it to be cleaned - QueryInterface: ChromeUtils.generateQI(["nsIStreamListener", "nsIRequestObserver"]), + QueryInterface: ChromeUtils.generateQI([ + "nsIStreamListener", + "nsIRequestObserver", + ]), onStartRequest: function test_onStartR(request) {}, - - onDataAvailable: function test_ODA(request, inputStream, - offset, count) { - var data = new BinaryInputStream(inputStream).readByteArray(count); - - // This is 'A' from a cache revalidation, but that reval will clean the cache - // because of mismatched last-modified response headers - - Assert.equal(data[0], "A".charCodeAt(0)); + + onDataAvailable: function test_ODA(request, inputStream, offset, count) { + var data = new BinaryInputStream(inputStream).readByteArray(count); + + // This is 'A' from a cache revalidation, but that reval will clean the cache + // because of mismatched last-modified response headers + + Assert.equal(data[0], "A".charCodeAt(0)); }, onStopRequest: function test_onStopR(request, status) { - var channel = request.QueryInterface(Ci.nsIHttpChannel); - var chan = NetUtil.newChannel({ - uri: "http://localhost:" + httpserver.identity.primaryPort + "/test1", - loadUsingSystemPrincipal: true - }); - chan.asyncOpen(listener_3); - } -}; + var channel = request.QueryInterface(Ci.nsIHttpChannel); + var chan = NetUtil.newChannel({ + uri: "http://localhost:" + httpserver.identity.primaryPort + "/test1", + loadUsingSystemPrincipal: true, + }); + chan.asyncOpen(listener_3); + }, + }; }); XPCOMUtils.defineLazyGetter(this, "listener_1", function() { - return { + return { // this listener processes the initial request from a empty cache. // the server responds with the wrong data ('A') - QueryInterface: ChromeUtils.generateQI(["nsIStreamListener", "nsIRequestObserver"]), + QueryInterface: ChromeUtils.generateQI([ + "nsIStreamListener", + "nsIRequestObserver", + ]), onStartRequest: function test_onStartR(request) {}, - - onDataAvailable: function test_ODA(request, inputStream, - offset, count) { - var data = new BinaryInputStream(inputStream).readByteArray(count); - Assert.equal(data[0], "A".charCodeAt(0)); + + onDataAvailable: function test_ODA(request, inputStream, offset, count) { + var data = new BinaryInputStream(inputStream).readByteArray(count); + Assert.equal(data[0], "A".charCodeAt(0)); }, onStopRequest: function test_onStopR(request, status) { - var channel = request.QueryInterface(Ci.nsIHttpChannel); - var chan = NetUtil.newChannel({ - uri: "http://localhost:" + httpserver.identity.primaryPort + "/test1", - loadUsingSystemPrincipal: true - }); - chan.asyncOpen(listener_2); - } -}; + var channel = request.QueryInterface(Ci.nsIHttpChannel); + var chan = NetUtil.newChannel({ + uri: "http://localhost:" + httpserver.identity.primaryPort + "/test1", + loadUsingSystemPrincipal: true, + }); + chan.asyncOpen(listener_2); + }, + }; }); function run_test() { - do_get_profile(); - ios = Cc["@mozilla.org/network/io-service;1"] - .getService(Ci.nsIIOService); + do_get_profile(); + ios = Cc["@mozilla.org/network/io-service;1"].getService(Ci.nsIIOService); - evict_cache_entries(); + evict_cache_entries(); - httpserver.registerPathHandler("/test1", handler); - httpserver.start(-1); + httpserver.registerPathHandler("/test1", handler); + httpserver.start(-1); - var port = httpserver.identity.primaryPort; - var chan = NetUtil.newChannel({ - uri: "http://localhost:" + port + "/test1", - loadUsingSystemPrincipal: true - }); - chan.asyncOpen(listener_1); + var port = httpserver.identity.primaryPort; + var chan = NetUtil.newChannel({ + uri: "http://localhost:" + port + "/test1", + loadUsingSystemPrincipal: true, + }); + chan.asyncOpen(listener_1); - do_test_pending(); + do_test_pending(); } -var iter=0; +var iter = 0; function handler(metadata, response) { - iter++; - if (metadata.hasHeader("If-Modified-Since")) { - response.setStatusLine(metadata.httpVersion, 304, "Not Modified"); - response.setHeader("Last-Modified", "Tue, 15 Nov 1994 12:45:26 GMT", false); - } - else { - response.setStatusLine(metadata.httpVersion, 200, "OK"); - response.setHeader("Cache-Control", "max-age=0", false) - if (iter == 1) { - // simulated wrong response - response.setHeader("Last-Modified", "Wed, 16 Nov 1994 00:00:00 GMT", false); - response.bodyOutputStream.write("A", 1); - } - if (iter == 3) { - // 'correct' response - response.setHeader("Last-Modified", "Tue, 15 Nov 1994 12:45:26 GMT", false); - response.bodyOutputStream.write("B", 1); - } + iter++; + if (metadata.hasHeader("If-Modified-Since")) { + response.setStatusLine(metadata.httpVersion, 304, "Not Modified"); + response.setHeader("Last-Modified", "Tue, 15 Nov 1994 12:45:26 GMT", false); + } else { + response.setStatusLine(metadata.httpVersion, 200, "OK"); + response.setHeader("Cache-Control", "max-age=0", false); + if (iter == 1) { + // simulated wrong response + response.setHeader( + "Last-Modified", + "Wed, 16 Nov 1994 00:00:00 GMT", + false + ); + response.bodyOutputStream.write("A", 1); } + if (iter == 3) { + // 'correct' response + response.setHeader( + "Last-Modified", + "Tue, 15 Nov 1994 12:45:26 GMT", + false + ); + response.bodyOutputStream.write("B", 1); + } + } } diff --git a/netwerk/test/unit/test_mozTXTToHTMLConv.js b/netwerk/test/unit/test_mozTXTToHTMLConv.js index 229f85e70fee..1a6c68c02533 100644 --- a/netwerk/test/unit/test_mozTXTToHTMLConv.js +++ b/netwerk/test/unit/test_mozTXTToHTMLConv.js @@ -7,158 +7,162 @@ */ function run_test() { - let converter = Cc["@mozilla.org/txttohtmlconv;1"] - .getService(Ci.mozITXTToHTMLConv); + let converter = Cc["@mozilla.org/txttohtmlconv;1"].getService( + Ci.mozITXTToHTMLConv + ); const scanTXTtests = [ // -- RFC1738 { input: "RFC1738: then", - url: "http://mozilla.org" + url: "http://mozilla.org", }, { input: "RFC1738: then", - url: "mailto:john.doe+test@mozilla.org" + url: "mailto:john.doe+test@mozilla.org", }, // -- RFC2396E { input: "RFC2396E: then", - url: "http://mozilla.org/" + url: "http://mozilla.org/", }, { input: "RFC2396E: then", - url: "mailto:john.doe+test@mozilla.org" + url: "mailto:john.doe+test@mozilla.org", }, // -- abbreviated { input: "see www.mozilla.org maybe", - url: "http://www.mozilla.org" + url: "http://www.mozilla.org", }, { input: "mail john.doe+test@mozilla.org maybe", - url: "mailto:john.doe+test@mozilla.org" + url: "mailto:john.doe+test@mozilla.org", }, // -- delimiters { - input: "see http://www.mozilla.org/maybe today", // Spaces - url: "http://www.mozilla.org/maybe" + input: "see http://www.mozilla.org/maybe today", // Spaces + url: "http://www.mozilla.org/maybe", }, { - input: "see \"http://www.mozilla.org/maybe today\"", // Double quotes - url: "http://www.mozilla.org/maybetoday" // spaces ignored + input: 'see "http://www.mozilla.org/maybe today"', // Double quotes + url: "http://www.mozilla.org/maybetoday", // spaces ignored }, { - input: "see ", // Angle brackets - url: "http://www.mozilla.org/maybetoday" // spaces ignored + input: "see ", // Angle brackets + url: "http://www.mozilla.org/maybetoday", // spaces ignored }, // -- freetext { - input:"I mean http://www.mozilla.org/.", - url: "http://www.mozilla.org/" + input: "I mean http://www.mozilla.org/.", + url: "http://www.mozilla.org/", }, { - input:"you mean http://mozilla.org:80, right?", - url: "http://mozilla.org:80" + input: "you mean http://mozilla.org:80, right?", + url: "http://mozilla.org:80", }, { - input:"go to http://mozilla.org; then go home", - url: "http://mozilla.org" + input: "go to http://mozilla.org; then go home", + url: "http://mozilla.org", }, { - input:"http://mozilla.org! yay!", - url: "http://mozilla.org" + input: "http://mozilla.org! yay!", + url: "http://mozilla.org", }, { - input:"er, http://mozilla.com?", - url: "http://mozilla.com" + input: "er, http://mozilla.com?", + url: "http://mozilla.com", }, { - input:"http://example.org- where things happen", - url: "http://example.org" + input: "http://example.org- where things happen", + url: "http://example.org", }, { - input:"see http://mozilla.org: front page", - url: "http://mozilla.org" + input: "see http://mozilla.org: front page", + url: "http://mozilla.org", }, { - input:"'http://mozilla.org/': that's the url", - url: "http://mozilla.org/" + input: "'http://mozilla.org/': that's the url", + url: "http://mozilla.org/", }, { - input:"some special http://mozilla.org/?x=.,;!-:x", - url: "http://mozilla.org/?x=.,;!-:x" + input: "some special http://mozilla.org/?x=.,;!-:x", + url: "http://mozilla.org/?x=.,;!-:x", }, { // escape & when producing html - input:"'http://example.org/?test=true&success=true': ok", - url: "http://example.org/?test=true&success=true" + input: "'http://example.org/?test=true&success=true': ok", + url: "http://example.org/?test=true&success=true", }, { input: "bracket: http://localhost/[1] etc.", - url: "http://localhost/" + url: "http://localhost/", }, { input: "bracket: john.doe+test@mozilla.org[1] etc.", - url: "mailto:john.doe+test@mozilla.org" + url: "mailto:john.doe+test@mozilla.org", }, { input: "parenthesis: (http://localhost/) etc.", - url: "http://localhost/" + url: "http://localhost/", }, { input: "parenthesis: (john.doe+test@mozilla.org) etc.", - url: "mailto:john.doe+test@mozilla.org" + url: "mailto:john.doe+test@mozilla.org", }, { input: "(thunderbird)http://mozilla.org/thunderbird", - url: "http://mozilla.org/thunderbird" + url: "http://mozilla.org/thunderbird", }, { input: "(mail)john.doe+test@mozilla.org", - url: "mailto:john.doe+test@mozilla.org" + url: "mailto:john.doe+test@mozilla.org", }, { input: "()http://mozilla.org", - url: "http://mozilla.org" + url: "http://mozilla.org", }, { - input: "parenthesis included: http://kb.mozillazine.org/Performance_(Thunderbird) etc.", - url: "http://kb.mozillazine.org/Performance_(Thunderbird)" + input: + "parenthesis included: http://kb.mozillazine.org/Performance_(Thunderbird) etc.", + url: "http://kb.mozillazine.org/Performance_(Thunderbird)", }, { input: "parenthesis slash bracket: (http://localhost/)[1] etc.", - url: "http://localhost/" + url: "http://localhost/", }, { input: "parenthesis bracket: (http://example.org[1]) etc.", - url: "http://example.org" + url: "http://example.org", }, { input: "ipv6 1: https://[1080::8:800:200C:417A]/foo?bar=x test", - url: "https://[1080::8:800:200C:417A]/foo?bar=x" + url: "https://[1080::8:800:200C:417A]/foo?bar=x", }, { input: "ipv6 2: http://[::ffff:127.0.0.1]/#yay test", - url: "http://[::ffff:127.0.0.1]/#yay" + url: "http://[::ffff:127.0.0.1]/#yay", }, { input: "ipv6 parenthesis port: (http://[2001:db8::1]:80/) test", - url: "http://[2001:db8::1]:80/" + url: "http://[2001:db8::1]:80/", }, { - input: "test http://www.map.com/map.php?t=Nova_Scotia&markers=//Not_a_survey||description=plm2 test", - url: "http://www.map.com/map.php?t=Nova_Scotia&markers=//Not_a_survey||description=plm2" + input: + "test http://www.map.com/map.php?t=Nova_Scotia&markers=//Not_a_survey||description=plm2 test", + url: + "http://www.map.com/map.php?t=Nova_Scotia&markers=//Not_a_survey||description=plm2", }, { input: "bug#1509493 (john@mozilla.org)john@mozilla.org test", url: "mailto:john@mozilla.org", - text: "john@mozilla.org" + text: "john@mozilla.org", }, { input: "bug#1509493 {john@mozilla.org}john@mozilla.org test", url: "mailto:john@mozilla.org", - text: "john@mozilla.org" - } + text: "john@mozilla.org", + }, ]; const scanTXTglyph = [ @@ -166,120 +170,121 @@ function run_test() { // smiley types). { input: "this is superscript: x^2", - results: [""] + results: [""], }, { input: "this is plus-minus: +/-", - results: ["±"] + results: ["±"], }, { input: "this is a smiley :)", - results: ["moz-smiley-s1"] + results: ["moz-smiley-s1"], }, { input: "this is a smiley :-)", - results: ["moz-smiley-s1"] + results: ["moz-smiley-s1"], }, { input: "this is a smiley :-(", - results: ["moz-smiley-s2"] + results: ["moz-smiley-s2"], }, ]; const scanTXTstrings = [ - "underline", // ASCII - "äöüßáéíóúî", // Latin-1 + "underline", // ASCII + "äöüßáéíóúî", // Latin-1 "a\u0301c\u0327c\u030Ce\u0309n\u0303t\u0326e\u0308d\u0323", - // áçčẻñțëḍ Latin + // áçčẻñțëḍ Latin "\u016B\u00F1\u0257\u0119\u0211\u0142\u00ED\u00F1\u0119", - // Pseudo-ese ūñɗęȑłíñę - "\u01DDu\u0131\u0283\u0279\u01DDpun", // Upside down ǝuıʃɹǝpun + // Pseudo-ese ūñɗęȑłíñę + "\u01DDu\u0131\u0283\u0279\u01DDpun", // Upside down ǝuıʃɹǝpun "\u03C5\u03C0\u03BF\u03B3\u03C1\u03AC\u03BC\u03BC\u03B9\u03C3\u03B7", - // Greek υπογράμμιση + // Greek υπογράμμιση "\u0441\u0438\u043B\u044C\u043D\u0443\u044E", // Russian сильную - "\u0C2C\u0C32\u0C2E\u0C46\u0C56\u0C28", // Telugu బలమైన - "\u508D\u7DDA\u3059\u308B", // Japanese 傍線する + "\u0C2C\u0C32\u0C2E\u0C46\u0C56\u0C28", // Telugu బలమైన + "\u508D\u7DDA\u3059\u308B", // Japanese 傍線する "\uD841\uDF0E\uD841\uDF31\uD841\uDF79\uD843\uDC53\uD843\uDC78", - // Chinese (supplementary plane) - "\uD801\uDC14\uD801\uDC2F\uD801\uDC45\uD801\uDC28\uD801\uDC49\uD801\uDC2F\uD801\uDC3B" - // Deseret 𐐔𐐯𐑅𐐨𐑉𐐯𐐻 + // Chinese (supplementary plane) + "\uD801\uDC14\uD801\uDC2F\uD801\uDC45\uD801\uDC28\uD801\uDC49\uD801\uDC2F\uD801\uDC3B", + // Deseret 𐐔𐐯𐑅𐐨𐑉𐐯𐐻 ]; const scanTXTstructs = [ - { - delimiter: "/", - tag: "i", - class: "moz-txt-slash" - }, - { - delimiter: "*", - tag: "b", - class: "moz-txt-star" - }, - { - delimiter: "_", - tag: "span", - class: "moz-txt-underscore" - }, - { - delimiter: "|", - tag: "code", - class: "moz-txt-verticalline" - } - ]; + { + delimiter: "/", + tag: "i", + class: "moz-txt-slash", + }, + { + delimiter: "*", + tag: "b", + class: "moz-txt-star", + }, + { + delimiter: "_", + tag: "span", + class: "moz-txt-underscore", + }, + { + delimiter: "|", + tag: "code", + class: "moz-txt-verticalline", + }, + ]; const scanHTMLtests = [ { input: "http://foo.example.com", - shouldChange: true + shouldChange: true, }, { input: " foo", - shouldChange: false + shouldChange: false, }, { input: "see http://abbr.example.com", - shouldChange: true + shouldChange: true, }, { input: "", - shouldChange: false + shouldChange: false, }, { input: "", - shouldChange: false + shouldChange: false, }, { input: "", - shouldChange: false + shouldChange: false, }, { - input: "", - shouldChange: false + input: + "", + shouldChange: false, }, { input: "", - shouldChange: false + shouldChange: false, }, { input: "", - shouldChange: false + shouldChange: false, }, { input: "http://head.example.com/", - shouldChange: false + shouldChange: false, }, { input: "
see http://header.example.com
", - shouldChange: true + shouldChange: true, }, { input: "